Upgraded drupal core with security updates
[yaffs-website] / web / core / tests / Drupal / KernelTests / Core / Session / AccountSwitcherTest.php
1 <?php
2
3 namespace Drupal\KernelTests\Core\Session;
4
5 use Drupal\Core\Session\UserSession;
6 use Drupal\KernelTests\KernelTestBase;
7
8 /**
9  * Test case for account switching.
10  *
11  * @group Session
12  */
13 class AccountSwitcherTest extends KernelTestBase {
14
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();
21
22     // Switch to user with uid 2.
23     $switcher->switchTo(new UserSession(['uid' => 2]));
24
25     // Verify that the active user has changed, and that session saving is
26     // disabled.
27     $this->assertEqual($user->id(), 2, 'Switched to user 2.');
28     $this->assertFalse($session_handler->isSessionWritable(), 'Session saving is disabled.');
29
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.');
33
34     // Revert to the user session that was active between the first and second
35     // switch.
36     $switcher->switchBack();
37
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.');
42
43     // Revert to the original account which was active before the first switch.
44     $switcher->switchBack();
45
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.');
50
51     // Verify that AccountSwitcherInterface::switchBack() will throw
52     // an exception if there are no accounts left in the stack.
53     try {
54       $switcher->switchBack();
55       $this->fail('::switchBack() throws exception if called without previous switch.');
56     }
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.');
60       }
61       else {
62         $this->fail($e->getMessage());
63       }
64     }
65   }
66
67 }