View source
<?php
namespace Drupal\Tests\user\Functional;
use Drupal\Tests\BrowserTestBase;
class UserRolesAssignmentTest extends BrowserTestBase {
protected function setUp() : void {
parent::setUp();
$admin_user = $this
->drupalCreateUser([
'administer permissions',
'administer users',
]);
$this
->drupalLogin($admin_user);
}
protected $defaultTheme = 'stark';
public function testAssignAndRemoveRole() {
$rid = $this
->drupalCreateRole([
'administer users',
]);
$account = $this
->drupalCreateUser();
$this
->drupalGet('user/' . $account
->id() . '/edit');
$this
->submitForm([
"roles[{$rid}]" => $rid,
], 'Save');
$this
->assertSession()
->pageTextContains('The changes have been saved.');
$this
->assertSession()
->checkboxChecked('edit-roles-' . $rid);
$this
->userLoadAndCheckRoleAssigned($account, $rid);
$this
->drupalGet('user/' . $account
->id() . '/edit');
$this
->submitForm([
"roles[{$rid}]" => FALSE,
], 'Save');
$this
->assertSession()
->pageTextContains('The changes have been saved.');
$this
->assertSession()
->checkboxNotChecked('edit-roles-' . $rid);
$this
->userLoadAndCheckRoleAssigned($account, $rid, FALSE);
}
public function testCreateUserWithRole() {
$rid = $this
->drupalCreateRole([
'administer users',
]);
$edit = [
'name' => $this
->randomMachineName(),
'mail' => $this
->randomMachineName() . '@example.com',
'pass[pass1]' => $pass = $this
->randomString(),
'pass[pass2]' => $pass,
"roles[{$rid}]" => $rid,
];
$this
->drupalGet('admin/people/create');
$this
->submitForm($edit, 'Create new account');
$this
->assertSession()
->pageTextContains('Created a new user account for ' . $edit['name'] . '.');
$account = user_load_by_name($edit['name']);
$this
->drupalGet('user/' . $account
->id() . '/edit');
$this
->assertSession()
->checkboxChecked('edit-roles-' . $rid);
$this
->userLoadAndCheckRoleAssigned($account, $rid);
$this
->drupalGet('user/' . $account
->id() . '/edit');
$this
->submitForm([
"roles[{$rid}]" => FALSE,
], 'Save');
$this
->assertSession()
->pageTextContains('The changes have been saved.');
$this
->assertSession()
->checkboxNotChecked('edit-roles-' . $rid);
$this
->userLoadAndCheckRoleAssigned($account, $rid, FALSE);
}
private function userLoadAndCheckRoleAssigned($account, $rid, $is_assigned = TRUE) {
$user_storage = $this->container
->get('entity_type.manager')
->getStorage('user');
$user_storage
->resetCache([
$account
->id(),
]);
$account = $user_storage
->load($account
->id());
if ($is_assigned) {
$this
->assertContains($rid, $account
->getRoles());
}
else {
$this
->assertNotContains($rid, $account
->getRoles());
}
}
}