| 7 drupal_web_test_case.php | protected DrupalWebTestCase::drupalLogin(stdClass $user) |
Log in a user with the internal browser.
If a user is already logged in, then the current user is logged out before logging in the specified user.
Please note that neither the global $user nor the passed-in user object is populated with data of the logged in user. If you need full access to the user object after logging in, it must be updated manually. If you also need access to the plain-text password of the user (set by drupalCreateUser()), e.g. to log in the same user again, then it must be re-assigned manually. For example:
// Create a user.
$account = $this->drupalCreateUser(array());
$this->drupalLogin($account);
// Load real user object.
$pass_raw = $account->pass_raw;
$account = user_load($account->uid);
$account->pass_raw = $pass_raw;
Parameters
$user: User object representing the user to log in.
See also
drupalCreateUser()
File
- modules/
simpletest/ drupal_web_test_case.php, line 1208
Code
protected function drupalLogin(stdClass $user) {
if ($this->loggedInUser) {
$this->drupalLogout();
}
$edit = array(
'name' => $user->name,
'pass' => $user->pass_raw,
);
$this->drupalPost('user', $edit, t('Log in'));
// If a "log out" link appears on the page, it is almost certainly because
// the login was successful.
$pass = $this->assertLink(t('Log out'), 0, t('User %name successfully logged in.', array('%name' => $user->name)), t('User login'));
if ($pass) {
$this->loggedInUser = $user;
}
}
Login or register to post comments
Comments
global vs. logged in user
Keep in mind after you call drupalLogin() that there are two users involved, in different Drupal installations. The "outer" user is the developer or tester, i.e. you, logged into the permanent Drupal installation, running tests. The "inner" user has just logged into the temporary test installation, and will go away again at the end of the test.
The outer user is contained in the global $user object. The inner user is available in $this->loggedInUser, after you call drupalLogin(). Just remember that these two users live in different Drupal installations.
One way this can trip you up is if, within a test, you try to call user_access() to determine whether the inner (test) user has certain permissions, e.g.
if (user_access('administer users')) { ...This won't work as you intend, because user_access() tells you about the logged in user (i.e. you) in the outer installation, not the inner one. You might think instead of trying
if (user_access('administer users', $this->loggedInUser)) { ...but that's also wrong, because $this->loggedInUser is from a different Drupal installation: the inner one, while user_access() checks permissions in the outer one.
Until DrupalWebTestCase provides a general method of calling API functions within the inner installation, you'll have to find a workaround to test permissions on the inner user.