Пример #1
0
 protected function createResponse($content = '')
 {
     $response = new Buzz\Message\Response();
     $response->addHeader('1.0 200 OK');
     $response->setContent($content);
     return $response;
 }
 public function testBind01()
 {
     $expectedJSON = file_get_contents(dirname(__DIR__) . '/../../Resources/json/client_aftership_couriers_response_handler_01.json');
     $this->response->expects($this->once())->method('getStatusCode')->will($this->returnValue(200));
     $this->response->expects($this->once())->method('getContent')->will($this->returnValue($expectedJSON));
     $this->responseHandler->bind($this->response, $this->collection);
     $this->assertEquals(26, $this->collection->count());
     $courier0 = $this->collection[0];
     $this->assertEquals('USPS', $courier0->getName());
     $this->assertEquals('United States Postal Service', $courier0->getOtherName());
     $this->assertEquals('+1 800-275-8777', $courier0->getPhone());
     $this->assertEquals(['USA'], $courier0->getServiceCountries());
     $this->assertEquals('usps', $courier0->getSlug());
     $this->assertEquals(['en'], $courier0->getSupportLanguages());
     $this->assertNotNull($courier0->getUpdatedAt());
     $this->assertEquals("https://www.usps.com", $courier0->getUrl());
     $courier13 = $this->collection[13];
     $this->assertEquals('Hong Kong Post', $courier13->getName());
     $this->assertEquals('香港郵政', $courier13->getOtherName());
     $this->assertEquals('+852 2921 2222', $courier13->getPhone());
     $this->assertEquals(['HKG'], $courier13->getServiceCountries());
     $this->assertEquals('hong-kong-post', $courier13->getSlug());
     $this->assertEquals(['en'], $courier13->getSupportLanguages());
     $this->assertNotNull($courier13->getUpdatedAt());
     $this->assertEquals("http://hongkongpost.com", $courier13->getUrl());
 }
Пример #3
0
 private function createResponse($content, $statusCode = 200)
 {
     $response = new Response();
     $response->setContent($content);
     $response->setHeaders(array('HTTP/1.1 ' . $statusCode . ' REASON'));
     return $response;
 }
Пример #4
0
 public function testAddHeadersResetsStatusLine()
 {
     $response = new Response();
     $this->assertNull($response->getStatusCode());
     $response->addHeaders(array('1.0 200 OK'));
     $this->assertEquals(200, $response->getStatusCode());
 }
Пример #5
0
 public function __construct(TransportResponse $response)
 {
     if (!$response->isSuccessful()) {
         throw new TransportException($response);
     }
     $this->response = $response;
 }
Пример #6
0
 /**
  * Verifies the last request.
  * If the last request was not successful, it will be throw an exception.
  *
  * @param \Buzz\Message\Response $response The response object from the last reques
  * @param string $url The url which was requested
  * @return \Buzz\Message\Response
  * @throws \Exception
  */
 protected function verifyResult(\Buzz\Message\Response $response, $url)
 {
     if ($response->getStatusCode() !== 200) {
         throw new \Exception('Request to "' . $url . '" failed', 1364061673);
     }
     return $response;
 }
Пример #7
0
 /**
  * @param Response $curlResponse
  *
  * @throws HttpStatusParserException
  */
 public function parse(Response $curlResponse)
 {
     $statusCode = $curlResponse->getStatusCode();
     if ($this->shouldThrowException($statusCode)) {
         throw new HttpStatusParserException($curlResponse->getContent(), $statusCode);
     }
 }
Пример #8
0
 public function rev(Response $response)
 {
     if ($response->isSuccessful()) {
         return $this->decode($response->getHeader('Etag'));
     }
     throw new RugException('not_found', 'The specified document or revision cannot be found or has been deleted');
 }
Пример #9
0
 /**
  * @param \Buzz\Message\Response $response
  */
 private function handleResponseAuthHeader(\Buzz\Message\Response $response)
 {
     $token = $response->getHeader('Update-Client-Auth');
     if ($token) {
         $this->client->setAuthToken($token);
         $this->setTokenToCache($token);
     }
 }
 /**
  * @see Client\ClientInterface
  */
 public function send(Message\Request $request, Message\Response $response)
 {
     if (!($queued = $this->receiveFromQueue())) {
         throw new \LogicException('There are no queued responses.');
     }
     $response->setHeaders($queued->getHeaders());
     $response->setContent($queued->getContent());
 }
Пример #11
0
 public function it_can_search_with__query(Browser $client, Response $response)
 {
     $response->getContent()->shouldBeCalled();
     $client->get(sprintf('%s/search?%s', 'http://endpoint', http_build_query(['q' => 'pilkington avenue, birmingham', 'format' => 'json'])), ['User-Agent' => 'Nomatim PHP Library (https://github.com/nixilla/nominatim-consumer); email: not set'])->shouldBeCalled()->willReturn($response);
     $query = new Query();
     $query->setQuery('pilkington avenue, birmingham');
     $this->search($query)->shouldReturnAnInstanceOf('Nominatim\\Result\\Collection');
 }
Пример #12
0
 public function testGetDomReturnsADomDocument()
 {
     $response = new Message\Response();
     $response->setContent('<html><head></head><body></body></html>');
     $this->browser->getClient()->sendToQueue($response);
     $this->browser->get('http://www.google.com');
     $this->assertTrue($this->browser->getDom() instanceof \DOMDocument);
 }
Пример #13
0
 protected function assertHttpResponseHasHeader(HttpResponse $response, $header, $expectedValue = null)
 {
     $headerValue = $response->getHeader($header);
     self::assertNotNull($headerValue, "Failed asserting that response has a {$header} header");
     if ($expectedValue !== null) {
         self::assertEquals($expectedValue, $headerValue);
     }
 }
Пример #14
0
 public function _parse(Response $response, $mime = null)
 {
     $data = $this->decode($response->getContent(), $mime);
     if (isset($data->error)) {
         throw new RugException($data->error, $this->_error($data));
     }
     return $data;
 }
Пример #15
0
 /**
  * Processes Set-Cookie headers from a request/response pair.
  * 
  * @param Message\Request  $request  A request object
  * @param Message\Response $response A response object
  */
 public function processSetCookieHeaders(Message\Request $request, Message\Response $response)
 {
     foreach ($response->getHeader('Set-Cookie', false) as $header) {
         $cookie = new Cookie();
         $cookie->fromSetCookieHeader($header, parse_url($request->getHost(), PHP_URL_HOST));
         $this->addCookie($cookie);
     }
 }
 /**
  * @param  Response $response
  *
  * @return string
  */
 private function processResponse(Response $response)
 {
     $matches = [];
     preg_match('/<input.*value="(.*)"/U', $response->getContent(), $matches);
     if (!isset($matches[1])) {
         throw new \RuntimeException('Screenshot upload failed');
     }
     return $matches[1];
 }
Пример #17
0
 /**
  * @test
  */
 public function it_translates_a_text()
 {
     $response = new Response();
     $response->setContent('<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">dit is een test</string>');
     $this->browser->expects($this->once())->method('get')->with('http://api.microsofttranslator.com/v2/Http.svc/Translate?from=en&to=nl&text=this+is+a+test')->willReturn($response);
     $translation = $this->translator->translate('en', 'nl', 'this is a test');
     $expectedTranslation = 'dit is een test';
     $this->assertEquals($expectedTranslation, $translation);
 }
Пример #18
0
 /**
  * @return SenderInterface
  */
 private function getSender()
 {
     $client = $this->getMockBuilder('\\Team3\\PayU\\Communication\\Sender\\SenderInterface')->getMock();
     $client->expects($this->any())->method('send')->willReturnCallback(function () {
         $response = new Response();
         $response->setContent(self::RESPONSE_CONTENT);
         return $response;
     });
     return $client;
 }
 /**
  * @param string|null $message
  */
 public function __construct(RequestInterface $request, Response $response, $message = null)
 {
     $this->request = $request;
     $this->response = $response;
     if ($message === null) {
         $curlError = $response->getHeader('X-Curl-Error-Result');
         $message = sprintf('HTTP %s request to "%s%s" failed: %d - "%s".', $request->getMethod(), $request->getHost(), $request->getResource(), $curlError ?: $response->getStatusCode(), $curlError ? curl_strerror($curlError) : $response->getReasonPhrase());
     }
     parent::__construct($message);
 }
Пример #20
0
 public function testGetBearerHeaderInvalidTokenTypeException()
 {
     $twitter = $this->getMockBuilder('Endroid\\Twitter\\Twitter')->setConstructorArgs(array('foo', 'bar'))->setMethods(array('getBasicHeader', 'call'))->getMock();
     $twitter->expects($this->any())->method('getBasicHeader')->willReturn(self::EXPECTED_BASIC_HEADER);
     $response = new Response();
     $response->setContent(json_encode(array('token_type' => 'something_wrong', 'access_token' => 'cc4f26cc4a3f61a84436014b2166e431')));
     $twitter->expects($this->any())->method('call')->with('POST', Twitter::BASE_URL . Twitter::TOKEN_URL)->willReturn($response);
     $this->setExpectedException('Endroid\\Twitter\\Exception\\InvalidTokenTypeException');
     Util::invokeMethod($twitter, 'getBearerHeader');
 }
Пример #21
0
 /**
  * Lets us know if something went wrong
  *
  * @param Response $response
  * @throws \Twitter\Exception\TwitterApiException
  * @throws \Exception
  */
 protected function handleException(Response $response)
 {
     $json_string = $response->getContent();
     $output = json_decode($json_string, true);
     if (count($output['errors'])) {
         throw new TwitterApiException($output['errors'][0]['message'], $output['errors'][0]['code']);
     } else {
         throw new \Exception(sprintf('Unknown error: %s', $json_string));
     }
 }
 /**
  * @test
  */
 public function it_should_be_future_proof()
 {
     // google keeps putting more comma's to break peoples implementations
     $response = new Response();
     $response->setContent('[[["What are you doing?","Wat ben jij aan het doen?",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,0]],,"nl"]');
     $this->browser->expects($this->once())->method('get')->with('https://translate.googleapis.com/translate_a/single?client=gtx&sl=nl&tl=en&dt=t&q=' . urlencode('Wat ben jij aan het doen?'))->willReturn($response);
     $translation = $this->translator->translate('nl', 'en', 'Wat ben jij aan het doen?');
     $expectedTranslation = 'What are you doing?';
     $this->assertEquals($expectedTranslation, $translation);
 }
Пример #23
0
 private function processResponse(Response $response)
 {
     if (null !== $this->logger) {
         $this->logger->info(sprintf('Status Code %s', $response->getStatusCode()));
         $this->logger->debug(var_export($response->getContent(), true));
     }
     if (500 <= $response->getStatusCode()) {
         throw new ApiServerException($response->getStatusCode(), $response->getContent(), $response->getReasonPhrase(), $response->getHeaders());
     }
     if (400 <= $response->getStatusCode()) {
         try {
             $error = $this->parser->parse($response->getContent());
             $error = $error instanceof Model\Error ? $error : new Model\Error();
         } catch (ApiParserException $e) {
             throw new ApiClientException($response->getStatusCode(), $response->getContent(), $response->getReasonPhrase(), $response->getHeaders(), null, $e);
         }
         throw new ApiClientException($response->getStatusCode(), $response->getContent(), $response->getReasonPhrase(), $response->getHeaders(), $error);
     }
     if (204 === $response->getStatusCode()) {
         return true;
     }
     $content = trim($response->getContent());
     if (empty($content)) {
         return true;
     }
     $object = $this->parser->parse($content);
     $object->setApi($this);
     return $object;
 }
Пример #24
0
 protected function getExportResponse()
 {
     $zip = new \ZipArchive();
     $zip->open($this->zipFile, $zip::CREATE);
     $zip->addFile('test/etc/diary.csv', 'diary.csv');
     $zip->close();
     $response = new Response();
     $response->setHeaders(array('HTTP/1.1 200 OK', 'Content-Type: application/zip'));
     $response->setContent(file_get_contents($this->zipFile));
     return $response;
 }
Пример #25
0
 /**
  * @param Response $response
  * @param int $minFresh
  * @return bool
  */
 public function isExpired(Response $response, $minFresh = 5)
 {
     $expires = $response->getHeader('expires');
     if ($expires !== null) {
         $parsedExpires = strtotime($expires);
         if ($parsedExpires === false || time() + $minFresh > $parsedExpires) {
             return true;
         }
     }
     return false;
 }
 /**
  * @test
  * @dataProvider getAuthCode
  */
 public function testGetAuthTokenGivenCode($code)
 {
     $response = new Response();
     $response->setContent('{"access_token": "ea135929105c4f29a0f5117d2960926f", "expires_in": 2592000}');
     $response->setHeaders(array('HTTP/1.1 200 OK'));
     $httpClient = $this->getHttpClientMock();
     $httpClient->expects($this->once())->method('post')->with($this->equalTo('https://oauth.yandex.ru/token'), $this->anything(), $this->stringContains($code))->will($this->returnValue($response));
     $auth = new Auth('test', 'test', $httpClient);
     $token = $auth->getAuthToken($code);
     $this->assertInstanceOf('\\Yandex\\Auth\\Token', $token);
     $this->assertEquals($token->getToken(), 'ea135929105c4f29a0f5117d2960926f');
 }
 /**
  * {@inheritdoc}
  */
 protected function validateResponse(Response $response)
 {
     $content = $response->getContent();
     $success = false;
     $xml = new \DOMDocument();
     if ($xml->loadXML($content)) {
         foreach ($xml->firstChild->childNodes as $child) {
             if ($child->nodeName === 'cas:authenticationSuccess') {
                 $root = $child;
                 $success = true;
                 break;
             } elseif ($child->nodeName === 'cas:authenticationFailure') {
                 $root = $child;
                 $success = false;
                 break;
             }
         }
         if ($success) {
             foreach ($root->childNodes as $child) {
                 switch ($child->nodeName) {
                     case 'cas:user':
                         $this->username = $child->textContent;
                         break;
                     case 'cas:attributes':
                         foreach ($child->childNodes as $attr) {
                             if ($attr->nodeName != '#text') {
                                 $this->attributes[$attr->nodeName] = $attr->textContent;
                             }
                         }
                         break;
                     case 'cas:attribute':
                         $name = $child->attributes->getNamedItem('name')->value;
                         $value = $child->attributes->getNamedItem('value')->value;
                         if ($name && $value) {
                             $this->attributes[$name] = $value;
                         }
                         break;
                     case '#text':
                         break;
                     default:
                         $this->attributes[substr($child->nodeName, 4)] = $child->textContent;
                 }
             }
         } else {
             $this->error = (string) $root->textContent;
         }
     } else {
         $success = false;
         $this->error = 'Invalid response';
     }
     return $success;
 }
 /**
  * {@inheritdoc}
  */
 protected function validateResponse(Response $response)
 {
     $content = $response->getContent();
     $data = explode("\n", str_replace("\n\n", "\n", str_replace("\r", "\n", $content)));
     $success = strtolower($data[0]) === 'yes';
     $message = count($data) > 1 && $data[1] ? $data[1] : null;
     if ($success) {
         $this->username = $message;
     } else {
         $this->error = $message;
     }
     return $success;
 }
 /**
  * @test
  */
 public function shouldAllowFactoryHttpExceptionFromRequestAndResponse()
 {
     $request = new Request();
     $request->setHost('http://example.com');
     $request->setResource('/foobar');
     $response = new Response();
     $response->setHeaders(array('HTTP/1.1 404 Not Found'));
     $httpException = HttpException::factory($request, $response);
     $this->assertInstanceOf('Payum\\Core\\Exception\\Http\\HttpException', $httpException);
     $this->assertSame($request, $httpException->getRequest());
     $this->assertSame($response, $httpException->getResponse());
     $this->assertEquals("Client error response\n[status code] 404\n[reason phrase] Not Found\n[url] http://example.com/foobar", $httpException->getMessage());
     $this->assertEquals(404, $httpException->getCode());
 }
Пример #30
0
    public function testGetStationBoardDelay()
    {
        $response = new Response();
        $response->setContent(file_get_contents(__DIR__ . '/../../fixtures/archive/stationboard-2013-10-15.xml'));
        $this->browser->expects($this->once())->method('post')->with($this->equalTo('http://fahrplan.sbb.ch/bin/extxml.exe/'), $this->equalTo(array('User-Agent: SBBMobile/4.8 CFNetwork/609.1.4 Darwin/13.0.0', 'Accept: application/xml', 'Content-Type: application/xml')), $this->equalTo('<?xml version="1.0" encoding="iso-8859-1"?>
<ReqC lang="EN" prod="iPhone3.1" ver="2.3" accessId="vWjygiRIy0uclbLz4qDO7S3G4dcIIViwoLFCZlopGhe88vlsfedGIqctZP9lvqb"><STBReq boardType="DEP" maxJourneys="40"><Time>22:20</Time><Period><DateBegin><Date>20131015</Date></DateBegin><DateEnd><Date>20131015</Date></DateEnd></Period><TableStation externalId="008591052"/><ProductFilter>1111111111111111</ProductFilter></STBReq></ReqC>
'))->will($this->returnValue($response));
        $station = new Station('008591052');
        // Zürich, Bäckeranlage
        $journeys = $this->api->getStationBoard(new StationBoardQuery($station, \DateTime::createFromFormat(\DateTime::ISO8601, '2013-10-15T22:20:00+01:00')));
        $this->assertEquals(1, count($journeys));
        $this->assertEquals('2013-10-15T22:10:00+0100', $journeys[0]->stop->departure);
        $this->assertEquals(12, $journeys[0]->stop->delay);
    }