Example #1
2
 /**
  * @expectedException \Aws\Sqs\Exception\SqsException
  * @expectedExceptionMessage Body MD5 mismatch for
  */
 public function testValidatesSuccessfulMd5OfBody()
 {
     $mock = new MockPlugin(array(Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Type: application/xml\r\n\r\n" . "<ReceiveMessageResponse>\n                  <ReceiveMessageResult>\n                    <Message>\n                      <MD5OfBody>fooo</MD5OfBody>\n                      <Body>This is a test message</Body>\n                    </Message>\n                  </ReceiveMessageResult>\n                </ReceiveMessageResponse>")));
     $sqs = SqsClient::factory(array('key' => 'abc', 'secret' => '123', 'region' => 'us-east-1'));
     $sqs->addSubscriber($mock);
     $sqs->receiveMessage(array('QueueUrl' => 'http://foo.com'));
 }
 /**
  * Get a mock response from a file
  *
  * @param string $path File to retrieve a mock response from
  *
  * @return Response
  * @throws InvalidArgumentException if the file is not found
  */
 public static function getMockFile($path)
 {
     if (!file_exists($path)) {
         throw new InvalidArgumentException('Unable to open mock file: ' . $path);
     }
     return Response::fromMessage(file_get_contents($path));
 }
 public function testParsesServerErrorResponsesWithMixedCasing()
 {
     $request = new Request('GET', 'http://example.com');
     $response = Response::fromMessage("HTTP/1.1 500 Internal Server Error\r\n" . "x-amzn-requestid: 123\r\n\r\n" . '{ "__Type": "abc#bazFault", "Message": "dolor" }');
     $parser = new JsonQueryExceptionParser();
     $this->assertEquals(array('code' => 'baz', 'message' => 'dolor', 'type' => 'server', 'request_id' => '123', 'parsed' => array('__type' => 'abc#bazFault', 'message' => 'dolor')), $parser->parse($request, $response));
 }
Example #4
0
 public function testAddsResponseObjectsToQueue()
 {
     $p = new MockPlugin();
     $response = Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
     $p->addResponse($response);
     $this->assertEquals(array($response), $p->getQueue());
 }
 /**
  * @dataProvider cacheRevalidationDataProvider
  */
 public function testRevalidatesResponsesAgainstOriginServer($can, $request, $response, $validate = null, $result = null)
 {
     // Send some responses to the test server for cache validation
     $server = $this->getServer();
     $server->flush();
     if ($validate) {
         $server->enqueue($validate);
     }
     $request = RequestFactory::getInstance()->fromMessage("GET / HTTP/1.1\r\nHost: 127.0.0.1:" . $server->getPort() . "\r\n" . $request);
     $response = Response::fromMessage($response);
     $request->setClient(new Client());
     $plugin = new CachePlugin(new DoctrineCacheAdapter(new ArrayCache()));
     $this->assertEquals($can, $plugin->canResponseSatisfyRequest($request, $response), '-> ' . $request . "\n" . $response);
     if ($result) {
         $result = Response::fromMessage($result);
         $result->removeHeader('Date');
         $request->getResponse()->removeHeader('Date');
         $request->getResponse()->removeHeader('Connection');
         // Get rid of dates
         $this->assertEquals((string) $result, (string) $request->getResponse());
     }
     if ($validate) {
         $this->assertEquals(1, count($server->getReceivedRequests()));
     }
 }
 public function testParsesResponseWith301()
 {
     $response = Response::fromMessage("HTTP/1.1 301 Moved Permanently\r\n\r\n<?xml version=\"1.0\" encoding=\"UTF-8\"?><Error><Code>PermanentRedirect</Code><Message>The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.</Message><RequestId>DUMMY_REQUEST_ID</RequestId><Bucket>DUMMY_BUCKET_NAME</Bucket><HostId>DUMMY_HOST_ID</HostId><Endpoint>s3.amazonaws.com</Endpoint></Error>");
     $parser = new S3ExceptionParser();
     $result = $parser->parse($response);
     $this->assertEquals('PermanentRedirect', $result['code']);
 }
 public function testParsesClientErrorResponseWithCodeInHeader()
 {
     $request = new Request('GET', 'http://example.com');
     $response = Response::fromMessage("HTTP/1.1 400 Bad Request\r\n" . "x-amzn-RequestId: xyz\r\n" . "x-amzn-ErrorType: foo:bar\r\n\r\n" . '{ "message": "lorem ipsum"}');
     $parser = new JsonRestExceptionParser();
     $this->assertEquals(array('code' => 'foo', 'message' => 'lorem ipsum', 'type' => 'client', 'request_id' => 'xyz', 'parsed' => array('message' => 'lorem ipsum')), $parser->parse($request, $response));
 }
 public function testParsesResponsesWithNoBody()
 {
     $response = Response::fromMessage("HTTP/1.1 400 Bad Request\r\nX-Amz-Request-ID: Foo\r\n\r\n");
     $parser = new DefaultXmlExceptionParser();
     $result = $parser->parse($response);
     $this->assertEquals('400 Bad Request (Request-ID: Foo)', $result['message']);
     $this->assertEquals('Foo', $result['request_id']);
 }
Example #9
0
 /**
  * 
  * @param string $fixtureName
  * @return \Guzzle\Http\Message\Response
  */
 protected function getHttpFixture($fixtureName = '', $contentType = 'application/xml')
 {
     $message = "HTTP/1.0 200 OK\nContent-Type:" . $contentType . "\n\n";
     if ($fixtureName != '') {
         $message .= $this->getFixture($fixtureName);
     }
     return \Guzzle\Http\Message\Response::fromMessage($message);
 }
 /**
  * @dataProvider getDataForParsingTest
  */
 public function testParsesResponsesWithNoBody($url, $message, $code)
 {
     $request = new Request('HEAD', $url);
     $response = Response::fromMessage("HTTP/1.1 {$message}\r\n\r\n");
     $response->setRequest($request);
     $parser = new S3ExceptionParser();
     $result = $parser->parse($response);
     $this->assertEquals($code, $result['code']);
 }
Example #11
0
 /**
  * Get a mock response from a file
  *
  * @param string $file File to retrieve a mock response from
  *
  * @return Response
  * @throws InvalidArgumentException if the file is not found
  */
 public static function getMockFile($path)
 {
     if (!file_exists($path)) {
         throw new InvalidArgumentException('Unable to open mock file: ' . $path);
     }
     $parts = explode("\n\n", file_get_contents($path), 2);
     // Convert \n to \r\n in headers
     $data = isset($parts[1]) ? str_replace("\n", "\r\n", $parts[0]) . "\r\n\r\n" . $parts[1] : $parts[0];
     return Response::fromMessage($data);
 }
 /**
  * Register a URI.
  *
  * @param string          $uri      URI (either complete or partial)
  * @param Response|string $response Response object, a string response or a path to a file containing a response
  *
  * @return self Reference to the matcher
  */
 public function registerUri($uri, $response)
 {
     if ($response instanceof Response) {
         $this->responses[$uri] = $response;
         return $this;
     }
     if (file_exists($response)) {
         $response = file_get_contents($response);
     }
     $this->responses[$uri] = Response::fromMessage($response);
     return $this;
 }
 public function testExcludeSourceUrlFromHistoryComparison()
 {
     $httpClient = new \Guzzle\Http\Client();
     $mockPlugin = new \Guzzle\Plugin\Mock\MockPlugin();
     $mockPlugin->addResponse(\Guzzle\Http\Message\Response::fromMessage('HTTP/1.1 301' . "\n" . 'Location: http://example.com/'));
     $mockPlugin->addResponse(\Guzzle\Http\Message\Response::fromMessage('HTTP/1.1 301' . "\n" . 'Location: http://example.com/2/'));
     $mockPlugin->addResponse(\Guzzle\Http\Message\Response::fromMessage('HTTP/1.1 301' . "\n" . 'Location: http://example.com/3/'));
     $mockPlugin->addResponse(\Guzzle\Http\Message\Response::fromMessage('HTTP/1.1 301' . "\n" . 'Location: http://example.com/4/'));
     $mockPlugin->addResponse(\Guzzle\Http\Message\Response::fromMessage('HTTP/1.1 301' . "\n" . 'Location: http://example.com/5/'));
     $httpClient->addSubscriber($mockPlugin);
     $detector = new \webignition\HttpRedirectLoopDetector\HttpRedirectLoopDetector();
     $detector->setHttpClient($httpClient);
     $detector->setUrl('https://example.com/');
     $this->assertFalse($detector->test());
 }
Example #14
0
 /**
  * Queue an array of responses or a single response on the server.
  *
  * Any currently queued responses will be overwritten.  Subsequent requests
  * on the server will return queued responses in FIFO order.
  *
  * @param array|Response $responses A single or array of Responses to queue
  * @throws BadResponseException
  */
 public function enqueue($responses)
 {
     $data = array();
     foreach ((array) $responses as $response) {
         // Create the response object from a string
         if (is_string($response)) {
             $response = Response::fromMessage($response);
         } elseif (!$response instanceof Response) {
             throw new BadResponseException('Responses must be strings or implement Response');
         }
         $data[] = array('statusCode' => $response->getStatusCode(), 'reasonPhrase' => $response->getReasonPhrase(), 'headers' => $response->getHeaders()->toArray(), 'body' => $response->getBody(true));
     }
     $request = $this->client->put('guzzle-server/responses', null, json_encode($data));
     $request->send();
 }
Example #15
0
 public function onBeforeSendFallback(Event $event)
 {
     if (strpos($event['request']->getUrl(), 'tokens') !== false) {
         // auth request must pass
         $message = file_get_contents(__DIR__ . '/_response/Auth.resp');
         $response = Response::fromMessage($message);
         $event['request']->setResponse($response)->setState(Request::STATE_COMPLETE);
         $event->stopPropagation();
     } else {
         // default fallback is a 404
         $response = new Response(200);
         $event['request']->setResponse($response)->setState(Request::STATE_COMPLETE);
         $event->stopPropagation();
     }
 }
 protected function getHttpFixtures($path)
 {
     $fixtures = array();
     $fixturesDirectory = new \DirectoryIterator($path);
     $fixturePathnames = array();
     foreach ($fixturesDirectory as $directoryItem) {
         if ($directoryItem->isFile()) {
             $fixturePathnames[] = $directoryItem->getPathname();
         }
     }
     sort($fixturePathnames);
     foreach ($fixturePathnames as $fixturePathname) {
         $fixtures[] = \Guzzle\Http\Message\Response::fromMessage(file_get_contents($fixturePathname));
     }
     return $fixtures;
 }
Example #17
0
 public function __invoke($url, array $subProtocols = [], array $headers = [])
 {
     try {
         $request = $this->generateRequest($url, $subProtocols, $headers);
     } catch (\Exception $e) {
         return new RejectedPromise($e);
     }
     $connector = 'wss' === substr($url, 0, 3) ? $this->_secureConnector : $this->_connector;
     return $connector->create($request->getHost(), $request->getPort())->then(function (DuplexStreamInterface $stream) use($request, $subProtocols) {
         $futureWsConn = new Deferred();
         $buffer = '';
         $headerParser = function ($data, DuplexStreamInterface $stream) use(&$headerParser, &$buffer, $futureWsConn, $request, $subProtocols) {
             $buffer .= $data;
             if (false == strpos($buffer, "\r\n\r\n")) {
                 return;
             }
             $stream->removeListener('data', $headerParser);
             $response = Response::fromMessage($buffer);
             if (101 !== $response->getStatusCode()) {
                 $futureWsConn->reject($response);
                 $stream->close();
                 return;
             }
             $acceptCheck = base64_encode(pack('H*', sha1($request->getHeader('Sec-WebSocket-Key') . RFC6455::GUID)));
             if ((string) $response->getHeader('Sec-WebSocket-Accept') !== $acceptCheck) {
                 $futureWsConn->reject(new \DomainException("Could not verify Accept Key during WebSocket handshake"));
                 $stream->close();
                 return;
             }
             $acceptedProtocol = $response->getHeader('Sec-WebSocket-Protocol');
             if ((count($subProtocols) > 0 || null !== $acceptedProtocol) && !in_array((string) $acceptedProtocol, $subProtocols)) {
                 $futureWsConn->reject(new \DomainException('Server did not respond with an expected Sec-WebSocket-Protocol'));
                 $stream->close();
                 return;
             }
             $futureWsConn->resolve(new WebSocket($stream, $response, $request));
             $futureWsConn->promise()->then(function (WebSocket $conn) use($stream) {
                 $stream->emit('data', [$conn->response->getBody(), $stream]);
             });
         };
         $stream->on('data', $headerParser);
         $stream->write($request);
         return $futureWsConn->promise();
     });
 }
 /**
  * The following is a bit of an integration test to ensure that the CachePlugin honors a
  * custom can cache strategy.
  */
 public function testIntegrationWithCachePlugin()
 {
     $c = new CallbackCanCacheStrategy(function ($request) {
         return true;
     }, function ($response) {
         return true;
     });
     // Make a request and response that have no business being cached
     $request = new Request('DELETE', 'http://www.foo.com');
     $response = Response::fromMessage("HTTP/1.1 200 OK\r\n" . "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n" . "Last-Modified: Wed, 09 Jan 2013 08:48:53 GMT\r\n" . "Content-Length: 2\r\n" . "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\n\r\n" . "hi");
     $this->assertTrue($c->canCacheRequest($request));
     $this->assertTrue($c->canCacheResponse($response));
     $s = $this->getMockBuilder('Guzzle\\Plugin\\Cache\\DefaultCacheStorage')->setConstructorArgs(array(new DoctrineCacheAdapter(new ArrayCache())))->setMethods(array('fetch'))->getMockForAbstractClass();
     $s->expects($this->once())->method('fetch')->will($this->returnValue(array(200, $response->getHeaders(), $response->getBody(true))));
     $plugin = new CachePlugin(array('can_cache' => $c, 'storage' => $s));
     $plugin->onRequestBeforeSend(new Event(array('request' => $request)));
     $this->assertEquals(200, $request->getResponse()->getStatusCode());
     $this->assertEquals('hi', $request->getResponse()->getBody(true));
 }
Example #19
0
 public function test_Listing_Load_Balancers()
 {
     // Load JSON HTTP data
     $authData = file_get_contents($this->getTestFilePath('Auth', './'));
     $data1 = file_get_contents($this->getTestFilePath('LoadBalancers1'));
     $data2 = file_get_contents($this->getTestFilePath('LoadBalancers2'));
     $data3 = file_get_contents($this->getTestFilePath('LoadBalancers3'));
     // Populate mock response queue
     $mock = new MockPlugin();
     $mock->addResponse(Response::fromMessage($authData))->addResponse(Response::fromMessage($data1))->addResponse(Response::fromMessage($data2))->addResponse(Response::fromMessage($data3));
     // We need to define our own setup because *jazz hands*
     $client = $this->newClient();
     $client->addSubscriber($mock);
     $service = $client->loadBalancerService(null, 'IAD');
     // Ensure that a series of paginated calls return a holistic collection
     $lbs = $service->loadBalancerList(false, array('limit' => 2));
     $ids = array();
     foreach ($lbs as $lb) {
         $ids[] = $lb->id;
     }
     // Check our assumptions
     $this->isCollection($lbs);
     $this->assertEquals($ids, array(1, 2, 3, 4, 5));
 }
Example #20
0
 /**
  * Get the streaming contents of the specified resource.
  *
  * @param string $uri
  *            Resource URI
  *            
  * @return EntityBody Returns the stream resource on success or false on failure
  * @throws \RuntimeException If the stream cannot be opened or an error occurs
  */
 public function getStream($uri)
 {
     $request = $this->createRequest('GET', $uri);
     $factory = new PhpStreamRequestFactory();
     $stream = $factory->fromRequest($request, array(), array('stream_class' => 'Guzzle\\Http\\EntityBody'));
     // The implementation of streaming download proposed by Guzzle's EntityBody class does not care about
     // HTTP errors. As a workaround, let's rebuild the HTTP response from the response headers sent in the
     // $http_response_header variable (http://www.php.net/manual/en/reserved.variables.httpresponseheader.php)
     $response = HttpResponse::fromMessage(implode("\r\n", $factory->getLastResponseHeaders()));
     // Creates History
     $this->lastRequest = $request;
     $this->lastResponse = $response;
     if (!$response->isSuccessful()) {
         $stream = false;
     }
     if (!$stream && $this->throwExceptions) {
         switch ($response->getStatusCode()) {
             case 404:
                 throw new NoSuchResourceException('No such file or directory');
             default:
                 throw new \RuntimeException($response->getReasonPhrase(), $response->getStatusCode());
         }
     }
     return $stream;
 }
Example #21
0
 /**
  * @covers Guzzle\Http\Message\Response::fromMessage
  */
 public function testFactoryRequiresMessage()
 {
     $this->assertFalse(Response::fromMessage(''));
 }
    public function testDoesNotDownloadGlacierStorageObjects()
    {
        $res = <<<EOT
HTTP/1.1 200 OK
x-amz-id-2: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
x-amz-request-id: XXXXXXXXXXXXXXXX
Date: Thu, 04 Jul 2012 12:00:00 GMT
Content-Type: application/xml
Server: AmazonS3

<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <Name>bucket-1</Name>
    <Prefix></Prefix>
    <Marker></Marker>
    <MaxKeys></MaxKeys>
    <Delimiter>/</Delimiter>
    <IsTruncated>false</IsTruncated>
    <Contents>
        <Key>e</Key>
        <LastModified>2012-04-07T12:00:00.000Z</LastModified>
        <ETag>"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"</ETag>
        <Size>0</Size>
        <Owner>
            <ID>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</ID>
            <DisplayName>XXXXXXXXXX</DisplayName>
        </Owner>
        <StorageClass>GLACIER</StorageClass>
    </Contents>
    <Contents>
        <Key>f</Key>
        <LastModified>2012-04-07T12:00:00.000Z</LastModified>
        <ETag>"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"</ETag>
        <Size>0</Size>
        <Owner>
            <ID>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</ID>
            <DisplayName>XXXXXXXXXX</DisplayName>
        </Owner>
        <StorageClass>STANDARD</StorageClass>
    </Contents>
</ListBucketResult>
EOT;
        $s3 = S3Client::factory(array('key' => 'foo', 'secret' => 'bar'));
        $s3->getEventDispatcher()->addSubscriber(new MockPlugin(array(Response::fromMessage($res), new Response(200))));
        $dir = __DIR__ . '/../../../../../build/artifacts';
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        DownloadSyncBuilder::getInstance()->setClient($s3)->setBucket('Foo')->setDirectory($dir)->build()->transfer();
        $this->assertFileNotExists($dir . '/e');
        $this->assertFileExists($dir . '/f');
        unlink($dir . '/f');
    }
 public function testGetPersonClassArrayJsonResponseWithSerializer()
 {
     $client = self::getClient('JMSSerializerBundle');
     $command = $client->getCommand('GetPersonClassArray');
     self::$mock->addResponse(Response::fromMessage(self::jsonArrayResponse()));
     $people = $client->execute($command);
     $this->assertTrue(is_array($people));
     $this->assertCount(2, $people);
     $this->assertInstanceOf('Misd\\GuzzleBundle\\Tests\\Fixtures\\Person', $people[0]);
     $this->assertEquals(1, $people[0]->id);
     $this->assertEquals('Foo', $people[0]->firstName);
     $this->assertEquals('Bar', $people[0]->familyName);
     $this->assertInstanceOf('Misd\\GuzzleBundle\\Tests\\Fixtures\\Person', $people[1]);
     $this->assertEquals(2, $people[1]->id);
     $this->assertEquals('Baz', $people[1]->firstName);
     $this->assertEquals('Qux', $people[1]->familyName);
 }
 public function sendData($data)
 {
     // check if we are mocking a request
     $mock = false;
     $listeners = $this->httpClient->getEventDispatcher()->getListeners('request.before_send');
     foreach ($listeners as $listener) {
         if (get_class($listener[0]) === 'Guzzle\\Plugin\\Mock\\MockPlugin') {
             $mock = true;
             break;
         }
     }
     // if we are mocking, use guzzle, otherwise use umTransaction
     if ($mock) {
         $httpRequest = $this->httpClient->createRequest($this->getHttpMethod(), $this->getEndpoint(), null, $data);
         $httpResponse = $httpRequest->send();
     } else {
         $umTransaction = new umTransaction();
         $umTransaction->usesandbox = $this->getSandbox();
         $umTransaction->testmode = $this->getTestMode();
         $umTransaction->key = $this->getSource();
         $umTransaction->pin = $this->getPin();
         $umTransaction->command = $this->getCommand();
         $umTransaction->invoice = $this->getInvoice();
         $umTransaction->amount = $data['amount'];
         $umTransaction->description = $this->getDescription();
         $umTransaction->addcustomer = $this->getAddCustomer();
         $umTransaction->schedule = $this->getInterval();
         $umTransaction->numleft = $this->getIntervalCount();
         $umTransaction->start = 'next';
         if (isset($data['card'])) {
             $umTransaction->card = $this->getCard()->getNumber();
             $umTransaction->exp = $this->getCard()->getExpiryDate('my');
             $umTransaction->cvv2 = $this->getCard()->getCvv();
             $umTransaction->cardholder = $this->getCard()->getName();
             $umTransaction->street = $this->getCard()->getAddress1();
             $umTransaction->zip = $this->getCard()->getPostcode();
             $umTransaction->email = $this->getCard()->getEmail();
             $umTransaction->billfname = $this->getCard()->getBillingFirstName();
             $umTransaction->billlname = $this->getCard()->getBillingLastName();
             $umTransaction->billcompany = $this->getCard()->getBillingCompany();
             $umTransaction->billstreet = $this->getCard()->getBillingAddress1();
             $umTransaction->billstreet2 = $this->getCard()->getBillingAddress2();
             $umTransaction->billcity = $this->getCard()->getBillingCity();
             $umTransaction->billstate = $this->getCard()->getBillingState();
             $umTransaction->billzip = $this->getCard()->getBillingPostcode();
             $umTransaction->billcountry = $this->getCard()->getBillingCountry();
             $umTransaction->billphone = $this->getCard()->getBillingPhone();
         } elseif ($this->getCardReference()) {
             $umTransaction->card = $this->getCardReference();
             $umTransaction->exp = '0000';
         } else {
             $umTransaction->refnum = $this->getTransactionReference();
         }
         $umTransaction->Process();
         $httpResponse = Guzzle\Http\Message\Response::fromMessage($umTransaction->rawresult);
     }
     return $this->response = new Response($this, $httpResponse->getBody());
 }
 /**
  * @covers Guzzle\Http\Plugin\CookiePlugin
  */
 public function testExtractsMultipleCookies()
 {
     $this->plugin->clearCookies();
     $response = Response::fromMessage("HTTP/1.1 200 OK\r\n" . "Set-Cookie: IU=deleted; expires=Wed, 03-Mar-2010 02:17:39 GMT; path=/; domain=127.0.0.1\r\n" . "Set-Cookie: PH=deleted; expires=Wed, 03-Mar-2010 02:17:39 GMT; path=/; domain=127.0.0.1\r\n" . "Set-Cookie: fpc=d=.Hm.yh4.1XmJWjJfs4orLQzKzPImxklQoxXSHOZATHUSEFciRueW_7704iYUtsXNEXq0M92Px2glMdWypmJ7HIQl6XIUvrZimWjQ3vIdeuRbI.FNQMAfcxu_XN1zSx7l.AcPdKL6guHc2V7hIQFhnjRW0rxm2oHY1P4bGQxFNz7f.tHm12ZD3DbdMDiDy7TBXsuP4DM-&v=2; expires=Fri, 02-Mar-2019 02:17:40 GMT; path=/; domain=127.0.0.1\r\n" . "Set-Cookie: FPCK3=AgBNbvoQAGpGEABZLRAAbFsQAF1tEABkDhAAeO0=; expires=Sat, 02-Apr-2019 02:17:40 GMT; path=/; domain=127.0.0.1\r\n" . "Set-Cookie: CH=deleted; expires=Wed, 03-Mar-2010 02:17:39 GMT; path=/; domain=127.0.0.1\r\n" . "Set-Cookie: CH=AgBNbvoQAAEcEAApuhAAMJcQADQvEAAvGxAALe0QAD6uEAATwhAAC1AQAC8t; expires=Sat, 02-Apr-2019 02:17:40 GMT; path=/; domain=127.0.0.1\r\n" . "Set-Cookie: fpt=d=_e2d6jLXesxx4AoiC0W7W3YktnpITDTHoJ6vNxF7TU6JEep6Y5BFk7Z9NgHmhiXoB7jGV4uR_GBQtSDOLjflKBUVZ6UgnGmDztoj4GREK30jm1qDgReyhPv7iWaN8e8ZLpUKXtPioOzQekGha1xR8ZqGR25GT7aYQpcxaaY.2ATjTpbm7HmX8tlBIte6mYMwFpIh_krxtofGPH3R337E_aNF3illhunC5SK6I0IfZvHzBXCoxu9fjH6e0IHzyOBY656YMUIElQiDkSd8werkBIRE6LJi6YU8AWgitEpMLisOIQSkqyGiahcPFt_fsD8DmIX2YAdSeVE0KycIqd0Z9aM7mdJ3xNQ4dmOOfcZ83dDrZ.4hvuKN2jB2FQDKuxEjTVO4DmiCCSyYgcs2wh0Lc3RODVKzqAZNMTYltWMELw9JdUyDFD3EGT3ZCnH8NQ6f_AAWffyj92ZMLYfWJnXHSG.DTKlVHj.IsihVT73QzrfoMFIs&v=1; path=/; domain=127.0.0.1\r\n" . "Set-Cookie: fpps=deleted; expires=Wed, 03-Mar-2010 02:17:39 GMT; path=/; domain=127.0.0.1\r\n" . "set-cookie: fpc_s=d=ng6sEJk.1XnLUt1pfJ2kiUon07QEppAUuwW3nk0tYwcHMQ1CijnSGVZHfgvWSXQxE5eW_1hjvDAA4Nu0CSSn2xk9_.DOkKI_fZLLLUrm0hJ41VMbSUTrklw.u5IlTM5JCeK_PDjSjZNkvHMbNYziu8vwd8fMnbecf9bSo3eDDv1boowyLFk_9mnGYBeSI4U86mnm.mnfOHMARxzL6BVMTAblIAml65cR486SHzPVO6KNYvkqh8zP3m0hVIkRaPhzvDjQkDG28HCbMjq745QR2FcCmI4TNJbk7EtJmsBrlL8wvVyX5DiBmP9W990-&v=2; path=/; domain=127.0.0.1\r\n" . "Content-Length: 0\r\n\r\n");
     $this->getServer()->enqueue(array((string) $response, "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\rn"));
     $request = RequestFactory::getInstance()->create('GET', $this->getServer()->getUrl());
     $request->getEventDispatcher()->addSubscriber($this->plugin);
     $request->setClient(new Client());
     $request->send();
     $this->assertNull($request->getHeader('Cookie'));
     $request->setState('new');
     $request->send();
     $this->assertNotNull($request->getHeader('Cookie'));
     // Doesn't send expired cookies
     $this->assertEmpty($request->getCookie('IU'));
     $this->assertEmpty($request->getCookie('PH'));
     $this->assertNotEmpty($request->getCookie('fpc'));
     $this->assertNotEmpty($request->getCookie('FPCK3'));
     $this->assertNotEmpty($request->getCookie('CH'));
     $this->assertNotEmpty($request->getCookie('fpt'));
     $this->assertNotEmpty($request->getCookie('fpc_s'));
     $this->assertNotEmpty($request->getCookie('CH'));
     $this->assertNotEmpty($request->getCookie('CH'));
     $this->assertEquals(9, count($this->plugin->extractCookies($response)));
 }
Example #26
0
 /**
  * 
  * @param array $items Collection of http messages and/or curl exceptions
  * @return array
  */
 protected function buildHttpFixtureSet($items)
 {
     $fixtures = array();
     foreach ($items as $item) {
         switch ($this->getHttpFixtureItemType($item)) {
             case 'httpMessage':
                 $fixtures[] = \Guzzle\Http\Message\Response::fromMessage($item);
                 break;
             case 'curlException':
                 $fixtures[] = $this->getCurlExceptionFromCurlMessage($item);
                 break;
             default:
                 throw new \LogicException();
         }
     }
     return $fixtures;
 }
 /**
  * @covers Guzzle\Http\Message\Response::fromMessage
  * @expectedException Guzzle\Common\Exception\InvalidArgumentException
  */
 public function testFactoryRequiresMessage()
 {
     $response = Response::fromMessage('');
 }
 protected function addFixtureResponse($fixture)
 {
     $this->guzzleMockPlugin->addResponse(Response::fromMessage($this->getFixture($fixture)));
 }
 public function testParsesClientErrorResponses()
 {
     $response = Response::fromMessage("HTTP/1.1 400 Bad Request\r\n" . "x-amzn-requestid: xyz\r\n\r\n" . '{ "type": "client", "message": "lorem ipsum", "code": "foo" }');
     $parser = new JsonRestExceptionParser();
     $this->assertEquals(array('code' => 'foo', 'message' => 'lorem ipsum', 'type' => 'client', 'request_id' => 'xyz', 'parsed' => array('type' => 'client', 'message' => 'lorem ipsum', 'code' => 'foo')), $parser->parse($response));
 }
Example #30
0
 /**
  * @covers Guzzle\Http\Plugin\CachePlugin::canResponseSatisfyRequest
  * @covers Guzzle\Http\Plugin\CachePlugin::revalidate
  * @dataProvider cacheRevalidationDataProvider
  */
 public function testRevalidatesResponsesAgainstOriginServer($can, $request, $response, $validate = null, $result = null, $param = null)
 {
     // Send some responses to the test server for cache validation
     $server = $this->getServer();
     $server->flush();
     if ($validate) {
         $server->enqueue($validate);
     }
     $request = RequestFactory::getInstance()->fromMessage("GET / HTTP/1.1\r\nHost: 127.0.0.1:" . $server->getPort() . "\r\n" . $request);
     $response = Response::fromMessage($response);
     $request->setClient(new Client());
     if ($param) {
         $request->getParams()->set('cache.revalidate', $param);
     }
     $plugin = new CachePlugin($this->adapter);
     $this->assertEquals($can, $plugin->canResponseSatisfyRequest($request, $response), '-> ' . $request . "\n" . $response);
     if ($result) {
         // Get rid of dates
         $this->assertEquals(preg_replace('/(Date:\\s)(.*)(\\r\\n)/', '$1$3', (string) $result), preg_replace('/(Date:\\s)(.*)(\\r\\n)/', '$1$3', (string) $request->getResponse()));
     }
     if ($validate) {
         $this->assertEquals(1, count($server->getReceivedRequests()));
     }
 }