Authentication processing in Symfony2 Unit-Tests

I want to write functional tests for controllers that are protected by Symfony2 authentication mechanisms. I read a lot of tutorials describing this, but unfortunately, all of them do not work for me with the current version of Symfony2 (tested from 2.0.4 to 2.0.7)

What i have done so far:

Adding security settings to config_test.yml

security: encoders: Symfony\Component\Security\Core\User\User: plaintext providers: main: users: admin: { password: adminsmurf, roles: [ 'ROLE_USER' ] } inventory: { password: inventorysmurf, roles: [ 'ROLE_ADMIN', 'ROLE_USER', 'ROLE_INVENTORY' ] } andon: { password: andonsmurf, roles: [ 'ROLE_ADMIN', 'ROLE_ANDON' ] } firewalls: main: pattern: /.* http_basic: realm: "Secured Area" provider: main logout: true security: true stateless: true anonymous: true 

Unit test

 class DefaultControllerTest extends WebTestCase { public function testCorrectAuthentificationCredentials() { $client = static::createClient(); $crawler = $client->request('GET', '/inventory/index', array(), array(), array( 'PHP_AUTH_USER' => 'admin', 'PHP_AUTH_PW' => 'adminsmurf' )); $response = $client->getResponse(); $this->assertEquals(200, $response->getStatusCode()); } } 

This test failed (200 expected, get 302). Can someone help what I am doing wrong?

Update 16/12

I took one more step. Since I use the form login in my regular security file. Symfony just added http_basic login to the firewall. This caused a redirect (302). I just added

 form_login: false 

to testing security settings. Now there is no redirection, but the result is a 401 status code.

+2
source share
2 answers

I show that basic HTTP auth should go as the 4th argument, not the 5th. The source is the documents - if they do not work, we need to update them. But let me know:

http://symfony.com/doc/2.0/cookbook/testing/http_authentication.html

In addition, once you have done this correctly, you can enable the auth form again, since Symfony will have no reason to use the form's entry point (<- fancy word :)) to redirect you.

Hope this helps!

+3
source

In my case, the problem was that the test environment uses a separate database, but I forgot to populate it with users. m)

I know this is probably not the solution to your problem, but let's see how much interest they have if everyone with the same problem has problems. If no one does, well, I'm the only one who is this stupid.

By the way, you can try the provider in memory to find out if your authentication fails due to database problems or the like. This is how I found out what my problem was.

+1
source

All Articles