/** * @covers Guzzle\Service\Command\DynamicCommand */ public function testUsesDifferentLocations() { $client = new Client('http://www.tazmania.com/'); $command = $this->factory->factory('body', array('b' => 'my-data', 'q' => 'abc', 'h' => 'haha')); $request = $command->setClient($client)->prepare(); $this->assertEquals("PUT /?test=abc&i=test HTTP/1.1\r\n" . "Host: www.tazmania.com\r\n" . "User-Agent: " . Utils::getDefaultUserAgent() . "\r\n" . "Expect: 100-Continue\r\n" . "Content-Length: 29\r\n" . "X-Custom: haha\r\n" . "\r\n" . "begin_body::my-data::end_body", (string) $request); unset($command); unset($request); $command = $this->factory->factory('body', array('b' => 'my-data', 'q' => 'abc', 'h' => 'haha', 'i' => 'does not change the value because it\'s static')); $request = $command->setClient($client)->prepare(); $this->assertEquals("PUT /?test=abc&i=test HTTP/1.1\r\n" . "Host: www.tazmania.com\r\n" . "User-Agent: " . Utils::getDefaultUserAgent() . "\r\n" . "Expect: 100-Continue\r\n" . "Content-Length: 29\r\n" . "X-Custom: haha\r\n" . "\r\n" . "begin_body::my-data::end_body", (string) $request); }
/** * @covers Guzzle\Http\Utils::getDefaultUserAgent */ public function testGetDefaultUserAgent() { // Clear out the user agent cache $refObject = new \ReflectionClass('Guzzle\\Http\\Utils'); $refProperty = $refObject->getProperty('userAgent'); $refProperty->setAccessible(true); $refProperty->setValue(null, null); $version = curl_version(); $agent = sprintf('Guzzle/%s curl/%s PHP/%s openssl/%s', Version::VERSION, PHP_VERSION, $version['version'], $version['ssl_version']); $this->assertEquals($agent, Utils::getDefaultUserAgent()); // Get it from cache this time $this->assertEquals($agent, Utils::getDefaultUserAgent()); }
/** * {@inheritdoc} */ public function cache($key, Response $response, $ttl = null) { if ($ttl === null) { $ttl = $this->defaultTtl; } if ($ttl) { $response->setHeader('X-Guzzle-Cache', "key={$key}, ttl={$ttl}"); // Remove excluded headers from the response (see RFC 2616:13.5.1) foreach ($this->excludeResponseHeaders as $header) { $response->removeHeader($header); } // Add a Date header to the response if none is set (for validation) if (!$response->getDate()) { $response->setHeader('Date', Utils::getHttpDate('now')); } $this->cache->save($key, array($response->getStatusCode(), $response->getHeaders()->getAll(), $response->getBody(true)), $ttl); } }
/** * @covers Guzzle\Http\Client::setUserAgent * @covers Guzzle\Http\Client::createRequest * @covers Guzzle\Http\Client::prepareRequest */ public function testSetsUserAgent() { $client = new Client('http://www.test.com/', array('api' => 'v1')); // Set the user agent string and include the default user agent appended $this->assertSame($client, $client->setUserAgent('Test/1.0Ab', true)); $this->assertEquals('Test/1.0Ab ' . Utils::getDefaultUserAgent(), $client->get()->getHeader('User-Agent')); // Set the user agent string without the default appended $client->setUserAgent('Test/1.0Ab'); $this->assertEquals('Test/1.0Ab', $client->get()->getHeader('User-Agent')); // Set default headers and make sure the user agent string is still set $client->setDefaultHeaders(array()); $this->assertEquals('Test/1.0Ab', $client->get()->getHeader('User-Agent')); }
/** * Create a new request * * @param string $method HTTP method * @param string|Url $url HTTP URL to connect to. The URI scheme, host header, and URI are parsed from the * full URL. If query string parameters are present they will be parsed as well. * @param array|Collection $headers HTTP headers */ public function __construct($method, $url, $headers = array()) { $this->method = strtoupper($method); $this->curlOptions = new Collection(); $this->params = new Collection(); $this->setUrl($url); if ($headers) { // Special handling for multi-value headers foreach ($headers as $key => $value) { $lkey = strtolower($key); // Deal with collisions with Host and Authorization if ($lkey == 'host') { $this->setHeader($key, $value); } elseif ($lkey == 'authorization') { $parts = explode(' ', $value); if ($parts[0] == 'Basic' && isset($parts[1])) { list($user, $pass) = explode(':', base64_decode($parts[1])); $this->setAuth($user, $pass); } else { $this->setHeader($key, $value); } } else { foreach ((array) $value as $v) { $this->addHeader($key, $v); } } } } if (!$this->hasHeader('User-Agent', true)) { $this->setHeader('User-Agent', Utils::getDefaultUserAgent()); } $this->setState(self::STATE_NEW); }
/** * @covers Guzzle\Http\Client::setUserAgent * @covers Guzzle\Http\Client::createRequest * @covers Guzzle\Http\Client::prepareRequest */ public function testSetsUserAgent() { $client = new Client('http://www.test.com/', array('api' => 'v1')); $this->assertSame($client, $client->setUserAgent('Test/1.0Ab', true)); $this->assertEquals('Test/1.0Ab ' . Utils::getDefaultUserAgent(), $client->get()->getHeader('User-Agent')); $client->setUserAgent('Test/1.0Ab'); $this->assertEquals('Test/1.0Ab', $client->get()->getHeader('User-Agent')); }
/** * @covers Guzzle\Http\CookieJar\ArrayCookieJar */ public function testClearsExpiredCookies() { self::addCookies($this->jar); $this->assertEquals(0, $this->jar->deleteExpired()); // Add an expired cookie $this->jar->save(array('cookie' => array('data', 'abc'), 'expires' => Utils::getHttpDate('-1 day'), 'domain' => '.example.com')); // Filters out expired cookies $this->hasCookies($this->jar->getCookies(), array('foo', 'baz', 'test', 'muppet', 'googoo')); $this->assertEquals(1, $this->jar->deleteExpired()); $this->assertEquals(0, $this->jar->deleteExpired()); }
/** * @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' => Utils::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')); }
/** * Save data to the cache adapter * * @param string $key The cache key * @param Response $response The response to cache * @param int $lifetime Amount of seconds to cache * * @return int Returns the lifetime of the cached data */ protected function saveCache($key, Response $response, $lifetime = null) { $lifetime = $lifetime ?: $this->defaultLifetime; // If the data is cacheable, then save it to the cache adapter if ($lifetime) { // Remove excluded headers from the response (see RFC 2616:13.5.1) foreach ($this->excludeResponseHeaders as $header) { $response->removeHeader($header); } // Add a Date header to the response if none is set (for validation) if (!$response->getDate()) { $response->setHeader('Date', Utils::getHttpDate('now')); } $data = array('c' => $response->getStatusCode(), 'h' => $response->getHeaders(), 'b' => $response->getBody(true)); if ($this->serialize) { $data = serialize($data); } $this->getCacheAdapter()->save($key, $data, $lifetime); } return $lifetime; }
/** * Data provider for factory tests * * @return array */ public function dataProvider() { $testFile = __DIR__ . '/../../../../../phpunit.xml.dist'; $postBody = new QueryString(array('file' => '@' . $testFile)); $qs = new QueryString(array('x' => 'y', 'z' => 'a')); $userAgent = Utils::getDefaultUserAgent(); $auth = base64_encode('michael:123'); $testFileSize = filesize($testFile); return array(array('GET', 'http://www.google.com/', null, null, array(CURLOPT_RETURNTRANSFER => 0, CURLOPT_HEADER => 0, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_USERAGENT => $userAgent, CURLOPT_WRITEFUNCTION => 'callback', CURLOPT_HEADERFUNCTION => 'callback', CURLOPT_HTTPHEADER => array('Accept:', 'Host: www.google.com', 'User-Agent: ' . $userAgent))), array('TRACE', 'http://www.google.com/', null, null, array(CURLOPT_CUSTOMREQUEST => 'TRACE')), array('GET', 'http://127.0.0.1:8080', null, null, array(CURLOPT_RETURNTRANSFER => 0, CURLOPT_HEADER => 0, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_USERAGENT => $userAgent, CURLOPT_WRITEFUNCTION => 'callback', CURLOPT_HEADERFUNCTION => 'callback', CURLOPT_PORT => 8080, CURLOPT_HTTPHEADER => array('Accept:', 'Host: 127.0.0.1:8080', 'User-Agent: ' . $userAgent))), array('HEAD', 'http://www.google.com/', null, null, array(CURLOPT_RETURNTRANSFER => 0, CURLOPT_HEADER => 0, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_USERAGENT => $userAgent, CURLOPT_HEADERFUNCTION => 'callback', CURLOPT_HTTPHEADER => array('Accept:', 'Host: www.google.com', 'User-Agent: ' . $userAgent), CURLOPT_NOBODY => 1)), array('GET', 'https://*****:*****@localhost/index.html?q=2', null, null, array(CURLOPT_RETURNTRANSFER => 0, CURLOPT_HEADER => 0, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_USERAGENT => $userAgent, CURLOPT_WRITEFUNCTION => 'callback', CURLOPT_HEADERFUNCTION => 'callback', CURLOPT_HTTPHEADER => array('Accept:', 'Host: localhost', 'Authorization: Basic ' . $auth, 'User-Agent: ' . $userAgent), CURLOPT_PORT => 443)), array('GET', 'http://*****:*****@' . $testFile . ';type=application/octet-stream;filename=phpunit.xml.dist'), CURLOPT_HTTPHEADER => array('Accept:', 'Host: localhost:8124', 'User-Agent: ' . $userAgent, 'Content-Type: multipart/form-data', 'Expect: 100-Continue')), array('Host' => '*', 'User-Agent' => '*', 'Content-Length' => '*', 'Expect' => '100-Continue', 'Content-Type' => 'multipart/form-data; boundary=*', '!Transfer-Encoding' => null)), array('POST', 'http://localhost:8124/post.php', array('Content-Type' => 'application/json'), '{"hi":"there"}', array(CURLOPT_RETURNTRANSFER => 0, CURLOPT_HEADER => 0, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_USERAGENT => $userAgent, CURLOPT_WRITEFUNCTION => 'callback', CURLOPT_HEADERFUNCTION => 'callback', CURLOPT_POST => 1, CURLOPT_HTTPHEADER => array('Expect:', 'Accept:', 'Host: localhost:8124', 'User-Agent: ' . $userAgent, 'Content-Type: application/json', 'Content-Length: 14')), array('Host' => '*', 'User-Agent' => '*', 'Content-Type' => 'application/json', '!Expect' => null, 'Content-Length' => '14', '!Transfer-Encoding' => null)), array('POST', 'http://localhost:8124/post.php', array('Content-Type' => 'application/json', 'Transfer-Encoding' => 'chunked'), '{"hi":"there"}', array(CURLOPT_RETURNTRANSFER => 0, CURLOPT_HEADER => 0, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_USERAGENT => $userAgent, CURLOPT_WRITEFUNCTION => 'callback', CURLOPT_HEADERFUNCTION => 'callback', CURLOPT_POST => 1, CURLOPT_HTTPHEADER => array('Expect:', 'Accept:', 'Host: localhost:8124', 'User-Agent: ' . $userAgent, 'Content-Type: application/json', 'Transfer-Encoding: chunked')), array('Host' => '*', 'User-Agent' => '*', 'Content-Type' => 'application/json', '!Expect' => null, 'Transfer-Encoding' => 'chunked', '!Content-Length' => '')), array('POST', 'http://localhost:8124/post.php', null, '', array(CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => array('Expect:', 'Accept:', 'Host: localhost:8124', 'User-Agent: ' . $userAgent)), array('Host' => '*', 'User-Agent' => '*', 'Content-Length' => '0', '!Transfer-Encoding' => null)), array('POST', 'http://localhost:8124/post.php', null, array(), array(CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => array('Expect:', 'Accept:', 'Host: localhost:8124', 'User-Agent: ' . $userAgent)), array('Host' => '*', 'User-Agent' => '*', 'Content-Length' => '0', '!Transfer-Encoding' => null)), array('PATCH', 'http://localhost:8124/patch.php', null, 'body', array(CURLOPT_INFILESIZE => 4, CURLOPT_HTTPHEADER => array('Expect:', 'Accept:', 'Host: localhost:8124', 'User-Agent: ' . $userAgent))), array('DELETE', 'http://localhost:8124/delete.php', null, 'body', array(CURLOPT_CUSTOMREQUEST => 'DELETE', CURLOPT_INFILESIZE => 4, CURLOPT_HTTPHEADER => array('Expect:', 'Accept:', 'Host: localhost:8124', 'User-Agent: ' . $userAgent)), array('Host' => '*', 'User-Agent' => '*', 'Content-Length' => '4', '!Expect' => null, '!Transfer-Encoding' => null))); }
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->assertContainsIns("User-Agent: " . Utils::getDefaultUserAgent(), $message); $this->assertContains("\n< HTTP/1.1 404 Not Found\r\n< Content-Length: 0", $message); }
private function setup_basic_payload() { $payload = json_encode(array('Thing' => 'Something')); $server = $this->getServer(); $server->enqueue(array("HTTP/1.1 200 OK\r\n" . "Date: " . Utils::getHttpDate('now') . "\r\n" . "Last-Modified: " . Utils::getHttpDate('-1 hours') . "\r\n" . "Cache-Control: max-age=600 \r\n" . "Content-Length: " . strlen($payload) . "\r\n\r\n" . $payload)); }
/** * {@inheritdoc} */ public function setUserAgent($userAgent, $includeDefault = false) { if ($includeDefault) { $userAgent .= ' ' . Utils::getDefaultUserAgent(); } $this->userAgent = $userAgent; return $this; }
/** * {@inheritdoc} */ public function setUserAgent($userAgent, $includeDefault = false) { if ($includeDefault) { $userAgent .= ' ' . Utils::getDefaultUserAgent(); } $this->defaultHeaders->set('User-Agent', $userAgent); return $this; }
/** * This test launches a dummy Guzzle\Http\Server\Server object that listens * for incoming requests. The server allows us to test how cURL sends * requests and receives responses. We can validate the request structure * and whether or not the response was interpreted correctly. * * @covers Guzzle\Http\Message\Request */ public function testRequestCanBeSentUsingCurl() { $this->getServer()->flush(); $this->getServer()->enqueue(array("HTTP/1.1 200 OK\r\nContent-Length: 4\r\nExpires: Thu, 01 Dec 1994 16:00:00 GMT\r\nConnection: close\r\n\r\ndata", "HTTP/1.1 200 OK\r\nContent-Length: 4\r\nExpires: Thu, 01 Dec 1994 16:00:00 GMT\r\nConnection: close\r\n\r\ndata", "HTTP/1.1 404 Not Found\r\nContent-Encoding: application/xml\r\nContent-Length: 48\r\n\r\n<error><mesage>File not found</message></error>")); $request = RequestFactory::getInstance()->create('GET', $this->getServer()->getUrl()); $request->setClient($this->client); $response = $request->send(); $this->assertEquals('data', $response->getBody(true)); $this->assertEquals(200, (int) $response->getStatusCode()); $this->assertEquals('OK', $response->getReasonPhrase()); $this->assertEquals(4, $response->getContentLength()); $this->assertEquals('Thu, 01 Dec 1994 16:00:00 GMT', $response->getExpires()); // Test that the same handle can be sent twice without setting state to new $response2 = $request->send(); $this->assertNotSame($response, $response2); try { $request = RequestFactory::getInstance()->create('GET', $this->getServer()->getUrl() . 'index.html'); $request->setClient($this->client); $response = $request->send(); $this->fail('Request did not receive a 404 response'); } catch (BadResponseException $e) { } $requests = $this->getServer()->getReceivedRequests(true); $messages = $this->getServer()->getReceivedRequests(false); $port = $this->getServer()->getPort(); $userAgent = Utils::getDefaultUserAgent(); $this->assertEquals('127.0.0.1:' . $port, $requests[0]->getHeader('Host')); $this->assertEquals('127.0.0.1:' . $port, $requests[1]->getHeader('Host')); $this->assertEquals('127.0.0.1:' . $port, $requests[2]->getHeader('Host')); $this->assertEquals('/', $requests[0]->getPath()); $this->assertEquals('/', $requests[1]->getPath()); $this->assertEquals('/index.html', $requests[2]->getPath()); $parts = explode("\r\n", $messages[0]); $this->assertEquals('GET / HTTP/1.1', $parts[0]); $parts = explode("\r\n", $messages[1]); $this->assertEquals('GET / HTTP/1.1', $parts[0]); $parts = explode("\r\n", $messages[2]); $this->assertEquals('GET /index.html HTTP/1.1', $parts[0]); }
/** * @covers Guzzle\Http\Message\Response::getMaxAge */ public function testDeterminesResponseMaxAge() { $this->assertEquals(null, $this->getResponse(200)->getMaxAge()); // Uses the response's s-maxage $this->assertEquals(140, $this->getResponse(200, array('Cache-Control' => 's-maxage=140'))->getMaxAge()); // Uses the response's max-age $this->assertEquals(120, $this->getResponse(200, array('Cache-Control' => 'max-age=120'))->getMaxAge()); // Uses the response's max-age $this->assertEquals(120, $this->getResponse(200, array('Cache-Control' => 'max-age=120', 'Expires' => Utils::getHttpDate('+1 day')))->getMaxAge()); // Uses the Expires date $this->assertGreaterThanOrEqual(82400, $this->getResponse(200, array('Expires' => Utils::getHttpDate('+1 day')))->getMaxAge()); // Uses the Expires date $this->assertGreaterThanOrEqual(82400, $this->getResponse(200, array('Expires' => Utils::getHttpDate('+1 day')))->getMaxAge()); }
/** * Data provider to test cache revalidation * * @return array */ public function cacheRevalidationDataProvider() { return array(array(true, "Pragma: no-cache\r\n\r\n", "HTTP/1.1 200 OK\r\nDate: " . Utils::getHttpDate('-100 hours') . "\r\nContent-Length: 4\r\n\r\nData", "HTTP/1.1 304 NOT MODIFIED\r\nCache-Control: max-age=2000000\r\nContent-Length: 0\r\n\r\n"), array(false, "\r\n\r\n", "HTTP/1.1 200 OK\r\nCache-Control: must-revalidate, no-cache\r\nDate: " . Utils::getHttpDate('-10 hours') . "\r\nContent-Length: 4\r\n\r\nData", "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nDatas", "HTTP/1.1 200 OK\r\nContent-Length: 5\r\nDate: " . Utils::getHttpDate('now') . "\r\n\r\nDatas"), array(false, "\r\n\r\n", "HTTP/1.1 200 OK\r\nCache-Control: no-cache\r\nDate: " . Utils::getHttpDate('-3 hours') . "\r\nContent-Length: 4\r\n\r\nData", null, null, 'never'), array(true, "\r\n\r\n", "HTTP/1.1 200 OK\r\nCache-Control: no-cache\r\nDate: " . Utils::getHttpDate('-3 hours') . "\r\nContent-Length: 4\r\n\r\nData", null, null, 'skip'), array(false, "\r\n\r\n", "HTTP/1.1 200 OK\r\nCache-Control: no-cache\r\nDate: " . Utils::getHttpDate('-3 hours') . "\r\n\r\nData", "HTTP/1.1 500 INTERNAL SERVER ERROR\r\nContent-Length: 0\r\n\r\n"), array(false, "\r\n\r\n", "HTTP/1.1 200 OK\r\nCache-Control: no-cache\r\nETag: \"123\"\r\nDate: " . Utils::getHttpDate('-10 hours') . "\r\n\r\nData", "HTTP/1.1 304 NOT MODIFIED\r\nETag: \"123456\"\r\n\r\n")); }
/** * @covers Guzzle\Http\Message\EntityEnclosingRequest::__toString * @covers Guzzle\Http\Message\EntityEnclosingRequest::addPostFields */ public function testAddsPostFieldsAndSetsContentLength() { $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/', null, array('data' => '123')); $this->assertEquals("POST / HTTP/1.1\r\n" . "Host: www.guzzle-project.com\r\n" . "User-Agent: " . Utils::getDefaultUserAgent() . "\r\n" . "Content-Type: application/x-www-form-urlencoded\r\n\r\n" . "data=123", (string) $request); }
/** * Add values to the cookiejar */ protected function addCookies() { $this->jar->save(array('cookie' => array('foo', 'bar'), 'domain' => 'example.com', 'path' => '/', 'max_age' => '86400', 'port' => array(80, 8080), 'version' => '1', 'secure' => true))->save(array('cookie' => array('test', '123'), 'domain' => 'www.foobar.com', 'path' => '/path/', 'discard' => true))->save(array('domain' => '.y.example.com', 'path' => '/acme/', 'cookie' => array('muppet', 'cookie_monster'), 'comment' => 'Comment goes here...', 'expires' => Utils::getHttpDate('+1 day')))->save(array('domain' => '.example.com', 'path' => '/test/acme/', 'cookie' => array('googoo', 'gaga'), 'max_age' => 1500, 'version' => 2)); }