'How to access Session in PHPUnit WebTestCase (Symfony 5)

I'm trying to test methods which requires Sessions in my PHPUnit WebTestCase, with no success.

PHP 8.0, Symfony 5.4

Here's my code:

When user log-in, I'm saving custom info in session:

public function methodCalledAfterLoginSuccess(int $id_internal_network, SessionInterface $session): Response
    {
        $session->set('current_internal_network',$id_internal_network);
        return $this->redirectToRoute("dashboard");
    }

In some controllers, I get this value like this:

#[Route('/contract/list', name: 'list_contract')]
public function listContracts(Request $request, SessionInterface $session): Response
    {
        $currentInternalNetwork = $session->get('current_internal_network');
        (...)

Everything works great. Then, I'm setting my functional tests:

class SomeController extends WebTestCase

public function setUp(): void
    {
        $this->client = static::createClient([], ['HTTPS' => true]);
        parent::setUp();
    }

public function testShowContractSearchForm(): void
    {
        $session = new Session(new MockFileSessionStorage());
        $session->start();
        $this->login('admin');
        dd($session->get('current_internal_network'));
        $this->client->request('GET', '/contract/list');
        self::assertResponseIsSuccessful();
    }

But $session->get('current_internal_network') is empty

The method $this->login('admin'); will submit a login form with correct info, so I'm "logged" in my tests, this part is ok.

my framework.yaml:

when@test:
    framework:
        test: true
        session:
            storage_factory_id: session.storage.factory.mock_file

I do not need specifically to access $session in my tests BUT the method listContracts() need to have a session filled with correct info from the login part.

What I'm missing?



Solution 1:[1]

I had the same issue and ended up implementing my own alternative to KernelBrowser::loginUser(). In my case, I have a multi-tenant application, and I am keeping the ID of the active tenant in the user session.

Just for context, here is my user case:

I'm using some event subscribers to verify the (1) the current user has access to the tenant in the user's session, and (2) all request parameters converted into Doctrine Entities belong to the tenant that is currently active.

This is my first-line defense against people trying to access things they should not.

In my functional tests, I'm using the KernelBrowser to call URLs like /task/1. A "Task" belongs to a single tenant and requires an authenticated user to access it, so the test case has to work with an authenticated user, and with a tenant stored in the session.

I did not want to introduce a test-only way how to specify the tenant ID some other way (such as /task/1?tenant=1). I think of things like this as a security disaster waiting to happen.

Anyway, here is the helper method that creates the session and adds some parameters to it, before setting the right session cookie in the client instance.

It works like a charm and I'm thinking of submitting a PR where KernelBrowser::loginUser() would accept an array of key/value pairs of properties that should be injected into the mocked session.

<?php

namespace App\Tests;

use App\Entity\User;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\TestBrowserToken;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\AbstractBrowser;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpFoundation\Request;

abstract class BaseWebTestCase extends WebTestCase
{
    protected function loginUser(KernelBrowser $client, OrganisationUser|User|string $user, string $firewallContext = 'main'): KernelBrowser
    {
        // If the $user is just a fixture key, we'll try to convert it into an actual entity.
        if (is_string($user)) {
            $fixture = $this->getFixture($user);

            if (!$fixture instanceof User && !$fixture instanceof OrganisationUser) {
                throw new Error(sprintf(
                    'The fixture "%s" must be an instance of User or OrganisationUser, "%s" found.',
                    $user,
                    get_debug_type($fixture)
                ));
            }

            $user = $fixture;
            unset($fixture);
        }

        $securityUser = $user instanceof User ? $user : $user->getUser();

        $token = new TestBrowserToken($securityUser->getRoles(), $securityUser, $firewallContext);

        $container = $client->getContainer();
        $container->get('security.untracked_token_storage')->setToken($token);

        if ($container->has('session.factory')) {
            $session = $container->get('session.factory')->createSession();
        } elseif ($container->has('session')) {
            $session = $container->get('session');
        } else {
            return $client;
        }
        $session->set('_security_'.$firewallContext, serialize($token));

        // The magic happens here: If the $user is a OrganisationUser, store the Organisation ID in the session that gets picked up by the client later
        if ($user instanceof OrganisationUser) {
            $session->set(OrganisationService::ACTIVE_ORGANISATION, $user->getOrganisation()->getId());
        }


        $session->save();

        // IMPORTANT: the domain name must be set to localhost, otherwise it does not work
        $cookie = new Cookie($session->getName(), $session->getId(), null, null, 'localhost');
        // End of magic

        $client->getCookieJar()->set($cookie);

        return $client;
    }
}

The key is to set the session ID at the same time the security-related things are added to it.

I'm sure there is a proper way to access the client session later on, anywhere from the code, but I have not found it yet. I'd love to know how to do it, if anybody knows.

I hope it helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1