|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Geocoder package. |
| 5 | + * For the full copyright and license information, please view the LICENSE |
| 6 | + * file that was distributed with this source code. |
| 7 | + * |
| 8 | + * @license MIT License |
| 9 | + */ |
| 10 | + |
| 11 | +namespace Geocoder\IntegrationTest; |
| 12 | + |
| 13 | +use GuzzleHttp\Psr7\Response; |
| 14 | +use Http\Client\Curl\Client as HttplugClient; |
| 15 | +use Http\Client\HttpClient; |
| 16 | +use Http\Mock\Client as MockedHttpClient; |
| 17 | +use Psr\Http\Message\RequestInterface; |
| 18 | +use Psr\Http\Message\ResponseInterface; |
| 19 | + |
| 20 | +/** |
| 21 | + * @author Tobias Nyholm <[email protected]> |
| 22 | + */ |
| 23 | +abstract class BaseTestCase extends \PHPUnit_Framework_TestCase |
| 24 | +{ |
| 25 | + /** |
| 26 | + * Get a real HTTP client. If $_SERVER['RESPONSE_CACHE'] is set to a path it will use cached responses. |
| 27 | + * |
| 28 | + * @return HttpClient |
| 29 | + */ |
| 30 | + protected function getHttpClient($apiKey = null) |
| 31 | + { |
| 32 | + if (isset($_SERVER['RESPONSE_CACHE']) && false !== $_SERVER['RESPONSE_CACHE']) { |
| 33 | + return new CachedResponseClient(new HttplugClient(), $_SERVER['RESPONSE_CACHE'], $apiKey); |
| 34 | + } else { |
| 35 | + return new HttplugClient(); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Get a mocked HTTP client that never do calls over the internet. Use this is you want to control the response data. |
| 41 | + * |
| 42 | + * @param string|null $body |
| 43 | + * @param int $statusCode |
| 44 | + * |
| 45 | + * @return HttpClient |
| 46 | + */ |
| 47 | + protected function getMockedHttpClient($body = null, $statusCode = 200) |
| 48 | + { |
| 49 | + $client = new MockedHttpClient(); |
| 50 | + $client->addResponse(new Response($statusCode, [], $body)); |
| 51 | + |
| 52 | + return $client; |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Get a mocked HTTP client where you may do tests on the request. |
| 57 | + * |
| 58 | + * @param string|null $body |
| 59 | + * @param int $statusCode |
| 60 | + * |
| 61 | + * @return HttpClient |
| 62 | + */ |
| 63 | + protected function getMockedHttpClientCallback(callable $requestCallback) |
| 64 | + { |
| 65 | + $client = $this->getMockBuilder(HttpClient::class)->getMock(); |
| 66 | + |
| 67 | + $client |
| 68 | + ->expects($this->once()) |
| 69 | + ->method('sendRequest') |
| 70 | + ->willReturnCallback(function (RequestInterface $request) use ($requestCallback) { |
| 71 | + $response = $requestCallback($request); |
| 72 | + |
| 73 | + if (!$response instanceof ResponseInterface) { |
| 74 | + $response = new Response(200, [], (string) $response); |
| 75 | + } |
| 76 | + |
| 77 | + return $response; |
| 78 | + }); |
| 79 | + |
| 80 | + return $client; |
| 81 | + } |
| 82 | +} |
0 commit comments