Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make functional tests that require to be authenticated, in Symfony 2?

I couldn't find any documentation about this.

I'm using the client object to send a request to /login, fill the form, and submit it. That works fine, but I'm getting a 302 response back to /login, as if the credentials were incorrect.

In any case, I think there should be at least one row in the sessions table after the first request, but there isn't any. How is that possible?

Any thoughts?

Edit: Here's 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'));

The last assert fails

like image 763
HappyDeveloper Avatar asked Jul 17 '11 23:07

HappyDeveloper


1 Answers

You should create a new firewal using http basic authentication:

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

Then create a client like this:

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

Happy coding !

like image 128
julesbou Avatar answered Oct 13 '22 21:10

julesbou