Update core 8.3.0

This commit is contained in:
Rob Davies 2017-04-13 15:53:35 +01:00
parent da7a7918f8
commit cd7a898e66
6144 changed files with 132297 additions and 87747 deletions

View file

@ -0,0 +1,56 @@
<?php
namespace Drupal\Tests\user\Functional;
use Drupal\system\Tests\Entity\EntityWithUriCacheTagsTestBase;
use Drupal\user\Entity\Role;
use Drupal\user\Entity\User;
use Drupal\user\RoleInterface;
/**
* Tests the User entity's cache tags.
*
* @group user
*/
class UserCacheTagsTest extends EntityWithUriCacheTagsTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['user'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Give anonymous users permission to view user profiles, so that we can
// verify the cache tags of cached versions of user profile pages.
$user_role = Role::load(RoleInterface::ANONYMOUS_ID);
$user_role->grantPermission('access user profiles');
$user_role->save();
}
/**
* {@inheritdoc}
*/
protected function createEntity() {
// Create a "Llama" user.
$user = User::create([
'name' => 'Llama',
'status' => TRUE,
]);
$user->save();
return $user;
}
/**
* {@inheritdoc}
*/
protected function getAdditionalCacheTagsForEntityListing() {
return ['user:0', 'user:1'];
}
}

View file

@ -0,0 +1,45 @@
<?php
namespace Drupal\Tests\user\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Tests the create user administration page.
*
* @group user
*/
class UserCreateFailMailTest extends BrowserTestBase {
/**
* Modules to enable
*
* @var array
*/
public static $modules = ['system_mail_failure_test'];
/**
* Tests the create user administration page.
*/
public function testUserAdd() {
$user = $this->drupalCreateUser(['administer users']);
$this->drupalLogin($user);
// Replace the mail functionality with a fake, malfunctioning service.
$this->config('system.mail')->set('interface.default', 'test_php_mail_failure')->save();
// Create a user, but fail to send an email.
$name = $this->randomMachineName();
$edit = [
'name' => $name,
'mail' => $this->randomMachineName() . '@example.com',
'pass[pass1]' => $pass = $this->randomString(),
'pass[pass2]' => $pass,
'notify' => TRUE,
];
$this->drupalPostForm('admin/people/create', $edit, t('Create new account'));
$this->assertText(t('Unable to send email. Contact the site administrator if the problem persists.'));
$this->assertNoText(t('A welcome message with further instructions has been emailed to the new user @name.', ['@name' => $edit['name']]));
}
}

View file

@ -0,0 +1,55 @@
<?php
namespace Drupal\Tests\user\Functional;
use Drupal\Tests\BrowserTestBase;
use Drupal\user\Entity\User;
/**
* Tests account deleting of users.
*
* @group user
*/
class UserDeleteTest extends BrowserTestBase {
/**
* Test deleting multiple users.
*/
public function testUserDeleteMultiple() {
// Create a few users with permissions, so roles will be created.
$user_a = $this->drupalCreateUser(['access user profiles']);
$user_b = $this->drupalCreateUser(['access user profiles']);
$user_c = $this->drupalCreateUser(['access user profiles']);
$uids = [$user_a->id(), $user_b->id(), $user_c->id()];
// These users should have a role
$query = db_select('user__roles', 'r');
$roles_created = $query
->fields('r', ['entity_id'])
->condition('entity_id', $uids, 'IN')
->countQuery()
->execute()
->fetchField();
$this->assertTrue($roles_created > 0, 'Role assignments created for new users and deletion of role assignments can be tested');
// We should be able to load one of the users.
$this->assertTrue(User::load($user_a->id()), 'User is created and deletion of user can be tested');
// Delete the users.
user_delete_multiple($uids);
// Test if the roles assignments are deleted.
$query = db_select('user__roles', 'r');
$roles_after_deletion = $query
->fields('r', ['entity_id'])
->condition('entity_id', $uids, 'IN')
->countQuery()
->execute()
->fetchField();
$this->assertTrue($roles_after_deletion == 0, 'Role assignments deleted along with users');
// Test if the users are deleted, User::load() will return NULL.
$this->assertNull(User::load($user_a->id()), format_string('User with id @uid deleted.', ['@uid' => $user_a->id()]));
$this->assertNull(User::load($user_b->id()), format_string('User with id @uid deleted.', ['@uid' => $user_b->id()]));
$this->assertNull(User::load($user_c->id()), format_string('User with id @uid deleted.', ['@uid' => $user_c->id()]));
}
}

View file

@ -0,0 +1,43 @@
<?php
namespace Drupal\Tests\user\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Tests user edited own account can still log in.
*
* @group user
*/
class UserEditedOwnAccountTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['user_form_test'];
public function testUserEditedOwnAccount() {
// Change account setting 'Who can register accounts?' to Administrators
// only.
$this->config('user.settings')->set('register', USER_REGISTER_ADMINISTRATORS_ONLY)->save();
// Create a new user account and log in.
$account = $this->drupalCreateUser(['change own username']);
$this->drupalLogin($account);
// Change own username.
$edit = [];
$edit['name'] = $this->randomMachineName();
$this->drupalPostForm('user/' . $account->id() . '/edit', $edit, t('Save'));
// Log out.
$this->drupalLogout();
// Set the new name on the user account and attempt to log back in.
$account->name = $edit['name'];
$this->drupalLogin($account);
}
}

View file

@ -0,0 +1,64 @@
<?php
namespace Drupal\Tests\user\Functional;
use Drupal\Tests\BrowserTestBase;
use Drupal\user\Entity\User;
/**
* Tests specific parts of the user entity like the URI callback and the label
* callback.
*
* @group user
*/
class UserEntityCallbacksTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['user', 'user_hooks_test'];
/**
* An authenticated user to use for testing.
*
* @var \Drupal\user\UserInterface
*/
protected $account;
/**
* An anonymous user to use for testing.
*
* @var \Drupal\user\UserInterface
*/
protected $anonymous;
protected function setUp() {
parent::setUp();
$this->account = $this->drupalCreateUser();
$this->anonymous = User::create(['uid' => 0]);
}
/**
* Test label callback.
*/
public function testLabelCallback() {
$this->assertEqual($this->account->label(), $this->account->getUsername(), 'The username should be used as label');
// Setup a random anonymous name to be sure the name is used.
$name = $this->randomMachineName();
$this->config('user.settings')->set('anonymous', $name)->save();
$this->assertEqual($this->anonymous->label(), $name, 'The variable anonymous should be used for name of uid 0');
$this->assertEqual($this->anonymous->getDisplayName(), $name, 'The variable anonymous should be used for display name of uid 0');
$this->assertEqual($this->anonymous->getUserName(), '', 'The raw anonymous user name should be empty string');
// Set to test the altered username.
\Drupal::state()->set('user_hooks_test_user_format_name_alter', TRUE);
$this->assertEqual($this->account->getDisplayName(), '<em>' . $this->account->id() . '</em>', 'The user display name should be altered.');
$this->assertEqual($this->account->getUsername(), $this->account->name->value, 'The user name should not be altered.');
}
}

View file

@ -0,0 +1,67 @@
<?php
namespace Drupal\Tests\user\Functional;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Tests\BrowserTestBase;
/**
* Functional tests for a user's ability to change their default language.
*
* @group user
*/
class UserLanguageTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['user', 'language'];
/**
* Test if user can change their default language.
*/
public function testUserLanguageConfiguration() {
// User to add and remove language.
$admin_user = $this->drupalCreateUser(['administer languages', 'access administration pages']);
// User to change their default language.
$web_user = $this->drupalCreateUser();
// Add custom language.
$this->drupalLogin($admin_user);
// Code for the language.
$langcode = 'xx';
// The English name for the language.
$name = $this->randomMachineName(16);
$edit = [
'predefined_langcode' => 'custom',
'langcode' => $langcode,
'label' => $name,
'direction' => LanguageInterface::DIRECTION_LTR,
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
$this->drupalLogout();
// Log in as normal user and edit account settings.
$this->drupalLogin($web_user);
$path = 'user/' . $web_user->id() . '/edit';
$this->drupalGet($path);
// Ensure language settings widget is available.
$this->assertText(t('Language'), 'Language selector available.');
// Ensure custom language is present.
$this->assertText($name, 'Language present on form.');
// Switch to our custom language.
$edit = [
'preferred_langcode' => $langcode,
];
$this->drupalPostForm($path, $edit, t('Save'));
// Ensure form was submitted successfully.
$this->assertText(t('The changes have been saved.'), 'Changes were saved.');
// Check if language was changed.
$this->assertOptionSelected('edit-preferred-langcode', $langcode, 'Default language successfully updated.');
$this->drupalLogout();
}
}

View file

@ -0,0 +1,76 @@
<?php
namespace Drupal\Tests\user\Functional;
use Drupal\Core\Test\AssertMailTrait;
use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
/**
* Tests _user_mail_notify() use of user.settings.notify.*.
*
* @group user
*/
class UserMailNotifyTest extends EntityKernelTestBase {
use AssertMailTrait {
getMails as drupalGetMails;
}
/**
* Data provider for user mail testing.
*
* @return array
*/
public function userMailsProvider() {
return [
['cancel_confirm', ['cancel_confirm']],
['password_reset', ['password_reset']],
['status_activated', ['status_activated']],
['status_blocked', ['status_blocked']],
['status_canceled', ['status_canceled']],
['register_admin_created', ['register_admin_created']],
['register_no_approval_required', ['register_no_approval_required']],
['register_pending_approval', ['register_pending_approval', 'register_pending_approval_admin']]
];
}
/**
* Tests mails are sent when notify.$op is TRUE.
*
* @param string $op
* The operation being performed on the account.
* @param array $mail_keys
* The mail keys to test for.
*
* @dataProvider userMailsProvider
*/
public function testUserMailsSent($op, array $mail_keys) {
$this->config('user.settings')->set('notify.' . $op, TRUE)->save();
$return = _user_mail_notify($op, $this->createUser());
$this->assertTrue($return, '_user_mail_notify() returns TRUE.');
foreach ($mail_keys as $key) {
$filter = ['key' => $key];
$this->assertNotEmpty($this->getMails($filter), "Mails with $key exists.");
}
$this->assertCount(count($mail_keys), $this->getMails(), 'The expected number of emails sent.');
}
/**
* Tests mails are not sent when notify.$op is FALSE.
*
* @param string $op
* The operation being performed on the account.
* @param array $mail_keys
* The mail keys to test for. Ignored by this test because we assert that no
* mails at all are sent.
*
* @dataProvider userMailsProvider
*/
public function testUserMailsNotSent($op, array $mail_keys) {
$this->config('user.settings')->set('notify.' . $op, FALSE)->save();
$return = _user_mail_notify($op, $this->createUser());
$this->assertFalse($return, '_user_mail_notify() returns FALSE.');
$this->assertEmpty($this->getMails(), 'No emails sent by _user_mail_notify().');
}
}

View file

@ -0,0 +1,94 @@
<?php
namespace Drupal\Tests\user\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Tests that users can be assigned and unassigned roles.
*
* @group user
*/
class UserRolesAssignmentTest extends BrowserTestBase {
protected function setUp() {
parent::setUp();
$admin_user = $this->drupalCreateUser(['administer permissions', 'administer users']);
$this->drupalLogin($admin_user);
}
/**
* Tests that a user can be assigned a role and that the role can be removed
* again.
*/
public function testAssignAndRemoveRole() {
$rid = $this->drupalCreateRole(['administer users']);
$account = $this->drupalCreateUser();
// Assign the role to the user.
$this->drupalPostForm('user/' . $account->id() . '/edit', ["roles[$rid]" => $rid], t('Save'));
$this->assertText(t('The changes have been saved.'));
$this->assertFieldChecked('edit-roles-' . $rid, 'Role is assigned.');
$this->userLoadAndCheckRoleAssigned($account, $rid);
// Remove the role from the user.
$this->drupalPostForm('user/' . $account->id() . '/edit', ["roles[$rid]" => FALSE], t('Save'));
$this->assertText(t('The changes have been saved.'));
$this->assertNoFieldChecked('edit-roles-' . $rid, 'Role is removed from user.');
$this->userLoadAndCheckRoleAssigned($account, $rid, FALSE);
}
/**
* Tests that when creating a user the role can be assigned. And that it can
* be removed again.
*/
public function testCreateUserWithRole() {
$rid = $this->drupalCreateRole(['administer users']);
// Create a new user and add the role at the same time.
$edit = [
'name' => $this->randomMachineName(),
'mail' => $this->randomMachineName() . '@example.com',
'pass[pass1]' => $pass = $this->randomString(),
'pass[pass2]' => $pass,
"roles[$rid]" => $rid,
];
$this->drupalPostForm('admin/people/create', $edit, t('Create new account'));
$this->assertText(t('Created a new user account for @name.', ['@name' => $edit['name']]));
// Get the newly added user.
$account = user_load_by_name($edit['name']);
$this->drupalGet('user/' . $account->id() . '/edit');
$this->assertFieldChecked('edit-roles-' . $rid, 'Role is assigned.');
$this->userLoadAndCheckRoleAssigned($account, $rid);
// Remove the role again.
$this->drupalPostForm('user/' . $account->id() . '/edit', ["roles[$rid]" => FALSE], t('Save'));
$this->assertText(t('The changes have been saved.'));
$this->assertNoFieldChecked('edit-roles-' . $rid, 'Role is removed from user.');
$this->userLoadAndCheckRoleAssigned($account, $rid, FALSE);
}
/**
* Check role on user object.
*
* @param object $account
* The user account to check.
* @param string $rid
* The role ID to search for.
* @param bool $is_assigned
* (optional) Whether to assert that $rid exists (TRUE) or not (FALSE).
* Defaults to TRUE.
*/
private function userLoadAndCheckRoleAssigned($account, $rid, $is_assigned = TRUE) {
$user_storage = $this->container->get('entity.manager')->getStorage('user');
$user_storage->resetCache([$account->id()]);
$account = $user_storage->load($account->id());
if ($is_assigned) {
$this->assertFalse(array_search($rid, $account->getRoles()) === FALSE, 'The role is present in the user object.');
}
else {
$this->assertTrue(array_search($rid, $account->getRoles()) === FALSE, 'The role is not present in the user object.');
}
}
}

View file

@ -0,0 +1,61 @@
<?php
namespace Drupal\Tests\user\Functional;
use Drupal\Tests\BrowserTestBase;
use Drupal\user\Entity\User;
/**
* Tests account saving for arbitrary new uid.
*
* @group user
*/
class UserSaveTest extends BrowserTestBase {
/**
* Test creating a user with arbitrary uid.
*/
public function testUserImport() {
// User ID must be a number that is not in the database.
$uids = \Drupal::entityManager()->getStorage('user')->getQuery()
->sort('uid', 'DESC')
->range(0, 1)
->execute();
$max_uid = reset($uids);
$test_uid = $max_uid + mt_rand(1000, 1000000);
$test_name = $this->randomMachineName();
// Create the base user, based on drupalCreateUser().
$user = User::create([
'name' => $test_name,
'uid' => $test_uid,
'mail' => $test_name . '@example.com',
'pass' => user_password(),
'status' => 1,
]);
$user->enforceIsNew();
$user->save();
// Test if created user exists.
$user_by_uid = User::load($test_uid);
$this->assertTrue($user_by_uid, 'Loading user by uid.');
$user_by_name = user_load_by_name($test_name);
$this->assertTrue($user_by_name, 'Loading user by name.');
}
/**
* Ensures that an existing password is unset after the user was saved.
*/
public function testExistingPasswordRemoval() {
/** @var \Drupal\user\Entity\User $user */
$user = User::create(['name' => $this->randomMachineName()]);
$user->save();
$user->setExistingPassword('existing password');
$this->assertNotNull($user->pass->existing);
$user->save();
$this->assertNull($user->pass->existing);
}
}

View file

@ -0,0 +1,120 @@
<?php
namespace Drupal\Tests\user\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Tests the user search page and verifies that sensitive information is hidden
* from unauthorized users.
*
* @group user
*/
class UserSearchTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['search'];
public function testUserSearch() {
// Verify that a user without 'administer users' permission cannot search
// for users by email address. Additionally, ensure that the username has a
// plus sign to ensure searching works with that.
$user1 = $this->drupalCreateUser(['access user profiles', 'search content'], "foo+bar");
$this->drupalLogin($user1);
$keys = $user1->getEmail();
$edit = ['keys' => $keys];
$this->drupalPostForm('search/user', $edit, t('Search'));
$this->assertText(t('Your search yielded no results.'), 'Search by email did not work for non-admin user');
$this->assertText('no results', 'Search by email gave no-match message');
// Verify that a non-matching query gives an appropriate message.
$keys = 'nomatch';
$edit = ['keys' => $keys];
$this->drupalPostForm('search/user', $edit, t('Search'));
$this->assertText('no results', 'Non-matching search gave appropriate message');
// Verify that a user with search permission can search for users by name.
$keys = $user1->getUsername();
$edit = ['keys' => $keys];
$this->drupalPostForm('search/user', $edit, t('Search'));
$this->assertLink($keys, 0, 'Search by username worked for non-admin user');
// Verify that searching by sub-string works too.
$subkey = substr($keys, 1, 5);
$edit = ['keys' => $subkey];
$this->drupalPostForm('search/user', $edit, t('Search'));
$this->assertLink($keys, 0, 'Search by username substring worked for non-admin user');
// Verify that wildcard search works.
$subkey = substr($keys, 0, 2) . '*' . substr($keys, 4, 2);
$edit = ['keys' => $subkey];
$this->drupalPostForm('search/user', $edit, t('Search'));
$this->assertLink($keys, 0, 'Search with wildcard worked for non-admin user');
// Verify that a user with 'administer users' permission can search by
// email.
$user2 = $this->drupalCreateUser(['administer users', 'access user profiles', 'search content']);
$this->drupalLogin($user2);
$keys = $user2->getEmail();
$edit = ['keys' => $keys];
$this->drupalPostForm('search/user', $edit, t('Search'));
$this->assertText($keys, 'Search by email works for administrative user');
$this->assertText($user2->getUsername(), 'Search by email resulted in username on page for administrative user');
// Verify that a substring works too for email.
$subkey = substr($keys, 1, 5);
$edit = ['keys' => $subkey];
$this->drupalPostForm('search/user', $edit, t('Search'));
$this->assertText($keys, 'Search by email substring works for administrative user');
$this->assertText($user2->getUsername(), 'Search by email substring resulted in username on page for administrative user');
// Verify that wildcard search works for email
$subkey = substr($keys, 0, 2) . '*' . substr($keys, 4, 2);
$edit = ['keys' => $subkey];
$this->drupalPostForm('search/user', $edit, t('Search'));
$this->assertText($user2->getUsername(), 'Search for email wildcard resulted in username on page for administrative user');
// Verify that if they search by user name, they see email address too.
$keys = $user1->getUsername();
$edit = ['keys' => $keys];
$this->drupalPostForm('search/user', $edit, t('Search'));
$this->assertText($keys, 'Search by username works for admin user');
$this->assertText($user1->getEmail(), 'Search by username for admin shows email address too');
// Create a blocked user.
$blocked_user = $this->drupalCreateUser();
$blocked_user->block();
$blocked_user->save();
// Verify that users with "administer users" permissions can see blocked
// accounts in search results.
$edit = ['keys' => $blocked_user->getUsername()];
$this->drupalPostForm('search/user', $edit, t('Search'));
$this->assertText($blocked_user->getUsername(), 'Blocked users are listed on the user search results for users with the "administer users" permission.');
// Verify that users without "administer users" permissions do not see
// blocked accounts in search results.
$this->drupalLogin($user1);
$edit = ['keys' => $blocked_user->getUsername()];
$this->drupalPostForm('search/user', $edit, t('Search'));
$this->assertText(t('Your search yielded no results.'), 'Blocked users are hidden from the user search results.');
// Create a user without search permission, and one without user page view
// permission. Verify that neither one can access the user search page.
$user3 = $this->drupalCreateUser(['search content']);
$this->drupalLogin($user3);
$this->drupalGet('search/user');
$this->assertResponse('403', 'User without user profile access cannot search');
$user4 = $this->drupalCreateUser(['access user profiles']);
$this->drupalLogin($user4);
$this->drupalGet('search/user');
$this->assertResponse('403', 'User without search permission cannot search');
$this->drupalLogout();
}
}

View file

@ -0,0 +1,168 @@
<?php
namespace Drupal\Tests\user\Functional;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\Tests\BrowserTestBase;
use Drupal\user\Entity\User;
/**
* Generates text using placeholders for dummy content to check user token
* replacement.
*
* @group user
*/
class UserTokenReplaceTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['language', 'user_hooks_test'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
ConfigurableLanguage::createFromLangcode('de')->save();
}
/**
* Creates a user, then tests the tokens generated from it.
*/
public function testUserTokenReplacement() {
$token_service = \Drupal::token();
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
$url_options = [
'absolute' => TRUE,
'language' => $language_interface,
];
\Drupal::state()->set('user_hooks_test_user_format_name_alter', TRUE);
\Drupal::state()->set('user_hooks_test_user_format_name_alter_safe', TRUE);
// Create two users and log them in one after another.
$user1 = $this->drupalCreateUser([]);
$user2 = $this->drupalCreateUser([]);
$this->drupalLogin($user1);
$this->drupalLogout();
$this->drupalLogin($user2);
$account = User::load($user1->id());
$global_account = User::load(\Drupal::currentUser()->id());
// Generate and test tokens.
$tests = [];
$tests['[user:uid]'] = $account->id();
$tests['[user:name]'] = $account->getAccountName();
$tests['[user:account-name]'] = $account->getAccountName();
$tests['[user:display-name]'] = $account->getDisplayName();
$tests['[user:mail]'] = $account->getEmail();
$tests['[user:url]'] = $account->url('canonical', $url_options);
$tests['[user:edit-url]'] = $account->url('edit-form', $url_options);
$tests['[user:last-login]'] = format_date($account->getLastLoginTime(), 'medium', '', NULL, $language_interface->getId());
$tests['[user:last-login:short]'] = format_date($account->getLastLoginTime(), 'short', '', NULL, $language_interface->getId());
$tests['[user:created]'] = format_date($account->getCreatedTime(), 'medium', '', NULL, $language_interface->getId());
$tests['[user:created:short]'] = format_date($account->getCreatedTime(), 'short', '', NULL, $language_interface->getId());
$tests['[current-user:name]'] = $global_account->getAccountName();
$tests['[current-user:account-name]'] = $global_account->getAccountName();
$tests['[current-user:display-name]'] = $global_account->getDisplayName();
$base_bubbleable_metadata = BubbleableMetadata::createFromObject($account);
$metadata_tests = [];
$metadata_tests['[user:uid]'] = $base_bubbleable_metadata;
$metadata_tests['[user:name]'] = $base_bubbleable_metadata;
$metadata_tests['[user:account-name]'] = $base_bubbleable_metadata;
$metadata_tests['[user:display-name]'] = $base_bubbleable_metadata;
$metadata_tests['[user:mail]'] = $base_bubbleable_metadata;
$metadata_tests['[user:url]'] = $base_bubbleable_metadata;
$metadata_tests['[user:edit-url]'] = $base_bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
// This test runs with the Language module enabled, which means config is
// overridden by LanguageConfigFactoryOverride (to provide translations of
// config). This causes the interface language cache context to be added for
// config entities. The four next tokens use DateFormat Config entities, and
// therefore have the interface language cache context.
$bubbleable_metadata->addCacheContexts(['languages:language_interface']);
$metadata_tests['[user:last-login]'] = $bubbleable_metadata->addCacheTags(['rendered']);
$metadata_tests['[user:last-login:short]'] = $bubbleable_metadata;
$metadata_tests['[user:created]'] = $bubbleable_metadata;
$metadata_tests['[user:created:short]'] = $bubbleable_metadata;
$metadata_tests['[current-user:name]'] = $base_bubbleable_metadata->merge(BubbleableMetadata::createFromObject($global_account)->addCacheContexts(['user']));
$metadata_tests['[current-user:account-name]'] = $base_bubbleable_metadata->merge(BubbleableMetadata::createFromObject($global_account)->addCacheContexts(['user']));
$metadata_tests['[current-user:display-name]'] = $base_bubbleable_metadata->merge(BubbleableMetadata::createFromObject($global_account)->addCacheContexts(['user']));
// Test to make sure that we generated something for each token.
$this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
foreach ($tests as $input => $expected) {
$bubbleable_metadata = new BubbleableMetadata();
$output = $token_service->replace($input, ['user' => $account], ['langcode' => $language_interface->getId()], $bubbleable_metadata);
$this->assertEqual($output, $expected, new FormattableMarkup('User token %token replaced.', ['%token' => $input]));
$this->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
}
// Generate tokens for the anonymous user.
$anonymous_user = User::load(0);
$tests = [];
$tests['[user:uid]'] = t('not yet assigned');
$tests['[user:display-name]'] = $anonymous_user->getDisplayName();
$base_bubbleable_metadata = BubbleableMetadata::createFromObject($anonymous_user);
$metadata_tests = [];
$metadata_tests['[user:uid]'] = $base_bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
$bubbleable_metadata->addCacheableDependency(\Drupal::config('user.settings'));
$metadata_tests['[user:display-name]'] = $bubbleable_metadata;
foreach ($tests as $input => $expected) {
$bubbleable_metadata = new BubbleableMetadata();
$output = $token_service->replace($input, ['user' => $anonymous_user], ['langcode' => $language_interface->getId()], $bubbleable_metadata);
$this->assertEqual($output, $expected, format_string('Sanitized user token %token replaced.', ['%token' => $input]));
$this->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
}
// Generate login and cancel link.
$tests = [];
$tests['[user:one-time-login-url]'] = user_pass_reset_url($account);
$tests['[user:cancel-url]'] = user_cancel_url($account);
// Generate tokens with interface language.
$link = \Drupal::url('user.page', [], ['absolute' => TRUE]);
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, ['user' => $account], ['langcode' => $language_interface->getId(), 'callback' => 'user_mail_tokens', 'clear' => TRUE]);
$this->assertTrue(strpos($output, $link) === 0, 'Generated URL is in interface language.');
}
// Generate tokens with the user's preferred language.
$account->preferred_langcode = 'de';
$account->save();
$link = \Drupal::url('user.page', [], ['language' => \Drupal::languageManager()->getLanguage($account->getPreferredLangcode()), 'absolute' => TRUE]);
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, ['user' => $account], ['callback' => 'user_mail_tokens', 'clear' => TRUE]);
$this->assertTrue(strpos($output, $link) === 0, "Generated URL is in the user's preferred language.");
}
// Generate tokens with one specific language.
$link = \Drupal::url('user.page', [], ['language' => \Drupal::languageManager()->getLanguage('de'), 'absolute' => TRUE]);
foreach ($tests as $input => $expected) {
foreach ([$user1, $user2] as $account) {
$output = $token_service->replace($input, ['user' => $account], ['langcode' => 'de', 'callback' => 'user_mail_tokens', 'clear' => TRUE]);
$this->assertTrue(strpos($output, $link) === 0, "Generated URL in the requested language.");
}
}
// Generate user display name tokens when safe markup is returned.
// @see user_hooks_test_user_format_name_alter()
\Drupal::state()->set('user_hooks_test_user_format_name_alter_safe', TRUE);
$input = '[user:display-name] [current-user:display-name]';
$expected = "<em>{$user1->id()}</em> <em>{$user2->id()}</em>";
$output = $token_service->replace($input, ['user' => $user1]);
$this->assertEqual($output, $expected, new FormattableMarkup('User token %token does not escape safe markup.', ['%token' => 'display-name']));
}
}

View file

@ -48,7 +48,7 @@ class UserRoleConditionTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('system', 'user', 'field');
public static $modules = ['system', 'user', 'field'];
/**
* {@inheritdoc}
@ -62,38 +62,38 @@ class UserRoleConditionTest extends KernelTestBase {
$this->manager = $this->container->get('plugin.manager.condition');
// Set up the authenticated and anonymous roles.
Role::create(array(
Role::create([
'id' => RoleInterface::ANONYMOUS_ID,
'label' => 'Anonymous user',
))->save();
Role::create(array(
])->save();
Role::create([
'id' => RoleInterface::AUTHENTICATED_ID,
'label' => 'Authenticated user',
))->save();
])->save();
// Create new role.
$rid = strtolower($this->randomMachineName(8));
$label = $this->randomString(8);
$role = Role::create(array(
$role = Role::create([
'id' => $rid,
'label' => $label,
));
]);
$role->save();
$this->role = $role;
// Setup an anonymous user for our tests.
$this->anonymous = User::create(array(
$this->anonymous = User::create([
'name' => '',
'uid' => 0,
));
]);
$this->anonymous->save();
// Loading the anonymous user adds the correct role.
$this->anonymous = User::load($this->anonymous->id());
// Setup an authenticated user for our tests.
$this->authenticated = User::create(array(
$this->authenticated = User::create([
'name' => $this->randomMachineName(),
));
]);
$this->authenticated->save();
// Add the custom role.
$this->authenticated->addRole($this->role->id());
@ -107,7 +107,7 @@ class UserRoleConditionTest extends KernelTestBase {
// authenticated user roles.
/** @var $condition \Drupal\Core\Condition\ConditionInterface */
$condition = $this->manager->createInstance('user_role')
->setConfig('roles', array(RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID))
->setConfig('roles', [RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID])
->setContextValue('user', $this->anonymous);
$this->assertFalse($condition->execute(), 'Anonymous users fail role checks for authenticated.');
// Check for the proper summary.
@ -115,13 +115,13 @@ class UserRoleConditionTest extends KernelTestBase {
$this->assertEqual($condition->summary(), 'The user is a member of Authenticated user');
// Set the user role to anonymous.
$condition->setConfig('roles', array(RoleInterface::ANONYMOUS_ID => RoleInterface::ANONYMOUS_ID));
$condition->setConfig('roles', [RoleInterface::ANONYMOUS_ID => RoleInterface::ANONYMOUS_ID]);
$this->assertTrue($condition->execute(), 'Anonymous users pass role checks for anonymous.');
// Check for the proper summary.
$this->assertEqual($condition->summary(), 'The user is a member of Anonymous user');
// Set the user role to check anonymous or authenticated.
$condition->setConfig('roles', array(RoleInterface::ANONYMOUS_ID => RoleInterface::ANONYMOUS_ID, RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID));
$condition->setConfig('roles', [RoleInterface::ANONYMOUS_ID => RoleInterface::ANONYMOUS_ID, RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID]);
$this->assertTrue($condition->execute(), 'Anonymous users pass role checks for anonymous or authenticated.');
// Check for the proper summary.
$this->assertEqual($condition->summary(), 'The user is a member of Anonymous user, Authenticated user');
@ -132,11 +132,11 @@ class UserRoleConditionTest extends KernelTestBase {
$this->assertTrue($condition->execute(), 'Authenticated users pass role checks for anonymous or authenticated.');
// Set the role to just authenticated and recheck.
$condition->setConfig('roles', array(RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID));
$condition->setConfig('roles', [RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID]);
$this->assertTrue($condition->execute(), 'Authenticated users pass role checks for authenticated.');
// Test Constructor injection.
$condition = $this->manager->createInstance('user_role', array('roles' => array(RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID), 'context' => array('user' => $this->authenticated)));
$condition = $this->manager->createInstance('user_role', ['roles' => [RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID], 'context' => ['user' => $this->authenticated]]);
$this->assertTrue($condition->execute(), 'Constructor injection of context and configuration working as anticipated.');
// Check the negated summary.
@ -144,14 +144,14 @@ class UserRoleConditionTest extends KernelTestBase {
$this->assertEqual($condition->summary(), 'The user is not a member of Authenticated user');
// Check the complex negated summary.
$condition->setConfig('roles', array(RoleInterface::ANONYMOUS_ID => RoleInterface::ANONYMOUS_ID, RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID));
$condition->setConfig('roles', [RoleInterface::ANONYMOUS_ID => RoleInterface::ANONYMOUS_ID, RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID]);
$this->assertEqual($condition->summary(), 'The user is not a member of Anonymous user, Authenticated user');
// Check a custom role.
$condition->setConfig('roles', array($this->role->id() => $this->role->id()));
$condition->setConfig('roles', [$this->role->id() => $this->role->id()]);
$condition->setConfig('negate', FALSE);
$this->assertTrue($condition->execute(), 'Authenticated user is a member of the custom role.');
$this->assertEqual($condition->summary(), SafeMarkup::format('The user is a member of @roles', array('@roles' => $this->role->label())));
$this->assertEqual($condition->summary(), SafeMarkup::format('The user is a member of @roles', ['@roles' => $this->role->label()]));
}
}

View file

@ -41,7 +41,7 @@ class MigrateUserProfileFieldTest extends MigrateDrupal6TestBase {
$field_storage = FieldStorageConfig::load('user.profile_sold_to');
$this->assertIdentical('list_string', $field_storage->getType(), 'Field type is list_string.');
$settings = $field_storage->getSettings();
$this->assertEqual($settings['allowed_values'], array(
$this->assertEqual($settings['allowed_values'], [
'Pill spammers' => 'Pill spammers',
'Fitness spammers' => 'Fitness spammers',
'Back\slash' => 'Back\slash',
@ -49,7 +49,7 @@ class MigrateUserProfileFieldTest extends MigrateDrupal6TestBase {
'Dot.in.the.middle' => 'Dot.in.the.middle',
'Faithful servant' => 'Faithful servant',
'Anonymous donor' => 'Anonymous donor',
));
]);
$this->assertIdentical('list_string', $field_storage->getType(), 'Field type is list_string.');
// Migrated list field.

View file

@ -2,7 +2,7 @@
namespace Drupal\Tests\user\Kernel\Migrate\d6;
use Drupal\config\Tests\SchemaCheckTestTrait;
use Drupal\Tests\SchemaCheckTestTrait;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
use Drupal\user\AccountSettingsForm;
use Drupal\Core\Database\Database;
@ -71,10 +71,10 @@ class MigrateUserConfigsTest extends MigrateDrupal6TestBase {
foreach ($user_register_map as $map) {
// Tests migration of user_register = 1
Database::getConnection('default', 'migrate')
->update('variable')
->fields(['value' => serialize($map[0])])
->condition('name', 'user_register')
->execute();
->update('variable')
->fields(['value' => serialize($map[0])])
->condition('name', 'user_register')
->execute();
/** @var \Drupal\migrate\Plugin\MigrationInterface $migration */
$migration = $this->getMigration('d6_user_settings');

View file

@ -0,0 +1,69 @@
<?php
namespace Drupal\Tests\user\Kernel\Migrate\d6;
use Drupal\file\Entity\File;
use Drupal\file\FileInterface;
use Drupal\Tests\file\Kernel\Migrate\d6\FileMigrationTestTrait;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**
* User pictures migration.
*
* @group migrate_drupal_6
*/
class MigrateUserPictureD6FileTest extends MigrateDrupal6TestBase {
use FileMigrationTestTrait;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installEntitySchema('file');
$this->executeMigration('d6_user_picture_file');
$this->setUpMigratedFiles();
}
/**
* Asserts a file entity.
*
* @param int $fid
* The file ID.
* @param string $name
* The expected file name.
* @param int $size
* The expected file size.
* @param string $uri
* The expected file URI.
* @param string $type
* The expected MIME type.
* @param int $uid
* The expected file owner ID.
*/
protected function assertEntity($fid, $name, $size, $uri, $type, $uid) {
/** @var \Drupal\file\FileInterface $file */
$file = File::load($fid);
$this->assertInstanceOf(FileInterface::class, $file);
$this->assertSame($name, $file->getFilename());
$this->assertSame($size, $file->getSize());
$this->assertSame($uri, $file->getFileUri());
$this->assertSame($type, $file->getMimeType());
$this->assertSame($uid, $file->getOwnerId());
}
/**
* Tests the D6 user pictures migration in combination with D6 file.
*/
public function testUserPicturesWithD6File() {
$this->assertEntity(1, 'image-test.jpg', '1901', 'public://image-test.jpg', 'image/jpeg', '2');
$this->assertEntity(2, 'image-test.png', '125', 'public://image-test.png', 'image/png', '8');
$this->assertEntity(3, 'Image1.png', '39325', 'public://image-1.png', 'image/png', '1');
$this->assertEntity(4, 'Image2.jpg', '1831', 'public://image-2.jpg', 'image/jpeg', '1');
$this->assertEntity(5, 'Image-test.gif', '183', 'public://image-test.gif', 'image/jpeg', '1');
$this->assertEntity(6, 'html-1.txt', '24', 'public://html-1.txt', 'text/plain', '1');
}
}

View file

@ -29,7 +29,7 @@ class MigrateUserPictureFileTest extends MigrateDrupal6TestBase {
* Tests the Drupal 6 user pictures to Drupal 8 migration.
*/
public function testUserPictures() {
$file_ids = array();
$file_ids = [];
foreach ($this->migration->getIdMap() as $destination_ids) {
$file_ids[] = reset($destination_ids);
}

View file

@ -38,6 +38,7 @@ class MigrateUserRoleTest extends MigrateDrupal6TestBase {
/** @var \Drupal\user\RoleInterface $role */
$role = Role::load($id);
$this->assertInstanceOf(RoleInterface::class, $role);
sort($permissions);
$this->assertSame($permissions, $role->getPermissions());
$this->assertSame([[$id]], $id_map->lookupDestinationIds(['rid' => $lookupId]));
}
@ -67,9 +68,9 @@ class MigrateUserRoleTest extends MigrateDrupal6TestBase {
// From permission table.
'access comments',
'access content',
'migrate test authenticated permission',
'post comments',
'skip comment approval',
'migrate test authenticated permission',
// From filter_format.
'use text format filtered_html',
];

View file

@ -37,7 +37,7 @@ class MigrateUserTest extends MigrateDrupal6TestBase {
// Make sure uid 1 is created.
user_install();
$file = File::create(array(
$file = File::create([
'fid' => 2,
'uid' => 2,
'filename' => 'image-test.jpg',
@ -46,12 +46,12 @@ class MigrateUserTest extends MigrateDrupal6TestBase {
'created' => 1,
'changed' => 1,
'status' => FILE_STATUS_PERMANENT,
));
]);
$file->enforceIsNew();
file_put_contents($file->getFileUri(), file_get_contents('core/modules/simpletest/files/image-1.png'));
$file->save();
$file = File::create(array(
$file = File::create([
'fid' => 8,
'uid' => 8,
'filename' => 'image-test.png',
@ -60,7 +60,7 @@ class MigrateUserTest extends MigrateDrupal6TestBase {
'created' => 1,
'changed' => 1,
'status' => FILE_STATUS_PERMANENT,
));
]);
$file->enforceIsNew();
file_put_contents($file->getFileUri(), file_get_contents('core/modules/simpletest/files/image-2.jpg'));
$file->save();
@ -84,14 +84,14 @@ class MigrateUserTest extends MigrateDrupal6TestBase {
// Get roles directly from the source.
$rids = Database::getConnection('default', 'migrate')
->select('users_roles', 'ur')
->fields('ur', array('rid'))
->fields('ur', ['rid'])
->condition('ur.uid', $source->uid)
->execute()
->fetchCol();
$roles = array(RoleInterface::AUTHENTICATED_ID);
$roles = [RoleInterface::AUTHENTICATED_ID];
$id_map = $this->getMigration('d6_user_role')->getIdMap();
foreach ($rids as $rid) {
$role = $id_map->lookupDestinationId(array($rid));
$role = $id_map->lookupDestinationId([$rid]);
$roles[] = reset($role);
}

View file

@ -45,6 +45,7 @@ class MigrateUserRoleTest extends MigrateDrupal7TestBase {
->condition('rid', $original_rid)
->execute()
->fetchCol();
sort($permissions);
$this->assertIdentical($permissions, $entity->getPermissions());
}
}

View file

@ -177,20 +177,20 @@ class MigrateUserTest extends MigrateDrupal7TestBase {
foreach ($users as $source) {
$rids = Database::getConnection('default', 'migrate')
->select('users_roles', 'ur')
->fields('ur', array('rid'))
->fields('ur', ['rid'])
->condition('ur.uid', $source->uid)
->execute()
->fetchCol();
$roles = array(RoleInterface::AUTHENTICATED_ID);
$roles = [RoleInterface::AUTHENTICATED_ID];
$id_map = $this->getMigration('d7_user_role')->getIdMap();
foreach ($rids as $rid) {
$role = $id_map->lookupDestinationId(array($rid));
$role = $id_map->lookupDestinationId([$rid]);
$roles[] = reset($role);
}
$field_integer = Database::getConnection('default', 'migrate')
->select('field_data_field_integer', 'fi')
->fields('fi', array('field_integer_value'))
->fields('fi', ['field_integer_value'])
->condition('fi.entity_id', $source->uid)
->execute()
->fetchCol();

View file

@ -21,7 +21,7 @@ class TempStoreDatabaseTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('system', 'user');
public static $modules = ['system', 'user'];
/**
* A key/value store factory.
@ -42,21 +42,21 @@ class TempStoreDatabaseTest extends KernelTestBase {
*
* @var array
*/
protected $users = array();
protected $users = [];
/**
* An array of random stdClass objects.
*
* @var array
*/
protected $objects = array();
protected $objects = [];
protected function setUp() {
parent::setUp();
// Install system tables to test the key/value storage without installing a
// full Drupal environment.
$this->installSchema('system', array('key_value_expire'));
$this->installSchema('system', ['key_value_expire']);
// Create several objects for testing.
for ($i = 0; $i <= 3; $i++) {
@ -135,7 +135,7 @@ class TempStoreDatabaseTest extends KernelTestBase {
// Now manually expire the item (this is not exposed by the API) and then
// assert it is no longer accessible.
db_update('key_value_expire')
->fields(array('expire' => REQUEST_TIME - 1))
->fields(['expire' => REQUEST_TIME - 1])
->condition('collection', "user.shared_tempstore.$collection")
->condition('name', $key)
->execute();

View file

@ -18,12 +18,12 @@ class UserAccountFormFieldsTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('system', 'user', 'field');
public static $modules = ['system', 'user', 'field'];
/**
* Tests the root user account form section in the "Configure site" form.
*/
function testInstallConfigureForm() {
public function testInstallConfigureForm() {
require_once \Drupal::root() . '/core/includes/install.core.inc';
require_once \Drupal::root() . '/core/includes/install.inc';
$install_state = install_state_defaults();
@ -37,7 +37,7 @@ class UserAccountFormFieldsTest extends KernelTestBase {
// Verify that web browsers may autocomplete the email value and
// autofill/prefill the name and pass values.
foreach (array('mail', 'name', 'pass') as $key) {
foreach (['mail', 'name', 'pass'] as $key) {
$this->assertFalse(isset($form['account'][$key]['#attributes']['autocomplete']), "'$key' field: 'autocomplete' attribute not found.");
}
}
@ -45,9 +45,9 @@ class UserAccountFormFieldsTest extends KernelTestBase {
/**
* Tests the user registration form.
*/
function testUserRegistrationForm() {
public function testUserRegistrationForm() {
// Install default configuration; required for AccountFormController.
$this->installConfig(array('user'));
$this->installConfig(['user']);
// Disable email confirmation to unlock the password field.
$this->config('user.settings')
@ -61,7 +61,7 @@ class UserAccountFormFieldsTest extends KernelTestBase {
// Verify that web browsers may autocomplete the email value and
// autofill/prefill the name and pass values.
foreach (array('mail', 'name', 'pass') as $key) {
foreach (['mail', 'name', 'pass'] as $key) {
$this->assertFalse(isset($form['account'][$key]['#attributes']['autocomplete']), "'$key' field: 'autocomplete' attribute not found.");
}
}
@ -69,9 +69,9 @@ class UserAccountFormFieldsTest extends KernelTestBase {
/**
* Tests the user edit form.
*/
function testUserEditForm() {
public function testUserEditForm() {
// Install default configuration; required for AccountFormController.
$this->installConfig(array('user'));
$this->installConfig(['user']);
// Install the router table and then rebuild.
\Drupal::service('router.builder')->rebuild();
@ -82,7 +82,7 @@ class UserAccountFormFieldsTest extends KernelTestBase {
$this->assertFieldOrder($form['account']);
// Verify that autocomplete is off on all account fields.
foreach (array('mail', 'name', 'pass') as $key) {
foreach (['mail', 'name', 'pass'] as $key) {
$this->assertIdentical($form['account'][$key]['#attributes']['autocomplete'], 'off', "'$key' field: 'autocomplete' attribute is 'off'.");
}
}
@ -128,7 +128,7 @@ class UserAccountFormFieldsTest extends KernelTestBase {
protected function buildAccountForm($operation) {
// @see HtmlEntityFormController::getFormObject()
$entity_type = 'user';
$fields = array();
$fields = [];
if ($operation != 'register') {
$fields['uid'] = 2;
}

View file

@ -2,7 +2,7 @@
namespace Drupal\Tests\user\Kernel;
use Drupal\config\Tests\SchemaCheckTestTrait;
use Drupal\Tests\SchemaCheckTestTrait;
use Drupal\KernelTests\KernelTestBase;
use Drupal\user\Entity\Role;
@ -21,14 +21,14 @@ class UserActionConfigSchemaTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('system', 'user');
public static $modules = ['system', 'user'];
/**
* Tests whether the user action config schema are valid.
*/
function testValidUserActionConfigSchema() {
public function testValidUserActionConfigSchema() {
$rid = strtolower($this->randomMachineName(8));
Role::create(array('id' => $rid))->save();
Role::create(['id' => $rid])->save();
// Test user_add_role_action configuration.
$config = $this->config('system.action.user_add_role_action.' . $rid);

View file

@ -36,16 +36,16 @@ class UserEntityReferenceTest extends EntityKernelTestBase {
protected function setUp() {
parent::setUp();
$this->role1 = Role::create(array(
$this->role1 = Role::create([
'id' => strtolower($this->randomMachineName(8)),
'label' => $this->randomMachineName(8),
));
]);
$this->role1->save();
$this->role2 = Role::create(array(
$this->role2 = Role::create([
'id' => strtolower($this->randomMachineName(8)),
'label' => $this->randomMachineName(8),
));
]);
$this->role2->save();
$this->createEntityReferenceField('user', 'user', 'user_reference', 'User reference', 'user');
@ -54,26 +54,26 @@ class UserEntityReferenceTest extends EntityKernelTestBase {
/**
* Tests user selection by roles.
*/
function testUserSelectionByRole() {
public function testUserSelectionByRole() {
$field_definition = FieldConfig::loadByName('user', 'user', 'user_reference');
$handler_settings = $field_definition->getSetting('handler_settings');
$handler_settings['filter']['role'] = array(
$handler_settings['filter']['role'] = [
$this->role1->id() => $this->role1->id(),
$this->role2->id() => 0,
);
];
$handler_settings['filter']['type'] = 'role';
$field_definition->setSetting('handler_settings', $handler_settings);
$field_definition->save();
$user1 = $this->createUser(array('name' => 'aabb'));
$user1 = $this->createUser(['name' => 'aabb']);
$user1->addRole($this->role1->id());
$user1->save();
$user2 = $this->createUser(array('name' => 'aabbb'));
$user2 = $this->createUser(['name' => 'aabbb']);
$user2->addRole($this->role1->id());
$user2->save();
$user3 = $this->createUser(array('name' => 'aabbbb'));
$user3 = $this->createUser(['name' => 'aabbbb']);
$user3->addRole($this->role2->id());
$user3->save();
@ -83,7 +83,7 @@ class UserEntityReferenceTest extends EntityKernelTestBase {
$matches = $autocomplete->getMatches('user', 'default', $field_definition->getSetting('handler_settings'), 'aabb');
$this->assertEqual(count($matches), 2);
$users = array();
$users = [];
foreach ($matches as $match) {
$users[] = $match['label'];
}

View file

@ -19,7 +19,7 @@ class UserEntityTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('system', 'user', 'field');
public static $modules = ['system', 'user', 'field'];
/**
* Tests some of the methods.
@ -30,39 +30,39 @@ class UserEntityTest extends KernelTestBase {
*/
public function testUserMethods() {
$role_storage = $this->container->get('entity.manager')->getStorage('user_role');
$role_storage->create(array('id' => 'test_role_one'))->save();
$role_storage->create(array('id' => 'test_role_two'))->save();
$role_storage->create(array('id' => 'test_role_three'))->save();
$role_storage->create(['id' => 'test_role_one'])->save();
$role_storage->create(['id' => 'test_role_two'])->save();
$role_storage->create(['id' => 'test_role_three'])->save();
$values = array(
$values = [
'uid' => 1,
'roles' => array('test_role_one'),
);
'roles' => ['test_role_one'],
];
$user = User::create($values);
$this->assertTrue($user->hasRole('test_role_one'));
$this->assertFalse($user->hasRole('test_role_two'));
$this->assertEqual(array(RoleInterface::AUTHENTICATED_ID, 'test_role_one'), $user->getRoles());
$this->assertEqual([RoleInterface::AUTHENTICATED_ID, 'test_role_one'], $user->getRoles());
$user->addRole('test_role_one');
$this->assertTrue($user->hasRole('test_role_one'));
$this->assertFalse($user->hasRole('test_role_two'));
$this->assertEqual(array(RoleInterface::AUTHENTICATED_ID, 'test_role_one'), $user->getRoles());
$this->assertEqual([RoleInterface::AUTHENTICATED_ID, 'test_role_one'], $user->getRoles());
$user->addRole('test_role_two');
$this->assertTrue($user->hasRole('test_role_one'));
$this->assertTrue($user->hasRole('test_role_two'));
$this->assertEqual(array(RoleInterface::AUTHENTICATED_ID, 'test_role_one', 'test_role_two'), $user->getRoles());
$this->assertEqual([RoleInterface::AUTHENTICATED_ID, 'test_role_one', 'test_role_two'], $user->getRoles());
$user->removeRole('test_role_three');
$this->assertTrue($user->hasRole('test_role_one'));
$this->assertTrue($user->hasRole('test_role_two'));
$this->assertEqual(array(RoleInterface::AUTHENTICATED_ID, 'test_role_one', 'test_role_two'), $user->getRoles());
$this->assertEqual([RoleInterface::AUTHENTICATED_ID, 'test_role_one', 'test_role_two'], $user->getRoles());
$user->removeRole('test_role_one');
$this->assertFalse($user->hasRole('test_role_one'));
$this->assertTrue($user->hasRole('test_role_two'));
$this->assertEqual(array(RoleInterface::AUTHENTICATED_ID, 'test_role_two'), $user->getRoles());
$this->assertEqual([RoleInterface::AUTHENTICATED_ID, 'test_role_two'], $user->getRoles());
}
}

View file

@ -27,7 +27,7 @@ class UserFieldsTest extends KernelTestBase {
$this->installEntitySchema('user');
// Set up a test theme that prints the user's mail field.
\Drupal::service('theme_handler')->install(array('user_test_theme'));
\Drupal::service('theme_handler')->install(['user_test_theme']);
\Drupal::theme()->setActiveTheme(\Drupal::service('theme.initialization')->initTheme('user_test_theme'));
// Clear the theme registry.
$this->container->set('theme.registry', NULL);
@ -36,7 +36,7 @@ class UserFieldsTest extends KernelTestBase {
/**
* Tests account's available fields.
*/
function testUserFields() {
public function testUserFields() {
// Create the user to test the user fields.
$user = User::create([
'name' => 'foobar',

View file

@ -16,7 +16,7 @@ class UserInstallTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('user');
public static $modules = ['user'];
/**
* {@inheritdoc}

View file

@ -17,7 +17,7 @@ class UserRoleDeleteTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('system', 'user', 'field');
public static $modules = ['system', 'user', 'field'];
protected function setUp() {
parent::setUp();
@ -32,15 +32,15 @@ class UserRoleDeleteTest extends KernelTestBase {
public function testRoleDeleteUserRoleReferenceDelete() {
// Create two test roles.
$role_storage = $this->container->get('entity.manager')->getStorage('user_role');
$role_storage->create(array('id' => 'test_role_one'))->save();
$role_storage->create(array('id' => 'test_role_two'))->save();
$role_storage->create(['id' => 'test_role_one'])->save();
$role_storage->create(['id' => 'test_role_two'])->save();
// Create user and assign both test roles.
$values = array(
$values = [
'uid' => 1,
'name' => $this->randomString(),
'roles' => array('test_role_one', 'test_role_two'),
);
'roles' => ['test_role_one', 'test_role_two'],
];
$user = User::create($values);
$user->save();
@ -60,7 +60,7 @@ class UserRoleDeleteTest extends KernelTestBase {
$this->assertTrue($user->hasRole('test_role_two'));
// Create new role with same name.
$role_storage->create(array('id' => 'test_role_one'))->save();
$role_storage->create(['id' => 'test_role_one'])->save();
// Load user again from the database.
$user = User::load($user->id());

View file

@ -0,0 +1,30 @@
<?php
namespace Drupal\Tests\user\Kernel;
use Drupal\KernelTests\KernelTestBase;
use Drupal\user\Entity\Role;
/**
* @group user
*/
class UserRoleEntityTest extends KernelTestBase {
public static $modules = ['system', 'user'];
public function testOrderOfPermissions() {
$role = Role::create(['id' => 'test_role']);
$role->grantPermission('b')
->grantPermission('a')
->grantPermission('c')
->save();
$this->assertEquals($role->getPermissions(), ['a', 'b', 'c']);
$role->revokePermission('b')->save();
$this->assertEquals($role->getPermissions(), ['a', 'c']);
$role->grantPermission('b')->save();
$this->assertEquals($role->getPermissions(), ['a', 'b', 'c']);
}
}

View file

@ -17,7 +17,7 @@ class UserSaveStatusTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('system', 'user', 'field');
public static $modules = ['system', 'user', 'field'];
protected function setUp() {
parent::setUp();
@ -27,12 +27,12 @@ class UserSaveStatusTest extends KernelTestBase {
/**
* Test SAVED_NEW and SAVED_UPDATED statuses for user entity type.
*/
function testUserSaveStatus() {
public function testUserSaveStatus() {
// Create a new user.
$values = array(
$values = [
'uid' => 1,
'name' => $this->randomMachineName(),
);
];
$user = User::create($values);
// Test SAVED_NEW.

View file

@ -21,7 +21,7 @@ class UserValidationTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('field', 'user', 'system');
public static $modules = ['field', 'user', 'system'];
/**
* {@inheritdoc}
@ -29,36 +29,36 @@ class UserValidationTest extends KernelTestBase {
protected function setUp() {
parent::setUp();
$this->installEntitySchema('user');
$this->installSchema('system', array('sequences'));
$this->installSchema('system', ['sequences']);
// Make sure that the default roles exist.
$this->installConfig(array('user'));
$this->installConfig(['user']);
}
/**
* Tests user name validation.
*/
function testUsernames() {
$test_cases = array( // '<username>' => array('<description>', 'assert<testName>'),
'foo' => array('Valid username', 'assertNull'),
'FOO' => array('Valid username', 'assertNull'),
'Foo O\'Bar' => array('Valid username', 'assertNull'),
'foo@bar' => array('Valid username', 'assertNull'),
'foo@example.com' => array('Valid username', 'assertNull'),
'foo@-example.com' => array('Valid username', 'assertNull'), // invalid domains are allowed in usernames
'þòøÇߪř€' => array('Valid username', 'assertNull'),
'foo+bar' => array('Valid username', 'assertNull'), // '+' symbol is allowed
'ᚠᛇᚻ᛫ᛒᛦᚦ' => array('Valid UTF8 username', 'assertNull'), // runes
' foo' => array('Invalid username that starts with a space', 'assertNotNull'),
'foo ' => array('Invalid username that ends with a space', 'assertNotNull'),
'foo bar' => array('Invalid username that contains 2 spaces \'&nbsp;&nbsp;\'', 'assertNotNull'),
'' => array('Invalid empty username', 'assertNotNull'),
'foo/' => array('Invalid username containing invalid chars', 'assertNotNull'),
'foo' . chr(0) . 'bar' => array('Invalid username containing chr(0)', 'assertNotNull'), // NULL
'foo' . chr(13) . 'bar' => array('Invalid username containing chr(13)', 'assertNotNull'), // CR
str_repeat('x', USERNAME_MAX_LENGTH + 1) => array('Invalid excessively long username', 'assertNotNull'),
);
public function testUsernames() {
$test_cases = [ // '<username>' => array('<description>', 'assert<testName>'),
'foo' => ['Valid username', 'assertNull'],
'FOO' => ['Valid username', 'assertNull'],
'Foo O\'Bar' => ['Valid username', 'assertNull'],
'foo@bar' => ['Valid username', 'assertNull'],
'foo@example.com' => ['Valid username', 'assertNull'],
'foo@-example.com' => ['Valid username', 'assertNull'], // invalid domains are allowed in usernames
'þòøÇߪř€' => ['Valid username', 'assertNull'],
'foo+bar' => ['Valid username', 'assertNull'], // '+' symbol is allowed
'ᚠᛇᚻ᛫ᛒᛦᚦ' => ['Valid UTF8 username', 'assertNull'], // runes
' foo' => ['Invalid username that starts with a space', 'assertNotNull'],
'foo ' => ['Invalid username that ends with a space', 'assertNotNull'],
'foo bar' => ['Invalid username that contains 2 spaces \'&nbsp;&nbsp;\'', 'assertNotNull'],
'' => ['Invalid empty username', 'assertNotNull'],
'foo/' => ['Invalid username containing invalid chars', 'assertNotNull'],
'foo' . chr(0) . 'bar' => ['Invalid username containing chr(0)', 'assertNotNull'], // NULL
'foo' . chr(13) . 'bar' => ['Invalid username containing chr(13)', 'assertNotNull'], // CR
str_repeat('x', USERNAME_MAX_LENGTH + 1) => ['Invalid excessively long username', 'assertNotNull'],
];
foreach ($test_cases as $name => $test_case) {
list($description, $test) = $test_case;
$result = user_validate_name($name);
@ -69,11 +69,11 @@ class UserValidationTest extends KernelTestBase {
/**
* Runs entity validation checks.
*/
function testValidation() {
$user = User::create(array(
public function testValidation() {
$user = User::create([
'name' => 'test',
'mail' => 'test@example.com',
));
]);
$violations = $user->validate();
$this->assertEqual(count($violations), 0, 'No violations when validating a default user.');
@ -84,7 +84,7 @@ class UserValidationTest extends KernelTestBase {
$violations = $user->validate();
$this->assertEqual(count($violations), 1, 'Violation found when name is too long.');
$this->assertEqual($violations[0]->getPropertyPath(), 'name');
$this->assertEqual($violations[0]->getMessage(), t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => 60)));
$this->assertEqual($violations[0]->getMessage(), t('The username %name is too long: it must be %max characters or less.', ['%name' => $name, '%max' => 60]));
// Create a second test user to provoke a name collision.
$user2 = User::create([
@ -96,7 +96,7 @@ class UserValidationTest extends KernelTestBase {
$violations = $user->validate();
$this->assertEqual(count($violations), 1, 'Violation found on name collision.');
$this->assertEqual($violations[0]->getPropertyPath(), 'name');
$this->assertEqual($violations[0]->getMessage(), t('The username %name is already taken.', array('%name' => 'existing')));
$this->assertEqual($violations[0]->getMessage(), t('The username %name is already taken.', ['%name' => 'existing']));
// Make the name valid.
$user->set('name', $this->randomMachineName());
@ -116,7 +116,7 @@ class UserValidationTest extends KernelTestBase {
// https://www.drupal.org/node/2023465.
$this->assertEqual(count($violations), 2, 'Violations found when email is too long');
$this->assertEqual($violations[0]->getPropertyPath(), 'mail.0.value');
$this->assertEqual($violations[0]->getMessage(), t('%name: the email address can not be longer than @max characters.', array('%name' => $user->get('mail')->getFieldDefinition()->getLabel(), '@max' => Email::EMAIL_MAX_LENGTH)));
$this->assertEqual($violations[0]->getMessage(), t('%name: the email address can not be longer than @max characters.', ['%name' => $user->get('mail')->getFieldDefinition()->getLabel(), '@max' => Email::EMAIL_MAX_LENGTH]));
$this->assertEqual($violations[1]->getPropertyPath(), 'mail.0.value');
$this->assertEqual($violations[1]->getMessage(), t('This value is not a valid email address.'));
@ -125,12 +125,12 @@ class UserValidationTest extends KernelTestBase {
$violations = $user->validate();
$this->assertEqual(count($violations), 1, 'Violation found when email already exists.');
$this->assertEqual($violations[0]->getPropertyPath(), 'mail');
$this->assertEqual($violations[0]->getMessage(), t('The email address %mail is already taken.', array('%mail' => 'existing@example.com')));
$this->assertEqual($violations[0]->getMessage(), t('The email address %mail is already taken.', ['%mail' => 'existing@example.com']));
$user->set('mail', NULL);
$violations = $user->validate();
$this->assertEqual(count($violations), 1, 'Email addresses may not be removed');
$this->assertEqual($violations[0]->getPropertyPath(), 'mail');
$this->assertEqual($violations[0]->getMessage(), t('@name field is required.', array('@name' => $user->getFieldDefinition('mail')->getLabel())));
$this->assertEqual($violations[0]->getMessage(), t('@name field is required.', ['@name' => $user->getFieldDefinition('mail')->getLabel()]));
$user->set('mail', 'someone@example.com');
$user->set('timezone', $this->randomString(33));
@ -157,14 +157,14 @@ class UserValidationTest extends KernelTestBase {
$this->assertAllowedValuesViolation($user, 'preferred_admin_langcode');
$user->set('preferred_admin_langcode', NULL);
Role::create(array('id' => 'role1'))->save();
Role::create(array('id' => 'role2'))->save();
Role::create(['id' => 'role1'])->save();
Role::create(['id' => 'role2'])->save();
// Test cardinality of user roles.
$user = User::create([
'name' => 'role_test',
'mail' => 'test@example.com',
'roles' => array('role1', 'role2'),
'roles' => ['role1', 'role2'],
]);
$violations = $user->validate();
$this->assertEqual(count($violations), 0);
@ -173,7 +173,7 @@ class UserValidationTest extends KernelTestBase {
$violations = $user->validate();
$this->assertEqual(count($violations), 1);
$this->assertEqual($violations[0]->getPropertyPath(), 'roles.1.target_id');
$this->assertEqual($violations[0]->getMessage(), t('The referenced entity (%entity_type: %name) does not exist.', array('%entity_type' => 'user_role', '%name' => 'unknown_role')));
$this->assertEqual($violations[0]->getMessage(), t('The referenced entity (%entity_type: %name) does not exist.', ['%entity_type' => 'user_role', '%name' => 'unknown_role']));
}
/**
@ -195,7 +195,7 @@ class UserValidationTest extends KernelTestBase {
$this->assertEqual(count($violations), $count, "Violation found when $field_name is too long.");
$this->assertEqual($violations[$expected_index]->getPropertyPath(), "$field_name.0.value");
$field_label = $entity->get($field_name)->getFieldDefinition()->getLabel();
$this->assertEqual($violations[$expected_index]->getMessage(), t('%name: may not be longer than @max characters.', array('%name' => $field_label, '@max' => $length)));
$this->assertEqual($violations[$expected_index]->getMessage(), t('%name: may not be longer than @max characters.', ['%name' => $field_label, '@max' => $length]));
}
/**

View file

@ -17,7 +17,7 @@ class HandlerFieldPermissionTest extends UserKernelTestBase {
*
* @var array
*/
public static $testViews = array('test_field_permission');
public static $testViews = ['test_field_permission'];
/**
* Tests the permission field handler output.
@ -31,15 +31,15 @@ class HandlerFieldPermissionTest extends UserKernelTestBase {
$view->render();
$style_plugin = $view->style_plugin;
$expected_permissions = array();
$expected_permissions[$this->users[0]->id()] = array();
$expected_permissions[$this->users[1]->id()] = array();
$expected_permissions = [];
$expected_permissions[$this->users[0]->id()] = [];
$expected_permissions[$this->users[1]->id()] = [];
$expected_permissions[$this->users[2]->id()][] = t('Administer permissions');
// View user profiles comes first, because we sort by the permission
// machine name.
$expected_permissions[$this->users[3]->id()][] = t('View user information');
$expected_permissions[$this->users[3]->id()][] = t('Administer permissions');
$expected_permissions[$this->users[3]->id()][] = t('Administer users');
$expected_permissions[$this->users[3]->id()][] = t('View user information');
foreach ($view->result as $index => $row) {
$uid = $view->field['uid']->getValue($row);

View file

@ -18,7 +18,7 @@ class HandlerFilterPermissionTest extends UserKernelTestBase {
*
* @var array
*/
public static $testViews = array('test_filter_permission');
public static $testViews = ['test_filter_permission'];
protected $columnMap;
@ -31,64 +31,64 @@ class HandlerFilterPermissionTest extends UserKernelTestBase {
public function testFilterPermission() {
$this->setupPermissionTestData();
$column_map = array('uid' => 'uid');
$column_map = ['uid' => 'uid'];
$view = Views::getView('test_filter_permission');
// Filter by a non existing permission.
$view->initHandlers();
$view->filter['permission']->value = array('non_existent_permission');
$view->filter['permission']->value = ['non_existent_permission'];
$this->executeView($view);
$this->assertEqual(count($view->result), 4, 'A non existent permission is not filtered so everything is the result.');
$expected[] = array('uid' => 1);
$expected[] = array('uid' => 2);
$expected[] = array('uid' => 3);
$expected[] = array('uid' => 4);
$expected[] = ['uid' => 1];
$expected[] = ['uid' => 2];
$expected[] = ['uid' => 3];
$expected[] = ['uid' => 4];
$this->assertIdenticalResultset($view, $expected, $column_map);
$view->destroy();
// Filter by a permission.
$view->initHandlers();
$view->filter['permission']->value = array('administer permissions');
$view->filter['permission']->value = ['administer permissions'];
$this->executeView($view);
$this->assertEqual(count($view->result), 2);
$expected = array();
$expected[] = array('uid' => 3);
$expected[] = array('uid' => 4);
$expected = [];
$expected[] = ['uid' => 3];
$expected[] = ['uid' => 4];
$this->assertIdenticalResultset($view, $expected, $column_map);
$view->destroy();
// Filter by not a permission.
$view->initHandlers();
$view->filter['permission']->operator = 'not';
$view->filter['permission']->value = array('administer users');
$view->filter['permission']->value = ['administer users'];
$this->executeView($view);
$this->assertEqual(count($view->result), 3);
$expected = array();
$expected[] = array('uid' => 1);
$expected[] = array('uid' => 2);
$expected[] = array('uid' => 3);
$expected = [];
$expected[] = ['uid' => 1];
$expected[] = ['uid' => 2];
$expected[] = ['uid' => 3];
$this->assertIdenticalResultset($view, $expected, $column_map);
$view->destroy();
// Filter by not multiple permissions, that are present in multiple roles.
$view->initHandlers();
$view->filter['permission']->operator = 'not';
$view->filter['permission']->value = array('administer users', 'administer permissions');
$view->filter['permission']->value = ['administer users', 'administer permissions'];
$this->executeView($view);
$this->assertEqual(count($view->result), 2);
$expected = array();
$expected[] = array('uid' => 1);
$expected[] = array('uid' => 2);
$expected = [];
$expected[] = ['uid' => 1];
$expected[] = ['uid' => 2];
$this->assertIdenticalResultset($view, $expected, $column_map);
$view->destroy();
// Filter by another permission of a role with multiple permissions.
$view->initHandlers();
$view->filter['permission']->value = array('administer users');
$view->filter['permission']->value = ['administer users'];
$this->executeView($view);
$this->assertEqual(count($view->result), 1);
$expected = array();
$expected[] = array('uid' => 4);
$expected = [];
$expected[] = ['uid' => 4];
$this->assertIdenticalResultset($view, $expected, $column_map);
$view->destroy();
@ -103,7 +103,7 @@ class HandlerFilterPermissionTest extends UserKernelTestBase {
foreach ($permissions as $name => $permission) {
$permission_by_module[$permission['provider']][$name] = $permission;
}
foreach (array('system' => 'System', 'user' => 'User') as $module => $title) {
foreach (['system' => 'System', 'user' => 'User'] as $module => $title) {
$expected = array_map(function ($permission) {
return Html::escape(strip_tags($permission['title']));
}, $permission_by_module[$module]);

View file

@ -20,7 +20,7 @@ class HandlerFilterRolesTest extends UserKernelTestBase {
*
* @var array
*/
public static $testViews = array('test_user_name');
public static $testViews = ['test_user_name'];
/**
* Tests that role filter dependencies are calculated correctly.

View file

@ -15,14 +15,14 @@ abstract class UserKernelTestBase extends ViewsKernelTestBase {
*
* @var array
*/
public static $modules = array('user_test_views', 'user', 'system', 'field');
public static $modules = ['user_test_views', 'user', 'system', 'field'];
/**
* Users to use during this test.
*
* @var array
*/
protected $users = array();
protected $users = [];
/**
* The entity storage for roles.
@ -41,7 +41,7 @@ abstract class UserKernelTestBase extends ViewsKernelTestBase {
protected function setUp($import_test_views = TRUE) {
parent::setUp();
ViewTestData::createTestViews(get_class($this), array('user_test_views'));
ViewTestData::createTestViews(get_class($this), ['user_test_views']);
$this->installEntitySchema('user');
@ -55,33 +55,33 @@ abstract class UserKernelTestBase extends ViewsKernelTestBase {
*/
protected function setupPermissionTestData() {
// Setup a role without any permission.
$this->roleStorage->create(array('id' => 'authenticated'))
$this->roleStorage->create(['id' => 'authenticated'])
->save();
$this->roleStorage->create(array('id' => 'no_permission'))
$this->roleStorage->create(['id' => 'no_permission'])
->save();
// Setup a role with just one permission.
$this->roleStorage->create(array('id' => 'one_permission'))
$this->roleStorage->create(['id' => 'one_permission'])
->save();
user_role_grant_permissions('one_permission', array('administer permissions'));
user_role_grant_permissions('one_permission', ['administer permissions']);
// Setup a role with multiple permissions.
$this->roleStorage->create(array('id' => 'multiple_permissions'))
$this->roleStorage->create(['id' => 'multiple_permissions'])
->save();
user_role_grant_permissions('multiple_permissions', array('administer permissions', 'administer users', 'access user profiles'));
user_role_grant_permissions('multiple_permissions', ['administer permissions', 'administer users', 'access user profiles']);
// Setup a user without an extra role.
$this->users[] = $account = $this->userStorage->create(['name' => $this->randomString()]);
$account->save();
// Setup a user with just the first role (so no permission beside the
// ones from the authenticated role).
$this->users[] = $account = $this->userStorage->create(array('name' => 'first_role'));
$this->users[] = $account = $this->userStorage->create(['name' => 'first_role']);
$account->addRole('no_permission');
$account->save();
// Setup a user with just the second role (so one additional permission).
$this->users[] = $account = $this->userStorage->create(array('name' => 'second_role'));
$this->users[] = $account = $this->userStorage->create(['name' => 'second_role']);
$account->addRole('one_permission');
$account->save();
// Setup a user with both the second and the third role.
$this->users[] = $account = $this->userStorage->create(array('name' => 'second_third_role'));
$this->users[] = $account = $this->userStorage->create(['name' => 'second_third_role']);
$account->addRole('one_permission');
$account->addRole('multiple_permissions');
$account->save();

View file

@ -12,7 +12,7 @@ use Drupal\Tests\Core\Menu\LocalTaskIntegrationTestBase;
class UserLocalTasksTest extends LocalTaskIntegrationTestBase {
protected function setUp() {
$this->directoryList = array('user' => 'core/modules/user');
$this->directoryList = ['user' => 'core/modules/user'];
parent::setUp();
}
@ -29,12 +29,12 @@ class UserLocalTasksTest extends LocalTaskIntegrationTestBase {
* Provides a list of routes to test.
*/
public function getUserAdminRoutes() {
return array(
array('entity.user.collection', array(array('entity.user.collection', 'user.admin_permissions', 'entity.user_role.collection'))),
array('user.admin_permissions', array(array('entity.user.collection', 'user.admin_permissions', 'entity.user_role.collection'))),
array('entity.user_role.collection', array(array('entity.user.collection', 'user.admin_permissions', 'entity.user_role.collection'))),
array('entity.user.admin_form', array(array('user.account_settings_tab'))),
);
return [
['entity.user.collection', [['entity.user.collection', 'user.admin_permissions', 'entity.user_role.collection']]],
['user.admin_permissions', [['entity.user.collection', 'user.admin_permissions', 'entity.user_role.collection']]],
['entity.user_role.collection', [['entity.user.collection', 'user.admin_permissions', 'entity.user_role.collection']]],
['entity.user.admin_form', [['user.account_settings_tab']]],
];
}
/**
@ -43,9 +43,9 @@ class UserLocalTasksTest extends LocalTaskIntegrationTestBase {
* @dataProvider getUserLoginRoutes
*/
public function testUserLoginLocalTasks($route) {
$tasks = array(
0 => array('user.register', 'user.pass', 'user.login',),
);
$tasks = [
0 => ['user.register', 'user.pass', 'user.login'],
];
$this->assertLocalTasks($route, $tasks);
}
@ -53,11 +53,11 @@ class UserLocalTasksTest extends LocalTaskIntegrationTestBase {
* Provides a list of routes to test.
*/
public function getUserLoginRoutes() {
return array(
array('user.login'),
array('user.register'),
array('user.pass'),
);
return [
['user.login'],
['user.register'],
['user.pass'],
];
}
/**
@ -65,10 +65,10 @@ class UserLocalTasksTest extends LocalTaskIntegrationTestBase {
*
* @dataProvider getUserPageRoutes
*/
public function testUserPageLocalTasks($route, $subtask = array()) {
$tasks = array(
0 => array('entity.user.canonical', 'entity.user.edit_form',),
);
public function testUserPageLocalTasks($route, $subtask = []) {
$tasks = [
0 => ['entity.user.canonical', 'entity.user.edit_form'],
];
if ($subtask) $tasks[] = $subtask;
$this->assertLocalTasks($route, $tasks);
}
@ -77,10 +77,10 @@ class UserLocalTasksTest extends LocalTaskIntegrationTestBase {
* Provides a list of routes to test.
*/
public function getUserPageRoutes() {
return array(
array('entity.user.canonical'),
array('entity.user.edit_form'),
);
return [
['entity.user.canonical'],
['entity.user.edit_form'],
];
}
}

View file

@ -55,10 +55,10 @@ class PermissionAccessCheckTest extends UnitTestCase {
return [
[[], FALSE],
[['_permission' => 'allowed'], TRUE, ['user.permissions']],
[['_permission' => 'denied'], FALSE, ['user.permissions']],
[['_permission' => 'denied'], FALSE, ['user.permissions'], "The 'denied' permission is required."],
[['_permission' => 'allowed+denied'], TRUE, ['user.permissions']],
[['_permission' => 'allowed+denied+other'], TRUE, ['user.permissions']],
[['_permission' => 'allowed,denied'], FALSE, ['user.permissions']],
[['_permission' => 'allowed,denied'], FALSE, ['user.permissions'], "The following permissions are required: 'allowed' AND 'denied'."],
];
}
@ -68,8 +68,11 @@ class PermissionAccessCheckTest extends UnitTestCase {
* @dataProvider providerTestAccess
* @covers ::access
*/
public function testAccess($requirements, $access, array $contexts = []) {
public function testAccess($requirements, $access, array $contexts = [], $message = '') {
$access_result = AccessResult::allowedIf($access)->addCacheContexts($contexts);
if (!empty($message)) {
$access_result->setReason($message);
}
$user = $this->getMock('Drupal\Core\Session\AccountInterface');
$user->expects($this->any())
->method('hasPermission')

View file

@ -97,11 +97,11 @@ class PermissionHandlerTest extends UnitTestCase {
$this->moduleHandler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface');
$this->moduleHandler->expects($this->once())
->method('getModuleDirectories')
->willReturn(array(
->willReturn([
'module_a' => vfsStream::url('modules/module_a'),
'module_b' => vfsStream::url('modules/module_b'),
'module_c' => vfsStream::url('modules/module_c'),
));
]);
$url = vfsStream::url('modules');
mkdir($url . '/module_a');
@ -124,16 +124,16 @@ EOF
'restrict access': TRUE
EOF
);
$modules = array('module_a', 'module_b', 'module_c');
$extensions = array(
$modules = ['module_a', 'module_b', 'module_c'];
$extensions = [
'module_a' => $this->mockModuleExtension('module_a', 'Module a'),
'module_b' => $this->mockModuleExtension('module_b', 'Module b'),
'module_c' => $this->mockModuleExtension('module_c', 'Module c'),
);
];
$this->moduleHandler->expects($this->any())
->method('getImplementations')
->with('permission')
->willReturn(array());
->willReturn([]);
$this->moduleHandler->expects($this->any())
->method('getModuleList')
@ -227,11 +227,11 @@ EOF
$this->moduleHandler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface');
$this->moduleHandler->expects($this->once())
->method('getModuleDirectories')
->willReturn(array(
->willReturn([
'module_a' => vfsStream::url('modules/module_a'),
'module_b' => vfsStream::url('modules/module_b'),
'module_c' => vfsStream::url('modules/module_c'),
));
]);
$url = vfsStream::url('modules');
mkdir($url . '/module_a');
@ -254,17 +254,17 @@ permission_callbacks:
EOF
);
$modules = array('module_a', 'module_b', 'module_c');
$extensions = array(
$modules = ['module_a', 'module_b', 'module_c'];
$extensions = [
'module_a' => $this->mockModuleExtension('module_a', 'Module a'),
'module_b' => $this->mockModuleExtension('module_b', 'Module b'),
'module_c' => $this->mockModuleExtension('module_c', 'Module c'),
);
];
$this->moduleHandler->expects($this->any())
->method('getImplementations')
->with('permission')
->willReturn(array());
->willReturn([]);
$this->moduleHandler->expects($this->any())
->method('getModuleList')
@ -273,19 +273,19 @@ EOF
$this->controllerResolver->expects($this->at(0))
->method('getControllerFromDefinition')
->with('Drupal\\user\\Tests\\TestPermissionCallbacks::singleDescription')
->willReturn(array(new TestPermissionCallbacks(), 'singleDescription'));
->willReturn([new TestPermissionCallbacks(), 'singleDescription']);
$this->controllerResolver->expects($this->at(1))
->method('getControllerFromDefinition')
->with('Drupal\\user\\Tests\\TestPermissionCallbacks::titleDescription')
->willReturn(array(new TestPermissionCallbacks(), 'titleDescription'));
->willReturn([new TestPermissionCallbacks(), 'titleDescription']);
$this->controllerResolver->expects($this->at(2))
->method('getControllerFromDefinition')
->with('Drupal\\user\\Tests\\TestPermissionCallbacks::titleProvider')
->willReturn(array(new TestPermissionCallbacks(), 'titleProvider'));
->willReturn([new TestPermissionCallbacks(), 'titleProvider']);
$this->controllerResolver->expects($this->at(3))
->method('getControllerFromDefinition')
->with('Drupal\\user\\Tests\\TestPermissionCallbacks::titleDescriptionRestrictAccess')
->willReturn(array(new TestPermissionCallbacks(), 'titleDescriptionRestrictAccess'));
->willReturn([new TestPermissionCallbacks(), 'titleDescriptionRestrictAccess']);
$this->permissionHandler = new TestPermissionHandler($this->moduleHandler, $this->stringTranslation, $this->controllerResolver);
@ -307,9 +307,9 @@ EOF
$this->moduleHandler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface');
$this->moduleHandler->expects($this->once())
->method('getModuleDirectories')
->willReturn(array(
->willReturn([
'module_a' => vfsStream::url('modules/module_a'),
));
]);
$url = vfsStream::url('modules');
mkdir($url . '/module_a');
@ -322,15 +322,15 @@ permission_callbacks:
EOF
);
$modules = array('module_a');
$extensions = array(
$modules = ['module_a'];
$extensions = [
'module_a' => $this->mockModuleExtension('module_a', 'Module a'),
);
];
$this->moduleHandler->expects($this->any())
->method('getImplementations')
->with('permission')
->willReturn(array());
->willReturn([]);
$this->moduleHandler->expects($this->any())
->method('getModuleList')
@ -339,7 +339,7 @@ EOF
$this->controllerResolver->expects($this->once())
->method('getControllerFromDefinition')
->with('Drupal\\user\\Tests\\TestPermissionCallbacks::titleDescription')
->willReturn(array(new TestPermissionCallbacks(), 'titleDescription'));
->willReturn([new TestPermissionCallbacks(), 'titleDescription']);
$this->permissionHandler = new TestPermissionHandler($this->moduleHandler, $this->stringTranslation, $this->controllerResolver);
@ -399,37 +399,37 @@ class TestPermissionHandler extends PermissionHandler {
class TestPermissionCallbacks {
public function singleDescription() {
return array(
return [
'access_module_a' => 'single_description'
);
];
}
public function titleDescription() {
return array(
'access module b' => array(
return [
'access module b' => [
'title' => 'Access B',
'description' => 'bla bla',
),
);
],
];
}
public function titleDescriptionRestrictAccess() {
return array(
'access_module_c' => array(
return [
'access_module_c' => [
'title' => 'Access C',
'description' => 'bla bla',
'restrict access' => TRUE,
),
);
],
];
}
public function titleProvider() {
return array(
'access module a via module b' => array(
return [
'access module a via module b' => [
'title' => 'Access A via B',
'provider' => 'module_a',
),
);
],
];
}
}
@ -442,7 +442,7 @@ class TestTranslationManager implements TranslationInterface {
/**
* {@inheritdoc}
*/
public function translate($string, array $args = array(), array $options = array()) {
public function translate($string, array $args = [], array $options = []) {
return new TranslatableMarkup($string, $args, $options, $this);
}
@ -456,7 +456,7 @@ class TestTranslationManager implements TranslationInterface {
/**
* {@inheritdoc}
*/
public function formatPlural($count, $singular, $plural, array $args = array(), array $options = array()) {
public function formatPlural($count, $singular, $plural, array $args = [], array $options = []) {
return new PluralTranslatableMarkup($count, $singular, $plural, $args, $options, $this);
}

View file

@ -22,8 +22,8 @@ class AddRoleUserTest extends RoleUserTestBase {
->with($this->equalTo('test_role_1'))
->will($this->returnValue(TRUE));
$config = array('rid' => 'test_role_1');
$remove_role_plugin = new AddRoleUser($config, 'user_add_role_action', array('type' => 'user'), $this->userRoleEntityType);
$config = ['rid' => 'test_role_1'];
$remove_role_plugin = new AddRoleUser($config, 'user_add_role_action', ['type' => 'user'], $this->userRoleEntityType);
$remove_role_plugin->execute($this->account);
}
@ -40,8 +40,8 @@ class AddRoleUserTest extends RoleUserTestBase {
->with($this->equalTo('test_role_1'))
->will($this->returnValue(FALSE));
$config = array('rid' => 'test_role_1');
$remove_role_plugin = new AddRoleUser($config, 'user_remove_role_action', array('type' => 'user'), $this->userRoleEntityType);
$config = ['rid' => 'test_role_1'];
$remove_role_plugin = new AddRoleUser($config, 'user_remove_role_action', ['type' => 'user'], $this->userRoleEntityType);
$remove_role_plugin->execute($this->account);
}

View file

@ -22,8 +22,8 @@ class RemoveRoleUserTest extends RoleUserTestBase {
->with($this->equalTo('test_role_1'))
->will($this->returnValue(TRUE));
$config = array('rid' => 'test_role_1');
$remove_role_plugin = new RemoveRoleUser($config, 'user_remove_role_action', array('type' => 'user'), $this->userRoleEntityType);
$config = ['rid' => 'test_role_1'];
$remove_role_plugin = new RemoveRoleUser($config, 'user_remove_role_action', ['type' => 'user'], $this->userRoleEntityType);
$remove_role_plugin->execute($this->account);
}
@ -40,8 +40,8 @@ class RemoveRoleUserTest extends RoleUserTestBase {
->with($this->equalTo('test_role_1'))
->will($this->returnValue(FALSE));
$config = array('rid' => 'test_role_1');
$remove_role_plugin = new RemoveRoleUser($config, 'user_remove_role_action', array('type' => 'user'), $this->userRoleEntityType);
$config = ['rid' => 'test_role_1'];
$remove_role_plugin = new RemoveRoleUser($config, 'user_remove_role_action', ['type' => 'user'], $this->userRoleEntityType);
$remove_role_plugin->execute($this->account);
}

View file

@ -14,20 +14,20 @@ class UserTest extends UserSessionTest {
/**
* {@inheritdoc}
*/
protected function createUserSession(array $rids = array(), $authenticated = FALSE) {
protected function createUserSession(array $rids = [], $authenticated = FALSE) {
$user = $this->getMockBuilder('Drupal\user\Entity\User')
->disableOriginalConstructor()
->setMethods(array('get', 'id'))
->setMethods(['get', 'id'])
->getMock();
$user->expects($this->any())
->method('id')
// @todo Also test the uid = 1 handling.
->will($this->returnValue($authenticated ? 2 : 0));
$roles = array();
$roles = [];
foreach ($rids as $rid) {
$roles[] = (object) array(
$roles[] = (object) [
'target_id' => $rid,
);
];
}
$user->expects($this->any())
->method('get')
@ -44,14 +44,14 @@ class UserTest extends UserSessionTest {
*/
public function testUserGetRoles() {
// Anonymous user.
$user = $this->createUserSession(array());
$this->assertEquals(array(RoleInterface::ANONYMOUS_ID), $user->getRoles());
$this->assertEquals(array(), $user->getRoles(TRUE));
$user = $this->createUserSession([]);
$this->assertEquals([RoleInterface::ANONYMOUS_ID], $user->getRoles());
$this->assertEquals([], $user->getRoles(TRUE));
// Authenticated user.
$user = $this->createUserSession(array(), TRUE);
$this->assertEquals(array(RoleInterface::AUTHENTICATED_ID), $user->getRoles());
$this->assertEquals(array(), $user->getRoles(TRUE));
$user = $this->createUserSession([], TRUE);
$this->assertEquals([RoleInterface::AUTHENTICATED_ID], $user->getRoles());
$this->assertEquals([], $user->getRoles(TRUE));
}
}

View file

@ -5,6 +5,7 @@ namespace Drupal\Tests\user\Unit\Plugin\Validation\Constraint;
use Drupal\Tests\UnitTestCase;
use Drupal\user\Plugin\Validation\Constraint\ProtectedUserFieldConstraint;
use Drupal\user\Plugin\Validation\Constraint\ProtectedUserFieldConstraintValidator;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* @coversDefaultClass \Drupal\user\Plugin\Validation\Constraint\ProtectedUserFieldConstraintValidator
@ -47,12 +48,12 @@ class ProtectedUserFieldConstraintValidatorTest extends UnitTestCase {
// If a violation is expected, then the context's addViolation method will
// be called, otherwise it should not be called.
$context = $this->getMock('Symfony\Component\Validator\ExecutionContextInterface');
$context = $this->getMock(ExecutionContextInterface::class);
if ($expected_violation) {
$context->expects($this->once())
->method('addViolation')
->with($constraint->message, array('%name' => $name));
->with($constraint->message, ['%name' => $name]);
}
else {
$context->expects($this->never())

View file

@ -25,7 +25,7 @@ class UserBulkFormTest extends UnitTestCase {
* Tests the constructor assignment of actions.
*/
public function testConstructor() {
$actions = array();
$actions = [];
for ($i = 1; $i <= 2; $i++) {
$action = $this->getMock('\Drupal\system\ActionConfigEntityInterface');
@ -60,7 +60,7 @@ class UserBulkFormTest extends UnitTestCase {
$views_data->expects($this->any())
->method('get')
->with('users')
->will($this->returnValue(array('table' => array('entity type' => 'user'))));
->will($this->returnValue(['table' => ['entity type' => 'user']]));
$container = new ContainerBuilder();
$container->set('views.views_data', $views_data);
$container->set('string_translation', $this->getStringTranslationStub());
@ -82,9 +82,9 @@ class UserBulkFormTest extends UnitTestCase {
->getMock();
$definition['title'] = '';
$options = array();
$options = [];
$user_bulk_form = new UserBulkForm(array(), 'user_bulk_form', $definition, $entity_manager, $language_manager);
$user_bulk_form = new UserBulkForm([], 'user_bulk_form', $definition, $entity_manager, $language_manager);
$user_bulk_form->init($executable, $display, $options);
$this->assertAttributeEquals(array_slice($actions, 0, -1, TRUE), 'actions', $user_bulk_form);

View file

@ -4,6 +4,7 @@ namespace Drupal\Tests\user\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\user\PrivateTempStore;
use Drupal\user\TempStoreException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
@ -81,11 +82,11 @@ class PrivateTempStoreTest extends UnitTestCase {
$this->tempStore = new PrivateTempStore($this->keyValue, $this->lock, $this->currentUser, $this->requestStack, 604800);
$this->ownObject = (object) array(
$this->ownObject = (object) [
'data' => 'test_data',
'owner' => $this->currentUser->id(),
'updated' => (int) $request->server->get('REQUEST_TIME'),
);
];
// Clone the object but change the owner.
$this->otherObject = clone $this->ownObject;
@ -121,7 +122,6 @@ class PrivateTempStoreTest extends UnitTestCase {
* Tests the set() method with no lock available.
*
* @covers ::set
* @expectedException \Drupal\user\TempStoreException
*/
public function testSetWithNoLockAvailable() {
$this->lock->expects($this->at(0))
@ -139,6 +139,7 @@ class PrivateTempStoreTest extends UnitTestCase {
$this->keyValue->expects($this->once())
->method('getCollectionName');
$this->setExpectedException(TempStoreException::class);
$this->tempStore->set('test', 'value');
}
@ -220,7 +221,6 @@ class PrivateTempStoreTest extends UnitTestCase {
* Tests the delete() method with no lock available.
*
* @covers ::delete
* @expectedException \Drupal\user\TempStoreException
*/
public function testDeleteWithNoLockAvailable() {
$this->keyValue->expects($this->once())
@ -242,6 +242,7 @@ class PrivateTempStoreTest extends UnitTestCase {
$this->keyValue->expects($this->once())
->method('getCollectionName');
$this->setExpectedException(TempStoreException::class);
$this->tempStore->delete('test');
}

View file

@ -4,6 +4,7 @@ namespace Drupal\Tests\user\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\user\SharedTempStore;
use Drupal\user\TempStoreException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
@ -76,11 +77,11 @@ class SharedTempStoreTest extends UnitTestCase {
$this->tempStore = new SharedTempStore($this->keyValue, $this->lock, $this->owner, $this->requestStack, 604800);
$this->ownObject = (object) array(
$this->ownObject = (object) [
'data' => 'test_data',
'owner' => $this->owner,
'updated' => (int) $request->server->get('REQUEST_TIME'),
);
];
// Clone the object but change the owner.
$this->otherObject = clone $this->ownObject;
@ -132,7 +133,6 @@ class SharedTempStoreTest extends UnitTestCase {
* Tests the set() method with no lock available.
*
* @covers ::set
* @expectedException \Drupal\user\TempStoreException
*/
public function testSetWithNoLockAvailable() {
$this->lock->expects($this->at(0))
@ -150,6 +150,7 @@ class SharedTempStoreTest extends UnitTestCase {
$this->keyValue->expects($this->once())
->method('getCollectionName');
$this->setExpectedException(TempStoreException::class);
$this->tempStore->set('test', 'value');
}
@ -296,7 +297,6 @@ class SharedTempStoreTest extends UnitTestCase {
* Tests the delete() method with no lock available.
*
* @covers ::delete
* @expectedException \Drupal\user\TempStoreException
*/
public function testDeleteWithNoLockAvailable() {
$this->lock->expects($this->at(0))
@ -314,6 +314,7 @@ class SharedTempStoreTest extends UnitTestCase {
$this->keyValue->expects($this->once())
->method('getCollectionName');
$this->setExpectedException(TempStoreException::class);
$this->tempStore->delete('test');
}

View file

@ -80,10 +80,10 @@ class UserAccessControlHandlerTest extends UnitTestCase {
$this->owner
->expects($this->any())
->method('hasPermission')
->will($this->returnValueMap(array(
array('administer users', FALSE),
array('change own username', TRUE),
)));
->will($this->returnValueMap([
['administer users', FALSE],
['change own username', TRUE],
]));
$this->owner
->expects($this->any())
@ -102,7 +102,7 @@ class UserAccessControlHandlerTest extends UnitTestCase {
$module_handler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface');
$module_handler->expects($this->any())
->method('getImplementations')
->will($this->returnValue(array()));
->will($this->returnValue([]));
$this->accessControlHandler->setModuleHandler($module_handler);
$this->items = $this->getMockBuilder('Drupal\Core\Field\FieldItemList')
@ -128,7 +128,7 @@ class UserAccessControlHandlerTest extends UnitTestCase {
->method('getEntity')
->will($this->returnValue($this->{$target}));
foreach (array('view' => $view, 'edit' => $edit) as $operation => $result) {
foreach (['view' => $view, 'edit' => $edit] as $operation => $result) {
$result_text = !isset($result) ? 'null' : ($result ? 'true' : 'false');
$message = "User '$field' field access returns '$result_text' with operation '$operation' for '$viewer' accessing '$target'";
$this->assertSame($result, $this->accessControlHandler->fieldAccess($operation, $field_definition, $this->{$viewer}, $this->items), $message);
@ -145,44 +145,44 @@ class UserAccessControlHandlerTest extends UnitTestCase {
}
/**
* Provides test data for estUserNameAccess().
* Provides test data for testUserNameAccess().
*/
public function userNameProvider() {
$name_access = array(
$name_access = [
// The viewer user is allowed to see user names on all accounts.
array(
[
'viewer' => 'viewer',
'target' => 'viewer',
'view' => TRUE,
'edit' => FALSE,
),
array(
],
[
'viewer' => 'owner',
'target' => 'viewer',
'view' => TRUE,
'edit' => FALSE,
),
array(
],
[
'viewer' => 'viewer',
'target' => 'owner',
'view' => TRUE,
'edit' => FALSE,
),
],
// The owner user is allowed to change its own user name.
array(
[
'viewer' => 'owner',
'target' => 'owner',
'view' => TRUE,
'edit' => TRUE,
),
],
// The users-administrator user has full access.
array(
[
'viewer' => 'admin',
'target' => 'owner',
'view' => TRUE,
'edit' => TRUE,
),
);
],
];
return $name_access;
}
@ -199,24 +199,24 @@ class UserAccessControlHandlerTest extends UnitTestCase {
* Provides test data for testHiddenUserSettings().
*/
public function hiddenUserSettingsProvider() {
$access_info = array();
$access_info = [];
$fields = array(
$fields = [
'preferred_langcode',
'preferred_admin_langcode',
'timezone',
'mail',
);
];
foreach ($fields as $field) {
$access_info[] = array(
$access_info[] = [
'field' => $field,
'viewer' => 'viewer',
'target' => 'viewer',
'view' => TRUE,
'edit' => TRUE,
);
$access_info[] = array(
];
$access_info[] = [
'field' => $field,
'viewer' => 'viewer',
'target' => 'owner',
@ -225,21 +225,21 @@ class UserAccessControlHandlerTest extends UnitTestCase {
// reality edit access will already be checked on entity level and the
// user without view access will typically not be able to edit.
'edit' => TRUE,
);
$access_info[] = array(
];
$access_info[] = [
'field' => $field,
'viewer' => 'owner',
'target' => 'owner',
'view' => TRUE,
'edit' => TRUE,
);
$access_info[] = array(
];
$access_info[] = [
'field' => $field,
'viewer' => 'admin',
'target' => 'owner',
'view' => TRUE,
'edit' => TRUE,
);
];
}
return $access_info;
@ -258,38 +258,38 @@ class UserAccessControlHandlerTest extends UnitTestCase {
* Provides test data for testAdminFieldAccess().
*/
public function adminFieldAccessProvider() {
$access_info = array();
$access_info = [];
$fields = array(
$fields = [
'roles',
'status',
'access',
'login',
'init',
);
];
foreach ($fields as $field) {
$access_info[] = array(
$access_info[] = [
'field' => $field,
'viewer' => 'viewer',
'target' => 'viewer',
'view' => FALSE,
'edit' => FALSE,
);
$access_info[] = array(
];
$access_info[] = [
'field' => $field,
'viewer' => 'viewer',
'target' => 'owner',
'view' => FALSE,
'edit' => FALSE,
);
$access_info[] = array(
];
$access_info[] = [
'field' => $field,
'viewer' => 'admin',
'target' => 'owner',
'view' => TRUE,
'edit' => TRUE,
);
];
}
return $access_info;
@ -308,14 +308,14 @@ class UserAccessControlHandlerTest extends UnitTestCase {
* Provides test data for passwordAccessProvider().
*/
public function passwordAccessProvider() {
$pass_access = array(
array(
$pass_access = [
[
'viewer' => 'viewer',
'target' => 'viewer',
'view' => FALSE,
'edit' => TRUE,
),
array(
],
[
'viewer' => 'viewer',
'target' => 'owner',
'view' => FALSE,
@ -323,20 +323,20 @@ class UserAccessControlHandlerTest extends UnitTestCase {
// reality edit access will already be checked on entity level and the
// user without view access will typically not be able to edit.
'edit' => TRUE,
),
array(
],
[
'viewer' => 'owner',
'target' => 'viewer',
'view' => FALSE,
'edit' => TRUE,
),
array(
],
[
'viewer' => 'admin',
'target' => 'owner',
'view' => FALSE,
'edit' => TRUE,
),
);
],
];
return $pass_access;
}
@ -353,26 +353,26 @@ class UserAccessControlHandlerTest extends UnitTestCase {
* Provides test data for testCreatedAccess().
*/
public function createdAccessProvider() {
$created_access = array(
array(
$created_access = [
[
'viewer' => 'viewer',
'target' => 'viewer',
'view' => TRUE,
'edit' => FALSE,
),
array(
],
[
'viewer' => 'owner',
'target' => 'viewer',
'view' => TRUE,
'edit' => FALSE,
),
array(
],
[
'viewer' => 'admin',
'target' => 'owner',
'view' => TRUE,
'edit' => TRUE,
),
);
],
];
return $created_access;
}
@ -392,26 +392,26 @@ class UserAccessControlHandlerTest extends UnitTestCase {
* Provides test data for testNonExistingFieldAccess().
*/
public function NonExistingFieldAccessProvider() {
$created_access = array(
array(
$created_access = [
[
'viewer' => 'viewer',
'target' => 'viewer',
'view' => TRUE,
'edit' => TRUE,
),
array(
],
[
'viewer' => 'owner',
'target' => 'viewer',
'view' => TRUE,
'edit' => TRUE,
),
array(
],
[
'viewer' => 'admin',
'target' => 'owner',
'view' => TRUE,
'edit' => TRUE,
),
);
],
];
return $created_access;
}

View file

@ -69,7 +69,7 @@ class UserAuthTest extends UnitTestCase {
$this->testUser = $this->getMockBuilder('Drupal\user\Entity\User')
->disableOriginalConstructor()
->setMethods(array('id', 'setPassword', 'save', 'getPassword'))
->setMethods(['id', 'setPassword', 'save', 'getPassword'])
->getMock();
$this->userAuth = new UserAuth($entity_manager, $this->passwordService);
@ -95,12 +95,12 @@ class UserAuthTest extends UnitTestCase {
* @return array
*/
public function providerTestAuthenticateWithMissingCredentials() {
return array(
array(NULL, NULL),
array(NULL, ''),
array('', NULL),
array('', ''),
);
return [
[NULL, NULL],
[NULL, ''],
['', NULL],
['', ''],
];
}
/**
@ -111,8 +111,8 @@ class UserAuthTest extends UnitTestCase {
public function testAuthenticateWithNoAccountReturned() {
$this->userStorage->expects($this->once())
->method('loadByProperties')
->with(array('name' => $this->username))
->will($this->returnValue(array()));
->with(['name' => $this->username])
->will($this->returnValue([]));
$this->assertFalse($this->userAuth->authenticate($this->username, $this->password));
}
@ -125,8 +125,8 @@ class UserAuthTest extends UnitTestCase {
public function testAuthenticateWithIncorrectPassword() {
$this->userStorage->expects($this->once())
->method('loadByProperties')
->with(array('name' => $this->username))
->will($this->returnValue(array($this->testUser)));
->with(['name' => $this->username])
->will($this->returnValue([$this->testUser]));
$this->passwordService->expects($this->once())
->method('check')
@ -148,8 +148,8 @@ class UserAuthTest extends UnitTestCase {
$this->userStorage->expects($this->once())
->method('loadByProperties')
->with(array('name' => $this->username))
->will($this->returnValue(array($this->testUser)));
->with(['name' => $this->username])
->will($this->returnValue([$this->testUser]));
$this->passwordService->expects($this->once())
->method('check')
@ -175,8 +175,8 @@ class UserAuthTest extends UnitTestCase {
$this->userStorage->expects($this->once())
->method('loadByProperties')
->with(array('name' => $this->username))
->will($this->returnValue(array($this->testUser)));
->with(['name' => $this->username])
->will($this->returnValue([$this->testUser]));
$this->passwordService->expects($this->once())
->method('check')
@ -203,8 +203,8 @@ class UserAuthTest extends UnitTestCase {
$this->userStorage->expects($this->once())
->method('loadByProperties')
->with(array('name' => $this->username))
->will($this->returnValue(array($this->testUser)));
->with(['name' => $this->username])
->will($this->returnValue([$this->testUser]));
$this->passwordService->expects($this->once())
->method('check')

View file

@ -0,0 +1,151 @@
<?php
namespace Drupal\Tests\user\Unit;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Session\AccountInterface;
use Drupal\Tests\UnitTestCase;
use Drupal\user\Entity\User;
use Drupal\user\Plugin\rest\resource\UserRegistrationResource;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
/**
* Only administrators can create user accounts.
*/
if (!defined('USER_REGISTER_ADMINISTRATORS_ONLY')) {
define('USER_REGISTER_ADMINISTRATORS_ONLY', 'admin_only');
}
/**
* Visitors can create their own accounts.
*/
if (!defined('USER_REGISTER_VISITORS')) {
define('USER_REGISTER_VISITORS', 'visitors');
}
/**
* Visitors can create accounts, but they don't become active without
* administrative approval.
*/
if (!defined('USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL')) {
define('USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL', 'visitors_admin_approval');
}
/**
* Tests User Registration REST resource.
*
* @coversDefaultClass \Drupal\user\Plugin\rest\resource\UserRegistrationResource
* @group user
*/
class UserRegistrationResourceTest extends UnitTestCase {
const ERROR_MESSAGE = "Unprocessable Entity: validation failed.\nproperty_path: message\nproperty_path_2: message_2\n";
/**
* Class to be tested.
*
* @var \Drupal\user\Plugin\rest\resource\UserRegistrationResource
*/
protected $testClass;
/**
* A reflection of self::$testClass.
*
* @var \ReflectionClass
*/
protected $reflection;
/**
* A user settings config instance.
*
* @var \Drupal\Core\Config\ImmutableConfig|\PHPUnit_Framework_MockObject_MockObject
*/
protected $userSettings;
/**
* Logger service.
*
* @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $logger;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $currentUser;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->logger = $this->prophesize(LoggerInterface::class)->reveal();
$this->userSettings = $this->prophesize(ImmutableConfig::class);
$this->currentUser = $this->prophesize(AccountInterface::class);
$this->testClass = new UserRegistrationResource([], 'plugin_id', '', [], $this->logger, $this->userSettings->reveal(), $this->currentUser->reveal());
$this->reflection = new \ReflectionClass($this->testClass);
}
/**
* Tests that an exception is thrown when no data provided for the account.
*/
public function testEmptyPost() {
$this->setExpectedException(BadRequestHttpException::class);
$this->testClass->post(NULL);
}
/**
* Tests that only new user accounts can be registered.
*/
public function testExistedEntityPost() {
$entity = $this->prophesize(User::class);
$entity->isNew()->willReturn(FALSE);
$this->setExpectedException(BadRequestHttpException::class);
$this->testClass->post($entity->reveal());
}
/**
* Tests that admin permissions are required to register a user account.
*/
public function testRegistrationAdminOnlyPost() {
$this->userSettings->get('register')->willReturn(USER_REGISTER_ADMINISTRATORS_ONLY);
$this->currentUser->isAnonymous()->willReturn(TRUE);
$this->testClass = new UserRegistrationResource([], 'plugin_id', '', [], $this->logger, $this->userSettings->reveal(), $this->currentUser->reveal());
$entity = $this->prophesize(User::class);
$entity->isNew()->willReturn(TRUE);
$this->setExpectedException(AccessDeniedHttpException::class);
$this->testClass->post($entity->reveal());
}
/**
* Tests that only anonymous users can register users.
*/
public function testRegistrationAnonymousOnlyPost() {
$this->currentUser->isAnonymous()->willReturn(FALSE);
$this->testClass = new UserRegistrationResource([], 'plugin_id', '', [], $this->logger, $this->userSettings->reveal(), $this->currentUser->reveal());
$entity = $this->prophesize(User::class);
$entity->isNew()->willReturn(TRUE);
$this->setExpectedException(AccessDeniedHttpException::class);
$this->testClass->post($entity->reveal());
}
}

View file

@ -19,24 +19,24 @@ class RolesRidTest extends UnitTestCase {
* @covers ::titleQuery
*/
public function testTitleQuery() {
$role1 = new Role(array(
$role1 = new Role([
'id' => 'test_rid_1',
'label' => 'test rid 1'
), 'user_role');
$role2 = new Role(array(
], 'user_role');
$role2 = new Role([
'id' => 'test_rid_2',
'label' => 'test <strong>rid 2</strong>',
), 'user_role');
], 'user_role');
// Creates a stub entity storage;
$role_storage = $this->getMockForAbstractClass('Drupal\Core\Entity\EntityStorageInterface');
$role_storage->expects($this->any())
->method('loadMultiple')
->will($this->returnValueMap(array(
array(array(), array()),
array(array('test_rid_1'), array('test_rid_1' => $role1)),
array(array('test_rid_1', 'test_rid_2'), array('test_rid_1' => $role1, 'test_rid_2' => $role2)),
)));
->will($this->returnValueMap([
[[], []],
[['test_rid_1'], ['test_rid_1' => $role1]],
[['test_rid_1', 'test_rid_2'], ['test_rid_1' => $role1, 'test_rid_2' => $role2]],
]));
$entity_type = $this->getMock('Drupal\Core\Entity\EntityTypeInterface');
$entity_type->expects($this->any())
@ -63,19 +63,19 @@ class RolesRidTest extends UnitTestCase {
$container->set('entity.manager', $entity_manager);
\Drupal::setContainer($container);
$roles_rid_argument = new RolesRid(array(), 'user__roles_rid', array(), $entity_manager);
$roles_rid_argument = new RolesRid([], 'user__roles_rid', [], $entity_manager);
$roles_rid_argument->value = array();
$roles_rid_argument->value = [];
$titles = $roles_rid_argument->titleQuery();
$this->assertEquals(array(), $titles);
$this->assertEquals([], $titles);
$roles_rid_argument->value = array('test_rid_1');
$roles_rid_argument->value = ['test_rid_1'];
$titles = $roles_rid_argument->titleQuery();
$this->assertEquals(array('test rid 1'), $titles);
$this->assertEquals(['test rid 1'], $titles);
$roles_rid_argument->value = array('test_rid_1', 'test_rid_2');
$roles_rid_argument->value = ['test_rid_1', 'test_rid_2'];
$titles = $roles_rid_argument->titleQuery();
$this->assertEquals(array('test rid 1', 'test <strong>rid 2</strong>'), $titles);
$this->assertEquals(['test rid 1', 'test <strong>rid 2</strong>'], $titles);
}
}