diff --git a/core/lib/Drupal/Core/Test/FunctionalTestSetupTrait.php b/core/lib/Drupal/Core/Test/FunctionalTestSetupTrait.php index f3c5eab8ca..602c7e158b 100644 --- a/core/lib/Drupal/Core/Test/FunctionalTestSetupTrait.php +++ b/core/lib/Drupal/Core/Test/FunctionalTestSetupTrait.php @@ -17,6 +17,7 @@ use Drupal\Core\Session\UserSession; use Drupal\Core\Site\Settings; use Drupal\Core\StreamWrapper\StreamWrapperInterface; +use Drupal\Tests\RequestSessionTestTrait; use Drupal\Tests\SessionTestTrait; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\Request; @@ -31,6 +32,7 @@ trait FunctionalTestSetupTrait { use SessionTestTrait; use RefreshVariablesTrait; + use RequestSessionTestTrait; /** * The "#1" admin user. @@ -272,6 +274,7 @@ protected function prepareRequestForGenerator($clean_urls = TRUE, $override_serv $server = array_merge($server, $override_server_vars); $request = Request::create($request_path, 'GET', [], [], [], $server); + $request->setSession($this->getSessionFromRequest()); // Ensure the request time is REQUEST_TIME to ensure that API calls // in the test use the right timestamp. $request->server->set('REQUEST_TIME', REQUEST_TIME); @@ -692,6 +695,24 @@ protected function prepareEnvironment() { $callbacks = []; } + /** + * Prepare the session and add it to the request. + */ + protected function prepareSession(ContainerInterface $container) { + // Disable session writing. + //** @var \Drupal\Core\Session\WriteSafeSessionHandlerInterface $writeSafeHandler*/ + $writeSafeHandler = $container->get('session_handler.write_safe'); + $writeSafeHandler->setSessionWritable(FALSE); + + /** @var \Symfony\Component\HttpFoundation\Session\SessionInterface $session */ + $session = $container->get('session'); + $session->start(); + + /** @var \Symfony\Component\HttpFoundation\Request $request */ + $request = $container->get('request_stack')->getCurrentRequest(); + $request->setSession($session); + } + /** * Returns all supported database driver installer objects. * diff --git a/core/modules/block_content/tests/src/Functional/BlockContentCacheTagsTest.php b/core/modules/block_content/tests/src/Functional/BlockContentCacheTagsTest.php index c6778cab98..147a68b5eb 100644 --- a/core/modules/block_content/tests/src/Functional/BlockContentCacheTagsTest.php +++ b/core/modules/block_content/tests/src/Functional/BlockContentCacheTagsTest.php @@ -83,8 +83,10 @@ public function testBlock() { // https://www.drupal.org/node/2367555 is fixed and the // corresponding $request->isMethodCacheable() checks are removed from // Drupal\Core\Render\Renderer. + $request = new Request(); + $request->setSession($this->getSessionFromRequest()); $request_stack = $this->container->get('request_stack'); - $request_stack->push(new Request()); + $request_stack->push($request); $this->container->get('renderer')->renderRoot($build); $request_stack->pop(); diff --git a/core/modules/comment/tests/src/Kernel/CommentDefaultFormatterCacheTagsTest.php b/core/modules/comment/tests/src/Kernel/CommentDefaultFormatterCacheTagsTest.php index e681a4d9ad..97deab75ae 100644 --- a/core/modules/comment/tests/src/Kernel/CommentDefaultFormatterCacheTagsTest.php +++ b/core/modules/comment/tests/src/Kernel/CommentDefaultFormatterCacheTagsTest.php @@ -34,10 +34,8 @@ class CommentDefaultFormatterCacheTagsTest extends EntityKernelTestBase { protected function setUp() { parent::setUp(); - $session = new Session(); - $request = Request::create('/'); - $request->setSession($session); + $request->setSession($this->getSessionFromRequest()); /** @var \Symfony\Component\HttpFoundation\RequestStack $stack */ $stack = $this->container->get('request_stack'); diff --git a/core/modules/comment/tests/src/Kernel/CommentHostnameTest.php b/core/modules/comment/tests/src/Kernel/CommentHostnameTest.php index cbf67985df..67c37d1c50 100644 --- a/core/modules/comment/tests/src/Kernel/CommentHostnameTest.php +++ b/core/modules/comment/tests/src/Kernel/CommentHostnameTest.php @@ -29,6 +29,7 @@ class CommentHostnameTest extends KernelTestBase { public function testGetDefaultHostname() { // Create a fake request to be used for testing. $request = Request::create('/', 'GET', [], [], [], ['REMOTE_ADDR' => '203.0.113.1']); + $request->setSession($this->getSessionFromRequest()); /** @var \Symfony\Component\HttpFoundation\RequestStack $stack */ $stack = $this->container->get('request_stack'); $stack->push($request); diff --git a/core/modules/content_moderation/tests/src/Kernel/ViewsModerationStateSortTest.php b/core/modules/content_moderation/tests/src/Kernel/ViewsModerationStateSortTest.php index 379e73a473..da9370d927 100644 --- a/core/modules/content_moderation/tests/src/Kernel/ViewsModerationStateSortTest.php +++ b/core/modules/content_moderation/tests/src/Kernel/ViewsModerationStateSortTest.php @@ -183,6 +183,7 @@ protected function assertSortResults($view_id, $column, $order, array $expected) 'order' => 'moderation_state', 'sort' => strtolower($order), ]); + $request->setSession($this->getSessionFromRequest()); $view->setRequest($request); $view->execute(); $this->assertIdenticalResultset($view, $expected, [$column => $column]); diff --git a/core/modules/editor/tests/src/Kernel/QuickEditIntegrationTest.php b/core/modules/editor/tests/src/Kernel/QuickEditIntegrationTest.php index 4131cefd45..6cc86f10c5 100644 --- a/core/modules/editor/tests/src/Kernel/QuickEditIntegrationTest.php +++ b/core/modules/editor/tests/src/Kernel/QuickEditIntegrationTest.php @@ -218,6 +218,7 @@ public function testGetUntransformedTextCommand() { // Verify AJAX response. $controller = new EditorController(); $request = new Request(); + $request->setSession($this->getSessionFromRequest()); $response = $controller->getUntransformedText($entity, $this->fieldName, LanguageInterface::LANGCODE_DEFAULT, 'default'); $expected = [ [ diff --git a/core/modules/jsonapi/src/Controller/FileUpload.php b/core/modules/jsonapi/src/Controller/FileUpload.php index eb9fd6cd44..9c35451b38 100644 --- a/core/modules/jsonapi/src/Controller/FileUpload.php +++ b/core/modules/jsonapi/src/Controller/FileUpload.php @@ -140,7 +140,9 @@ public function handleFileUploadForExistingResource(Request $request, ResourceTy $route_parameters = ['entity' => $entity->uuid()]; $route_name = sprintf('jsonapi.%s.%s.related', $resource_type->getTypeName(), $file_field_name); $related_url = Url::fromRoute($route_name, $route_parameters)->toString(TRUE); + $session = $request->getSession(); $request = Request::create($related_url->getGeneratedUrl(), 'GET', [], $request->cookies->all(), [], $request->server->all()); + $request->setSession($session); return $this->httpKernel->handle($request, HttpKernelInterface::SUB_REQUEST); } diff --git a/core/modules/jsonapi/tests/src/Kernel/Normalizer/JsonApiDocumentTopLevelNormalizerTest.php b/core/modules/jsonapi/tests/src/Kernel/Normalizer/JsonApiDocumentTopLevelNormalizerTest.php index 0d2f093f01..9e9988c598 100644 --- a/core/modules/jsonapi/tests/src/Kernel/Normalizer/JsonApiDocumentTopLevelNormalizerTest.php +++ b/core/modules/jsonapi/tests/src/Kernel/Normalizer/JsonApiDocumentTopLevelNormalizerTest.php @@ -752,7 +752,10 @@ protected function getNormalizer() { protected function generateProphecies($entity_type_id, $bundle) { $resource_type = $this->container->get('jsonapi.resource_type.repository')->get($entity_type_id, $bundle); - return [new Request(), $resource_type]; + $request = new Request(); + $request->setSession($this->getSessionFromRequest()); + + return [$request, $resource_type]; } } diff --git a/core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationSession.php b/core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationSession.php index 971e907aae..1c5365a0c5 100644 --- a/core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationSession.php +++ b/core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationSession.php @@ -4,11 +4,14 @@ use Drupal\Core\Language\LanguageInterface; use Drupal\Core\PathProcessor\OutboundPathProcessorInterface; +use Drupal\Core\Plugin\ContainerFactoryPluginInterface; use Drupal\Core\Render\BubbleableMetadata; use Drupal\Core\Url; use Drupal\language\LanguageNegotiationMethodBase; use Drupal\language\LanguageSwitcherInterface; +use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; /** * Identify language from a request/session parameter. @@ -21,7 +24,7 @@ * config_route_name = "language.negotiation_session" * ) */ -class LanguageNegotiationSession extends LanguageNegotiationMethodBase implements OutboundPathProcessorInterface, LanguageSwitcherInterface { +class LanguageNegotiationSession extends LanguageNegotiationMethodBase implements OutboundPathProcessorInterface, LanguageSwitcherInterface, ContainerFactoryPluginInterface { /** * Flag used to determine whether query rewriting is active. @@ -44,11 +47,37 @@ class LanguageNegotiationSession extends LanguageNegotiationMethodBase implement */ protected $queryValue; + /** + * The request stack. + * + * @var \Symfony\Component\HttpFoundation\RequestStack + */ + protected $requestStack; + /** * The language negotiation method id. */ const METHOD_ID = 'language-session'; + /** + * Constructs a LanguageNegotiationSession object. + * + * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack + * The request stack. + */ + public function __construct(RequestStack $request_stack) { + $this->requestStack = $request_stack; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { + return new static( + $container->get('request_stack') + ); + } + /** * {@inheritdoc} */ @@ -56,8 +85,8 @@ public function getLangcode(Request $request = NULL) { $config = $this->config->get('language.negotiation')->get('session'); $param = $config['parameter']; $langcode = $request && $request->query->get($param) ? $request->query->get($param) : NULL; - if (!$langcode && isset($_SESSION[$param])) { - $langcode = $_SESSION[$param]; + if (!$langcode && $request && $request->getSession()->has($param)) { + $langcode = $request->getSession()->get($param); } return $langcode; } @@ -73,7 +102,7 @@ public function persist(LanguageInterface $language) { $languages = $this->languageManager->getLanguages(); if ($this->currentUser->isAuthenticated() && isset($languages[$langcode])) { $config = $this->config->get('language.negotiation')->get('session'); - $_SESSION[$config['parameter']] = $langcode; + $this->requestStack->getCurrentRequest()->getSession()->set($config['parameter'], $langcode); } } } @@ -127,7 +156,7 @@ public function getLanguageSwitchLinks(Request $request, $type, Url $url) { $links = []; $config = $this->config->get('language.negotiation')->get('session'); $param = $config['parameter']; - $language_query = isset($_SESSION[$param]) ? $_SESSION[$param] : $this->languageManager->getCurrentLanguage($type)->getId(); + $language_query = $request->getSession()->has($param) ? $request->getSession()->get($param) : $this->languageManager->getCurrentLanguage($type)->getId(); $query = []; parse_str($request->getQueryString(), $query); diff --git a/core/modules/language/tests/src/Functional/LanguageNegotiationContentEntityTest.php b/core/modules/language/tests/src/Functional/LanguageNegotiationContentEntityTest.php index 66ea59ac1e..b96141c0d2 100644 --- a/core/modules/language/tests/src/Functional/LanguageNegotiationContentEntityTest.php +++ b/core/modules/language/tests/src/Functional/LanguageNegotiationContentEntityTest.php @@ -174,6 +174,7 @@ protected function createTranslatableEntity() { */ protected function setCurrentRequestForRoute($path, $route_name) { $request = Request::create($path); + $request->setSession($this->getSessionFromRequest()); $request->attributes->set(RouteObjectInterface::ROUTE_NAME, $route_name); $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route($path)); $this->container->get('request_stack')->push($request); diff --git a/core/modules/language/tests/src/Functional/LanguageUILanguageNegotiationTest.php b/core/modules/language/tests/src/Functional/LanguageUILanguageNegotiationTest.php index 239a561427..85308a27b9 100644 --- a/core/modules/language/tests/src/Functional/LanguageUILanguageNegotiationTest.php +++ b/core/modules/language/tests/src/Functional/LanguageUILanguageNegotiationTest.php @@ -528,6 +528,7 @@ public function testLanguageDomain() { // Test HTTPS via current URL scheme. $request = Request::create('', 'GET', [], [], [], ['HTTPS' => 'on']); + $request->setSession($this->getSessionFromRequest()); $this->container->get('request_stack')->push($request); $italian_url = Url::fromRoute('system.admin', [], ['language' => $languages['it']])->toString(); $correct_link = 'https://' . $link; diff --git a/core/modules/language/tests/src/Kernel/EntityUrlLanguageTest.php b/core/modules/language/tests/src/Kernel/EntityUrlLanguageTest.php index 802d1a2431..95cfbca012 100644 --- a/core/modules/language/tests/src/Kernel/EntityUrlLanguageTest.php +++ b/core/modules/language/tests/src/Kernel/EntityUrlLanguageTest.php @@ -128,6 +128,7 @@ protected function createTranslatableEntity() { */ protected function setCurrentRequestForRoute($path, $route_name) { $request = Request::create($path); + $request->setSession($this->getSessionFromRequest()); $request->attributes->set(RouteObjectInterface::ROUTE_NAME, $route_name); $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route($path)); $this->container->get('request_stack')->push($request); diff --git a/core/modules/media_library/tests/src/Kernel/MediaLibraryStateTest.php b/core/modules/media_library/tests/src/Kernel/MediaLibraryStateTest.php index ab0bdcce20..dabc994667 100644 --- a/core/modules/media_library/tests/src/Kernel/MediaLibraryStateTest.php +++ b/core/modules/media_library/tests/src/Kernel/MediaLibraryStateTest.php @@ -279,7 +279,9 @@ public function testFromRequest(array $query_overrides, $exception_expected) { $this->expectException(BadRequestHttpException::class); $this->expectExceptionMessage("Invalid media library parameters specified."); } - $state = MediaLibraryState::fromRequest(new Request($query)); + $request = new Request($query); + $request->setSession($this->getSessionFromRequest()); + $state = MediaLibraryState::fromRequest($request); $this->assertInstanceOf(MediaLibraryState::class, $state); } @@ -289,7 +291,9 @@ public function testFromRequest(array $query_overrides, $exception_expected) { public function testFromRequestQueryLess() { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('The opener ID parameter is required and must be a string.'); - $state = MediaLibraryState::fromRequest(new Request()); + $request = new Request(); + $request->setSession($this->getSessionFromRequest()); + $state = MediaLibraryState::fromRequest($request); $this->assertInstanceOf(MediaLibraryState::class, $state); } diff --git a/core/modules/menu_link_content/tests/src/Kernel/MenuLinkContentCacheabilityBubblingTest.php b/core/modules/menu_link_content/tests/src/Kernel/MenuLinkContentCacheabilityBubblingTest.php index c783d852df..2a67010f31 100644 --- a/core/modules/menu_link_content/tests/src/Kernel/MenuLinkContentCacheabilityBubblingTest.php +++ b/core/modules/menu_link_content/tests/src/Kernel/MenuLinkContentCacheabilityBubblingTest.php @@ -54,6 +54,7 @@ public function testOutboundPathAndRouteProcessing() { $request_context = \Drupal::service('router.request_context'); $request = Request::create('/'); + $request->setSession($this->getSessionFromRequest()); $request->attributes->set(RouteObjectInterface::ROUTE_NAME, ''); $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/')); $request_stack->push($request); diff --git a/core/modules/node/tests/src/Kernel/Migrate/d6/NodeTranslationRedirectTest.php b/core/modules/node/tests/src/Kernel/Migrate/d6/NodeTranslationRedirectTest.php index 35976ee246..dcc24f8d20 100644 --- a/core/modules/node/tests/src/Kernel/Migrate/d6/NodeTranslationRedirectTest.php +++ b/core/modules/node/tests/src/Kernel/Migrate/d6/NodeTranslationRedirectTest.php @@ -58,6 +58,7 @@ protected function setUp() { public function testNodeTranslationRedirect() { $kernel = $this->container->get('http_kernel'); $request = Request::create('/node/11'); + $request->getSession($this->getSessionFromRequest()); $response = $kernel->handle($request); $this->assertSame(301, $response->getStatusCode()); $this->assertSame('/node/10', $response->getTargetUrl()); diff --git a/core/modules/node/tests/src/Kernel/Migrate/d7/NodeTranslationRedirectTest.php b/core/modules/node/tests/src/Kernel/Migrate/d7/NodeTranslationRedirectTest.php index 7b54d5b169..4cf0c57b60 100644 --- a/core/modules/node/tests/src/Kernel/Migrate/d7/NodeTranslationRedirectTest.php +++ b/core/modules/node/tests/src/Kernel/Migrate/d7/NodeTranslationRedirectTest.php @@ -58,6 +58,7 @@ protected function setUp() { public function testNodeTranslationRedirect() { $kernel = $this->container->get('http_kernel'); $request = Request::create('/node/3'); + $request->setSession($this->getSessionFromRequest()); $response = $kernel->handle($request); $this->assertSame(301, $response->getStatusCode()); $this->assertSame('/node/2', $response->getTargetUrl()); diff --git a/core/modules/rest/tests/src/Functional/Views/StyleSerializerTest.php b/core/modules/rest/tests/src/Functional/Views/StyleSerializerTest.php index 094d8797a6..173dc39035 100644 --- a/core/modules/rest/tests/src/Functional/Views/StyleSerializerTest.php +++ b/core/modules/rest/tests/src/Functional/Views/StyleSerializerTest.php @@ -572,6 +572,7 @@ public function testFieldRawOutput() { public function testLivePreview() { // We set up a request so it looks like an request in the live preview. $request = new Request(); + $request->setSession($this->getSessionFromRequest()); $request->query->add([MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']); /** @var \Symfony\Component\HttpFoundation\RequestStack $request_stack */ $request_stack = \Drupal::service('request_stack'); diff --git a/core/modules/syslog/tests/src/Kernel/SyslogTest.php b/core/modules/syslog/tests/src/Kernel/SyslogTest.php index 3b2a587a40..170bac21b9 100644 --- a/core/modules/syslog/tests/src/Kernel/SyslogTest.php +++ b/core/modules/syslog/tests/src/Kernel/SyslogTest.php @@ -29,6 +29,7 @@ protected function setUp() { public function testSyslogWriting() { $request = Request::create('/page-not-found', 'GET', [], [], [], ['REMOTE_ADDR' => '1.2.3.4']); + $request->setSession($this->getSessionFromRequest()); $request->headers->set('Referer', 'other-site'); \Drupal::requestStack()->push($request); diff --git a/core/modules/system/tests/src/Functional/Database/SelectPagerDefaultTest.php b/core/modules/system/tests/src/Functional/Database/SelectPagerDefaultTest.php index a38a5f0180..a6f8e4c4a3 100644 --- a/core/modules/system/tests/src/Functional/Database/SelectPagerDefaultTest.php +++ b/core/modules/system/tests/src/Functional/Database/SelectPagerDefaultTest.php @@ -136,6 +136,7 @@ public function testHavingPagerQuery() { public function testElementNumbers() { $request = Request::createFromGlobals(); + $request->setSession($this->getSessionFromRequest()); $request->query->replace([ 'page' => '3, 2, 1, 0', ]); diff --git a/core/modules/system/tests/src/Functional/Theme/ThemeTest.php b/core/modules/system/tests/src/Functional/Theme/ThemeTest.php index fe4471a2fa..810d130bb1 100644 --- a/core/modules/system/tests/src/Functional/Theme/ThemeTest.php +++ b/core/modules/system/tests/src/Functional/Theme/ThemeTest.php @@ -75,6 +75,7 @@ public function testFrontPageThemeSuggestion() { // Set the current route to user.login because theme_get_suggestions() will // query it to see if we are on the front page. $request = Request::create('/user/login'); + $request->setSession($this->getSessionFromRequest()); $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'user.login'); $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/user/login')); \Drupal::requestStack()->push($request); diff --git a/core/modules/system/tests/src/Kernel/Block/SystemMenuBlockTest.php b/core/modules/system/tests/src/Kernel/Block/SystemMenuBlockTest.php index 8d0ef50df2..5704ac8276 100644 --- a/core/modules/system/tests/src/Kernel/Block/SystemMenuBlockTest.php +++ b/core/modules/system/tests/src/Kernel/Block/SystemMenuBlockTest.php @@ -234,6 +234,7 @@ public function testConfigLevelDepth() { // Scenario 2: test all block instances when there's an active trail. $route = $this->container->get('router.route_provider')->getRouteByName('example3'); $request = new Request(); + $request->setSession($this->getSessionFromRequest()); $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'example3'); $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, $route); $this->container->get('request_stack')->push($request); @@ -301,6 +302,7 @@ public function testConfigExpanded($active_route, $menu_block_level, $expected_i $route = $this->container->get('router.route_provider')->getRouteByName($active_route); $request = new Request(); + $request->setSession($this->getSessionFromRequest()); $request->attributes->set(RouteObjectInterface::ROUTE_NAME, $active_route); $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, $route); $this->container->get('request_stack')->push($request); diff --git a/core/modules/views/src/Tests/AssertViewsCacheTagsTrait.php b/core/modules/views/src/Tests/AssertViewsCacheTagsTrait.php index 26c1ffe0b5..b57e33de73 100644 --- a/core/modules/views/src/Tests/AssertViewsCacheTagsTrait.php +++ b/core/modules/views/src/Tests/AssertViewsCacheTagsTrait.php @@ -45,6 +45,7 @@ protected function assertViewsCacheTags(ViewExecutable $view, $expected_results_ /** @var \Symfony\Component\HttpFoundation\RequestStack $request_stack */ $request_stack = \Drupal::service('request_stack'); $request = new Request(); + $request->setSession($this->getSessionFromRequest()); $request->server->set('REQUEST_TIME', REQUEST_TIME); $view->setRequest($request); $request_stack->push($request); @@ -128,6 +129,7 @@ protected function assertViewsCacheTagsFromStaticRenderArray(ViewExecutable $vie /** @var \Symfony\Component\HttpFoundation\RequestStack $request_stack */ $request_stack = \Drupal::service('request_stack'); $request = new Request(); + $request->setSession($this->getSessionFromRequest()); $request->server->set('REQUEST_TIME', REQUEST_TIME); $request_stack->push($request); $renderer->renderRoot($build); diff --git a/core/modules/views/tests/src/Kernel/Handler/AreaDisplayLinkTest.php b/core/modules/views/tests/src/Kernel/Handler/AreaDisplayLinkTest.php index e409a2be0f..4b4fec2e2a 100644 --- a/core/modules/views/tests/src/Kernel/Handler/AreaDisplayLinkTest.php +++ b/core/modules/views/tests/src/Kernel/Handler/AreaDisplayLinkTest.php @@ -149,7 +149,7 @@ public function testAreaDisplayLink() { // Assert some special request parameters are filtered from the display // links. $request_stack = new RequestStack(); - $request_stack->push(Request::create('page_1', 'GET', [ + $request = Request::create('page_1', 'GET', [ 'name' => 'John', 'sort_by' => 'created', 'sort_order' => 'ASC', @@ -166,7 +166,9 @@ public function testAreaDisplayLink() { AjaxResponseSubscriber::AJAX_REQUEST_PARAMETER => 1, FormBuilderInterface::AJAX_FORM_REQUEST => 1, MainContentViewSubscriber::WRAPPER_FORMAT => 1, - ])); + ]); + $request->setSession($this->getSessionFromRequest()); + $request_stack->push($request); $this->container->set('request_stack', $request_stack); $view->destroy(); $view->setDisplay('page_1'); diff --git a/core/modules/views/tests/src/Kernel/Plugin/DisplayPageTest.php b/core/modules/views/tests/src/Kernel/Plugin/DisplayPageTest.php index 07dff07dfd..e3fb5ce385 100644 --- a/core/modules/views/tests/src/Kernel/Plugin/DisplayPageTest.php +++ b/core/modules/views/tests/src/Kernel/Plugin/DisplayPageTest.php @@ -58,6 +58,7 @@ public function testPageResponses() { $this->assertEqual($response->getStatusCode(), 200); $subrequest = Request::create('/test_page_display_200', 'GET'); + $subrequest->setSession($this->getSessionFromRequest()); \Drupal::getContainer()->get('request_stack')->push($subrequest); // Test accessing a disabled page for a view. diff --git a/core/modules/views_ui/src/ViewUI.php b/core/modules/views_ui/src/ViewUI.php index 28c32f72e8..aba279dd27 100644 --- a/core/modules/views_ui/src/ViewUI.php +++ b/core/modules/views_ui/src/ViewUI.php @@ -581,6 +581,7 @@ public function renderPreview($display_id, $args = []) { $raw_parameters->set('view', $this->id()); $raw_parameters->set('display_id', $display_id); $request->attributes->set('_raw_variables', $raw_parameters); + $request->setSession($current_request->getSession()); foreach ($args as $key => $arg) { $request->attributes->set('arg_' . $key, $arg); diff --git a/core/tests/Drupal/FunctionalTests/BrowserTestBaseTest.php b/core/tests/Drupal/FunctionalTests/BrowserTestBaseTest.php index b8247ea88f..a580157043 100644 --- a/core/tests/Drupal/FunctionalTests/BrowserTestBaseTest.php +++ b/core/tests/Drupal/FunctionalTests/BrowserTestBaseTest.php @@ -743,6 +743,25 @@ public function testEscapingAssertions() { $assert->assertNoEscaped(""); } + /** + * Tests that a usable session is on the request in test-runner. + */ + public function testSessionOnRequest() { + /** @var \Symfony\Component\HttpFoundation\Request $request */ + $request = $this->container->get('request_stack')->getCurrentRequest(); + + // Verify that a usable session is available from the request. + /** @var \Symfony\Component\HttpFoundation\Session\SessionInterface $session */ + $session = $request->getSession(); + $this->assertNotNull($session); + + $session->set('some-val', 'do-not-cleanup'); + $this->assertEqual('do-not-cleanup', $session->get('some-val')); + + $session->set('some-other-val', 'do-cleanup'); + $this->assertEqual('do-cleanup', $session->remove('some-other-val')); + } + /** * Tests that deprecation headers do not get duplicated. * diff --git a/core/tests/Drupal/KernelTests/Core/Database/ReplicaKillSwitchTest.php b/core/tests/Drupal/KernelTests/Core/Database/ReplicaKillSwitchTest.php index b2cdf72407..f9fb3d59e0 100644 --- a/core/tests/Drupal/KernelTests/Core/Database/ReplicaKillSwitchTest.php +++ b/core/tests/Drupal/KernelTests/Core/Database/ReplicaKillSwitchTest.php @@ -6,7 +6,6 @@ use Drupal\Core\DrupalKernel; use Drupal\Core\Site\Settings; use Drupal\KernelTests\KernelTestBase; -use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\Event\GetResponseEvent; @@ -32,7 +31,7 @@ public function testSystemInitIgnoresSecondaries() { $service->trigger(); $class_loader = require $this->root . '/autoload.php'; $kernel = new DrupalKernel('testing', $class_loader, FALSE); - $event = new GetResponseEvent($kernel, Request::create('http://example.com'), HttpKernelInterface::MASTER_REQUEST); + $event = new GetResponseEvent($kernel, \Drupal::request(), HttpKernelInterface::MASTER_REQUEST); $service->checkReplicaServer($event); $db1 = Database::getConnection('default', 'default'); diff --git a/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php b/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php index 43fb9c76a8..74395d6e55 100644 --- a/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php +++ b/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php @@ -417,6 +417,7 @@ public function testSort() { // Test the pager by setting element #1 to page 2 with a page size of 4. // Results will be #8-12 from above. $request = Request::createFromGlobals(); + $request->setSession($this->getSessionFromRequest()); $request->query->replace([ 'page' => '0,2', ]); @@ -450,6 +451,7 @@ public function testTableSort() { // assert that all entities from one bundle are after the other as the // order dictates. $request = Request::createFromGlobals(); + $request->setSession($this->getSessionFromRequest()); $request->query->replace([ 'sort' => 'asc', 'order' => 'Type', diff --git a/core/tests/Drupal/KernelTests/Core/File/UrlRewritingTest.php b/core/tests/Drupal/KernelTests/Core/File/UrlRewritingTest.php index d5ad4e8915..ba72e26ece 100644 --- a/core/tests/Drupal/KernelTests/Core/File/UrlRewritingTest.php +++ b/core/tests/Drupal/KernelTests/Core/File/UrlRewritingTest.php @@ -102,6 +102,7 @@ public function testRelativeFileURL() { // Create a mock Request for file_url_transform_relative(). $request = Request::create($GLOBALS['base_url']); + $request->setSession($this->getSessionFromRequest()); $this->container->get('request_stack')->push($request); \Drupal::setContainer($this->container); diff --git a/core/tests/Drupal/KernelTests/Core/File/UrlTransformRelativeTest.php b/core/tests/Drupal/KernelTests/Core/File/UrlTransformRelativeTest.php index 6614b2d5b4..75f09dc36b 100644 --- a/core/tests/Drupal/KernelTests/Core/File/UrlTransformRelativeTest.php +++ b/core/tests/Drupal/KernelTests/Core/File/UrlTransformRelativeTest.php @@ -35,6 +35,7 @@ public function testFileUrlTransformRelative($host, $port, $https, $url, $expect $_SERVER['HTTPS'] = $https; $request = Request::createFromGlobals(); + $request->setSession($this->getSessionFromRequest()); \Drupal::requestStack()->push($request); $this->assertSame($expected, file_url_transform_relative($url)); diff --git a/core/tests/Drupal/KernelTests/Core/Form/ExternalFormUrlTest.php b/core/tests/Drupal/KernelTests/Core/Form/ExternalFormUrlTest.php index f3fbc4f76c..9b345b834a 100644 --- a/core/tests/Drupal/KernelTests/Core/Form/ExternalFormUrlTest.php +++ b/core/tests/Drupal/KernelTests/Core/Form/ExternalFormUrlTest.php @@ -77,6 +77,7 @@ public function testActionUrlBehavior() { $request_stack->pop(); $request_stack->pop(); $request = Request::create($original_request->getSchemeAndHttpHost() . '//example.org'); + $request->setSession($this->getSessionFromRequest()); $request_stack->push($request); $form = \Drupal::formBuilder()->getForm($this); @@ -92,6 +93,7 @@ public function testActionUrlBehavior() { $request_stack = \Drupal::service('request_stack'); $original_request = $request_stack->pop(); $request = Request::create($original_request->getSchemeAndHttpHost() . '/example.org'); + $request->setSession($this->getSessionFromRequest()); $request_stack->push($request); $form = \Drupal::formBuilder()->getForm($this); diff --git a/core/tests/Drupal/KernelTests/Core/Pager/PagerManagerTest.php b/core/tests/Drupal/KernelTests/Core/Pager/PagerManagerTest.php index 169793a459..4d05b41e29 100644 --- a/core/tests/Drupal/KernelTests/Core/Pager/PagerManagerTest.php +++ b/core/tests/Drupal/KernelTests/Core/Pager/PagerManagerTest.php @@ -45,6 +45,7 @@ public function testGetUpdatedParameters() { 'other' => 'arbitrary', ]; $request = Request::create('http://example.com', 'GET', $test_parameters); + $request->setSession($this->getSessionFromRequest()); /* @var $request_stack \Symfony\Component\HttpFoundation\RequestStack */ $request_stack = $this->container->get('request_stack'); diff --git a/core/tests/Drupal/KernelTests/Core/Pager/RequestPagerTest.php b/core/tests/Drupal/KernelTests/Core/Pager/RequestPagerTest.php index bb1bc9066b..3040cf6c73 100644 --- a/core/tests/Drupal/KernelTests/Core/Pager/RequestPagerTest.php +++ b/core/tests/Drupal/KernelTests/Core/Pager/RequestPagerTest.php @@ -17,6 +17,7 @@ class RequestPagerTest extends KernelTestBase { */ public function testFindPage() { $request = Request::create('http://example.com', 'GET', ['page' => '0,10']); + $request->setSession($this->getSessionFromRequest()); /* @var $request_stack \Symfony\Component\HttpFoundation\RequestStack */ $request_stack = $this->container->get('request_stack'); @@ -35,6 +36,7 @@ public function testGetQueryParameters() { 'other' => 'arbitrary', ]; $request = Request::create('http://example.com', 'GET', array_merge(['page' => '0,10'], $test_parameters)); + $request->setSession($this->getSessionFromRequest()); /* @var $request_stack \Symfony\Component\HttpFoundation\RequestStack */ $request_stack = $this->container->get('request_stack'); diff --git a/core/tests/Drupal/KernelTests/Core/Plugin/Condition/RequestPathTest.php b/core/tests/Drupal/KernelTests/Core/Plugin/Condition/RequestPathTest.php index 12569a6ca7..73daac3ebf 100644 --- a/core/tests/Drupal/KernelTests/Core/Plugin/Condition/RequestPathTest.php +++ b/core/tests/Drupal/KernelTests/Core/Plugin/Condition/RequestPathTest.php @@ -84,6 +84,7 @@ public function testConditions() { $pages = "/my/pass/page\r\n/my/pass/page2\r\n/foo"; $request = Request::create('/my/pass/page2'); + $request->setSession($this->getSessionFromRequest()); $this->requestStack->push($request); /* @var \Drupal\system\Plugin\Condition\RequestPath $condition */ diff --git a/core/tests/Drupal/KernelTests/Core/Render/Element/TableSortExtenderTest.php b/core/tests/Drupal/KernelTests/Core/Render/Element/TableSortExtenderTest.php index 2a7ea0410c..c2317445b3 100644 --- a/core/tests/Drupal/KernelTests/Core/Render/Element/TableSortExtenderTest.php +++ b/core/tests/Drupal/KernelTests/Core/Render/Element/TableSortExtenderTest.php @@ -31,6 +31,7 @@ public function testTableSortInit() { 'query' => [], ]; $request = Request::createFromGlobals(); + $request->setSession($this->getSessionFromRequest()); $request->query->replace([]); \Drupal::getContainer()->get('request_stack')->push($request); $ts = TableSort::getContextFromRequest($headers, $request); @@ -40,6 +41,7 @@ public function testTableSortInit() { // Test with simple table headers plus $_GET parameters that should _not_ // override the default. $request = Request::createFromGlobals(); + $request->setSession($this->getSessionFromRequest()); $request->query->replace([ // This should not override the table order because only complex // headers are overridable. @@ -53,6 +55,7 @@ public function testTableSortInit() { // Test with simple table headers plus $_GET parameters that _should_ // override the default. $request = Request::createFromGlobals(); + $request->setSession($this->getSessionFromRequest()); $request->query->replace([ 'sort' => 'DESC', // Add an unrelated parameter to ensure that tablesort will include @@ -84,6 +87,7 @@ public function testTableSortInit() { ]; // Reset $_GET from previous assertion. $request = Request::createFromGlobals(); + $request->setSession($this->getSessionFromRequest()); $request->query->replace([ 'order' => '2', ]); @@ -101,6 +105,7 @@ public function testTableSortInit() { // Test complex table headers plus $_GET parameters that should _not_ // override the default. $request = Request::createFromGlobals(); + $request->setSession($this->getSessionFromRequest()); $request->query->replace([ // This should not override the table order because this header does not // exist. @@ -120,6 +125,7 @@ public function testTableSortInit() { // Test complex table headers plus $_GET parameters that _should_ // override the default. $request = Request::createFromGlobals(); + $request->setSession($this->getSessionFromRequest()); $request->query->replace([ 'order' => '1', 'sort' => 'ASC', @@ -169,6 +175,7 @@ public function testTableSortInit() { ], ]; $request = Request::createFromGlobals(); + $request->setSession($this->getSessionFromRequest()); $request->query->replace([ 'order' => '1', ]); @@ -187,6 +194,7 @@ public function testTableSortInit() { // Test that if the initial_click_sort parameter is not defined, the default // must be used instead (which is "asc"). $request = Request::createFromGlobals(); + $request->setSession($this->getSessionFromRequest()); $request->query->replace([ 'order' => '2', ]); @@ -204,6 +212,7 @@ public function testTableSortInit() { // Test that if the initial_click_sort parameter is defined, and the sort // parameter is defined as well, the sort parameter has precedence. $request = Request::createFromGlobals(); + $request->setSession($this->getSessionFromRequest()); $request->query->replace([ 'order' => '3', ]); @@ -221,6 +230,7 @@ public function testTableSortInit() { // Test that if the initial_click_sort parameter is defined and the value // is "asc" it should be sorted correctly. $request = Request::createFromGlobals(); + $request->setSession($this->getSessionFromRequest()); $request->query->replace([ 'order' => '4', ]); @@ -238,6 +248,7 @@ public function testTableSortInit() { // Tests that if the initial_click_sort is defined with a non expected value // that value will be passed as the "sort" value. $request = Request::createFromGlobals(); + $request->setSession($this->getSessionFromRequest()); $request->query->replace([ 'order' => '5', ]); diff --git a/core/tests/Drupal/KernelTests/Core/RouteProcessor/RouteNoneTest.php b/core/tests/Drupal/KernelTests/Core/RouteProcessor/RouteNoneTest.php index 6d26891fdb..e832c24ca2 100644 --- a/core/tests/Drupal/KernelTests/Core/RouteProcessor/RouteNoneTest.php +++ b/core/tests/Drupal/KernelTests/Core/RouteProcessor/RouteNoneTest.php @@ -57,6 +57,7 @@ public function testProcessOutbound() { 'SERVER_NAME' => 'http://www.example.com', ]; $request = Request::create('/subdir', 'GET', [], [], [], $server); + $request->setSession($this->getSessionFromRequest()); $request->attributes->set(RouteObjectInterface::ROUTE_NAME, ''); $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/')); @@ -74,6 +75,7 @@ public function testProcessOutbound() { 'SERVER_NAME' => 'http://www.example.com', ]; $request = Request::create('/subdir/node/add', 'GET', [], [], [], $server); + $request->setSession($this->getSessionFromRequest()); $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add'); $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add')); @@ -91,6 +93,7 @@ public function testProcessOutbound() { 'SERVER_NAME' => 'http://www.example.com', ]; $request = Request::create('/', 'GET', [], [], [], $server); + $request->setSession($this->getSessionFromRequest()); $request->attributes->set(RouteObjectInterface::ROUTE_NAME, ''); $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/')); @@ -108,6 +111,7 @@ public function testProcessOutbound() { 'SERVER_NAME' => 'http://www.example.com', ]; $request = Request::create('/node/add', 'GET', [], [], [], $server); + $request->setSession($this->getSessionFromRequest()); $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add'); $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add')); diff --git a/core/tests/Drupal/KernelTests/Core/RouteProcessor/RouteProcessorCurrentIntegrationTest.php b/core/tests/Drupal/KernelTests/Core/RouteProcessor/RouteProcessorCurrentIntegrationTest.php index 4e42271aa5..6af106e1a4 100644 --- a/core/tests/Drupal/KernelTests/Core/RouteProcessor/RouteProcessorCurrentIntegrationTest.php +++ b/core/tests/Drupal/KernelTests/Core/RouteProcessor/RouteProcessorCurrentIntegrationTest.php @@ -58,6 +58,7 @@ public function testProcessOutbound() { 'SERVER_NAME' => 'http://www.example.com', ]; $request = Request::create('/subdir/', 'GET', [], [], [], $server); + $request->setSession($this->getSessionFromRequest()); $request->attributes->set(RouteObjectInterface::ROUTE_NAME, ''); $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/')); @@ -73,6 +74,7 @@ public function testProcessOutbound() { 'SERVER_NAME' => 'http://www.example.com', ]; $request = Request::create('/subdir/node/add', 'GET', [], [], [], $server); + $request->setSession($this->getSessionFromRequest()); $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add'); $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add')); @@ -88,6 +90,7 @@ public function testProcessOutbound() { 'SERVER_NAME' => 'http://www.example.com', ]; $request = Request::create('/', 'GET', [], [], [], $server); + $request->setSession($this->getSessionFromRequest()); $request->attributes->set(RouteObjectInterface::ROUTE_NAME, ''); $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/')); @@ -103,6 +106,7 @@ public function testProcessOutbound() { 'SERVER_NAME' => 'http://www.example.com', ]; $request = Request::create('/node/add', 'GET', [], [], [], $server); + $request->setSession($this->getSessionFromRequest()); $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add'); $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add')); @@ -119,6 +123,7 @@ public function testProcessOutbound() { 'SERVER_NAME' => 'http://www.example.com', ]; $request = Request::create('/invalid-path', 'GET', [], [], [], $server); + $request->setSession($this->getSessionFromRequest()); $request_stack->push($request); $request_context->fromRequest($request); diff --git a/core/tests/Drupal/KernelTests/Core/Session/MockSessionManager.php b/core/tests/Drupal/KernelTests/Core/Session/MockSessionManager.php new file mode 100644 index 0000000000..97204c99bf --- /dev/null +++ b/core/tests/Drupal/KernelTests/Core/Session/MockSessionManager.php @@ -0,0 +1,139 @@ +storage = new MockArraySessionStorage('MOCKSESSID', $metadata_bag); + } + + /** + * {@inheritdoc} + */ + public function start() { + return $this->storage->start(); + } + + /** + * {@inheritdoc} + */ + public function isStarted() { + return $this->storage->isStarted(); + } + + /** + * {@inheritdoc} + */ + public function getId() { + return $this->storage->getId(); + } + + /** + * {@inheritdoc} + */ + public function setId($id) { + return $this->storage->setId($id); + } + + /** + * {@inheritdoc} + */ + public function getName() { + return $this->storage->getName(); + } + + /** + * {@inheritdoc} + */ + public function setName($name) { + $this->storage->setName($name); + } + + /** + * {@inheritdoc} + */ + public function regenerate($destroy = FALSE, $lifetime = NULL) { + $this->storage->regenerate($destroy, $lifetime); + } + + /** + * {@inheritdoc} + */ + public function save() { + $this->storage->save(); + } + + /** + * {@inheritdoc} + */ + public function clear() { + $this->storage->clear(); + } + + /** + * {@inheritdoc} + */ + public function getBag($name) { + return $this->storage->getBag($name); + } + + /** + * {@inheritdoc} + */ + public function registerBag(SessionBagInterface $bag) { + $this->storage->registerBag($bag); + } + + /** + * {@inheritdoc} + */ + public function getMetadataBag() { + return $this->storage->getMetadataBag(); + } + + /** + * {@inheritdoc} + */ + public function delete($uid) { + // Ignored. + } + + /** + * {@inheritdoc} + */ + public function destroy() { + @trigger_error(__METHOD__ . ' not implemented in MockSessionManager', E_USER_ERROR); + } + + /** + * {@inheritdoc} + */ + public function setWriteSafeHandler(WriteSafeSessionHandlerInterface $handler) { + @trigger_error(__METHOD__ . ' not implemented in MockSessionManager', E_USER_ERROR); + } + +} diff --git a/core/tests/Drupal/KernelTests/Core/TempStore/AnonymousPrivateTempStoreTest.php b/core/tests/Drupal/KernelTests/Core/TempStore/AnonymousPrivateTempStoreTest.php index f5000fb234..892e03c8cd 100644 --- a/core/tests/Drupal/KernelTests/Core/TempStore/AnonymousPrivateTempStoreTest.php +++ b/core/tests/Drupal/KernelTests/Core/TempStore/AnonymousPrivateTempStoreTest.php @@ -37,6 +37,7 @@ protected function setUp() { $this->installSchema('system', ['key_value_expire']); $request = Request::create('/'); + $request->setSession($this->getSessionFromRequest()); $stack = $this->container->get('request_stack'); $stack->pop(); $stack->push($request); diff --git a/core/tests/Drupal/KernelTests/Core/Theme/ImageTest.php b/core/tests/Drupal/KernelTests/Core/Theme/ImageTest.php index 72cecce229..2ccf1f2e7e 100644 --- a/core/tests/Drupal/KernelTests/Core/Theme/ImageTest.php +++ b/core/tests/Drupal/KernelTests/Core/Theme/ImageTest.php @@ -33,6 +33,7 @@ protected function setUp() { // the Request containing the correct hostname. KernelTestBase doesn't set // it, so push another request onto the stack to ensure it's correct. $request = Request::create('/', 'GET', [], [], [], $_SERVER); + $request->setSession($this->getSessionFromRequest()); $this->container = \Drupal::service('kernel')->getContainer(); $this->container->get('request_stack')->push($request); diff --git a/core/tests/Drupal/KernelTests/KernelTestBase.php b/core/tests/Drupal/KernelTests/KernelTestBase.php index a9999936a0..c670bb9448 100644 --- a/core/tests/Drupal/KernelTests/KernelTestBase.php +++ b/core/tests/Drupal/KernelTests/KernelTestBase.php @@ -21,6 +21,7 @@ use Drupal\Tests\ConfigTestTrait; use Drupal\Tests\PhpunitCompatibilityTrait; use Drupal\Tests\RandomGeneratorTrait; +use Drupal\Tests\RequestSessionTestTrait; use Drupal\Tests\TestRequirementsTrait; use Drupal\TestTools\Comparator\MarkupInterfaceComparator; use PHPUnit\Framework\Exception; @@ -82,6 +83,7 @@ abstract class KernelTestBase extends TestCase implements ServiceProviderInterfa use ConfigTestTrait; use TestRequirementsTrait; use PhpunitCompatibilityTrait; + use RequestSessionTestTrait; /** * {@inheritdoc} @@ -360,6 +362,12 @@ private function bootKernel() { $this->container = $kernel->getContainer(); + // Prepare session and add it to the request. + /** @var \Symfony\Component\HttpFoundation\Session\SessionInterface $session */ + $session = $this->container->get('session'); + $session->start(); + $request->setSession($session); + // Ensure database tasks have been run. require_once __DIR__ . '/../../../includes/install.inc'; $connection = Database::getConnection(); @@ -535,6 +543,11 @@ public function register(ContainerBuilder $container) { ->addTag('persist'); $container ->setAlias('keyvalue', 'keyvalue.memory'); + $container + ->register('session_manager.memory', 'Drupal\KernelTests\Core\Session\MockSessionManager') + ->addArgument(new Reference('session_manager.metadata_bag')); + $container + ->setAlias('session_manager', 'session_manager.memory'); // Set the default language on the minimal container. $container->setParameter('language.default_values', Language::$defaultValues); diff --git a/core/tests/Drupal/KernelTests/KernelTestBaseTest.php b/core/tests/Drupal/KernelTests/KernelTestBaseTest.php index 426fa8bb27..61addd66a3 100644 --- a/core/tests/Drupal/KernelTests/KernelTestBaseTest.php +++ b/core/tests/Drupal/KernelTests/KernelTestBaseTest.php @@ -142,6 +142,19 @@ public function testRegister() { // Ensure getting the router.route_provider does not trigger a deprecation // message that errors. $this->container->get('router.route_provider'); + + // Verify that a usable session is available from the request. + /** @var \Symfony\Component\HttpFoundation\Session\SessionInterface $session */ + $session = $request->getSession(); + + $this->assertNotNull($session); + $this->assertTrue($session->isStarted()); + + $session->set('some-val', 'do-not-cleanup'); + $this->assertEqual('do-not-cleanup', $session->get('some-val')); + + $session->set('some-other-val', 'do-cleanup'); + $this->assertEqual('do-cleanup', $session->remove('some-other-val')); } /** diff --git a/core/tests/Drupal/Tests/BrowserTestBase.php b/core/tests/Drupal/Tests/BrowserTestBase.php index 4845bf86bd..82ba4ce74c 100644 --- a/core/tests/Drupal/Tests/BrowserTestBase.php +++ b/core/tests/Drupal/Tests/BrowserTestBase.php @@ -455,6 +455,15 @@ protected function cleanupEnvironment() { \Drupal::service('file_system')->deleteRecursive($this->siteDirectory, [$this, 'filePreDeleteCallback']); } + /** + * Clear and stop a session triggered during test run. + */ + protected function cleanupSession() { + $session = $this->getSessionFromRequest(); + $session->clear(); + $session->save(); + } + /** * {@inheritdoc} */ @@ -463,6 +472,7 @@ protected function tearDown() { // Destroy the testing kernel. if (isset($this->kernel)) { + $this->cleanupSession(); $this->cleanupEnvironment(); $this->kernel->shutdown(); } @@ -569,6 +579,7 @@ public function installDrupal() { $this->doInstall(); $this->initSettings(); $container = $this->initKernel(\Drupal::request()); + $this->prepareSession($container); $this->initConfig($container); $this->installDefaultThemeFromClassProperty($container); $this->installModulesFromClassProperty($container); diff --git a/core/tests/Drupal/Tests/RequestSessionTestTrait.php b/core/tests/Drupal/Tests/RequestSessionTestTrait.php new file mode 100644 index 0000000000..e3579c5195 --- /dev/null +++ b/core/tests/Drupal/Tests/RequestSessionTestTrait.php @@ -0,0 +1,33 @@ +container->get('request_stack'); + $request = $request_stack->getCurrentRequest(); + + if ($request && $request->hasSession()) { + $session = $request->getSession(); + } + else { + /** @var \Symfony\Component\HttpFoundation\Session\Session $session */ + $session = $this->container->get('session'); + @trigger_error('Failed to retrieve session from current request, request stack was modified during test.', E_USER_ERROR); + } + + return $session; + } + +}