Ejemplo n.º 1
0
 public static function addDebugOptionsToHttpClient(Client $guzzleClient)
 {
     $guzzleClient->setDefaultOption('debug', true);
     $echoCb = function (Event $event) {
         echo (string) $event['request'] . PHP_EOL;
         echo (string) $event['response'] . PHP_EOL;
     };
     $guzzleClient->getEventDispatcher()->addListener('request.complete', $echoCb);
     $guzzleClient->getEventDispatcher()->addListener('request.exception', $echoCb);
 }
Ejemplo n.º 2
0
 protected function getGuzzle()
 {
     $this->historyPlugin = new HistoryPlugin();
     $this->mockPlugin = new MockPlugin();
     $this->mockPlugin->addResponse(new GuzzleResponse(200, null, '<html><body><p>Hi</p></body></html>'));
     $guzzle = new GuzzleClient('', array('redirect.disable' => true));
     $guzzle->getEventDispatcher()->addSubscriber($this->mockPlugin);
     $guzzle->getEventDispatcher()->addSubscriber($this->historyPlugin);
     return $guzzle;
 }
Ejemplo n.º 3
0
 /**
  * @test
  * @dataProvider getAuthenticationFullData
  */
 public function shouldAuthenticateUsingAllGivenParameters($site, $login, $password)
 {
     $client = new GuzzleClient();
     $listeners = $client->getEventDispatcher()->getListeners('request.before_send');
     $this->assertCount(1, $listeners);
     $httpClient = new HttpClient(array(), $client);
     $httpClient->authenticate($site, $login, $password);
     $listeners = $client->getEventDispatcher()->getListeners('request.before_send');
     $this->assertCount(2, $listeners);
     $authListener = $listeners[1][0];
     $this->assertInstanceOf('Eloqua\\HttpClient\\Listener\\AuthListener', $authListener);
 }
Ejemplo n.º 4
0
 public function setUp()
 {
     $this->guzzleClient = new Client('http://[::1]:8999');
     global $argv;
     if (in_array('--debug', $argv, true)) {
         $echoCb = function (Event $event) {
             echo (string) $event['request'] . PHP_EOL;
             echo (string) $event['response'] . PHP_EOL;
         };
         $this->guzzleClient->getEventDispatcher()->addListener('request.complete', $echoCb);
         $this->guzzleClient->getEventDispatcher()->addListener('request.exception', $echoCb);
     }
 }
Ejemplo n.º 5
0
 protected function getClient($response, $code = 200, $throwCurlException = false)
 {
     $plugin = new MockPlugin();
     $plugin->addResponse(new Response($code, null, $response));
     $clientHttp = new GuzzleClient('http://my.domain.tld/api/v1');
     $clientHttp->getEventDispatcher()->addSubscriber($plugin);
     if ($throwCurlException) {
         $clientHttp->getEventDispatcher()->addListener('request.before_send', function (\Guzzle\Common\Event $event) {
             throw new \Guzzle\Http\Exception\CurlException();
         });
     }
     $logger = new Logger('tests');
     $logger->pushHandler(new NullHandler());
     return new Client('123456', '654321', new GuzzleAdapter($clientHttp), $logger);
 }
Ejemplo n.º 6
0
 private function createClient()
 {
     $client = new Client($this->getBaseUrl());
     $client->getEventDispatcher()->addListener('request.error', static function (Event $event) {
         $event->stopPropagation();
     });
     return $client;
 }
Ejemplo n.º 7
0
 /**
  * @param Url $url
  * @return \Guzzle\Http\Message\Response
  */
 protected function executeRequest(Url $url)
 {
     $guzzle = new GuzzleClient();
     $guzzle->getEventDispatcher()->addListener('request.error', function (Event $event) {
         if ($event['response']->getStatusCode() != 200) {
             $event->stopPropagation();
         }
     });
     return $guzzle->createRequest('GET', $url)->send();
 }
Ejemplo n.º 8
0
 /**
  * Sets the authorization header provided by the token 
  * 
  * @param Array token Array with token info
  * @return Void
  */
 protected function setAuthHeader(array $token)
 {
     $this->configs = array_merge($this->configs, $token);
     if (!empty($this->configs['access_token'])) {
         $authorization = sprintf('Bearer %s', $this->configs['access_token']);
         $this->client->getEventDispatcher()->addListener('request.before_send', function (Event $event) use($authorization) {
             $event['request']->addHeader('Authorization', $authorization);
         });
     }
 }
Ejemplo n.º 9
0
 /**
  * Sanity check to make sure that OoyalaCache is a subscriber.
  *
  * The only reason this is needed is because the plugin might be disabled
  * because of configuration, so it's good to check when some configuration
  * is present that the plugin actually does not remove itself as a subscriber.
  */
 public function test_cache_configuration_config_present()
 {
     $client = new Client('http://test.com', array('ooyala.cache' => true));
     $plugin = new OoyalaCache();
     $className = get_class($plugin);
     $client->addSubscriber($plugin);
     $client->getEventDispatcher()->dispatch(OoyalaClient::EVENT_INITIALIZED, new Event(array('client' => $client)));
     $subscribedEvents = array_keys(OoyalaCache::getSubscribedEvents());
     foreach ($client->getEventDispatcher()->getListeners() as $eventName => $listeners) {
         if (!in_array($eventName, $subscribedEvents)) {
             continue;
         }
         $actual = array();
         foreach ($listeners as $listener) {
             $actual[] = get_class($listener[0]);
         }
         $this->assertTrue(in_array($className, $actual));
     }
 }
Ejemplo n.º 10
0
 public function testAddMixpanelAuthentication()
 {
     $plugin = new MixGuzzleAuthPlugin('key', 'secret');
     $client = new Client('http://test.com/');
     $client->getEventDispatcher()->addSubscriber($plugin);
     $request = $client->get('/');
     $event = new Event(array('request' => $request, 'timestamp' => 123456789));
     $params = $plugin->onRequestBeforeSend($event);
     $this->assertArrayHasKey('sig', $params);
 }
Ejemplo n.º 11
0
 /**
  * Creates the GuzzleTeleporter
  *
  * @return GuzzleTeleporter
  */
 public static function create()
 {
     $client = new Client();
     $client->getEventDispatcher()->addListener('request.error', function (Event $event) {
         // override guzzle default behavior of throwing exceptions
         // when 4xx & 5xx responses are encountered
         $event->stopPropagation();
     }, -254);
     $client->addSubscriber(BackoffPlugin::getExponentialBackoff(5, array(500, 502, 503, 408)));
     return new static($client);
 }
 public function testAddPsrLoggerToClient()
 {
     $client = new Client();
     $listenersBefore = $client->getEventDispatcher()->getListeners('request.sent');
     $logger = $this->getMockForAbstractClass('Psr\\Log\\LoggerInterface');
     $plugin = GuzzleClientHelper::addPsrLoggerToClient($client, $logger);
     $this->assertTrue($client->getEventDispatcher()->hasListeners('request.sent'));
     $expectedListenersCount = count($listenersBefore) + 1;
     $this->assertCount($expectedListenersCount, $client->getEventDispatcher()->getListeners('request.sent'));
     $this->assertContains([$plugin, 'onRequestSent'], $client->getEventDispatcher()->getListeners('request.sent'));
 }
 public function testAddsDigestAuthentication()
 {
     $plugin = new CurlAuthPlugin('julian', 'test', CURLAUTH_DIGEST);
     $client = new Client('http://www.test.com/');
     $client->getEventDispatcher()->addSubscriber($plugin);
     $request = $client->get('/');
     $this->assertEquals('julian', $request->getUsername());
     $this->assertEquals('test', $request->getPassword());
     $this->assertEquals('julian:test', $request->getCurlOptions()->get(CURLOPT_USERPWD));
     $this->assertEquals(CURLAUTH_DIGEST, $request->getCurlOptions()->get(CURLOPT_HTTPAUTH));
 }
 public function testAddsWsseAuthenticationWithCustomDigest()
 {
     $plugin = new WsseAuthPlugin('michael', 'test', function ($nonce, $created, $password) {
         return 'this_digest_wont_work';
     });
     $client = new Client('http://www.test.com/');
     $client->getEventDispatcher()->addSubscriber($plugin);
     $request = $client->get('/');
     $headers = $request->getHeaders();
     $this->assertTrue(false !== $headers->hasKey('Authorization'));
     $this->assertTrue(false !== $headers->hasKey('X-WSSE'));
     $this->assertTrue(false !== strpos(array_shift($headers->get('X-WSSE')), 'this_digest_wont_work'));
 }
Ejemplo n.º 15
0
 public function testNotLimited()
 {
     // Create a script to return a 429 response like Desk.com
     $this->getServer()->flush();
     $this->getServer()->enqueue(array("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata"));
     $plugin = new BackoffPlugin($this->strategy());
     $client = new Client($this->getServer()->getUrl());
     $client->getEventDispatcher()->addSubscriber($plugin);
     $request = $client->get();
     $request->send();
     // Make sure it eventually completed successfully
     $this->assertEquals(200, $request->getResponse()->getStatusCode());
     $this->assertEquals('data', $request->getResponse()->getBody(true));
     // Check that two requests were made to retry this request
     $this->assertEquals(1, count($this->getServer()->getReceivedRequests(false)));
     $this->assertEquals(0, $request->getParams()->get(BackoffPlugin::RETRY_PARAM));
 }
 public function testCookiesAreNotAddedWhenParamIsSet()
 {
     $jar = new ArrayCookieJar();
     $plugin = new CookiePlugin($jar);
     $jar->add(new Cookie(array('domain' => 'example.com', 'path' => '/', 'name' => 'test', 'value' => 'hi', 'expires' => time() + 3600)));
     $client = new Client('http://example.com');
     $client->getEventDispatcher()->addSubscriber($plugin);
     // Ensure that it is normally added
     $request = $client->get();
     $request->setResponse(new Response(200), true);
     $request->send();
     $this->assertEquals('hi', $request->getCookie('test'));
     // Now ensure that it is not added
     $request = $client->get();
     $request->getParams()->set('cookies.disable', true);
     $request->setResponse(new Response(200), true);
     $request->send();
     $this->assertNull($request->getCookie('test'));
 }
Ejemplo n.º 17
0
 public function testWiresBodiesWhenNeeded()
 {
     $client = new Client($this->getServer()->getUrl());
     $plugin = new LogPlugin($this->adapter, '{req_body} | {res_body}', true);
     $client->getEventDispatcher()->addSubscriber($plugin);
     $request = $client->put();
     // Send the response from the dummy server as the request body
     $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nsend");
     $stream = fopen($this->getServer()->getUrl(), 'r');
     $request->setBody(EntityBody::factory($stream, 4));
     $tmpFile = tempnam(sys_get_temp_dir(), 'non_repeatable');
     $request->setResponseBody(EntityBody::factory(fopen($tmpFile, 'w')));
     $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nresponse");
     ob_start();
     $request->send();
     $message = ob_get_clean();
     unlink($tmpFile);
     $this->assertContains("send", $message);
     $this->assertContains("response", $message);
 }
 /**
  * @covers Guzzle\Http\Plugin\CookiePlugin::onRequestBeforeSend
  */
 public function testCookiesAreNotAddedWhenParamIsSet()
 {
     $this->storage->clear();
     $this->storage->save(array('domain' => 'example.com', 'path' => '/', 'cookie' => array('test', 'hi'), 'expires' => Guzzle::getHttpDate('+1 day')));
     $client = new Client('http://example.com');
     $client->getEventDispatcher()->addSubscriber($this->plugin);
     $request = $client->get();
     $request->setResponse(new Response(200), true);
     $request->send();
     $this->assertEquals('hi', $request->getCookie()->get('test'));
     $request = $client->get();
     $request->getParams()->set('cookies.disable', true);
     $request->setResponse(new Response(200), true);
     $request->send();
     $this->assertNull($request->getCookie()->get('test'));
 }
Ejemplo n.º 19
0
 /**
  * @test
  */
 public function constructShouldAppendANewErrorListener()
 {
     $client = new Client($this->httpClient);
     $this->assertAttributeSame($this->httpClient, 'client', $client);
     $this->assertTrue($this->httpClient->getEventDispatcher()->hasListeners('request.error'));
 }
Ejemplo n.º 20
0
 public function testCanDisableExceptionsWithErrorListener()
 {
     $client = new Client();
     $client->getEventDispatcher()->addListener('request.error', function () {
     });
     $request = $client->get('/', array(), array('plugins' => array(new MockPlugin(array(new Response(500)))), 'exceptions' => false));
     $this->assertEquals(500, $request->send()->getStatusCode());
 }
Ejemplo n.º 21
0
 public function testCanCastToString()
 {
     $client = new Client('http://127.0.0.1/');
     $h = new HistoryPlugin();
     $client->getEventDispatcher()->addSubscriber($h);
     $mock = new MockPlugin(array(new Response(301, array('Location' => '/redirect1', 'Content-Length' => 0)), new Response(307, array('Location' => '/redirect2', 'Content-Length' => 0)), new Response(200, array('Content-Length' => '2'), 'HI')));
     $client->getEventDispatcher()->addSubscriber($mock);
     $request = $client->get();
     $request->send();
     $this->assertEquals(3, count($h));
     $this->assertEquals(3, count($mock->getReceivedRequests()));
     $h = str_replace("\r", '', $h);
     $this->assertContains("> GET / HTTP/1.1\nHost: 127.0.0.1\nUser-Agent:", $h);
     $this->assertContains("< HTTP/1.1 301 Moved Permanently\nLocation: /redirect1", $h);
     $this->assertContains("< HTTP/1.1 307 Temporary Redirect\nLocation: /redirect2", $h);
     $this->assertContains("< HTTP/1.1 200 OK\nContent-Length: 2\n\nHI", $h);
 }
 /**
  * @covers Guzzle\Http\Curl\CurlMulti::reset
  */
 public function testHardResetReopensMultiHandle()
 {
     $this->getServer()->enqueue(array("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"));
     $client = new Client($this->getServer()->getUrl());
     $message = '';
     $plugin = new LogPlugin(new ClosureLogAdapter(function ($msg) use(&$message) {
         $message .= $msg . "\n";
     }), LogPlugin::LOG_VERBOSE);
     $client->getEventDispatcher()->addSubscriber($plugin);
     $request = $client->get();
     $multi = new CurlMulti();
     $multi->add($request);
     $multi->send();
     $multi->reset(true);
     $multi->add($request);
     $multi->send();
     $this->assertNotContains('Re-using existing connection', $message);
 }
Ejemplo n.º 23
0
 /**
  * @covers Guzzle\Http\Plugin\MockPlugin::readBodies
  * @covers Guzzle\Http\Plugin\MockPlugin::dequeue
  */
 public function testReadsBodiesFromMockedRequests()
 {
     $p = new MockPlugin(array(new Response(200)));
     $p->readBodies(true);
     $client = new Client('http://localhost:123/');
     $client->getEventDispatcher()->addSubscriber($p, 9999);
     $body = EntityBody::factory('foo');
     $request = $client->put();
     $request->setBody($body);
     $request->send();
     $this->assertEquals(3, $body->ftell());
 }
 public function testLogsWhenExceptionsAreThrown()
 {
     $client = new Client($this->getServer()->getUrl());
     $plugin = new LogPlugin($this->logAdapter, LogPlugin::LOG_VERBOSE);
     $client->getEventDispatcher()->addSubscriber($plugin);
     $request = $client->get();
     $this->getServer()->enqueue("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");
     ob_start();
     try {
         $request->send();
         $this->fail('Exception for 404 was not thrown');
     } catch (\Exception $e) {
     }
     $message = ob_get_clean();
     $this->assertContains('127.0.0.1 - "GET / HTTP/1.1" - 404 0 - ', $message);
     $this->assertContains("GET / HTTP/1.1\r\n", $message);
     $this->assertContains("User-Agent: " . Guzzle::getDefaultUserAgent(), $message);
     $this->assertContains("\n< HTTP/1.1 404 Not Found\r\n< Content-Length: 0", $message);
 }
 /**
  * @covers Guzzle\Http\Plugin\HistoryPlugin::onRequestComplete
  * @depends testAddsRequests
  */
 public function testUpdatesAddRequests()
 {
     $h = new HistoryPlugin();
     $client = new Client('http://localhost/');
     $client->getEventDispatcher()->addSubscriber($h);
     $request = $client->get();
     $request->setResponse(new Response(200), true);
     $request->send();
     $this->assertSame($request, $h->getLastRequest());
 }
Ejemplo n.º 26
0
 /**
  * @expectedException \Guzzle\Common\Exception\ExceptionCollection
  */
 public function testClientThrowsExceptionForMultipleRequests()
 {
     $client = new Client($this->getServer()->getUrl());
     $mock = new MockPlugin();
     $mock->addResponse(new Response(200));
     $mock->addResponse(new Response(404));
     $client->getEventDispatcher()->addSubscriber($mock);
     $client->send(array($client->get(), $client->head()));
 }
Ejemplo n.º 27
0
 /**
  * @covers Guzzle\Http\Plugin\MockPlugin::getReceivedRequests
  * @covers Guzzle\Http\Plugin\MockPlugin::flush
  */
 public function testStoresMockedRequests()
 {
     $p = new MockPlugin(array(new Response(200), new Response(200)));
     $client = new Client('http://localhost:123/');
     $client->getEventDispatcher()->addSubscriber($p, 9999);
     $request1 = $client->get();
     $request1->send();
     $this->assertEquals(array($request1), $p->getReceivedRequests());
     $request2 = $client->get();
     $request2->send();
     $this->assertEquals(array($request1, $request2), $p->getReceivedRequests());
     $p->flush();
     $this->assertEquals(array(), $p->getReceivedRequests());
 }
Ejemplo n.º 28
0
 /**
  * Add a request header for the next request
  *
  * @param string $key The name of the header
  * @param mixed $value The value of the header
  */
 protected function addHeaderToNextRequest($key, $value)
 {
     $this->client->getEventDispatcher()->addListener('request.before_send', function ($event) use($key, $value) {
         $event['request']->setHeader($key, $value);
     });
 }
Ejemplo n.º 29
0
 /**
  * @group issue-437
  */
 public function testDoesNotTouchClosureListeners()
 {
     $this->getServer()->flush();
     $this->getServer()->enqueue(array("HTTP/1.1 200 OK\r\n" . "Date: Mon, 12 Nov 2012 03:06:37 GMT\r\n" . "Cache-Control: private, s-maxage=0, max-age=0, must-revalidate\r\n" . "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" . "Content-Length: 2\r\n\r\nhi", "HTTP/1.0 304 Not Modified\r\n" . "Date: Mon, 12 Nov 2012 03:06:38 GMT\r\n" . "Content-Type: text/html; charset=UTF-8\r\n" . "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" . "Age: 6302\r\n\r\n", "HTTP/1.0 304 Not Modified\r\n" . "Date: Mon, 12 Nov 2012 03:06:38 GMT\r\n" . "Content-Type: text/html; charset=UTF-8\r\n" . "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" . "Age: 6302\r\n\r\n"));
     $client = new Client($this->getServer()->getUrl());
     $client->addSubscriber(new CachePlugin());
     $client->getEventDispatcher()->addListener('command.after_send', function () {
     });
     $this->assertEquals(200, $client->get()->send()->getStatusCode());
     $this->assertEquals(200, $client->get()->send()->getStatusCode());
     $this->assertEquals(200, $client->get()->send()->getStatusCode());
 }
Ejemplo n.º 30
0
 /**
  * @covers Guzzle\Plugin\Backoff\BackoffPlugin
  * @covers Guzzle\Http\Curl\CurlMulti
  */
 public function testRetriesPooledRequestsUsingDelayAndPollingEvent()
 {
     $this->getServer()->flush();
     $this->getServer()->enqueue(array("HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n", "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata"));
     // Need to sleep for some time ensure that the polling works correctly in the observer
     $plugin = new BackoffPlugin(new HttpBackoffStrategy(null, new TruncatedBackoffStrategy(1, new ConstantBackoffStrategy(0.5))));
     $client = new Client($this->getServer()->getUrl());
     $client->getEventDispatcher()->addSubscriber($plugin);
     $request = $client->get();
     $request->send();
     // Make sure it eventually completed successfully
     $this->assertEquals('data', $request->getResponse()->getBody(true));
     // Check that two requests were made to retry this request
     $this->assertEquals(2, count($this->getServer()->getReceivedRequests(false)));
 }