Ejemplo n.º 1
0
 public function testRedirectsRequests()
 {
     $mock = new Mock();
     $history = new History();
     $mock->addMultiple(["HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect1\r\nContent-Length: 0\r\n\r\n", "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect2\r\nContent-Length: 0\r\n\r\n", "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"]);
     $client = new Client(['base_url' => 'http://test.com']);
     $client->getEmitter()->attach($history);
     $client->getEmitter()->attach($mock);
     $request = $client->createRequest('GET', '/foo');
     // Ensure "end" is called only once
     $called = 0;
     $request->getEmitter()->on('end', function () use(&$called) {
         $called++;
     });
     $response = $client->send($request);
     $this->assertEquals(200, $response->getStatusCode());
     $this->assertContains('/redirect2', $response->getEffectiveUrl());
     // Ensure that two requests were sent
     $requests = $history->getRequests(true);
     $this->assertEquals('/foo', $requests[0]->getPath());
     $this->assertEquals('GET', $requests[0]->getMethod());
     $this->assertEquals('/redirect1', $requests[1]->getPath());
     $this->assertEquals('GET', $requests[1]->getMethod());
     $this->assertEquals('/redirect2', $requests[2]->getPath());
     $this->assertEquals('GET', $requests[2]->getMethod());
     $this->assertEquals(1, $called);
 }
Ejemplo n.º 2
0
 public function testSend()
 {
     $self = $this;
     $eventsDispatched = [];
     $history = new History();
     $mock = new Mock();
     $mockRequestData = ['foo' => 'bar', 'token' => self::TOKEN];
     $mockResponseData = ['ok' => true, 'foo' => 'bar'];
     $mockPayload = new MockPayload();
     $mockPayload->setFoo('bar');
     $mockResponseBody = json_encode($mockResponseData);
     $mock->addResponse(sprintf("HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n%s", strlen($mockResponseBody), $mockResponseBody));
     $client = new Client();
     $client->getEmitter()->attach($history);
     $client->getEmitter()->attach($mock);
     $apiClient = new ApiClient(self::TOKEN, $client);
     $apiClient->addRequestListener(function (RequestEvent $event) use(&$eventsDispatched, $mockRequestData, $self) {
         $eventsDispatched[ApiClient::EVENT_REQUEST] = true;
         $self->assertEquals($mockRequestData, $event->getRawPayload());
     });
     $apiClient->addResponseListener(function (ResponseEvent $event) use(&$eventsDispatched, $mockResponseData, $self) {
         $eventsDispatched[ApiClient::EVENT_RESPONSE] = true;
         $self->assertEquals($mockResponseData, $event->getRawPayloadResponse());
     });
     $apiClient->send($mockPayload);
     $lastRequest = $history->getLastRequest();
     $expectedUrl = ApiClient::API_BASE_URL . 'mock';
     parse_str($lastRequest->getBody()->__toString(), $lastRequestContent);
     $lastResponseContent = json_decode($history->getLastResponse()->getBody(), true);
     $this->assertEquals($mockRequestData, $lastRequestContent);
     $this->assertEquals($mockResponseData, $lastResponseContent);
     $this->assertEquals($expectedUrl, $history->getLastRequest()->getUrl());
     $this->assertArrayHasKey(ApiClient::EVENT_REQUEST, $eventsDispatched);
     $this->assertArrayHasKey(ApiClient::EVENT_RESPONSE, $eventsDispatched);
 }
 public function testGetAdData()
 {
     $response = $this->getResponse(dirname(__DIR__) . '/content/ad_897011669.html');
     $mock = new Mock();
     $mock->addResponse($response);
     $mock->addResponse($response);
     $getFrom = new GetFrom();
     $getFrom->getHttpClient()->getEmitter()->attach($mock);
     $getFrom->getHttpClient()->getEmitter()->attach($mock);
     $dataByUrl = $getFrom->ad('http://www.leboncoin.fr/ventes_immobilieres/897011669.htm?ca=3_s');
     $dataById = $getFrom->ad('897011669', 'ventes_immobilieres');
     $this->assertEquals($dataById, $dataByUrl);
     $this->assertEquals('897011669', $dataById['id']);
     $this->assertEquals('ventes_immobilieres', $dataById['category']);
     $this->assertEquals(3, count($dataById['thumbs']));
     $this->assertEquals(3, count($dataById['pictures']));
     $this->assertEquals('Appartement F3 de 71m2,Clermont-fd hyper centre', $dataById['title']);
     $this->assertEquals('63000', $dataById['cp']);
     $this->assertEquals('Clermont-Ferrand', $dataById['city']);
     $this->assertEquals(118000, $dataById['price']);
     $this->assertEquals('Appartement', $dataById['criterias']['type_de_bien']);
     $this->assertEquals('3', $dataById['criterias']['pieces']);
     $this->assertEquals('71 m2', $dataById['criterias']['surface']);
     $this->assertEquals('E (de 36 à 55)', $dataById['criterias']['ges']);
     $this->assertEquals('D (de 151 à 230)', $dataById['criterias']['classe_energie']);
     $this->assertNotEmpty($dataById['description']);
 }
 public function testResportSpamResponseValid()
 {
     $client = new Client();
     $mock = new Mock();
     $mock->addResponse(__DIR__ . '/raw/reportspam-valid.txt');
     $client->getEmitter()->attach($mock);
     $response = $client->get();
     $this->assertEquals('Thanks for making the web a better place.', trim($response->getBody()));
 }
Ejemplo n.º 5
0
 public function testGetUsersResponse()
 {
     $client = new Client();
     $mock = new Mock();
     $mock->addResponse(__DIR__ . '/responses/getCompetitorResponse.txt');
     $client->getEmitter()->attach($mock);
     $db = new Rankinity('foo_api_key', $client);
     $result = $db->project('project_id')->getCompetitors();
     $this->assertEquals(1, count($result->competitors));
 }
Ejemplo n.º 6
0
 public function testIsSpamResponseMissingRequiredValues()
 {
     $client = new Client();
     $mock = new Mock();
     $mock->addResponse(__DIR__ . '/raw/isspam-missing.txt');
     $client->getEmitter()->attach($mock);
     $response = $client->get();
     $this->assertTrue($response->hasHeader("X-akismet-server"));
     $this->assertTrue($response->hasHeader("X-akismet-debug-help"));
     $this->assertSame('Empty "user_ip" value', $response->getHeader('X-akismet-debug-help'));
     $this->assertEquals('Missing required field: user_ip.', trim($response->getBody()));
 }
 public function testRegisterPlugin()
 {
     $client = new Client(['base_url' => 'http://example.com']);
     $client->getEmitter()->attach($this->getPlugin());
     $mock = new Mock();
     $mock->addResponse(new Response(200));
     $client->getEmitter()->attach($mock);
     $request = $client->createRequest('GET', '/resource/1');
     $client->send($request);
     $authorization = (string) $request->getHeader('Authorization');
     $this->assertRegExp('@Acquia 1:([a-zA-Z0-9+/]+={0,2})$@', $authorization);
 }
 public function testValidateKeyResponseMissing2()
 {
     $client = new Client();
     $mock = new Mock();
     $mock->addResponse(__DIR__ . '/raw/validatekey-invalid-missing2.txt');
     $client->getEmitter()->attach($mock);
     $response = $client->get();
     $this->assertTrue($response->hasHeader("X-akismet-server"));
     $this->assertTrue($response->hasHeader("X-akismet-debug-help"));
     $this->assertEquals('Empty "key" value', $response->getHeader("X-akismet-debug-help"));
     $this->assertEquals('invalid', trim($response->getBody()));
 }
Ejemplo n.º 9
0
 /**
  * @expectedException \Columnis\Exception\Api\ApiRequestException
  */
 public function testRequestFail()
 {
     $serviceManager = Bootstrap::getServiceManager();
     $apiService = $serviceManager->get('Columnis\\Service\\ApiService');
     /* @var $apiService ApiService */
     $plugin = new Mock();
     $plugin->addResponse(Bootstrap::getTestFilesDir() . 'api-responses' . DIRECTORY_SEPARATOR . 'forbidden.mock');
     $mockedClient = $apiService->getHttpClient();
     $mockedClient->getEmitter()->attach($plugin);
     $endpoint = '/non/existant/endpoint';
     $uri = $apiService->getUri($endpoint);
     $apiService->request($uri);
 }
Ejemplo n.º 10
0
 public function testDeleteWebhook()
 {
     $data = ['success' => 1];
     $client = $this->getClient();
     $mock = new Mock();
     $mockResponseBody = Stream::factory(json_encode($data));
     $mockResponse = new Response(200, [], $mockResponseBody);
     $mock->addResponse($mockResponse);
     $client->getEmitter()->attach($mock);
     // Deletes a Webhook
     $webhook = $client->deleteWebhook('http://example1.com/webhooks');
     $this->assertEquals($data, $webhook->json());
 }
Ejemplo n.º 11
0
 /**
  * @testdox Calling resolveUri anonymously returns correct resolved target uri.
  * @medium
  * @group integration
  */
 public function testResolveUriAnonymous()
 {
     $playlistId = getenv('playlist_id') ?: '1';
     $playlistUri = getenv('playlist_uri') ?: 'https://soundcloud.com/myUsername/sets/myPlaylist';
     $location = 'http://soundcloud.com/resolved/' . $playlistId;
     $location .= '?client_id=' . $this->soundcloud->getAuthSubscriber()->getClientId();
     if (isset($this->mock)) {
         $this->mock->addMultiple([new Response(302, ['Location' => $location]), new Response(200)]);
     }
     $result = $this->soundcloud->resolveUri($playlistUri);
     $this->assertEquals(1, preg_match('/(\\d+)/', $result, $matches));
     $this->assertEquals($playlistId, $matches[1]);
     if (isset($this->mock)) {
         $this->assertEquals($location, $result);
     }
 }
Ejemplo n.º 12
0
 /**
  * @expectedException \Columnis\Exception\Page\PageWithoutTemplateException
  */
 public function testFetchWithoutTemplate()
 {
     $serviceManager = Bootstrap::getServiceManager();
     $pageService = $serviceManager->get('Columnis\\Service\\PageService');
     /* @var $pageService \Columnis\Service\PageService */
     $apiService = $pageService->getApiService();
     $plugin = new Mock();
     $plugin->addResponse(Bootstrap::getTestFilesDir() . 'api-responses' . DIRECTORY_SEPARATOR . 'generate-invalid.mock');
     $mockedClient = $apiService->getHttpClient();
     $mockedClient->getEmitter()->attach($plugin);
     $page = new Page();
     $page->setId(1);
     $pageService->fetch($page);
 }
Ejemplo n.º 13
0
 /**
  * @expectedException \OutOfBoundsException
  */
 public function testUpdateThrowsExceptionWhenEmpty()
 {
     $p = new Mock();
     $ev = new BeforeEvent(new Transaction(new Client(), new Request('GET', '/')));
     $p->onBefore($ev);
 }
Ejemplo n.º 14
0
 public function testUpdatesTokenFieldsOnFetch()
 {
     $testConfig = $this->fetchAuthTokenMinimal;
     $wanted_updates = ['expires_at' => '1', 'expires_in' => '57', 'issued_at' => '2', 'access_token' => 'an_access_token', 'id_token' => 'an_id_token', 'refresh_token' => 'a_refresh_token'];
     $json = json_encode($wanted_updates);
     $client = new Client();
     $plugin = new Mock();
     $plugin->addResponse(new Response(200, [], Stream::factory($json)));
     $client->getEmitter()->attach($plugin);
     $o = new OAuth2($testConfig);
     $this->assertNull($o->getExpiresAt());
     $this->assertNull($o->getExpiresIn());
     $this->assertNull($o->getIssuedAt());
     $this->assertNull($o->getAccessToken());
     $this->assertNull($o->getIdToken());
     $this->assertNull($o->getRefreshToken());
     $tokens = $o->fetchAuthToken($client);
     $this->assertEquals(1, $o->getExpiresAt());
     $this->assertEquals(57, $o->getExpiresIn());
     $this->assertEquals(2, $o->getIssuedAt());
     $this->assertEquals('an_access_token', $o->getAccessToken());
     $this->assertEquals('an_id_token', $o->getIdToken());
     $this->assertEquals('a_refresh_token', $o->getRefreshToken());
 }
Ejemplo n.º 15
0
 /**
  * @expectedException Eva\EvaOAuth\Exception\RequestException
  */
 public function testGetAccessTokenFailed()
 {
     $this->mock->addResponse(new Response(400, [], Stream::factory('error happened')));
     $this->consumer->getAccessToken(new Twitter(), ['oauth_token' => 'test_request_token', 'oauth_verifier' => 'test_request_token_verifier'], new RequestToken('test_request_token', 'test_request_token_secret'));
 }
Ejemplo n.º 16
0
 public function addMockResponse($status, $body = '')
 {
     $this->mock->addResponse(new Response($status, [], Stream::factory($body)));
 }
Ejemplo n.º 17
0
 /**
  * Build a fake guzzle client so we don't actually send requests.
  *
  * @param $textfile
  * @return \GuzzleHttp\Client
  */
 private function buildMockClient($textfile)
 {
     $client = new Client();
     $mockResponse = new Response(200);
     $mockResponseBody = Stream::factory(fopen(__DIR__ . '/../../../tests/' . $textfile . '.txt', 'r+'));
     $mockResponse->setBody($mockResponseBody);
     $mock = new Mock();
     $mock->addResponse($mockResponse);
     $client->getEmitter()->attach($mock);
     return $client;
 }
Ejemplo n.º 18
0
 public function testListEntities()
 {
     $data = $this->setListOfEntities();
     $client = $this->getClient();
     $mock = new Mock();
     $mockResponseBody = Stream::factory(json_encode($data));
     $mockResponse = new Response(200, [], $mockResponseBody);
     $mock->addResponse($mockResponse);
     $client->getEmitter()->attach($mock);
     // Listing entities
     $options = ['limit' => 20, 'type' => 'node', 'origin' => '11111111-1111-1111-1111-111111111111', 'fields' => 'status,title,body,field_tags,description', 'filters' => ['status' => 1, 'title' => 'New*', 'body' => '/Custom/']];
     $response = $client->listEntities($options);
     $this->assertEquals($data, $response);
 }
Ejemplo n.º 19
0
 protected function addResponse($json)
 {
     $response = new Guzzle\Message\Response(200, [], Guzzle\Stream\Stream::factory($json));
     $this->mock->addResponse($response);
 }
 /**
  * @expectedException \Wonnova\SDK\Exception\RuntimeException
  */
 public function testUnsupportedStatusThrowsRuntimeException()
 {
     $body = new Stream(fopen('data://text/plain,[]', 'r'));
     $this->subscriber->addResponse(new Response(403, [], $body));
     $this->client->getUsers();
 }
 private function mockResponse($status, $body = null)
 {
     $mock = new Mock();
     if ($status === 200) {
         $mock->addResponse(new Response($status, array(), $body === null ? null : Stream::factory($body)));
     } else {
         $mock->addException(new RequestException('Exception', new Request('GET', 'http://graph.facebook.com/xyz')));
     }
     $this->guzzleClient->getEmitter()->attach($mock);
 }