Symfony2: Unable to simulate HTTP authentication in functional test

I am trying to use the following method described at symfony.com: http://symfony.com/doc/current/cookbook/testing/http_authentication.html in an attempt to functionally test a controller that requires user login.

My login form still works, I can log in, and the Symfony2 debug toolbar shows my user as authenticated. In addition, I have already written a functional test for the login process itself, which passes. Therefore, I now have two scenarios that my login is working.

The only problem I encountered is trying to simulate HTTP authentication for other controllers:

$client = static::createClient(array(), array( 'PHP_AUTH_USER' => 'tester', 'PHP_AUTH_PW' => 'testpass', )); 

I see, checking $ client, that they redirect me to my login page as soon as I try something like this:

 $crawler = $client->request('GET', '/'); 

I know that a user tester with the password testpass exists in the database, since I can log into this account through the browser.

I can use the following code from a security controller test:

  $client = $this->createClient(array(), array('HTTP_HOST' => 'myapp.test')); // Visit user login page and login $crawler = $client->request('GET', '/login'); $form = $crawler->selectButton('Login')->form(); $crawler = $client->submit($form, array('_username' => 'tester', '_password' => 'testpass')); // ... carry on with remainder of tests 

but I'm not sure if this is the most efficient way to do this.

I am a little overwhelmed by what's wrong. Any ideas? Was there a change for Symfony2, which means that this process has changed, and the simulation of HTTP authentication does not work now or works differently?

+4
source share
2 answers

Thinking about this, I can simply log in using the following setUp method:

 public function setUp() { // Perform user login. $this->client = $this->createClient(array(), array('HTTP_HOST' => 'scire.test')); $crawler = $this->client->request('GET', '/login'); $form = $crawler->selectButton('Login')->form(); $this->client->submit($form, array('_username' => 'tester', '_password' => 'tester')); } 

HTTP authentication will not work here unless I change my config_test.yml with some security setting to allow HTTP authentication.

Note to yourself: HTTP authentication is different from using the Doctrine user provider !!!

+5
source

Send your request as follows:

 <?php $client->request( 'GET', '/', array(), array(), array('PHP_AUTH_USER' => 'username', 'PHP_AUTH_PW' => 'pa$$word') ); 

It actually sends the information as real authentication header information.

0
source

Source: https://habr.com/ru/post/1393364/


All Articles