1

Since all my project resources are protected so user needs to get authenticated. In my tests I authenticate once in the setUp function. This works only for the first $client->request, if I try another $client->request after the first request, $client->getResponse()->getContent() says that I'm not authenticated!!

If I call the auth function (definition's below) to get authenticated, the second request works.

So to sum up, currently I'm compelled to authenticate for every $client->request(...

Here is my function I'm using for authentication (How to log in User in Session within a Functional Test in Symfony 2.3?)

public function auth($username, &$client)
{
    $session = $client->getContainer()->get('session');
    $firewall = 'front';

    $user = $this->doctrine->getRepository('FOSUserBundle:User')->findOneBy(array('username' => $username));

    $token = new UsernamePasswordToken($user, null, $firewall, $user->getRoles());

    $client->getContainer()->get('security.context')->setToken($token);

    $session->set('_security_'.$firewall, serialize($token));
    $session->save();

    $cookie = new Cookie(session_name(), $session->getId());
    $client->getCookieJar()->set($cookie);
}

Why do I need to authenticate for every request? Is it because somehow the session or the cookiejar generated by public function auth are not passed to the other requests ?

Community
  • 1
  • 1
smarber
  • 4,829
  • 7
  • 37
  • 78
  • 1
    If you're writing your tests properly, each test is independent from the others. Ergo, you need to authenticate each and every time. If you only want to authenticate once, set up a test fixture at the beginning of the tests, and write your tests to all use that same test fixture. – Robert Harvey Jan 13 '15 at 17:30
  • My bad, I meant into the same test I need to run many requests. So into say `public function testMytest1` for instance, I have to authenticate for every request? – smarber Jan 13 '15 at 17:36
  • 1
    Just found a better way here http://symfony.com/doc/2.3/cookbook/testing/http_authentication.html. Works like a charm. I'd be very interested to understand the difference between the two types of authentication though – smarber Jan 13 '15 at 17:39
  • @smarber HTTP authentification uses a dialog displayed by the browser, not a `
    ` in a HTML page.
    – A.L Jan 14 '15 at 14:32

0 Answers0