A session object backed by symfony MockArraySessionStorage is added unconditionally to every request in DrupalKernel::preHandle()
As a result, a session is automatically available on every request in the following environments:
- All tests inheriting from KernelTestBase.
- All tests using FunctionalTestSetupTrait::initKernel().
- All drush commands (since bootstrapDrupalFull() calls
DrupalKernel::preHandle(). - All drupal console commands (since boot() calls
DrupalKernel::preHandle().
Note: This change affects test code and command line utilities. Availability of the session backed by persistent storage in production code remains unchanged.
Deprecations
Tests in contrib and custom modules might start generating the following deprecation warning:
Pushing requests without a session onto the request_stack is deprecated in drupal 10.3.0 and an error will be thrown from drupal 11.0.0.
This happens when a Request object is constructed and pushed on the request_stack service during a test. The correct way to fix this deprecation is to add a mock session on the request before pushing it on the stack. The following example is from core RouteNoneTest.php:
diff --git a/core/tests/Drupal/KernelTests/Core/RouteProcessor/RouteNoneTest.php b/core/tests/Drupal/KernelTests/Core/RouteProcessor/RouteNoneTest.php
index 21e62d9680..7e35066eeb 100644
--- a/core/tests/Drupal/KernelTests/Core/RouteProcessor/RouteNoneTest.php
+++ b/core/tests/Drupal/KernelTests/Core/RouteProcessor/RouteNoneTest.php
@@ -8,6 +8,8 @@
use Drupal\KernelTests\KernelTestBase;
use Drupal\Core\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\Session\Session;
+use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\Routing\Route;
/**
@@ -59,6 +61,7 @@ public function testProcessOutbound() {
$request = Request::create('/subdir', 'GET', [], [], [], $server);
$request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
$request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));
+ $request->setSession(new Session(new MockArraySessionStorage()));
$request_stack->push($request);
$request_context->fromRequest($request);
Comments
Confusingly, this can also
Confusingly, this can also happen if you are writing a new kernel test even without any request object being constructed when making a mistake with dependencies or services.
Interesting. Do you have any
Interesting. Do you have any pointers for a repro? E.g., does that happen when requesting an non-existing service inside a kernel test?
It happens when trying to
It happens when trying to enable a module without enabling its dependencies first.
In my case, working on a migration for the ui_patterns_legacy module, just adding ui_patterns_legacy without first enabling ui_patterns and ui_patterns_library triggers the error.