How to make functional tests that require authentication in Symfony 2?

I could not find documentation about this.

I use a client object to submit a request / login, fill out a form, and submit. This works fine, but I get the answer 302 back / login, as if the credentials were incorrect.

In any case, I think that after the first query there should be at least one row in the session table, but it does not exist. How is this possible?

Any thoughts?

Edit: Here is the code:

// Go to login page $client = $this->createClient(); $crawler = $client->request('GET', '/login'); $this->assertTrue($crawler->filter('html:contains("Username")')->count() > 0); // Fill in the form and submit it $form = $crawler->selectButton('login')->form(); $form['_username'] = 'admin'; $form['_password'] = 'admin'; $client->submit($form); $this->assertEquals(302,$client->getResponse()->getStatusCode()); $this->assertFalse($client->getResponse()->isRedirect('http://localhost/login')); 

Last statement fails

+6
source share
2 answers

You must create a new firewal using http basic authentication:

  security:
     ...
     firewalls:
         functional_test:
             pattern: /secure/.*
             stateless: true
             http_basic:
                 provider: provider_name
     ...

Then create the client as follows:

 $client = $this->createClient(array(), array( 'PHP_AUTH_USER' => 'username', 'PHP_AUTH_PW' => 'password', )); 

Happy coding!

+2
source

The article β€œ How to simulate authentication with a token in a functional test” refers to far from official documentation. Maybe this helps someone.

0
source

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


All Articles