3 namespace Drupal\KernelTests\Core\Session;
5 use Drupal\Core\Session\UserSession;
6 use Drupal\KernelTests\KernelTestBase;
9 * Test case for account switching.
13 class AccountSwitcherTest extends KernelTestBase {
15 public function testAccountSwitching() {
16 $session_handler = $this->container->get('session_handler.write_safe');
17 $user = $this->container->get('current_user');
18 $switcher = $this->container->get('account_switcher');
19 $original_user = $user->getAccount();
20 $original_session_saving = $session_handler->isSessionWritable();
22 // Switch to user with uid 2.
23 $switcher->switchTo(new UserSession(['uid' => 2]));
25 // Verify that the active user has changed, and that session saving is
27 $this->assertEqual($user->id(), 2, 'Switched to user 2.');
28 $this->assertFalse($session_handler->isSessionWritable(), 'Session saving is disabled.');
30 // Perform a second (nested) user account switch.
31 $switcher->switchTo(new UserSession(['uid' => 3]));
32 $this->assertEqual($user->id(), 3, 'Switched to user 3.');
34 // Revert to the user session that was active between the first and second
36 $switcher->switchBack();
38 // Since we are still in the account from the first switch, session handling
39 // still needs to be disabled.
40 $this->assertEqual($user->id(), 2, 'Reverted to user 2.');
41 $this->assertFalse($session_handler->isSessionWritable(), 'Session saving still disabled.');
43 // Revert to the original account which was active before the first switch.
44 $switcher->switchBack();
46 // Assert that the original account is active again, and that session saving
47 // has been re-enabled.
48 $this->assertEqual($user->id(), $original_user->id(), 'Original user correctly restored.');
49 $this->assertEqual($session_handler->isSessionWritable(), $original_session_saving, 'Original session saving correctly restored.');
51 // Verify that AccountSwitcherInterface::switchBack() will throw
52 // an exception if there are no accounts left in the stack.
54 $switcher->switchBack();
55 $this->fail('::switchBack() throws exception if called without previous switch.');
57 catch (\RuntimeException $e) {
58 if ($e->getMessage() == 'No more accounts to revert to.') {
59 $this->pass('::switchBack() throws exception if called without previous switch.');
62 $this->fail($e->getMessage());