AccountSwitcherTest.php in Drupal 9
File
core/tests/Drupal/KernelTests/Core/Session/AccountSwitcherTest.php
View source
<?php
namespace Drupal\KernelTests\Core\Session;
use Drupal\Core\Session\UserSession;
use Drupal\KernelTests\KernelTestBase;
class AccountSwitcherTest extends KernelTestBase {
public function testAccountSwitching() {
$session_handler = $this->container
->get('session_handler.write_safe');
$user = $this->container
->get('current_user');
$switcher = $this->container
->get('account_switcher');
$original_user = $user
->getAccount();
$original_session_saving = $session_handler
->isSessionWritable();
$switcher
->switchTo(new UserSession([
'uid' => 2,
]));
$this
->assertEquals(2, $user
->id(), 'Switched to user 2.');
$this
->assertFalse($session_handler
->isSessionWritable(), 'Session saving is disabled.');
$switcher
->switchTo(new UserSession([
'uid' => 3,
]));
$this
->assertEquals(3, $user
->id(), 'Switched to user 3.');
$switcher
->switchBack();
$this
->assertEquals(2, $user
->id(), 'Reverted to user 2.');
$this
->assertFalse($session_handler
->isSessionWritable(), 'Session saving still disabled.');
$switcher
->switchBack();
$this
->assertEquals($original_user
->id(), $user
->id(), 'Original user correctly restored.');
$this
->assertEquals($original_session_saving, $session_handler
->isSessionWritable(), 'Original session saving correctly restored.');
$this
->expectException(\RuntimeException::class);
$this
->expectExceptionMessage('No more accounts to revert to.');
$switcher
->switchBack();
}
}