Author: Fabien Potencier (fabien@symfony.com)
Inheritance: extends Symfony\Component\BrowserKit\Client
 /**
  * @dataProvider provideIncorrectValues
  * @expectedException RuntimeException
  */
 public function testGetSessionDataIncorrectSessionData($value)
 {
     $cookie = new Cookie('TEST', $value);
     $client = new Client(new Application());
     $client->getCookieJar()->set($cookie);
     $this->getSessionData($client, 'TEST');
 }
 protected function makeRequest($method, $uri, $annotationOptions = array())
 {
     $this->getClient($annotationOptions);
     $this->client->request($method, $uri, array(), array(), $this->requestOptions);
     $response = $this->client->getResponse();
     return $response;
 }
 /**
  * test login
  */
 public function testLoginSuccess()
 {
     $data = array('username' => 'user', 'password' => 'password');
     $this->client->request('POST', $this->getUrl('api_login_check'), $data);
     $this->assertJsonResponse($this->client->getResponse(), 200);
     $response = json_decode($this->client->getResponse()->getContent(), true);
     $this->assertArrayHasKey('token', $response);
     // check token from query string work
     $client = static::createClient();
     $client->request('HEAD', $this->getUrl('api_ping', array($this->queryParameterName => $response['token'])));
     $this->assertJsonResponse($client->getResponse(), 200, false);
     // check token work
     $client = static::createClient();
     $client->setServerParameter('HTTP_Authorization', sprintf('%s %s', $this->authorizationHeaderPrefix, $response['token']));
     $client->request('HEAD', $this->getUrl('api_ping'));
     $this->assertJsonResponse($client->getResponse(), 200, false);
     // check token works several times, as long as it is valid
     $client = static::createClient();
     $client->setServerParameter('HTTP_Authorization', sprintf('%s %s', $this->authorizationHeaderPrefix, $response['token']));
     $client->request('HEAD', $this->getUrl('api_ping'));
     $this->assertJsonResponse($client->getResponse(), 200, false);
     // check a bad token does not work
     $client = static::createClient();
     $client->setServerParameter('HTTP_Authorization', sprintf('%s %s', $this->authorizationHeaderPrefix, $response['token'] . 'changed'));
     $client->request('HEAD', $this->getUrl('api_ping'));
     $this->assertJsonResponse($client->getResponse(), 401, false);
     // check error if no authorization header
     $client = static::createClient();
     $client->request('HEAD', $this->getUrl('api_ping'));
     $this->assertJsonResponse($client->getResponse(), 401, false);
 }
 /**
  * Do login with username
  *
  * @param string $username
  */
 private function doLogin($username = '******')
 {
     $crawler = $this->client->request('GET', $this->getUrl('fos_user_security_login', array()));
     $form = $crawler->selectButton('_submit')->form(array('_username' => $username, '_password' => 'qwerty'));
     $this->client->submit($form);
     $this->assertTrue($this->client->getResponse()->isRedirect());
     $this->client->followRedirects();
 }
 /**
  * @param string $method
  * @param string $url
  * @param array|null $content
  */
 private function sendRequest($method, $url, $content = null)
 {
     $header = array('HTTP_ACCEPT' => 'application/json');
     if ($method == 'POST') {
         $header['CONTENT_TYPE'] = 'application/json';
     }
     $this->client->request($method, $url, array(), array(), $header, json_encode($content));
 }
Esempio n. 6
0
 /**
  * @param string $uri
  * @param string $responseType
  */
 public function navigateToPageAndAssertSuccess($uri, $responseType = null)
 {
     $this->client->request('GET', $uri);
     $this->assertTrue($this->client->getResponse()->isSuccessful(), 'Navigation to ' . $uri . ' did not trigger a successful response.');
     if (null !== $responseType) {
         $responseTypeIsTheOneExpected = $this->client->getResponse()->headers->contains('Content-Type', $responseType);
         $this->assertTrue($responseTypeIsTheOneExpected, 'The content type of the response was not ' . $responseType . '. The header provided was: ' . var_export($this->client->getResponse()->headers, true));
     }
 }
 public function testDoesNotReturn401IfValidToken()
 {
     $this->register('chain');
     $jwt = JWT::encode(['sub' => 'John'], 'secret', 'HS256');
     $client = new Client($this->app);
     $client->request('GET', '/?jwt=' . $jwt);
     $response = $client->getResponse();
     $this->assertEquals(200, $response->getStatusCode());
 }
 /**
  * test login
  */
 public function testLoginSuccess()
 {
     $data = array('username' => 'user', 'password' => 'password');
     $this->client->request('POST', $this->getUrl('login_check'), $data);
     $this->assertJsonResponse($this->client->getResponse(), 200);
     $response = json_decode($this->client->getResponse()->getContent(), true);
     $this->assertArrayHasKey('token', $response);
     $this->assertArrayHasKey('data', $response);
 }
 /**
  * @dataProvider provideData
  */
 public function testValidJsonData($label, $data, $expectedResponse)
 {
     $this->app['aiv.input'] = new \AIV\Input\SymfonyRequest\JSONInput();
     $client = new Client($this->app, []);
     $label = 'Test Case: ' . $label;
     $client->request('POST', '/', [], [], [], json_encode(['test-name' => $data]));
     $response = $client->getResponse();
     $this->assertTrue($response->isOk(), $label);
     $this->assertContains($expectedResponse, $response->getContent(), $label);
 }
 /**
  * @dataProvider provideExceptionsAndCode
  */
 public function testError($exception, $code)
 {
     $app = new Application('test');
     $app['dispatcher']->addSubscriber(new ApiExceptionHandlerSubscriber($app));
     $app->get('/', function () use($exception) {
         throw $exception;
     });
     $client = new Client($app);
     $client->request('GET', '/');
     $this->assertEquals($code, $client->getResponse()->getStatusCode());
 }
 private function request($accept)
 {
     $app = new Application(Application::ENV_TEST);
     $app['dispatcher']->addSubscriber(new ContentNegotiationSubscriber($app['negotiator'], $app['phraseanet.content-negotiation.priorities']));
     $app->get('/content/negociation', function () {
         return '';
     });
     $client = new Client($app);
     $client->request('GET', '/content/negociation', array(), array(), array('HTTP_Accept' => $accept));
     return $client->getResponse();
 }
Esempio n. 12
0
 public function getAccessToken(Client $client)
 {
     $app = $this->app;
     $this->assertArrayHasKey('session.storage.handler', $app, 'Renegare\\SilexCSH\\CookieSessionServiceProvider has not been registered.');
     $sessionStorageHandler = $app['session.storage.handler'];
     $this->assertInstanceOf('Renegare\\SilexCSH\\CookieSessionHandler', $sessionStorageHandler, 'Can only support Renegare\\SilexCSH\\CookieSessionHandler sessions');
     $cookie = $client->getCookieJar()->get($sessionStorageHandler->getCookieName());
     $sessionData = unserialize(unserialize($cookie->getValue())[1]);
     $token = unserialize($sessionData['_security_app']);
     return $token;
 }
 private function request($accept)
 {
     $app = new Application('test');
     $app['dispatcher']->addSubscriber(new ContentNegotiationSubscriber($app));
     $app->get('/content/negociation', function () {
         return '';
     });
     $client = new Client($app);
     $client->request('GET', '/content/negociation', array(), array(), array('HTTP_Accept' => $accept));
     return $client->getResponse();
 }
Esempio n. 14
0
 protected function assertLinkRel(Client $client, string $linkRel, string $expected)
 {
     $this->assertTrue($client->getResponse()->isSuccessful(), 'request is successful');
     foreach ($client->getResponse()->headers->get('Link', null, false) as $linkValue) {
         if (strpos($linkValue, 'rel="' . $linkRel . '"') !== false) {
             $this->assertSame($expected, $linkValue);
             return;
         }
     }
     $this->fail('No link with rel "' . $linkRel . '" found.');
 }
Esempio n. 15
0
 /**
  * @param array  $conf
  * @param string $method
  * @param array  $extraHeaders
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 private function request(array $conf, $method = 'GET', array $extraHeaders = [])
 {
     $app = new Application('test');
     $app['phraseanet.configuration']['api_cors'] = $conf;
     $app['dispatcher']->addSubscriber(new ApiCorsSubscriber($app));
     $app->get('/api/v1/test-route', function () {
         return '';
     });
     $client = new Client($app);
     $client->request($method, '/api/v1/test-route', [], [], array_merge($extraHeaders, ['HTTP_Origin' => $this->origin]));
     return $client->getResponse();
 }
 public function testGetVariants()
 {
     $preferred = null;
     $app = new Application();
     $app->register(new BadFaithServiceProvider());
     $app->get('/', function (Application $app) use(&$preferred) {
         $preferred = $app['bad-faith']->headerLists['accept_language']->getPreferred();
     });
     $client = new Client($app, array());
     $client->request('GET', '/', array(), array(), array('HTTP_ACCEPT_ENCODING' => 'gzip,deflate,sdch', 'HTTP_ACCEPT_LANGUAGE' => 'de-DE,en;q=0.8'));
     $this->assertEquals('de-DE', $preferred->pref);
 }
 /**
  * @dataProvider provideExceptionsAndCode
  */
 public function testErrorOnOtherRoutes($exception, $code, $contentType)
 {
     $app = new Application('test');
     unset($app['exception_handler']);
     $app['dispatcher']->addSubscriber(new ApiOauth2ErrorsSubscriber(PhraseaExceptionHandler::register(), $this->createTranslatorMock()));
     $app->get('/', function () use($exception) {
         throw $exception;
     });
     $client = new Client($app);
     $this->setExpectedException(get_class($exception));
     $client->request('GET', '/');
 }
 public function testItCanBeDisabled()
 {
     $app = new Application();
     $app['exception_handler'] = new PhraseaExceptionHandlerSubscriber(PhraseaExceptionHandler::register());
     $app->get('/', function () {
         throw new \Exception();
     });
     $app['exception_handler']->disable();
     $client = new Client($app);
     $this->setExpectedException('\\Exception');
     $client->request('GET', '/');
 }
 public function testNoHeaderNoRedirection()
 {
     $app = new Application();
     unset($app['exception_handler']);
     $app['dispatcher']->addSubscriber(new FirewallSubscriber());
     $app->get('/', function () {
         throw new HttpException(500);
     });
     $client = new Client($app);
     $this->setExpectedException('Symfony\\Component\\HttpKernel\\Exception\\HttpException');
     $client->request('GET', '/');
 }
 public function testErrorOnOtherExceptions()
 {
     $app = new Application('test');
     $app['bridge.account'] = $this->getMockBuilder('Bridge_Account')->disableOriginalConstructor()->getMock();
     unset($app['exception_handler']);
     $app['dispatcher']->addSubscriber(new BridgeExceptionSubscriber($app));
     $app->get('/', function () {
         throw new \InvalidArgumentException();
     });
     $client = new Client($app);
     $this->setExpectedException('\\InvalidArgumentException');
     $client->request('GET', '/');
 }
Esempio n. 21
0
 public function logInBackend($username = '******', $password = '******')
 {
     if ($this->um->isAuthenticated() === false) {
         $this->client->request('GET', '/' . $this->api['backend'] . '/user/login/?username='******'&password='******'CONTENT_TYPE' => 'application/json']);
         $response = $this->client->getResponse();
         $content = $response->getContent();
         $result = json_decode($content, true);
         if ($result['status'] !== true) {
             throw new \LogicException('Authentication failed.');
         }
     }
     return $this->um->isAuthenticated();
 }
 public function testCookieIsSet()
 {
     $client = new Client(self::$DI['app']);
     $client->request('GET', '/', [], [], ['HTTP_ACCEPT_LANGUAGE' => 'fr-FR,fr;q=0.9']);
     $settedCookie = null;
     foreach ($client->getResponse()->headers->getCookies() as $cookie) {
         if ($cookie->getName() === 'locale') {
             $settedCookie = $cookie;
             break;
         }
     }
     $this->assertNotNull($settedCookie);
     $this->assertEquals('fr', $settedCookie->getValue());
 }
 /**
  * @dataProvider dataProviderHTMLSyntax
  * @test
  */
 public function should_use_title_and_resources_if_html($syntax, $dir, $extension)
 {
     // GIVEN
     $this->app->register(new DocumentationProvider(), array("documentation.dir" => __DIR__ . "/datas/" . $dir, "documentation.url" => '/doc', "documentation.extension" => $extension, "documentation.home" => 'index', "documentation.syntax" => $syntax, "documentation.title" => 'My Documentation', "documentation.styles" => array('/components/bootstrap/css/bootstrap.min.css'), "documentation.scripts" => array('/components/jquery/jquery.min.js', '/components/bootstrap/js/bootstrap.min.js')));
     $client = new Client($this->app);
     // WHEN
     $crawler = $client->request('GET', '/doc');
     // THEN
     $this->assertTrue($client->getResponse()->isOk());
     $this->assertContains('text/html', $client->getResponse()->headers->get('Content-Type'));
     $this->assertCount(1, $crawler->filter("title"));
     $this->assertCount(1, $crawler->filter("link"));
     $this->assertCount(2, $crawler->filter("script"));
 }
Esempio n. 24
0
 public function logInFrontend($username = '******', $password = '******')
 {
     if ($this->um->isAuthenticated() === false) {
         $data = ['username' => $username, 'password' => $password];
         $this->client->request('POST', '/' . $this->api['frontend'] . '/user/login/', [], [], ['CONTENT_TYPE' => 'application/json'], json_encode($data));
         $response = $this->client->getResponse();
         $content = $response->getContent();
         $result = json_decode($content, true);
         if ($result['status'] !== true) {
             throw new \LogicException('Authentication failed.');
         }
     }
     return $this->um->isAuthenticated();
 }
 /**
  * @test
  */
 public function notReplaceIfBodyContentIsNotJson()
 {
     $self = $this;
     $body = array("number" => 123, "string" => "foo", "array" => array(5, 27, 42), "object" => (object) array("bar" => "baz"), "true" => true, "false" => false);
     $this->app->register(new JsonBodyProvider());
     $this->app->post("/", function (Request $req) use($self) {
         $self->assertCount(0, $req->request);
         return "Done.";
     });
     $client = new Client($this->app);
     $client->request('POST', '/', array(), array(), array('CONTENT_TYPE' => 'application/json'), json_encode($body) . "..broken!!!");
     $response = $client->getResponse();
     $this->assertEquals("Done.", $response->getContent());
 }
 public function testAllowedIpsAreSetWhenEmpty()
 {
     $configuration = $this->getConfigurationMock();
     $configuration->expects($this->once())->method('isSetup')->will($this->returnValue(true));
     $configuration->expects($this->once())->method('offsetExists')->with('trusted-proxies')->will($this->returnValue(false));
     $app = new Application();
     $app['dispatcher']->addSubscriber(new TrustedProxySubscriber($configuration));
     $app->get('/', function () {
         return 'data';
     });
     $client = new Client($app);
     $client->request('GET', '/');
     $this->assertEquals(200, $client->getResponse()->getStatusCode());
     $this->assertEquals([], Request::getTrustedProxies());
 }
 /**
  * @dataProvider provideExceptionsAndCode
  */
 public function testError($exception, $code)
 {
     $app = new Application('test');
     $app['api'] = function () use($app) {
         return new \API_V1_adapter($app);
     };
     $app->register(new \API_V1_Timer());
     $app['dispatcher']->addSubscriber(new ApiExceptionHandlerSubscriber($app));
     $app->get('/', function () use($exception) {
         throw $exception;
     });
     $client = new Client($app);
     $client->request('GET', '/');
     $this->assertEquals($code, $client->getResponse()->getStatusCode());
     $this->assertEquals('application/json', $client->getResponse()->headers->get('content-type'));
 }
Esempio n. 28
0
 protected function getScript($request)
 {
     $script = parent::getScript($request);
     $autoload = file_exists(__DIR__ . '/../../vendor/autoload.php') ? __DIR__ . '/../../vendor/autoload.php' : __DIR__ . '/../../../../../../vendor/autoload.php';
     $script = preg_replace('/(\\->register\\(\\);)/', "\$0\nrequire_once '{$autoload}';\n", $script);
     return $script;
 }
Esempio n. 29
0
 private function writeResponse(OutputInterface $output, $method, $path, $to, $authenticateUser = false)
 {
     $environment = Application::ENV_TEST;
     $app = (require __DIR__ . '/../../Application/Root.php');
     $user = $this->createUser($app);
     // force load of non cached template
     $app['twig']->enableAutoReload();
     $client = new Client($app);
     $fixturePath = 'www/scripts/tests/fixtures';
     $target = sprintf('%s/%s/%s', $app['root.path'], $fixturePath, $to);
     $output->writeln(sprintf("Generating %s", $target));
     if ($authenticateUser) {
         $this->loginUser($app, $user);
     }
     $client->request($method, $path);
     $response = $client->getResponse();
     if ($authenticateUser) {
         $this->logoutUser($app);
     }
     if (false === $response->isOk()) {
         $this->deleteUser($user);
         throw new RuntimeException(sprintf('Request %s %s returns %d code error', $method, $path, $response->getStatusCode()));
     }
     $this->container['filesystem']->mkdir(str_replace(basename($target), '', $target));
     $this->container['filesystem']->dumpFile($target, $this->removeHeadTag($this->removeScriptTags($response->getContent())));
     $this->deleteUser($user);
 }
 /**
  * Отображение ошибки при ответе
  */
 public function testTicketReplyErrors()
 {
     $crawler = $this->client->request('GET', '/ticket/6/show?_locale=ru');
     $form = $crawler->selectButton('Message[submit]')->form();
     $crawler = $this->client->submit($form);
     static::assertGreaterThan(0, $crawler->filter('html:contains("Заполните поле Сообщение или загрузите изображение")')->count());
 }