I want to write functional tests for Controllers that are secured via the Symfony2 authentication mechanisms. I read a lot of tutorials describing it but unfortunately all of them doesn't work for me with current Symfony2 version (tested 2.0.4 to 2.0.7)
What I have done so far:
Adding security settings in 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 fails (Expected 200, get 302). Can anybody help what I'm doing wrong?
Update 16/12
I got a step further. As I'm using a form login in my regular security file. Symfony just added the http_basic login to the firewall. This was the reason for the redirect (302). I just added a
form_login: false
to the test security settings. Now there is no redirect but I get an 401 status code as a result.