How to save data in a Symfony2 session during a functional test?

I am writing a functional test for an action that uses the Symfony2 session service to retrieve data. In my setUp class setUp I call $this->get('session')->set('foo', 'bar'); . If I output all the session data (using print_r($this->get('session')->all()); ) either in setUp or in the real testing method, I will return foo => bar . But if I try to fetch session data from the action being checked, I return an empty array. Does anyone know why this is happening, and how can I prevent this?

It should be noted that if I call $_SESSION['foo'] = 'bar' from setUp() , the data is saved and I can access it from the action - this problem seems local to the Symfony2 session service.

+4
source share
2 answers

First try using your client container (I assume you are using WebTestCase):

 $client = static::createClient(); $container = $client->getContainer(); 

If it still does not work, try saving the session:

 $session = $container->get('session'); $session->set('foo', 'bar'); $session->save(); 

I have not tried this in functional tests, but how it works in Behat steps.

+6
source

You can get the "session" service. Using this service you can:

  • start a session
  • set some parameters to the session,
  • save session
  • pass cookie with sessionId to request

The code may be as follows:

 use Symfony\Component\BrowserKit\Cookie; .... .... public function testARequestWithSession() { $client = static::createClient(); $session = $client->getContainer()->get('session'); $session->start(); // optional because the ->set() method do the start $session->set('foo', 'bar'); // the session is started here if you do not use the ->start() method $session->save(); // important if you want to persist the params $client->getCookieJar()->set(new Cookie($session->getName(), $session->getId())); // important if you want that the request retrieve the session $client->request( .... ... 

A cookie with $ session-> getId () must be created after the session starts

See documentation http://symfony.com/doc/current/testing/http_authentication.html#creating-the-authentication-token

0
source

Source: https://habr.com/ru/post/1400415/


All Articles