AccountSwitcherTest.php 2.4 KB

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