AccountSwitcherTest.php in Zircon Profile 8
File
core/modules/system/src/Tests/Session/AccountSwitcherTest.php
View source
<?php
namespace Drupal\system\Tests\Session;
use Drupal\Core\Session\UserSession;
use Drupal\simpletest\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(array(
'uid' => 2,
)));
$this
->assertEqual($user
->id(), 2, 'Switched to user 2.');
$this
->assertFalse($session_handler
->isSessionWritable(), 'Session saving is disabled.');
$switcher
->switchTo(new UserSession(array(
'uid' => 3,
)));
$this
->assertEqual($user
->id(), 3, 'Switched to user 3.');
$switcher
->switchBack();
$this
->assertEqual($user
->id(), 2, 'Reverted to user 2.');
$this
->assertFalse($session_handler
->isSessionWritable(), 'Session saving still disabled.');
$switcher
->switchBack();
$this
->assertEqual($user
->id(), $original_user
->id(), 'Original user correctly restored.');
$this
->assertEqual($session_handler
->isSessionWritable(), $original_session_saving, 'Original session saving correctly restored.');
try {
$switcher
->switchBack();
$this
->fail('::switchBack() throws exception if called without previous switch.');
} catch (\RuntimeException $e) {
if ($e
->getMessage() == 'No more accounts to revert to.') {
$this
->pass('::switchBack() throws exception if called without previous switch.');
}
else {
$this
->fail($e
->getMessage());
}
}
}
}