protected function getResponse($body) { $stream = Stream::factory($body); $response = new Response(200); $response->setBody($stream); return $response; }
/** * Adds a mock repsonse to the response queue * * @param \GuzzleHttp\Stream\Stream $data Stream data object * @param int $response_code desired response code */ protected function addClientMock($data, $response_code = 200) { //create a response with the data and response code $api_response = new Response($response_code); $api_response->setBody($data); $mock_response = $this->getMockObject(); $mock_response->addResponse($api_response); }
/** * Create a Response object from a stub. * * @param $stub * @return \GuzzleHttp\Message\Response */ private function makeResponse($stub) { $response = new Response(200); $response->setHeader('Content-Type', 'application/json'); $responseBody = Stream::factory(fopen('./tests/Destiny/stubs/' . $stub . '.txt', 'r+')); $response->setBody($responseBody); return $response; }
private function getMockWithCode($code, $body = null) { $response = new Response($code, array()); if (isset($body) === true) { $response->setBody(Stream::factory(json_encode($body))); } $this->mockResponse = new Mock(array($response)); }
public function testConvertsToStringAndSeeksToByteZero() { $response = new Response(200); $s = Stream::factory('foo'); $s->read(1); $response->setBody($s); $this->assertEquals("HTTP/1.1 200 OK\r\n\r\nfoo", (string) $response); }
/** * Tests the search method. */ public function testSearch() { $http_client = new HttpClient(); $response = new Response(200); $response->setBody(Stream::factory(fopen(__DIR__ . '/../Fixtures/search-results.json', 'r+'))); $mock = new Mock([$response]); // Add the mock subscriber to the client. $http_client->getEmitter()->attach($mock); $config = ['base_url' => 'http://agencysearch.australia.gov.au', 'collection' => 'agencies']; $client = new Client($config, $http_client); $response = $client->search('test'); // Check the response. $this->assertEquals(0, $response->getReturnCode(), 'Return code ok'); $this->assertEquals('form', $response->getQuery(), 'Query matches'); $this->assertEquals(408, $response->getTotalTimeMillis(), 'Total time millis matches'); // Check the summary. $summary = $response->getResultsSummary(); $this->assertEquals(1, $summary->getStart(), 'Start matches'); $this->assertEquals(10, $summary->getEnd(), 'End matches'); $this->assertEquals(10, $summary->getPageSize(), 'Page size matches'); $this->assertEquals(17632, $summary->getTotal(), 'Total matches'); // Check the results. $results = $response->getResults(); $this->assertNotEmpty($results, "Results are found"); // Check an individual result. $result = $results[0]; $this->assertEquals('Forms', $result->getTitle(), 'Title matches'); $this->assertEquals('Forms. We provide electronic and printable forms that you can download, complete and return to us. ... An A to Z list by name of forms for Centrelink, Child Support and Medicare.', $result->getSummary(), 'Summary matches'); $this->assertEquals('2014-10-27', $result->getDate()->format('Y-m-d'), 'Date matches'); $this->assertEquals('http://cache-au.funnelback.com/search/cache.cgi?collection=fed-gov&doc=funnelback-web-crawl.warc&off=27605782&len=6529&url=http%3A%2F%2Fwww.humanservices.gov.au%2Fcustomer%2Fforms%2F&profile=_default', $result->getCacheUrl(), 'Cache URL matches'); $this->assertEquals('/search/click.cgi?rank=1&collection=agencies&url=http%3A%2F%2Fwww.humanservices.gov.au%2Fcustomer%2Fforms%2F&index_url=http%3A%2F%2Fwww.humanservices.gov.au%2Fcustomer%2Fforms%2F&auth=1gCsYnROvefyAqpyeyY78g&query=form&profile=_default', $result->getClickUrl(), 'Click URL matches'); $this->assertEquals('http://www.humanservices.gov.au/customer/forms/', $result->getLiveUrl(), 'Live URL matches'); // Check the facets. $facets = $response->getFacets(); $this->assertNotEmpty($facets, "Facets were found"); // Check a facet. $facet = $facets[0]; $this->assertEquals('Keyword', $facet->getName(), 'The name matches'); $facet_items = $facet->getFacetItems(); $this->assertNotEmpty($facet_items, "Facet items are not empty"); // Check a facet item. $facet_item = $facet_items[0]; $this->assertEquals('13. Year books and other multi-subject products', $facet_item->getLabel(), 'Label matches'); $this->assertEquals(7353, $facet_item->getCount(), 'Count matches'); $this->assertEquals('f.Keyword%7Cs=13.+Year+books+and+other+multi-subject+products', $facet_item->getQueryStringParam(), 'Query string param matches'); }
/** * @param ClientInterface $client * @param DescriptionInterface $description * @param array $config */ public function __construct(ClientInterface $client = null, DescriptionInterface $description = null, array $config = []) { $client = $client instanceof ClientInterface ? $client : new Client(); $description = $description instanceof DescriptionInterface ? $description : new Description(); parent::__construct($client, $description, $config); $cachedResponse = new Response(200); $this->getHttpClient()->getEmitter()->on('complete', function (CompleteEvent $e) use($cachedResponse) { $array1 = explode(PHP_EOL, trim((string) $e->getResponse()->getBody())); $result = array(); foreach ($array1 as $key => $value) { $array2 = explode(':', $value); $result[$array2[0]] = isset($array2[1]) ? trim($array2[1]) : ''; } $stream = Stream::factory(json_encode($result)); $cachedResponse->setBody($stream); $e->intercept($cachedResponse); }); }
/** * @param int $code * @param string $class * * @dataProvider dataProviderErrorCodes */ public function testClientThrowsRateLimitException($code, $class) { $this->setExpectedException($class); $this->createTestConfig(); $request = new Request('POST', 'http://not-important'); $response = new Response($code); $requestException = new RequestException('Not Important', $request, $response); $httpClientMock = $this->getMock('GuzzleHttp\\Client', ['send']); $httpClientMock->expects($this->at(0))->method('send')->will($this->throwException($requestException)); if ($code === 401) { // 401 renew auth token handling $jsonResponseData = ['access_token' => '__token__', 'expires_in' => '1337']; $renewAuthTokenResponse = new Response(200); $renewAuthTokenResponse->setBody(Stream::factory(json_encode($jsonResponseData))); $httpClientMock->expects($this->at(1))->method('send')->will($this->returnValue($renewAuthTokenResponse)); $httpClientMock->expects($this->at(2))->method('send')->will($this->throwException($requestException)); } $client = new Api\Client('__oauthId__', $this->app['hc.config'], $this->app['hc.api_registry'], $httpClientMock, $this->app['logger']); $client->send('/not-important', []); }
public function fetch(RequestInterface $request) { $key = $this->getCacheKey($request); $entries = $this->cache->fetch($key); if (!$entries) { return null; } $match = $matchIndex = null; $headers = $this->persistHeaders($request); $entries = unserialize($entries); foreach ($entries as $index => $entry) { $vary = isset($entry[1]['vary']) ? $entry[1]['vary'] : ''; if ($this->requestsMatch($vary, $headers, $entry[0])) { $match = $entry; $matchIndex = $index; break; } } if (!$match) { return null; } // Ensure that the response is not expired $response = null; if ($match[4] < time()) { $response = -1; } else { $response = new Response($match[2], $match[1]); if ($match[3]) { if ($body = $this->cache->fetch($match[3])) { $response->setBody(Stream\Utils::create($body)); } else { // The response is not valid because the body was somehow // deleted $response = -1; } } } if ($response === -1) { // Remove the entry from the metadata and update the cache unset($entries[$matchIndex]); if ($entries) { $this->cache->save($key, serialize($entries)); } else { $this->cache->delete($key); } return null; } return $response; }
/** * Build a fake guzzle client so we don't actually send requests. * * @param $textfile * @return \GuzzleHttp\Client */ private function buildMockClient($textfile) { $client = new Client(); $mockResponse = new Response(200); $mockResponseBody = Stream::factory(fopen(__DIR__ . '/../../../tests/' . $textfile . '.txt', 'r+')); $mockResponse->setBody($mockResponseBody); $mock = new Mock(); $mock->addResponse($mockResponse); $client->getEmitter()->attach($mock); return $client; }
public function setBodyContent($body) { parent::setBody(Stream::factory($body)); }
/** * Getting Guzzle mock response. * * @param string $requestUrl Full API endpoint URL * @param mixed $requestBody Request body. * * @return Mock Guzzle mock response. */ private function getMock($requestUrl, $requestBody) { if (!is_string($requestBody)) { $requestBody = print_r($requestBody, true); } $filename = self::$settings->mockResponsesDir . md5($requestUrl) . md5($requestBody) . '.inc'; if (file_exists($filename)) { $data = null; require $filename; $data['headers'] = (array) json_decode(htmlspecialchars_decode($data['headers_json'], ENT_QUOTES)); $mockResponse = new Response($data['httpCode']); $mockResponse->setHeaders($data['headers']); $separator = "\r\n\r\n"; $bodyParts = explode($separator, htmlspecialchars_decode($data['response']), ENT_QUOTES); if (count($bodyParts) > 1) { $mockResponse->setBody(Stream::factory($bodyParts[count($bodyParts) - 1])); } else { $mockResponse->setBody(Stream::factory(htmlspecialchars_decode($data['response']))); } $mock = new Mock([$mockResponse]); } else { $mockResponse = new Response(404); $mock = new Mock([$mockResponse]); } return $mock; }
private function setResponseStream(Response $response, $socket) { if ($response->getHeader('Transfer-Encoding') == "chunked") { $stream = new ChunkedStream($socket); } elseif ($response->getHeader('Content-Type') == "application/vnd.docker.raw-stream") { $stream = new AttachStream($socket); } else { $stream = new Stream($socket); } $response->setBody($stream); }
function it_can_perform_a_post_request_with_parameters(ClientInterface $client) { $url = 'http://doc.build/api/documents'; $response = new Response(200); $response->setBody(Stream::factory("")); $client->post($url, ['body' => ['document[name]' => 'Test File 1', 'document[extension]' => 'docx'], 'headers' => ['Auth' => 'myapikey'], 'exceptions' => true])->shouldBeCalled()->willReturn($response); $this->post('documents', ['document[name]' => 'Test File 1', 'document[extension]' => 'docx'], ['Auth' => 'myapikey']); }
private function setResponseStream(Response $response, $socket, EmitterInterface $emitter, $useFilter = false) { if ($response->getHeader('Transfer-Encoding') == "chunked") { stream_filter_append($socket, 'dechunk'); } // Attach filter if ($useFilter) { stream_filter_append($socket, 'event', STREAM_FILTER_READ, ['emitter' => $emitter, 'content_type' => $response->getHeader('Content-Type')]); } $stream = new Stream($socket); $response->setBody($stream); }
public function setUp() { $response = new Response(404); $response->setBody(Stream::factory($this->getBody())); $this->result = new PingResult($response); }
private function getResponse($file) { $response = new Response(200); $response->setBody(Stream::factory(fopen($file, 'r'))); return $response; }