|
| 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