Skip to content

Commit 7384903

Browse files
committed
Merge pull request #2468 from jakzal/login-in-func-tests
Documented simulating an authentication by manual token creation.
2 parents f1e3ca9 + bd0d2ff commit 7384903

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

cookbook/testing/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ Testing
55
:maxdepth: 2
66

77
http_authentication
8+
simulating_authentication
89
insulating_clients
910
profiling
1011
doctrine
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
.. index::
2+
single: Tests; Simulating authentication
3+
4+
How to simulate Authentication with a token in a Functional Test
5+
================================================================
6+
7+
Authenticating requests in functional tests might slow down the suite.
8+
It could become an issue especially when ``form_login`` is used, since
9+
it requires additional requests to fill in and submit the form.
10+
11+
One of the solutions is to configure your firewall to use ``http_basic`` in
12+
the test environment as explained in
13+
:doc:`/cookbook/testing/http_authentication`.
14+
Another way would be creating a token yourself and storing it in a session.
15+
While doing this you have to make sure that appropriate cookie is sent
16+
with a request. Following example demonstrates this technique::
17+
18+
// src/Acme/DemoBundle/Tests/Controller/DemoControllerTest.php
19+
namespace Acme\DemoBundle\Tests\Controller;
20+
21+
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
22+
use Symfony\Component\BrowserKit\Cookie;
23+
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
24+
25+
class DemoControllerTest extends WebTestCase
26+
{
27+
private $client = null;
28+
29+
public function setUp()
30+
{
31+
$this->client = static::createClient();
32+
}
33+
34+
public function testSecuredHello()
35+
{
36+
$this->logIn();
37+
38+
$this->client->request('GET', '/demo/secured/hello/Fabien');
39+
40+
$this->assertTrue($this->client->getResponse()->isSuccessful());
41+
$this->assertGreaterThan(0, $crawler->filter('html:contains("Hello Fabien")')->count());
42+
}
43+
44+
private function logIn()
45+
{
46+
$session = $this->client->getContainer()->get('session');
47+
48+
$firewall = 'secured_area';
49+
$token = new UsernamePasswordToken('admin', null, $firewall, array('ROLE_ADMIN'));
50+
$session->set('_security_'.$firewall, serialize($token));
51+
$session->save();
52+
53+
$cookie = new Cookie($session->getName(), $session->getId());
54+
$this->client->getCookieJar()->set($cookie);
55+
}
56+
}
57+
58+
.. note::
59+
60+
Technique described in :doc:`/cookbook/testing/http_authentication`.
61+
is cleaner and therefore preferred way.

0 commit comments

Comments
 (0)