DrupalWebTestCase::drupalCreateUser

7 drupal_web_test_case.php protected DrupalWebTestCase::drupalCreateUser(array $permissions = array())

Create a user with a given set of permissions.

Parameters

array $permissions: Array of permission names to assign to user. Note that the user always has the default permissions derived from the "authenticated users" role.

Return value

object|false A fully loaded user object with pass_raw property, or FALSE if account creation fails.

File

modules/simpletest/drupal_web_test_case.php, line 1084

Code

protected function drupalCreateUser(array $permissions = array()) {
  // Create a role with the given permission set, if any.
  $rid = FALSE;
  if ($permissions) {
    $rid = $this->drupalCreateRole($permissions);
    if (!$rid) {
      return FALSE;
    }
  }

  // Create a user assigned to that role.
  $edit = array();
  $edit['name']   = $this->randomName();
  $edit['mail']   = $edit['name'] . '@example.com';
  $edit['pass']   = user_password();
  $edit['status'] = 1;
  if ($rid) {
    $edit['roles'] = array($rid => $rid);
  }

  $account = user_save(drupal_anonymous_user(), $edit);

  $this->assertTrue(!empty($account->uid), t('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), t('User login'));
  if (empty($account->uid)) {
    return FALSE;
  }

  // Add the raw password so that we can log in as this user.
  $account->pass_raw = $edit['pass'];
  return $account;
}

Comments

There is a *really* annoying

There is a *really* annoying inconstancy in how to create a user with certain permissions, $this->drupalCreateUser(..) act's VERY different to drupalPost'ing a set of permissions into admin/people/permissions.

A typical use-case is where your test creates a new content type.

drupalCreateUser(array("some new permission") will always return "permission not found" for *NEW* permissions, you *MUST* do a drupalPost into admin/people/permissions

Drupal SimpleTest

CORRECT method

    $edit = array();
    $rid = 2;
    $test_type_name = "mynewtype";
    $edit["{$rid}[create {$test_type_name} content]"] = true;
    $edit["{$rid}[edit any {$test_type_name} content]"] = true;
    $this->drupalPost('admin/people/permissions', $edit, t('Save permissions'));
    drupal_static_reset('user_access');
    drupal_static_reset('user_role_permissions');
    $this->assertText(t('The changes have been saved.'), t('Successful save message displayed.'));

INCORRECT method

  $this->admin_user = $this->drupalCreateUser(array(
      'administer content types',
      'administer permissions',
      'create mynewtype content',
      'edit any mynewtype content'
      ));

very annoying!

reset permission cache

$permissions = array('your_new_permission'); or empty array.

$this->checkPermissions($permissions, TRUE);

Login or register to post comments