Example #1
0
 public function testGetLastRequest()
 {
     $request = new HttpClients\Message\Request('');
     $this->mockHandler->append(new Response('200'));
     $this->client->send($request);
     $this->assertSame($request, $this->client->getLastRequest());
 }
 protected function shouldHaveMadeATokenRequest()
 {
     $lastRequest = $this->mockHandler->getLastRequest();
     $this->assertEquals('POST', $lastRequest->getMethod());
     $this->assertEquals($this->apiBaseUrl . '/oauth/token', $lastRequest->getUri());
     $requestBody = $lastRequest->getBody();
     $expectedBody = new MultipartStream([['name' => 'grant_type', 'contents' => 'authorization_code'], ['name' => 'code', 'contents' => $this->authorization->getCode()], ['name' => 'redirect_uri', 'contents' => $this->clientConfig->getParams()['redirect_uri']], ['name' => 'client_id', 'contents' => $this->clientConfig->getParams()['client_id']]], $requestBody->getBoundary());
     $this->assertEquals((string) $expectedBody, (string) $requestBody);
 }
 public function shouldHaveMadeATokenRequest()
 {
     $lastRequest = $this->mockHandler->getLastRequest();
     $requestParams = $this->getRequestParams();
     $this->assertEquals('POST', $lastRequest->getMethod());
     $this->assertEquals($this->getTokenEndpoint(), $lastRequest->getUri());
     $this->assertInstanceOf(MultipartStream::class, $lastRequest->getBody());
     $expectedBody = new MultipartStream($requestParams, $lastRequest->getBody()->getBoundary());
     $this->assertEquals((string) $expectedBody, (string) $lastRequest->getBody());
 }
Example #4
0
 /**
  * @param Response|RequestException|string $response
  * @param string $language
  */
 protected function mockResponse($response, $language = 'en')
 {
     $this->api();
     if (is_string($response)) {
         $this->mock->append(new Response(200, ['Content-Type' => 'application/json; charset=utf-8', 'Content-Language' => $language], Psr7\stream_for($response)));
     } elseif ($response instanceof RequestException) {
         $this->mock->append($response);
     } else {
         $this->mock->append($response);
     }
 }
 public function testRewind()
 {
     $users = $this->client->getRepository(User::class)->findAll();
     $this->assertInstanceOf(UserSet::class, $users);
     $this->guzzleMock->append(new Response(200, ['Content-Type' => 'application/json'], file_get_contents(__DIR__ . '/../Resources/http/admin/users@per_page=100&page=1.json')));
     $originalUser = $users->current();
     $users->next();
     $this->assertNotSame($originalUser, $users->current());
     $users->rewind();
     $this->assertSame($originalUser, $users->current());
 }
 /**
  * @test
  */
 public function it_uses_default_uri_when_non_is_specified()
 {
     $doSomething = new DoSomething(["data" => "test command"]);
     $messageProducer = $this->httpMessageProducer;
     $messageProducer($doSomething);
     $this->assertNotNull($this->mockHandler->getLastRequest());
     $request = $this->mockHandler->getLastRequest();
     $messageArr = json_decode($request->getBody(), true);
     $doSomethingArr = $doSomething->toArray();
     $doSomethingArr['created_at'] = $doSomething->createdAt()->format('Y-m-d\\TH:i:s.u');
     $this->assertEquals($doSomethingArr, $messageArr);
     $this->assertEquals('http://localhost:8080/api/messages', $request->getUri());
 }
Example #7
0
 public function testGetTournamentPrizePool()
 {
     $file = file_get_contents('./tests/Responses/getTournamentPrizePool.json');
     $this->mockHandler->append(new Response('200', [], $file));
     $response = $this->client->getTournamentPrizePool();
     $this->assertArraySubset(json_decode($file, true), $response->getJson());
 }
Example #8
0
 /**
  * Instantiate a client
  */
 public function doSetup($requestNumber)
 {
     $handler = new MockHandler([]);
     for ($i = 0; $i < $requestNumber; $i++) {
         $handler->append(new Response(200));
     }
     $guzzle = new GuzzleClient(["handler" => $handler]);
     $this->requestFactory = $this->getMock('Silktide\\SemRushApi\\Model\\Factory\\RequestFactory');
     $this->request = $this->getMockBuilder('Silktide\\SemRushApi\\Model\\Request')->disableOriginalConstructor()->getMock();
     $this->requestFactory->expects($this->exactly($requestNumber))->method('create')->willReturn($this->request);
     $this->resultFactory = $this->getMockBuilder('Silktide\\SemRushApi\\Model\\Factory\\ResultFactory')->disableOriginalConstructor()->getMock();
     $result = $this->getMockBuilder('Silktide\\SemRushApi\\Model\\Result')->disableOriginalConstructor()->getMock();
     $this->resultFactory->expects($this->exactly(1))->method('create')->willReturn($result);
     $this->responseParser = $this->getMock('Silktide\\SemRushApi\\Helper\\ResponseParser');
     $urlBuilder = $this->getMock('Silktide\\SemRushApi\\Helper\\UrlBuilder');
     $this->instance = new Client($this->key, $this->requestFactory, $this->resultFactory, $this->responseParser, $urlBuilder, $guzzle);
 }
Example #9
0
 /**
  * Test get
  */
 public function testGet()
 {
     $responseData = ['success' => true];
     $this->mockHandler->append(new Response(200, [], json_encode($responseData)));
     // Make the call
     $endpoint = '/v4/blah';
     $params = ['some-param' => 'some-value'];
     $actualResponse = $this->api->get($endpoint, $params);
     $this->checkResponse('GET', $endpoint, $params, $responseData, $actualResponse, true);
 }
 /**
  * @covers ::load
  * @covers ::loadMultiple
  * @covers ::request
  * @covers ::parseResponse
  */
 public function testLoadWithAvailableExchangeRate()
 {
     $expectedExchangeRate = sprintf('%s.%s', mt_rand(), mt_rand());
     $httpResponse = $this->getMock(ResponseInterface::class);
     $httpResponse->expects($this->atLeastOnce())->method('getBody')->willReturn(sprintf('"EURUSP=X",%s', $expectedExchangeRate));
     $this->httpClientHandler->append($httpResponse);
     $exchangeRate = $this->sut->load('EUR', 'UAH');
     $this->assertInstanceOf('\\Commercie\\CurrencyExchange\\ExchangeRateInterface', $exchangeRate);
     $this->assertSame($expectedExchangeRate, $exchangeRate->getRate());
 }
Example #11
0
 public function createAccountInfoHandler()
 {
     $handler = new MockHandler();
     for ($i = 0; $i < 1000; $i++) {
         $handler->append(function () {
             $uid = 'diofu90ifgdf';
             $timestamp = time();
             $signatureValidator = new Signature();
             $signature = $signatureValidator->calculateSignature($timestamp . '_' . $uid, 'secret');
             return new Response(200, [], sprintf('{
                 "UID": "%s",
                 "UIDSignature": "%s",
                 "signatureTimestamp": "%d",
                 "statusCode": 200,
                 "errorCode": 0,
                 "statusReason": "OK",
                 "callId": "123456",
                 "time": "2015-03-22T11:42:25.943Z"
             }', $uid, $signature, $timestamp));
         });
     }
     $this->gigya = new Gigya('key', 'secret', null, null, ['guzzle' => ['handler' => new HandlerStack($handler)]]);
 }
Example #12
0
 /**
  * Test submitting a ticket
  */
 public function testSubmitTicket()
 {
     // Our sample data
     $sampleDescription = "Sample description";
     $sampleSubject = "Sample subject";
     $sampleEmail = "*****@*****.**";
     $samplePriority = 3;
     $sampleStatus = 4;
     // Mock a response from the response factory
     $mockResponse = $this->getMockBuilder('Silktide\\FreshdeskApi\\Response')->disableOriginalConstructor()->getMock();
     $this->responseFactoryMock->expects($this->atLeastOnce())->method('generateResponse')->willReturn($mockResponse);
     // Mock a guzzle response and add it to the queue
     $this->addMockResponse(200, ['Content-Type' => 'application/json'], '{"helpdesk_ticket" : {}}');
     // Submit ticket
     $response = $this->client->submitTicket($sampleDescription, $sampleSubject, $sampleEmail, $samplePriority, $sampleStatus);
     // Expected structure of request to Freshdesk
     $expectedRequestStructure = ['helpdesk_ticket' => ["description" => $sampleDescription, "subject" => $sampleSubject, "email" => $sampleEmail, "priority" => $samplePriority, "status" => $sampleStatus]];
     // Get the last request made and check it conforms
     $lastRequest = $this->guzzleMockHandler->getLastRequest();
     $this->assertEquals($this->domain . '/helpdesk/tickets.json', $lastRequest->getUri(), 'API URL called was incorrect');
     $this->assertEquals('POST', $lastRequest->getMethod(), 'Call should have been POST');
     $this->assertArrayMatches($expectedRequestStructure, json_decode($lastRequest->getBody()->__toString(), true), 'request body JSON');
     $this->assertSame($mockResponse, $response, 'Expected response object to be passed back');
 }
 public function testHttpDefaultSchemeIfUriHasNone()
 {
     $mockHandler = new MockHandler([new Response()]);
     $client = new Client(['handler' => $mockHandler]);
     $client->request('GET', '//example.org/test');
     $this->assertSame('http://example.org/test', (string) $mockHandler->getLastRequest()->getUri());
 }
 /**
  * @param string                       $method
  * @param string                       $url
  * @param array                        $headers
  * @param mixed                        $body
  * @param \Exception|ResponseInterface $responseOrException
  */
 protected function mockClientRequest($method, $url, array $headers, $body = null, $responseOrException)
 {
     // TODO it would be nice if we could assert the request arguments as well
     $this->handler->append($responseOrException);
 }
 public function testDoesNotAddRefererWhenGoingFromHttpsToHttp()
 {
     $mock = new MockHandler([new Response(302, ['Location' => 'http://test.com']), new Response(200)]);
     $stack = new HandlerStack($mock);
     $stack->push(Middleware::redirect());
     $handler = $stack->resolve();
     $request = new Request('GET', 'https://example.com?a=b');
     $promise = $handler($request, ['allow_redirects' => ['max' => 2, 'referer' => true]]);
     $promise->wait();
     $this->assertFalse($mock->getLastRequest()->hasHeader('Referer'));
 }
Example #16
0
 /**
  * @test
  *
  * Should get Guzzle response and JSON body
  */
 function itShouldReturnGuzzleResponseAndJsonBody()
 {
     $response = new Response(200, ['http_x_shopify_shop_api_call_limit' => '2/80'], file_get_contents(__DIR__ . '/fixtures/admin__shop.json'));
     $mock = new MockHandler([$response]);
     $client = new Client(['handler' => $mock]);
     $api = new BasicShopifyAPI();
     $api->setClient($client);
     $api->setShop('example.myshopify.com');
     $api->setApiKey('123');
     $api->setAccessToken('!@#');
     // Fake param just to test it receives it
     $request = $api->request('GET', '/admin/shop.json', ['limit' => 1]);
     $data = json_decode($mock->getLastRequest()->getBody());
     $token_header = $mock->getLastRequest()->getHeader('X-Shopify-Access-Token')[0];
     $this->assertEquals(true, is_object($request));
     $this->assertInstanceOf('GuzzleHttp\\Psr7\\Response', $request->response);
     $this->assertEquals(200, $request->response->getStatusCode());
     $this->assertEquals(true, is_object($request->body));
     $this->assertEquals('Apple Computers', $request->body->shop->name);
     $this->assertEquals(1, $data->limit);
     $this->assertEquals('!@#', $token_header);
 }
 /**
  * @expectedException \GuzzleHttp\Exception\BadResponseException
  */
 public function testCanCreateWithDefaultMiddleware()
 {
     $r = new Response(500);
     $mock = MockHandler::createWithMiddleware([$r]);
     $request = new Request('GET', 'http://example.com');
     $mock($request, ['http_errors' => true])->wait();
 }
 /**
  * Setup the response with Guzzle mock plugin
  *
  * @param string $responseFile
  */
 protected function setupResponse($responseFile)
 {
     $this->guzzleHandler->append(new Response(200, [], ResponseExampleHelper::getResponseExample($responseFile)));
 }
Example #19
0
 /**
  * @param string $token
  * @param Scope $scope
  * @param MockHandler $mockHandler
  */
 public function iAmReadyToRespondToATokenRequest($token, Scope $scope, MockHandler $mockHandler)
 {
     $mockHandler->append($this->rawTokenResponse($token, $scope));
 }
Example #20
0
 public function addRuntimeException(\GuzzleHttp\Handler\MockHandler $mock)
 {
     $mock->append(new \RuntimeException("Runtime error", 999));
 }