enqueue() публичный статический Метод

Any currently queued responses will be overwritten. Subsequent requests on the server will return queued responses in FIFO order.
public static enqueue ( array | Psr\Http\Message\ResponseInterface $responses )
$responses array | Psr\Http\Message\ResponseInterface A single or array of Responses to queue.
Пример #1
0
 public function testStripsFragmentFromHost()
 {
     Server::flush();
     Server::enqueue("HTTP/1.1 200 OK\r\n\r\nContent-Length: 0\r\n\r\n");
     // This will fail if the removal of the #fragment is not performed
     $url = Url::fromString(Server::$url)->setPath(null)->setFragment('foo');
     $client = new Client();
     $client->get($url);
 }
 public function testDelaysConcurrently()
 {
     Server::flush();
     Server::enqueue([new Response()]);
     $a = new CurlMultiHandler();
     $expected = microtime(true) + 100 / 1000;
     $response = $a(new Request('GET', Server::$url), ['delay' => 100]);
     $response->wait();
     $this->assertGreaterThanOrEqual($expected, microtime(true));
 }
Пример #3
0
 /**
  * @dataProvider hasBodyProvider
  */
 public function testSendsWithBody($method)
 {
     Server::flush();
     Server::enqueue([new Response(200)]);
     call_user_func("GuzzleHttp\\{$method}", Server::$url, ['headers' => ['foo' => 'bar'], 'body' => 'test', 'query' => ['a' => '1']]);
     $sent = Server::received(true)[0];
     $this->assertEquals(strtoupper($method), $sent->getMethod());
     $this->assertEquals('/?a=1', $sent->getResource());
     $this->assertEquals('bar', $sent->getHeader('foo'));
     $this->assertEquals('test', $sent->getBody());
 }
 public function testUsesContentLengthWhenOverInMemorySize()
 {
     Server::flush();
     Server::enqueue([new Response()]);
     $stream = Psr7\stream_for(str_repeat('.', 1000000));
     $handler = new CurlHandler();
     $request = new Request('PUT', Server::$url, ['Content-Length' => 1000000], $stream);
     $handler($request, [])->wait();
     $received = Server::received()[0];
     $this->assertEquals(1000000, $received->getHeaderLine('Content-Length'));
     $this->assertFalse($received->hasHeader('Transfer-Encoding'));
 }
Пример #5
0
 public function testCanSendMagicAsyncRequests()
 {
     $client = new Client();
     Server::flush();
     Server::enqueue([new Response(200, ['Content-Length' => 2], 'hi')]);
     $p = $client->getAsync(Server::$url, ['query' => ['test' => 'foo']]);
     $this->assertInstanceOf(PromiseInterface::class, $p);
     $this->assertEquals(200, $p->wait()->getStatusCode());
     $received = Server::received(true);
     $this->assertCount(1, $received);
     $this->assertEquals('test=foo', $received[0]->getUri()->getQuery());
 }
Пример #6
0
 /**
  * @issue https://github.com/guzzle/guzzle/issues/866
  */
 public function testProperyGetsTransferStats()
 {
     $transfer = [];
     Server::enqueue([new Response(200)]);
     $c = new Client();
     $response = $c->get(Server::$url . '/foo', ['events' => ['end' => function (EndEvent $e) use(&$transfer) {
         $transfer = $e->getTransferInfo();
     }]]);
     $this->assertEquals(Server::$url . '/foo', $response->getEffectiveUrl());
     $this->assertNotEmpty($transfer);
     $this->assertArrayHasKey('url', $transfer);
 }
Пример #7
0
 public function testAddsProgress()
 {
     Server::enqueue([new Response(200)]);
     $client = new Client(['base_url' => Server::$url]);
     $request = $client->createRequest('GET');
     $called = false;
     $request->getEmitter()->on('progress', function (ProgressEvent $e) use(&$called) {
         $called = true;
     });
     $this->assertEquals(200, $client->send($request)->getStatusCode());
     $this->assertTrue($called);
 }
Пример #8
0
 public function testReleasesAdditionalEasyHandles()
 {
     Server::flush();
     Server::enqueue(["HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"]);
     $a = new CurlAdapter(new MessageFactory(), ['max_handles' => 2]);
     $client = new Client(['base_url' => Server::$url, 'adapter' => $a]);
     $request = $client->createRequest('GET', '/', ['events' => ['headers' => function (HeadersEvent $e) use($client) {
         $client->get('/', ['events' => ['headers' => function (HeadersEvent $e) {
             $e->getClient()->get('/');
         }]]);
     }]]);
     $transaction = new Transaction($client, $request);
     $a->send($transaction);
     $this->assertCount(2, $this->readAttribute($a, 'handles'));
 }
 public function testCachesResponses()
 {
     Server::enqueue([new Response(200, ['Vary' => 'Accept-Encoding,Cookie,X-Use-HHVM', 'Date' => 'Wed, 29 Oct 2014 20:52:15 GMT', 'Cache-Control' => 'private, s-maxage=0, max-age=0, must-revalidate', 'Last-Modified' => 'Wed, 29 Oct 2014 20:30:57 GMT', 'Age' => '1277']), new Response(304, ['Content-Type' => 'text/html; charset=UTF-8', 'Vary' => 'Accept-Encoding,Cookie,X-Use-HHVM', 'Date' => 'Wed, 29 Oct 2014 20:52:16 GMT', 'Cache-Control' => 'private, s-maxage=0, max-age=0, must-revalidate', 'Last-Modified' => 'Wed, 29 Oct 2014 20:30:57 GMT', 'Age' => '1278'])]);
     $client = new Client(['base_url' => Server::$url]);
     CacheSubscriber::attach($client);
     $history = new History();
     $client->getEmitter()->attach($history);
     $response1 = $client->get('/foo');
     $this->assertEquals(200, $response1->getStatusCode());
     $response2 = $client->get('/foo');
     $this->assertEquals(200, $response2->getStatusCode());
     $this->assertCount(2, Server::received());
     $last = $history->getLastResponse();
     $this->assertEquals('HIT from GuzzleCache', $last->getHeader('X-Cache-Lookup'));
     $this->assertEquals('HIT from GuzzleCache', $last->getHeader('X-Cache'));
 }
 public function testNestedFutureErrorsAreResolvedWhenSending()
 {
     $c = new Client();
     $total = 3;
     Server::enqueue([new Response(500), new Response(501), new Response(502)]);
     $c->getEmitter()->on('error', function (ErrorEvent $e) use(&$total) {
         if (--$total) {
             $e->retry();
         }
     });
     try {
         $c->get(Server::$url);
         $this->fail('Did not throw!');
     } catch (RequestException $e) {
         $this->assertEquals(502, $e->getResponse()->getStatusCode());
     }
 }
Пример #11
0
 /**
  * @dataProvider recordingProvider
  */
 public function testRecording($name, $requests, $responses)
 {
     $this->setName($name);
     $this->assertGreaterThanOrEqual(sizeof($requests), sizeof($responses));
     \GuzzleHttp\Tests\Server::enqueue($responses);
     $cassette = __DIR__ . '/fixtures/temp/' . str_replace([" with data set #", "test", " "], ["-", "", "-"], $this->getName()) . '.json';
     $responses = [];
     $vcr = \Dshafik\GuzzleHttp\VcrHandler::turnOn($cassette);
     $this->assertInstanceOf(\GuzzleHttp\HandlerStack::class, $vcr);
     $client = new \GuzzleHttp\Client(['handler' => $vcr]);
     foreach ($requests as $key => $request) {
         try {
             $response = $client->send($request);
         } catch (\GuzzleHttp\Exception\ClientException $e) {
             $response = $e->getResponse();
         }
         $this->assertEmpty($response->getHeader('X-VCR-Recording'));
         $responses[$key] = $response;
     }
     $vcr = \Dshafik\GuzzleHttp\VcrHandler::turnOn($cassette);
     $this->assertInstanceOf(\GuzzleHttp\HandlerStack::class, $vcr);
     $client = new \GuzzleHttp\Client(['handler' => $vcr]);
     foreach ($requests as $key => $request) {
         try {
             $recording = $client->send($request);
         } catch (\GuzzleHttp\Exception\ClientException $e) {
             $recording = $e->getResponse();
         }
         $this->assertTrue(ctype_digit($recording->getHeader('X-VCR-Recording')[0]));
         $this->assertEquals($responses[$key]->getStatusCode(), $recording->getStatusCode());
         foreach ($responses[$key]->getHeaders() as $header => $value) {
             $this->assertEquals($value, $recording->getHeader($header));
         }
         $this->assertEquals((string) $responses[$key]->getBody(), (string) $recording->getBody());
     }
 }
 public function testThrowsImmediatelyWhenInstructed()
 {
     Server::flush();
     Server::enqueue(["HTTP/1.1 501\r\nContent-Length: 0\r\n\r\n"]);
     $c = new Client(['base_url' => Server::$url]);
     $request = $c->createRequest('GET', '/');
     $request->getEmitter()->on('error', function (ErrorEvent $e) {
         $e->throwImmediately(true);
     });
     $transactions = [new Transaction($c, $request)];
     $a = new MultiAdapter(new MessageFactory());
     try {
         $a->sendAll(new \ArrayIterator($transactions), 1);
         $this->fail('Did not throw');
     } catch (RequestException $e) {
         $this->assertSame($request, $e->getRequest());
     }
 }
 public function testEmitsHeadersEventForHeadRequest()
 {
     Server::enqueue(["HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK"]);
     $ee = null;
     $client = new Client(['adapter' => new MultiAdapter(new MessageFactory())]);
     $client->head(Server::$url, ['events' => ['headers' => function (HeadersEvent $e) use(&$ee) {
         $ee = $e;
     }]]);
     $this->assertInstanceOf('GuzzleHttp\\Event\\HeadersEvent', $ee);
 }
 public function testDoesNotAddContentTypeByDefault()
 {
     Server::flush();
     Server::enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
     $client = new Client(['base_url' => Server::$url, 'adapter' => new StreamAdapter(new MessageFactory())]);
     $client->put('/', ['body' => 'foo']);
     $requests = Server::received(true);
     $this->assertEquals('', $requests[0]->getHeader('Content-Type'));
     $this->assertEquals(3, $requests[0]->getHeader('Content-Length'));
 }
Пример #15
0
 public function testCanSendPayloadWithGet()
 {
     Server::flush();
     Server::enqueue(["HTTP/1.1 200 OK\r\n\r\n"]);
     $request = new Request('GET', Server::$url, [], Stream::factory('foo'));
     $this->emit($request);
     $t = new Transaction(new Client(), $request);
     $f = new CurlFactory();
     $h = $f($t, new MessageFactory());
     curl_exec($h);
     curl_close($h);
     $sent = Server::received(true)[0];
     $this->assertEquals('foo', (string) $sent->getBody());
     $this->assertEquals(3, (string) $sent->getHeader('Content-Length'));
 }
Пример #16
0
 public function testThrowsAndReleasesWhenErrorDuringCompleteEvent()
 {
     Server::flush();
     Server::enqueue("HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n");
     $request = new Request('GET', Server::$url);
     $request->getEmitter()->on('complete', function (CompleteEvent $e) {
         throw new RequestException('foo', $e->getRequest());
     });
     $t = new Transaction(new Client(), $request);
     $a = new MultiAdapter(new MessageFactory());
     try {
         $a->send($t);
         $this->fail('Did not throw');
     } catch (RequestException $e) {
         $this->assertSame($request, $e->getRequest());
     }
 }
 public function testInvokesOnStatsOnSuccess()
 {
     Server::flush();
     Server::enqueue([new Psr7\Response(200)]);
     $req = new Psr7\Request('GET', Server::$url);
     $gotStats = null;
     $handler = new Handler\CurlHandler();
     $promise = $handler($req, ['on_stats' => function (TransferStats $stats) use(&$gotStats) {
         $gotStats = $stats;
     }]);
     $response = $promise->wait();
     $this->assertEquals(200, $response->getStatusCode());
     $this->assertEquals(200, $gotStats->getResponse()->getStatusCode());
     $this->assertEquals(Server::$url, (string) $gotStats->getEffectiveUri());
     $this->assertEquals(Server::$url, (string) $gotStats->getRequest()->getUri());
     $this->assertGreaterThan(0, $gotStats->getTransferTime());
 }
 private function runConnectionTest($queue, $stream, $msg, $statusCode = null)
 {
     $obj = new \stdClass();
     $er = null;
     $client = new Client();
     $request = $client->createRequest('PUT', Server::$url, ['body' => $stream]);
     $request->getEmitter()->on('error', function (ErrorEvent $e) use(&$er) {
         $er = $e;
     });
     $transaction = $this->getMockBuilder('GuzzleHttp\\Adapter\\Transaction')->setMethods(['getResponse', 'setResponse'])->setConstructorArgs([$client, $request])->getMock();
     $transaction->expects($this->any())->method('setResponse')->will($this->returnCallback(function ($r) use(&$obj) {
         $obj->res = $r;
     }));
     $transaction->expects($this->any())->method('getResponse')->will($this->returnCallback(function () use($obj, &$called) {
         $caller = debug_backtrace()[6]['function'];
         if ($caller == 'addHandle') {
             return null;
         } elseif ($caller == 'validateResponseWasSet') {
             return ++$called == 2 ? $obj->res : null;
         } else {
             return $obj->res;
         }
     }));
     $a = new MultiAdapter(new MessageFactory());
     Server::flush();
     Server::enqueue($queue);
     $a->sendAll(new \ArrayIterator([$transaction]), 10);
     if ($msg) {
         $this->assertNotNull($er);
         $this->assertContains($msg, $er->getException()->getMessage());
     } else {
         $this->assertEquals($statusCode, $transaction->getResponse()->getStatusCode());
     }
 }
Пример #19
0
 public function testContentLengthIntegrationTest()
 {
     Server::flush();
     Server::enqueue([new Response(200)]);
     $client = new Client(['base_url' => Server::$url]);
     $this->assertEquals(200, $client->put('/', ['body' => 'test'])->getStatusCode());
     $request = Server::received(true)[0];
     $this->assertEquals('PUT', $request->getMethod());
     $this->assertEquals('4', $request->getHeader('Content-Length'));
     $this->assertEquals('test', (string) $request->getBody());
 }
Пример #20
0
 public function testClientUsesSslByDefault()
 {
     Server::flush();
     Server::enqueue(["HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nfoo"]);
     $f = new CurlFactory();
     $client = new Client(['base_url' => Server::$url, 'adapter' => new MultiAdapter(new MessageFactory(), ['handle_factory' => $f])]);
     $client->get();
     $this->assertEquals(2, $_SERVER['last_curl'][CURLOPT_SSL_VERIFYHOST]);
     $this->assertEquals(true, $_SERVER['last_curl'][CURLOPT_SSL_VERIFYPEER]);
     $this->assertFileExists($_SERVER['last_curl'][CURLOPT_CAINFO]);
 }
 public function testDebugAttributeWritesStreamInfoToBuffer()
 {
     if (defined('HHVM_VERSION')) {
         $this->markTestSkipped('HHVM has not implemented this?');
         return;
     }
     $buffer = fopen('php://temp', 'r+');
     Server::flush();
     Server::enqueue("HTTP/1.1 200 OK\r\nContent-Length: 8\r\nContent-Type: text/plain\r\n\r\nhi there");
     $client = new Client(['base_url' => Server::$url, 'adapter' => new StreamAdapter(new MessageFactory())]);
     $client->get('/', ['debug' => $buffer]);
     fseek($buffer, 0);
     $contents = stream_get_contents($buffer);
     $this->assertContains('<http://127.0.0.1:8125/> [CONNECT]', $contents);
     $this->assertContains('<http://127.0.0.1:8125/> [FILE_SIZE_IS] message: "Content-Length: 8"', $contents);
     $this->assertContains('<http://127.0.0.1:8125/> [PROGRESS] bytes_max: "8"', $contents);
     $this->assertContains('<http://127.0.0.1:8125/> [MIME_TYPE_IS] message: "text/plain"', $contents);
 }
Пример #22
0
 public function testDoesNotSaveToWhenFailed()
 {
     Server::flush();
     Server::enqueue(["HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n"]);
     $tmp = tempnam('/tmp', 'test_save_to');
     unlink($tmp);
     $a = new CurlAdapter(new MessageFactory());
     $client = new Client(['base_url' => Server::$url, 'adapter' => $a]);
     try {
         $client->get('/', ['save_to' => $tmp]);
     } catch (ServerException $e) {
         $this->assertFileNotExists($tmp);
     }
 }
 public function testStreamIgnoresZeroTimeout()
 {
     Server::flush();
     Server::enqueue([new Psr7\Response(200)]);
     $req = new Psr7\Request('GET', Server::$url);
     $gotStats = null;
     $handler = new StreamHandler();
     $promise = $handler($req, ['connect_timeout' => 10, 'timeout' => 0]);
     $response = $promise->wait();
     $this->assertEquals(200, $response->getStatusCode());
 }
Пример #24
0
 public function testRewindsStreamOnComplete()
 {
     Server::flush();
     Server::enqueue("HTTP/1.1 200 OK\r\nFoo: bar\r\nContent-Length: 4\r\n\r\ntest");
     $t = new Transaction(new Client(), new Request('GET', Server::$url));
     $a = new MultiAdapter(new MessageFactory());
     $response = $a->send($t);
     $this->assertEquals('test', $response->getBody()->read(4));
 }
Пример #25
0
 public function testDoesNotAlwaysAddContentType()
 {
     Server::flush();
     Server::enqueue(["HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"]);
     $client = new Client();
     $client->put(Server::$url . '/foo', ['body' => 'foo']);
     $request = Server::received(true)[0];
     $this->assertEquals('', $request->getHeader('Content-Type'));
 }
 /**
  * Helper to test that a 400 response deletes cache entries.
  *
  * @param int $errorCode The error code to test, such as 404 or 410.
  *
  * @throws \Exception
  */
 private function fourXXCacheDelete($errorCode)
 {
     $now = $this->date();
     Server::enqueue([new Response(200, ['Date' => $now, 'Cache-Control' => 'public, max-age=1000, must-revalidate', 'Last-Modified' => $now]), new Response(304, ['Date' => $now, 'Cache-Control' => 'public, max-age=1000, must-revalidate', 'Last-Modified' => $now, 'Age' => 0]), new Response($errorCode, ['Date' => $now, 'Cache-Control' => 'public, max-age=1000, must-revalidate', 'Last-Modified' => $now]), new Response(200, ['Date' => $now, 'Cache-Control' => 'public, max-age=1000, must-revalidate', 'Last-Modified' => $now])]);
     $client = $this->setupClient();
     $response1 = $client->get('/foo');
     $this->assertEquals('MISS from GuzzleCache', $response1->getHeader('X-Cache-Lookup'));
     $response2 = $client->get('/foo');
     $this->assertEquals('HIT from GuzzleCache', $response2->getHeader('X-Cache-Lookup'));
     try {
         $client->get('/foo');
         $this->fail($errorCode . ' was not thrown.');
     } catch (RequestException $e) {
         $response3 = $e->getResponse();
         $this->assertEquals($errorCode, $response3->getStatusCode());
         $this->assertEquals('MISS from GuzzleCache', $response3->getHeader('X-Cache-Lookup'));
     }
     $response4 = $client->get('/foo');
     $this->assertEquals('MISS from GuzzleCache', $response4->getHeader('X-Cache-Lookup'));
 }