public function testHandles404RevalidationResponses() { $request = new Request('GET', 'http://foo.com'); $request->setClient(new Client()); $badResponse = new Response(404, array(), 'Oh no!'); $badRequest = clone $request; $badRequest->setResponse($badResponse, true); $response = new Response(200, array(), 'foo'); $plugin = new CachePlugin(); $c = new ArrayCache(); $c->save('foo', array(200, array(), 'foo')); $s = new DefaultCacheStorage(new DoctrineCacheAdapter($c)); $k = new CallbackCacheKeyProvider(function () { return 'foo'; }); $rev = $this->getMockBuilder('Guzzle\\Plugin\\Cache\\DefaultRevalidation')->setConstructorArgs(array($k, $s, $plugin))->setMethods(array('createRevalidationRequest'))->getMock(); $rev->expects($this->once())->method('createRevalidationRequest')->will($this->returnValue($badRequest)); try { $rev->revalidate($request, $response); $this->fail('Should have thrown an exception'); } catch (BadResponseException $e) { $this->assertSame($badResponse, $e->getResponse()); $this->assertFalse($c->fetch('foo')); } }
public function setUp() { $this->client = $this->getSimpleMock('Guzzle\\Http\\ClientInterface'); $this->facade = new RequestCollectionFacade($this->client); $this->request = new Request('GET', '/_request/last'); $this->request->setClient($this->client); }
/** * @param Request $request * @return array|null * @throws BadResponseException * @throws FormatException */ protected function proceedResponse(Request $request) { try { $response = $request->send(); } catch (ClientErrorResponseException $e) { $response = $e->getResponse(); } $body = $response->getBody(true); if (empty($body) && $response->getStatusCode() >= 200 && $response->getStatusCode() < 300) { return null; } $result = json_decode($body, true); if ($result === null) { # When response is just a sting. $result = $body; } if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) { return $result; } if (!$result || !$result['error']) { throw new FormatException('Not valid error response', 3, null, $request, $response); } $message = $result['error']['message']; $code = $result['error']['code']; if ($response->getStatusCode() == 429) { throw new RateLimitException($message, $code, null, $request, $response); } $e = new BadResponseException($message, $code, null, $request, $response); $e->setError($result['error']); throw $e; }
protected function generateRequest($url, array $subProtocols, array $headers) { $headers = array_merge($this->defaultHeaders, $headers); $headers['Sec-WebSocket-Key'] = $this->generateKey(); $request = new Request('GET', $url, $headers); $scheme = strtolower($request->getScheme()); if (!in_array($scheme, ['ws', 'wss'])) { throw new \InvalidArgumentException(sprintf('Cannot connect to invalid URL (%s)', $url)); } $request->setScheme('HTTP'); if (!$request->getPort()) { $request->setPort('wss' === $scheme ? 443 : 80); } else { $request->setHeader('Host', $request->getHeader('Host') . ":{$request->getPort()}"); } if (!$request->getHeader('Origin')) { $request->setHeader('Origin', str_replace('ws', 'http', $scheme) . '://' . $request->getHost()); } // do protocol headers if (count($subProtocols) > 0) { $protocols = implode(',', $subProtocols); if ($protocols != "") { $request->setHeader('Sec-WebSocket-Protocol', $protocols); } } return $request; }
public function testOnRequestBeforeSendPOST() { $request = new Request('POST', 'www.url.com'); $event = new Event(array('request' => $request)); $this->plugin->onRequestBeforeSend($event); $this->assertContains('key=' . $this->key, $request->getUrl()); }
function it_set_up_request_custom_authentication_when_provided(Request $request, RequestBuilder $builder) { $this->beConstructedWith('digest'); $request->setAuth('username', 'password', 'digest')->shouldBeCalled(1); $builder->getCredentials()->shouldBeCalled()->willReturn(['username' => 'username', 'password' => 'password']); $this->secureRequest($request, $builder); }
public function debug() { $r = new Response(); var_dump($r->getReasonPhrase()); $req = new Request(); $req->getPath(); }
/** * @param \Guzzle\Http\Message\Request $request * @param string $username * @param string $password * * @return \BigOven\BigOvenAuthPlugin */ public function addAuthorizationHeader(Request $request, $username, $password) { $encodedString = base64_encode($username . ':' . $password); $headerValue = 'Basic ' . $encodedString; $request->addHeader('Authorization', $headerValue); return $this; }
public function secureRequest(Request $request, RequestBuilder $builder) { $credentials = $builder->getCredentials(); if (!isset($credentials['username']) || !isset($credentials['password'])) { throw new \RuntimeException('You must specified a "username" and a "password" for the http basic authentication.'); } $request->setAuth($credentials['username'], $credentials['password']); }
/** * Guzzle should take care of encoding signatures. This test is just a safety net to ensure that happens. */ public function testUrlEncodedSignature() { $expected = '1234 ] 5678'; $request = new Request('GET', "/fake?signature={$expected}"); $url = explode('signature=', $request->getUrl()); $signature = end($url); $this->assertEquals(rawurlencode($expected), $signature, 'Request should be encoding the signature before sending (required by Ooyala).'); }
/** * is test connection * @return boolean */ private function isTestConnection() { $url = $this->request->getUrl(true); if ($url->getPath() == '/k/v1/form.json' && $url->getQuery()->get('app') == -1) { // 通信テスト成功 return true; } return false; }
private function fireRequest(GuzzleRequest $request, $cookie) { try { $response = $request->addCookie('authenticator', $cookie)->send(); return $response->json(); } catch (\Guzzle\Http\Exception\BadResponseException $client_error) { return $this->app->abort($client_error->getResponse()->getStatusCode(), $client_error->getResponse()->getReasonPhrase()); } }
/** * @test * @expectedException PHPSC\PagSeguro\Client\PagSeguroException */ public function handleErrorShouldRaiseExceptionWhenHostIsFromPagSeguro() { $client = new Client($this->httpClient); $event = new Event(['request' => $this->request, 'response' => $this->response]); $this->request->expects($this->any())->method('getHost')->willReturn(Production::WS_HOST); $this->response->expects($this->any())->method('getStatusCode')->willReturn(401); $this->response->expects($this->any())->method('getBody')->willReturn('Unauthorized'); $client->handleError($event); }
public function testOnRequestBeforeSend() { $request = new Request('GET', 'https://example.com'); $event = new Event(['request' => $request]); $oauth = new OAuth('example'); $oauth->onRequestBeforeSend($event); $this->assertTrue($request->getQuery()->hasKey('access_token')); $this->assertEquals('example', $request->getQuery()->get('access_token')); }
public function testCreatesPreSignedUrlWithXAmzHeaders() { $signature = new S3Signature(); $request = new Request('GET', 'https://s3.amazonaws.com', array('X-Amz-Acl' => 'public-read')); $c = $this->getServiceBuilder()->get('s3'); $request->setClient($c); $this->assertContains('x-amz-acl:public-read', $signature->createCanonicalizedString($request, time())); $this->assertContains('&x-amz-acl=public-read', $signature->createPresignedUrl($request, $c->getCredentials(), time())); }
public function request(Request $request) { try { $response = $request->send(); } catch (\Exception $e) { throw new ApiException($e->getMessage(), $e->getCode(), $e); } $apiResponse = new ApiResponse($response->getBody(), $response->getStatusCode(), $response->getContentType()); return $apiResponse; }
/** * @covers Aws\Common\Signature\AbstractSignature::getCanonicalizedQueryString * @dataProvider queryStringProvider */ public function testCreatesCanonicalizedQueryString($headers, $string) { // Make the method publicly callable $method = new \ReflectionMethod('Aws\\Common\\Signature\\AbstractSignature', 'getCanonicalizedQueryString'); $method->setAccessible(true); // Create a request and replace the headers with the test headers $request = new Request('GET', 'http://www.example.com'); $request->getQuery()->replace($headers); $this->assertEquals($string, $method->invoke($this->signature, $request)); }
/** * @covers PusherSignature::signRequest */ public function testAssertEmptyParametersAreStrippedWhenSignRequest() { $request = new HttpRequest('POST', '/apps/3/events'); // We set variables in query to have always the same result $request->getQuery()->replace(array('key-with-value' => 'value', 'key-without-value' => '')); $this->pusherSignature->signRequest($request, $this->credentials); $queryParameters = $request->getQuery()->toArray(); $this->assertArrayHasKey('key-with-value', $queryParameters); $this->assertArrayNotHasKey('key-without-value', $queryParameters); }
public function printResult() { echo sprintf('%s %s : %s calls', strtoupper($this->request->getMethod()), $this->request->getUrl(), $this->nbCalls) . PHP_EOL; foreach ($this->httpTimeDataCollector->getIterator() as $httpTimeResult) { echo sprintf('total time = %s ms', $httpTimeResult) . PHP_EOL; } echo '--- statistics ---' . PHP_EOL; echo sprintf('results filter on %s percentile', $this->httpTimeDataCollector->getPercentile()) . PHP_EOL; echo sprintf('min/avg/max = %s/%s/%s ms', $this->httpTimeDataCollector->getMinTime(), $this->httpTimeDataCollector->getAverageTime(), $this->httpTimeDataCollector->getMaxTime()) . PHP_EOL; }
/** * Actual health check logic. * * @param HealthBuilder $builder * * @throws \Exception any Exception that should create a Status::DOWN * system status. */ protected function doHealthCheck(HealthBuilder $builder) { /** @var Response $response */ $response = $this->request->send(); $builder->withDetail('statusCode', $response->getStatusCode()); if (!$response->isSuccessful()) { $builder->down()->withDetail('body', $response->getBody(true)); return; } $builder->up(); }
public function setRequestAuthentication(\Guzzle\Http\Message\Request $request) { $oauthAccessToken = $this->configuration->get('oauthAccessToken'); // Do we have an oAuth2 access token? if (!empty($oauthAccessToken)) { $request->setHeader('Authorization', 'Bearer ' . $oauthAccessToken); } else { // Otherwise, use basic authentication $request->setAuth($this->configuration->get('apiToken'), $this->configuration->get('apiSecret')); } return $request; }
public function testFiltersCacheKey() { $request = new Request('GET', 'http://foo.com?a=b&c=d', array('Abc' => '123', 'Def' => '456')); $request->getParams()->set(DefaultCacheKeyProvider::CACHE_KEY_FILTER, 'header=Def; query=c'); $provider = new DefaultCacheKeyProvider(); $provider->getCacheKey($request); $this->assertNotEmpty($request->getParams()->get(DefaultCacheKeyProvider::CACHE_KEY)); $cloned = clone $request; $cloned->getQuery()->remove('c'); $cloned->removeHeader('Def'); $this->assertEquals((string) $cloned, $request->getParams()->get(DefaultCacheKeyProvider::CACHE_KEY_RAW)); }
public function testListenerShouldAppendToRemoteHeadersAddTokenHeader() { $token = 'foo'; $requestStack = new RequestStack(); $plugin = new RequestTokenPlugin($token, $requestStack); $httpRequest = new \Symfony\Component\HttpFoundation\Request(); $httpRequest->headers->set('x-remote-request-token', 'bar'); $requestStack->push($httpRequest); $guzzleRequest = new Request('GET', 'http://example.com'); $event = new Event(array('request' => $guzzleRequest)); $plugin->onBeforeRequestSend($event); $this->assertEquals('bar foo', $guzzleRequest->getHeaders()->get('x-remote-request-token')); }
/** * @covers Aws\Common\Signature\SignatureListener */ public function testSignsRequestsProperly() { $request = new Request('GET', 'http://www.example.com'); $request->getEventDispatcher(); $credentials = new Credentials('a', 'b'); $signature = $this->getMock('Aws\\Common\\Signature\\SignatureV4'); // Ensure that signing the request occurred once with the correct args $signature->expects($this->once())->method('signRequest')->with($this->equalTo($request), $this->equalTo($credentials)); $listener = new SignatureListener($credentials, $signature); // Create a mock event $event = new Event(array('request' => $request)); $listener->onRequestBeforeSend($event); }
public function fromRequest(Request $request, $secretKey) { $method = strtolower($request->getMethod()); switch ($method) { case 'post': case 'patch': case 'put': case 'delete': $body = (string) $request->getBody(); break; default: $body = $request->getQuery(true); } return $this->generate($body, $secretKey); }
public function testUpdatesRequestForRetry() { $request = new Request('GET', 'http://www.example.com'); $request->setState('transfer'); $response = new Response(500); $handle = $this->getMockBuilder('Guzzle\\Http\\Curl\\CurlHandle')->disableOriginalConstructor()->getMock(); $e = new CurlException(); $e->setCurlHandle($handle); $plugin = new BackoffPlugin(new ConstantBackoffStrategy(10)); $plugin->addSubscriber($this); $event = new Event(array('request' => $request, 'response' => $response, 'exception' => $e)); $plugin->onRequestSent($event); $this->assertEquals(array('request' => $request, 'response' => $response, 'handle' => $handle, 'retries' => 1, 'delay' => 10), $this->readAttribute($this->retried, 'context')); $plugin->onRequestSent($event); $this->assertEquals(array('request' => $request, 'response' => $response, 'handle' => $handle, 'retries' => 2, 'delay' => 10), $this->readAttribute($this->retried, 'context')); }
private function generateAuthHeader(Request $request, $timestamp, $nonce) { $url = $request->getUrl(); $hash = $this->getSHA1(md5(self::$consumer_secret), $this->urlencode($url)); $headers = ['OAuth realm' => '']; $headers[self::$keys['OAuthVersionKey']] = self::$oAuthVersion; $headers[self::$keys['OAuthTimestampKey']] = $timestamp; $headers[self::$keys['OAuthNonceKey']] = $nonce; $headers[self::$keys['OAuthSignatureMethodKey']] = 'HMAC-SHA1'; $headers[self::$keys['OAuthConsumerKeyKey']] = self::$consumer_key; $headers[self::$keys['OAuthSignatureKey']] = $hash; $h = []; foreach ($headers as $name => $value) { $h[] = $name . '="' . $value . '"'; } return implode(',', $h); }
public function setState($state, array $context = array()) { parent::setState($state, $context); if ($state == self::STATE_TRANSFER && !$this->body && !count($this->postFields) && !count($this->postFiles)) { $this->setHeader('Content-Length', 0)->removeHeader('Transfer-Encoding'); } return $this->state; }
/** * Function to send the request to the remote API * * @return \Trucker\Responses\Response */ public function sendRequest() { try { $response = $this->request->send(); } catch (\Guzzle\Http\Exception\BadResponseException $e) { $response = $e->getResponse(); } return $this->app->make('trucker.response')->newInstance($this->app, $response); }
public function send() { try { return parent::send(); } catch (BadResponseException $e) { $response = $e->getResponse(); $data = json_decode($response->getBody()); throw new GroongaException($data[0][3]); } }