Update to Drupal 8.1.1. For more information, see https://www.drupal.org/node/2718713

This commit is contained in:
Pantheon Automation 2016-05-04 14:35:41 -07:00 committed by Greg Anderson
parent c0a0d5a94c
commit 9eae24d844
669 changed files with 3873 additions and 1553 deletions

View file

@ -214,7 +214,7 @@ class AccountSettingsForm extends ConfigFormBase {
$form['email_admin_created']['user_mail_register_admin_created_body'] = array(
'#type' => 'textarea',
'#title' => $this->t('Body'),
'#default_value' => $mail_config->get('register_admin_created.body'),
'#default_value' => $mail_config->get('register_admin_created.body'),
'#rows' => 15,
);

View file

@ -94,7 +94,7 @@ class UserController extends ControllerBase {
// A different user is already logged in on the computer.
else {
if ($reset_link_user = $this->userStorage->load($uid)) {
drupal_set_message($this->t('Another user (%other_user) is already logged into the site on this computer, but you tried to use a one-time link for user %resetting_user. Please <a href=":logout">logout</a> and try using the link again.',
drupal_set_message($this->t('Another user (%other_user) is already logged into the site on this computer, but you tried to use a one-time link for user %resetting_user. Please <a href=":logout">log out</a> and try using the link again.',
array('%other_user' => $account->getUsername(), '%resetting_user' => $reset_link_user->getUsername(), ':logout' => $this->url('user.logout'))), 'warning');
}
else {

View file

@ -11,7 +11,7 @@ use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Maintenance mode subscriber to logout users.
* Maintenance mode subscriber to log out users.
*/
class MaintenanceModeSubscriber implements EventSubscriberInterface {

View file

@ -115,4 +115,3 @@ class UserPasswordResetForm extends FormBase {
}
}

View file

@ -50,4 +50,3 @@ interface PermissionHandlerInterface {
public function moduleProvidesPermissions($module_name);
}

View file

@ -143,6 +143,13 @@ class UserSelection extends DefaultSelection {
*/
protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
$query = parent::buildEntityQuery($match, $match_operator);
$handler_settings = $this->configuration['handler_settings'];
// Filter out the Anonymous user if the selection handler is configured to
// exclude it.
if (isset($handler_settings['include_anonymous']) && !$handler_settings['include_anonymous']) {
$query->condition('uid', 0, '<>');
}
// The user entity doesn't have a label column.
if (isset($match)) {
@ -150,7 +157,6 @@ class UserSelection extends DefaultSelection {
}
// Filter by role.
$handler_settings = $this->configuration['handler_settings'];
if (!empty($handler_settings['filter']['role'])) {
$query->condition('roles', $handler_settings['filter']['role'], 'IN');
}

View file

@ -163,4 +163,3 @@ class Role extends AccessPluginBase implements CacheableDependencyInterface {
}
}

View file

@ -1,157 +0,0 @@
<?php
namespace Drupal\user\Tests\Condition;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\simpletest\KernelTestBase;
use Drupal\user\Entity\Role;
use Drupal\user\Entity\User;
use Drupal\user\RoleInterface;
/**
* Tests the user role condition.
*
* @group user
*/
class UserRoleConditionTest extends KernelTestBase {
/**
* The condition plugin manager.
*
* @var \Drupal\Core\Condition\ConditionManager
*/
protected $manager;
/**
* An anonymous user for testing purposes.
*
* @var \Drupal\user\UserInterface
*/
protected $anonymous;
/**
* An authenticated user for testing purposes.
*
* @var \Drupal\user\UserInterface
*/
protected $authenticated;
/**
* A custom role for testing purposes.
*
* @var \Drupal\user\Entity\RoleInterface
*/
protected $role;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('system', 'user', 'field');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installSchema('system', 'sequences');
$this->installEntitySchema('user');
$this->manager = $this->container->get('plugin.manager.condition');
// Set up the authenticated and anonymous roles.
Role::create(array(
'id' => RoleInterface::ANONYMOUS_ID,
'label' => 'Anonymous user',
))->save();
Role::create(array(
'id' => RoleInterface::AUTHENTICATED_ID,
'label' => 'Authenticated user',
))->save();
// Create new role.
$rid = strtolower($this->randomMachineName(8));
$label = $this->randomString(8);
$role = Role::create(array(
'id' => $rid,
'label' => $label,
));
$role->save();
$this->role = $role;
// Setup an anonymous user for our tests.
$this->anonymous = User::create(array(
'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(
'name' => $this->randomMachineName(),
));
$this->authenticated->save();
// Add the custom role.
$this->authenticated->addRole($this->role->id());
}
/**
* Test the user_role condition.
*/
public function testConditions() {
// Grab the user role condition and configure it to check against
// authenticated user roles.
/** @var $condition \Drupal\Core\Condition\ConditionInterface */
$condition = $this->manager->createInstance('user_role')
->setConfig('roles', array(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.
// Summaries require an extra space due to negate handling in summary().
$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));
$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));
$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');
// Set the context to the authenticated user and check that they also pass
// against anonymous or authenticated roles.
$condition->setContextValue('user', $this->authenticated);
$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));
$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)));
$this->assertTrue($condition->execute(), 'Constructor injection of context and configuration working as anticipated.');
// Check the negated summary.
$condition->setConfig('negate', TRUE);
$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));
$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('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())));
}
}

View file

@ -1,98 +0,0 @@
<?php
namespace Drupal\user\Tests\Field;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\simpletest\KernelTestBase;
use Drupal\user\Entity\User;
/**
* Tests the user_name formatter.
*
* @group field
*/
class UserNameFormatterTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['field', 'user', 'system'];
/**
* @var string
*/
protected $entityType;
/**
* @var string
*/
protected $bundle;
/**
* @var string
*/
protected $fieldName;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(['field']);
$this->installEntitySchema('user');
$this->installSchema('system', ['sequences']);
$this->entityType = 'user';
$this->bundle = $this->entityType;
$this->fieldName = 'name';
}
/**
* Renders fields of a given entity with a given display.
*
* @param \Drupal\Core\Entity\FieldableEntityInterface $entity
* The entity object with attached fields to render.
* @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
* The display to render the fields in.
*
* @return string
* The rendered entity fields.
*/
protected function renderEntityFields(FieldableEntityInterface $entity, EntityViewDisplayInterface $display) {
$content = $display->build($entity);
$content = $this->render($content);
return $content;
}
/**
* Tests the formatter output.
*/
public function testFormatter() {
$user = User::create([
'name' => 'test name',
]);
$user->save();
$result = $user->{$this->fieldName}->view(['type' => 'user_name']);
$this->assertEqual('username', $result[0]['#theme']);
$this->assertEqual(spl_object_hash($user), spl_object_hash($result[0]['#account']));
$result = $user->{$this->fieldName}->view(['type' => 'user_name', 'settings' => ['link_to_entity' => FALSE]]);
$this->assertEqual($user->getDisplayName(), $result[0]['#markup']);
$user = User::getAnonymousUser();
$result = $user->{$this->fieldName}->view(['type' => 'user_name']);
$this->assertEqual('username', $result[0]['#theme']);
$this->assertEqual(spl_object_hash($user), spl_object_hash($result[0]['#account']));
$result = $user->{$this->fieldName}->view(['type' => 'user_name', 'settings' => ['link_to_entity' => FALSE]]);
$this->assertEqual($user->getDisplayName(), $result[0]['#markup']);
$this->assertEqual($this->config('user.settings')->get('anonymous'), $result[0]['#markup']);
}
}

View file

@ -1,146 +0,0 @@
<?php
namespace Drupal\user\Tests;
use Drupal\Core\KeyValueStore\KeyValueExpirableFactory;
use Drupal\simpletest\KernelTestBase;
use Drupal\user\SharedTempStoreFactory;
use Drupal\Core\Lock\DatabaseLockBackend;
use Drupal\Core\Database\Database;
/**
* Tests the temporary object storage system.
*
* @group user
* @see \Drupal\Core\TempStore\TempStore.
*/
class TempStoreDatabaseTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('system', 'user');
/**
* A key/value store factory.
*
* @var \Drupal\user\SharedTempStoreFactory
*/
protected $storeFactory;
/**
* The name of the key/value collection to set and retrieve.
*
* @var string
*/
protected $collection;
/**
* An array of (fake) user IDs.
*
* @var array
*/
protected $users = array();
/**
* An array of random stdClass objects.
*
* @var array
*/
protected $objects = array();
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'));
// Create several objects for testing.
for ($i = 0; $i <= 3; $i++) {
$this->objects[$i] = $this->randomObject();
}
}
/**
* Tests the UserTempStore API.
*/
public function testUserTempStore() {
// Create a key/value collection.
$factory = new SharedTempStoreFactory(new KeyValueExpirableFactory(\Drupal::getContainer()), new DatabaseLockBackend(Database::getConnection()), $this->container->get('request_stack'));
$collection = $this->randomMachineName();
// Create two mock users.
for ($i = 0; $i <= 1; $i++) {
$users[$i] = mt_rand(500, 5000000);
// Storing the SharedTempStore objects in a class member variable causes a
// fatal exception, because in that situation garbage collection is not
// triggered until the test class itself is destructed, after tearDown()
// has deleted the database tables. Store the objects locally instead.
$stores[$i] = $factory->get($collection, $users[$i]);
}
$key = $this->randomMachineName();
// Test that setIfNotExists() succeeds only the first time.
for ($i = 0; $i <= 1; $i++) {
// setIfNotExists() should be TRUE the first time (when $i is 0) and
// FALSE the second time (when $i is 1).
$this->assertEqual(!$i, $stores[0]->setIfNotExists($key, $this->objects[$i]));
$metadata = $stores[0]->getMetadata($key);
$this->assertEqual($users[0], $metadata->owner);
$this->assertIdenticalObject($this->objects[0], $stores[0]->get($key));
// Another user should get the same result.
$metadata = $stores[1]->getMetadata($key);
$this->assertEqual($users[0], $metadata->owner);
$this->assertIdenticalObject($this->objects[0], $stores[1]->get($key));
}
// Remove the item and try to set it again.
$stores[0]->delete($key);
$stores[0]->setIfNotExists($key, $this->objects[1]);
// This time it should succeed.
$this->assertIdenticalObject($this->objects[1], $stores[0]->get($key));
// This user can update the object.
$stores[0]->set($key, $this->objects[2]);
$this->assertIdenticalObject($this->objects[2], $stores[0]->get($key));
// The object is the same when another user loads it.
$this->assertIdenticalObject($this->objects[2], $stores[1]->get($key));
// This user should be allowed to get, update, delete.
$this->assertTrue($stores[0]->getIfOwner($key) instanceof \stdClass);
$this->assertTrue($stores[0]->setIfOwner($key, $this->objects[1]));
$this->assertTrue($stores[0]->deleteIfOwner($key));
// Another user can update the object and become the owner.
$stores[1]->set($key, $this->objects[3]);
$this->assertIdenticalObject($this->objects[3], $stores[0]->get($key));
$this->assertIdenticalObject($this->objects[3], $stores[1]->get($key));
$metadata = $stores[1]->getMetadata($key);
$this->assertEqual($users[1], $metadata->owner);
// The first user should be informed that the second now owns the data.
$metadata = $stores[0]->getMetadata($key);
$this->assertEqual($users[1], $metadata->owner);
// The first user should no longer be allowed to get, update, delete.
$this->assertNull($stores[0]->getIfOwner($key));
$this->assertFalse($stores[0]->setIfOwner($key, $this->objects[1]));
$this->assertFalse($stores[0]->deleteIfOwner($key));
// 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))
->condition('collection', "user.shared_tempstore.$collection")
->condition('name', $key)
->execute();
$this->assertFalse($stores[0]->get($key));
$this->assertFalse($stores[1]->get($key));
}
}

View file

@ -1,146 +0,0 @@
<?php
namespace Drupal\user\Tests;
use Drupal\Core\Form\FormState;
use Drupal\simpletest\KernelTestBase;
/**
* Verifies that the field order in user account forms is compatible with
* password managers of web browsers.
*
* @group user
*/
class UserAccountFormFieldsTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('system', 'user', 'field');
/**
* Tests the root user account form section in the "Configure site" form.
*/
function testInstallConfigureForm() {
require_once \Drupal::root() . '/core/includes/install.core.inc';
require_once \Drupal::root() . '/core/includes/install.inc';
$install_state = install_state_defaults();
$form_state = new FormState();
$form_state->addBuildInfo('args', [&$install_state]);
$form = $this->container->get('form_builder')
->buildForm('Drupal\Core\Installer\Form\SiteConfigureForm', $form_state);
// Verify name and pass field order.
$this->assertFieldOrder($form['admin_account']['account']);
// Verify that web browsers may autocomplete the email value and
// autofill/prefill the name and pass values.
foreach (array('mail', 'name', 'pass') as $key) {
$this->assertFalse(isset($form['account'][$key]['#attributes']['autocomplete']), "'$key' field: 'autocomplete' attribute not found.");
}
}
/**
* Tests the user registration form.
*/
function testUserRegistrationForm() {
// Install default configuration; required for AccountFormController.
$this->installConfig(array('user'));
// Disable email confirmation to unlock the password field.
$this->config('user.settings')
->set('verify_mail', FALSE)
->save();
$form = $this->buildAccountForm('register');
// Verify name and pass field order.
$this->assertFieldOrder($form['account']);
// Verify that web browsers may autocomplete the email value and
// autofill/prefill the name and pass values.
foreach (array('mail', 'name', 'pass') as $key) {
$this->assertFalse(isset($form['account'][$key]['#attributes']['autocomplete']), "'$key' field: 'autocomplete' attribute not found.");
}
}
/**
* Tests the user edit form.
*/
function testUserEditForm() {
// Install default configuration; required for AccountFormController.
$this->installConfig(array('user'));
// Install the router table and then rebuild.
\Drupal::service('router.builder')->rebuild();
$form = $this->buildAccountForm('default');
// Verify name and pass field order.
$this->assertFieldOrder($form['account']);
// Verify that autocomplete is off on all account fields.
foreach (array('mail', 'name', 'pass') as $key) {
$this->assertIdentical($form['account'][$key]['#attributes']['autocomplete'], 'off', "'$key' field: 'autocomplete' attribute is 'off'.");
}
}
/**
* Asserts that the 'name' form element is directly before the 'pass' element.
*
* @param array $elements
* A form array section that contains the user account form elements.
*/
protected function assertFieldOrder(array $elements) {
$name_index = 0;
$name_weight = 0;
$pass_index = 0;
$pass_weight = 0;
$index = 0;
foreach ($elements as $key => $element) {
if ($key === 'name') {
$name_index = $index;
$name_weight = $element['#weight'];
$this->assertTrue($element['#sorted'], "'name' field is #sorted.");
}
elseif ($key === 'pass') {
$pass_index = $index;
$pass_weight = $element['#weight'];
$this->assertTrue($element['#sorted'], "'pass' field is #sorted.");
}
$index++;
}
$this->assertEqual($name_index, $pass_index - 1, "'name' field ($name_index) appears before 'pass' field ($pass_index).");
$this->assertTrue($name_weight < $pass_weight, "'name' field weight ($name_weight) is smaller than 'pass' field weight ($pass_weight).");
}
/**
* Builds the user account form for a given operation.
*
* @param string $operation
* The entity operation; one of 'register' or 'default'.
*
* @return array
* The form array.
*/
protected function buildAccountForm($operation) {
// @see HtmlEntityFormController::getFormObject()
$entity_type = 'user';
$fields = array();
if ($operation != 'register') {
$fields['uid'] = 2;
}
$entity = $this->container->get('entity.manager')
->getStorage($entity_type)
->create($fields);
$form_object = $this->container->get('entity.manager')
->getFormObject($entity_type, $operation)
->setEntity($entity);
// @see EntityFormBuilder::getForm()
return $this->container->get('entity.form_builder')->getForm($entity, $operation);
}
}

View file

@ -1,44 +0,0 @@
<?php
namespace Drupal\user\Tests;
use Drupal\config\Tests\SchemaCheckTestTrait;
use Drupal\simpletest\KernelTestBase;
use Drupal\user\Entity\Role;
/**
* Ensures the user action for adding and removing roles have valid config
* schema.
*
* @group user
*/
class UserActionConfigSchemaTest extends KernelTestBase {
use SchemaCheckTestTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('system', 'user');
/**
* Tests whether the user action config schema are valid.
*/
function testValidUserActionConfigSchema() {
$rid = strtolower($this->randomMachineName(8));
Role::create(array('id' => $rid))->save();
// Test user_add_role_action configuration.
$config = $this->config('system.action.user_add_role_action.' . $rid);
$this->assertEqual($config->get('id'), 'user_add_role_action.' . $rid);
$this->assertConfigSchema(\Drupal::service('config.typed'), $config->getName(), $config->get());
// Test user_remove_role_action configuration.
$config = $this->config('system.action.user_remove_role_action.' . $rid);
$this->assertEqual($config->get('id'), 'user_remove_role_action.' . $rid);
$this->assertConfigSchema(\Drupal::service('config.typed'), $config->getName(), $config->get());
}
}

View file

@ -149,11 +149,11 @@ class UserAdminLanguageTest extends WebTestBase {
/**
* Sets the User interface negotiation detection method.
*
* @param bool $admin_first
* Whether the admin negotiation should be first.
*
* Enables the "Account preference for administration pages" language
* detection method for the User interface language negotiation type.
*
* @param bool $admin_first
* Whether the admin negotiation should be first.
*/
function setLanguageNegotiation($admin_first = FALSE) {
$edit = array(

View file

@ -1,97 +0,0 @@
<?php
namespace Drupal\user\Tests;
use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
use Drupal\field\Entity\FieldConfig;
use Drupal\system\Tests\Entity\EntityUnitTestBase;
use Drupal\user\Entity\Role;
/**
* Tests the user reference field functionality.
*
* @group user
*/
class UserEntityReferenceTest extends EntityUnitTestBase {
use EntityReferenceTestTrait;
/**
* A randomly-generated role for testing purposes.
*
* @var \Drupal\user\Entity\RoleInterface
*/
protected $role1;
/**
* A randomly-generated role for testing purposes.
*
* @var \Drupal\user\Entity\RoleInterface
*/
protected $role2;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->role1 = Role::create(array(
'id' => strtolower($this->randomMachineName(8)),
'label' => $this->randomMachineName(8),
));
$this->role1->save();
$this->role2 = Role::create(array(
'id' => strtolower($this->randomMachineName(8)),
'label' => $this->randomMachineName(8),
));
$this->role2->save();
$this->createEntityReferenceField('user', 'user', 'user_reference', 'User reference', 'user');
}
/**
* Tests user selection by roles.
*/
function testUserSelectionByRole() {
$field_definition = FieldConfig::loadByName('user', 'user', 'user_reference');
$handler_settings = $field_definition->getSetting('handler_settings');
$handler_settings['filter']['role'] = array(
$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->addRole($this->role1->id());
$user1->save();
$user2 = $this->createUser(array('name' => 'aabbb'));
$user2->addRole($this->role1->id());
$user2->save();
$user3 = $this->createUser(array('name' => 'aabbbb'));
$user3->addRole($this->role2->id());
$user3->save();
/** @var \Drupal\Core\Entity\EntityAutocompleteMatcher $autocomplete */
$autocomplete = \Drupal::service('entity.autocomplete_matcher');
$matches = $autocomplete->getMatches('user', 'default', $field_definition->getSetting('handler_settings'), 'aabb');
$this->assertEqual(count($matches), 2);
$users = array();
foreach ($matches as $match) {
$users[] = $match['label'];
}
$this->assertTrue(in_array($user1->label(), $users));
$this->assertTrue(in_array($user2->label(), $users));
$this->assertFalse(in_array($user3->label(), $users));
$matches = $autocomplete->getMatches('user', 'default', $field_definition->getSetting('handler_settings'), 'aabbbb');
$this->assertEqual(count($matches), 0, '');
}
}

View file

@ -1,68 +0,0 @@
<?php
namespace Drupal\user\Tests;
use Drupal\simpletest\KernelTestBase;
use Drupal\user\Entity\User;
use Drupal\user\RoleInterface;
/**
* Tests the user entity class.
*
* @group user
* @see \Drupal\user\Entity\User
*/
class UserEntityTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('system', 'user', 'field');
/**
* Tests some of the methods.
*
* @see \Drupal\user\Entity\User::getRoles()
* @see \Drupal\user\Entity\User::addRole()
* @see \Drupal\user\Entity\User::removeRole()
*/
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();
$values = array(
'uid' => 1,
'roles' => array('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());
$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());
$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());
$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());
$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());
}
}

View file

@ -1,52 +0,0 @@
<?php
namespace Drupal\user\Tests;
use Drupal\user\Entity\User;
use Drupal\simpletest\KernelTestBase;
/**
* Tests available user fields in twig.
*
* @group user
*/
class UserFieldsTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['user', 'system'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$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::theme()->setActiveTheme(\Drupal::service('theme.initialization')->initTheme('user_test_theme'));
// Clear the theme registry.
$this->container->set('theme.registry', NULL);
}
/**
* Tests account's available fields.
*/
function testUserFields() {
// Create the user to test the user fields.
$user = User::create([
'name' => 'foobar',
'mail' => 'foobar@example.com',
]);
$build = user_view($user);
$output = \Drupal::service('renderer')->renderRoot($build);
$this->setRawContent($output);
$userEmail = $user->getEmail();
$this->assertText($userEmail, "User's mail field is found in the twig template");
}
}

View file

@ -1,54 +0,0 @@
<?php
namespace Drupal\user\Tests;
use Drupal\simpletest\KernelTestBase;
/**
* Tests user_install().
*
* @group user
*/
class UserInstallTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('user');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->container->get('module_handler')->loadInclude('user', 'install');
$this->installEntitySchema('user');
user_install();
}
/**
* Test that the initial users have correct values.
*/
public function testUserInstall() {
$result = db_query('SELECT u.uid, u.uuid, u.langcode, uf.status FROM {users} u INNER JOIN {users_field_data} uf ON u.uid=uf.uid ORDER BY u.uid')
->fetchAllAssoc('uid');
$anon = $result[0];
$admin = $result[1];
$this->assertFalse(empty($anon->uuid), 'Anon user has a UUID');
$this->assertFalse(empty($admin->uuid), 'Admin user has a UUID');
// Test that the anonymous and administrators languages are equal to the
// site's default language.
$this->assertEqual($anon->langcode, \Drupal::languageManager()->getDefaultLanguage()->getId());
$this->assertEqual($admin->langcode, \Drupal::languageManager()->getDefaultLanguage()->getId());
// Test that the administrator is active.
$this->assertEqual($admin->status, 1);
// Test that the anonymous user is blocked.
$this->assertEqual($anon->status, 0);
}
}

View file

@ -86,7 +86,7 @@ class UserLanguageCreationTest extends WebTestBase {
$this->drupalGet($user_edit);
$this->assertOptionSelected("edit-preferred-langcode", $langcode, 'Language selector is accessible and correct language is selected.');
// Set pass_raw so we can login the new user.
// Set pass_raw so we can log in the new user.
$user->pass_raw = $this->randomMachineName(10);
$edit = array(
'pass[pass1]' => $user->pass_raw,

View file

@ -43,7 +43,7 @@ class UserLanguageTest extends WebTestBase {
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
$this->drupalLogout();
// Login as normal user and edit account settings.
// Log in as normal user and edit account settings.
$this->drupalLogin($web_user);
$path = 'user/' . $web_user->id() . '/edit';
$this->drupalGet($path);

View file

@ -99,13 +99,13 @@ class UserRegistrationTest extends WebTestBase {
$this->drupalPostForm('user/register', $edit, t('Create new account'));
$this->assertText(t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.'), 'Users are notified of pending approval');
// Try to login before administrator approval.
// Try to log in before administrator approval.
$auth = array(
'name' => $name,
'pass' => $pass,
);
$this->drupalPostForm('user/login', $auth, t('Log in'));
$this->assertText(t('The username @name has not been activated or is blocked.', array('@name' => $name)), 'User cannot login yet.');
$this->assertText(t('The username @name has not been activated or is blocked.', array('@name' => $name)), 'User cannot log in yet.');
// Activate the new account.
$accounts = entity_load_multiple_by_properties('user', array('name' => $name, 'mail' => $mail));
@ -118,7 +118,7 @@ class UserRegistrationTest extends WebTestBase {
$this->drupalPostForm('user/' . $new_user->id() . '/edit', $edit, t('Save'));
$this->drupalLogout();
// Login after administrator approval.
// Log in after administrator approval.
$this->drupalPostForm('user/login', $auth, t('Log in'));
$this->assertText(t('Member for'), 'User can log in after administrator approval.');
}

View file

@ -1,74 +0,0 @@
<?php
namespace Drupal\user\Tests;
use Drupal\simpletest\KernelTestBase;
use Drupal\user\Entity\User;
/**
* Tests the handling of user_role entity from the user module
*
* @group user
*/
class UserRoleDeleteTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('system', 'user', 'field');
protected function setUp() {
parent::setUp();
$this->installEntitySchema('user');
}
/**
* Tests removal of role references on role entity delete.
*
* @see user_user_role_delete()
*/
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();
// Create user and assign both test roles.
$values = array(
'uid' => 1,
'name' => $this->randomString(),
'roles' => array('test_role_one', 'test_role_two'),
);
$user = User::create($values);
$user->save();
// Check that user has both roles.
$this->assertTrue($user->hasRole('test_role_one'));
$this->assertTrue($user->hasRole('test_role_two'));
// Delete test role one.
$test_role_one = $role_storage->load('test_role_one');
$test_role_one->delete();
// Load user again from the database.
$user = User::load($user->id());
// Check that user does not have role one anymore, still has role two.
$this->assertFalse($user->hasRole('test_role_one'));
$this->assertTrue($user->hasRole('test_role_two'));
// Create new role with same name.
$role_storage->create(array('id' => 'test_role_one'))->save();
// Load user again from the database.
$user = User::load($user->id());
// Check that user does not have role one.
$this->assertFalse($user->hasRole('test_role_one'));
$this->assertTrue($user->hasRole('test_role_two'));
}
}

View file

@ -1,48 +0,0 @@
<?php
namespace Drupal\user\Tests;
use Drupal\simpletest\KernelTestBase;
use Drupal\user\Entity\User;
/**
* Tests user saving status.
*
* @group user
*/
class UserSaveStatusTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('system', 'user', 'field');
protected function setUp() {
parent::setUp();
$this->installEntitySchema('user');
}
/**
* Test SAVED_NEW and SAVED_UPDATED statuses for user entity type.
*/
function testUserSaveStatus() {
// Create a new user.
$values = array(
'uid' => 1,
'name' => $this->randomMachineName(),
);
$user = User::create($values);
// Test SAVED_NEW.
$return = $user->save();
$this->assertEqual($return, SAVED_NEW, "User was saved with SAVED_NEW status.");
// Test SAVED_UPDATED.
$user->name = $this->randomMachineName();
$return = $user->save();
$this->assertEqual($return, SAVED_UPDATED, "User was saved with SAVED_UPDATED status.");
}
}

View file

@ -1,215 +0,0 @@
<?php
namespace Drupal\user\Tests;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Language\Language;
use Drupal\Core\Render\Element\Email;
use Drupal\simpletest\KernelTestBase;
use Drupal\user\Entity\Role;
use Drupal\user\Entity\User;
/**
* Verify that user validity checks behave as designed.
*
* @group user
*/
class UserValidationTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('field', 'user', 'system');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installEntitySchema('user');
$this->installSchema('system', array('sequences'));
// Make sure that the default roles exist.
$this->installConfig(array('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'),
'ᚠᛇᚻ᛫ᛒᛦᚦ' => 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'),
);
foreach ($test_cases as $name => $test_case) {
list($description, $test) = $test_case;
$result = user_validate_name($name);
$this->$test($result, $description . ' (' . $name . ')');
}
}
/**
* Runs entity validation checks.
*/
function testValidation() {
$user = User::create(array(
'name' => 'test',
'mail' => 'test@example.com',
));
$violations = $user->validate();
$this->assertEqual(count($violations), 0, 'No violations when validating a default user.');
// Only test one example invalid name here, the rest is already covered in
// the testUsernames() method in this class.
$name = $this->randomMachineName(61);
$user->set('name', $name);
$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)));
// Create a second test user to provoke a name collision.
$user2 = User::create([
'name' => 'existing',
'mail' => 'existing@example.com',
]);
$user2->save();
$user->set('name', 'existing');
$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')));
// Make the name valid.
$user->set('name', $this->randomMachineName());
$user->set('mail', 'invalid');
$violations = $user->validate();
$this->assertEqual(count($violations), 1, 'Violation found when email is invalid');
$this->assertEqual($violations[0]->getPropertyPath(), 'mail.0.value');
$this->assertEqual($violations[0]->getMessage(), t('This value is not a valid email address.'));
$mail = $this->randomMachineName(Email::EMAIL_MAX_LENGTH - 11) . '@example.com';
$user->set('mail', $mail);
$violations = $user->validate();
// @todo There are two violations because EmailItem::getConstraints()
// overlaps with the implicit constraint of the 'email' property type used
// in EmailItem::propertyDefinitions(). Resolve this in
// 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[1]->getPropertyPath(), 'mail.0.value');
$this->assertEqual($violations[1]->getMessage(), t('This value is not a valid email address.'));
// Provoke an email collision with an existing user.
$user->set('mail', 'existing@example.com');
$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')));
$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())));
$user->set('mail', 'someone@example.com');
$user->set('timezone', $this->randomString(33));
$this->assertLengthViolation($user, 'timezone', 32, 2, 1);
$user->set('timezone', 'invalid zone');
$this->assertAllowedValuesViolation($user, 'timezone');
$user->set('timezone', NULL);
$user->set('init', 'invalid');
$violations = $user->validate();
$this->assertEqual(count($violations), 1, 'Violation found when init email is invalid');
$user->set('init', NULL);
$user->set('langcode', 'invalid');
$this->assertAllowedValuesViolation($user, 'langcode');
$user->set('langcode', NULL);
// Only configurable langcodes are allowed for preferred languages.
$user->set('preferred_langcode', Language::LANGCODE_NOT_SPECIFIED);
$this->assertAllowedValuesViolation($user, 'preferred_langcode');
$user->set('preferred_langcode', NULL);
$user->set('preferred_admin_langcode', Language::LANGCODE_NOT_SPECIFIED);
$this->assertAllowedValuesViolation($user, 'preferred_admin_langcode');
$user->set('preferred_admin_langcode', NULL);
Role::create(array('id' => 'role1'))->save();
Role::create(array('id' => 'role2'))->save();
// Test cardinality of user roles.
$user = User::create([
'name' => 'role_test',
'mail' => 'test@example.com',
'roles' => array('role1', 'role2'),
]);
$violations = $user->validate();
$this->assertEqual(count($violations), 0);
$user->roles[1]->target_id = 'unknown_role';
$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')));
}
/**
* Verifies that a length violation exists for the given field.
*
* @param \Drupal\core\Entity\EntityInterface $entity
* The entity object to validate.
* @param string $field_name
* The field that violates the maximum length.
* @param int $length
* Number of characters that was exceeded.
* @param int $count
* (optional) The number of expected violations. Defaults to 1.
* @param int $expected_index
* (optional) The index at which to expect the violation. Defaults to 0.
*/
protected function assertLengthViolation(EntityInterface $entity, $field_name, $length, $count = 1, $expected_index = 0) {
$violations = $entity->validate();
$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)));
}
/**
* Verifies that a AllowedValues violation exists for the given field.
*
* @param \Drupal\core\Entity\EntityInterface $entity
* The entity object to validate.
* @param string $field_name
* The name of the field to verify.
*/
protected function assertAllowedValuesViolation(EntityInterface $entity, $field_name) {
$violations = $entity->validate();
$this->assertEqual(count($violations), 1, "Allowed values violation for $field_name found.");
$this->assertEqual($violations[0]->getPropertyPath(), "$field_name.0.value");
$this->assertEqual($violations[0]->getMessage(), t('The value you selected is not a valid choice.'));
}
}

View file

@ -36,7 +36,7 @@ class BulkFormAccessTest extends UserTestBase {
// Ensure this account is not blocked.
$this->assertFalse($no_edit_user->isBlocked(), 'The user is not blocked.');
// Login as user admin.
// Log in as user admin.
$admin_user = $this->drupalCreateUser(array('administer users'));
$this->drupalLogin($admin_user);
@ -47,7 +47,7 @@ class BulkFormAccessTest extends UserTestBase {
// Test blocking the account "no_edit".
$edit = array(
'user_bulk_form[' . ($no_edit_user->id() -1) . ']' => TRUE,
'user_bulk_form[' . ($no_edit_user->id() - 1) . ']' => TRUE,
'action' => 'user_block_user_action',
);
$this->drupalPostForm('test-user-bulk-form', $edit, t('Apply'));
@ -68,7 +68,7 @@ class BulkFormAccessTest extends UserTestBase {
$this->assertTrue($normal_user->access('update', $admin_user));
$edit = array(
'user_bulk_form[' . ($normal_user->id() -1) . ']' => TRUE,
'user_bulk_form[' . ($normal_user->id() - 1) . ']' => TRUE,
'action' => 'user_block_user_action',
);
$this->drupalPostForm('test-user-bulk-form', $edit, t('Apply'));
@ -76,11 +76,11 @@ class BulkFormAccessTest extends UserTestBase {
$normal_user = User::load($normal_user->id());
$this->assertTrue($normal_user->isBlocked(), 'The user is blocked.');
// Login as user without the 'administer users' permission.
// Log in as user without the 'administer users' permission.
$this->drupalLogin($this->drupalCreateUser());
$edit = array(
'user_bulk_form[' . ($normal_user->id() -1) . ']' => TRUE,
'user_bulk_form[' . ($normal_user->id() - 1) . ']' => TRUE,
'action' => 'user_unblock_user_action',
);
$this->drupalPostForm('test-user-bulk-form', $edit, t('Apply'));
@ -98,7 +98,7 @@ class BulkFormAccessTest extends UserTestBase {
$account = $this->drupalCreateUser(array(), 'no_delete');
$account2 = $this->drupalCreateUser(array(), 'may_delete');
// Login as user admin.
// Log in as user admin.
$this->drupalLogin($this->drupalCreateUser(array('administer users')));
// Ensure that the account "no_delete" can not be deleted.
@ -110,8 +110,8 @@ class BulkFormAccessTest extends UserTestBase {
// Test deleting the accounts "no_delete" and "may_delete".
$edit = array(
'user_bulk_form[' . ($account->id() -1) . ']' => TRUE,
'user_bulk_form[' . ($account2->id() -1) . ']' => TRUE,
'user_bulk_form[' . ($account->id() - 1) . ']' => TRUE,
'user_bulk_form[' . ($account2->id() - 1) . ']' => TRUE,
'action' => 'user_cancel_user_action',
);
$this->drupalPostForm('test-user-bulk-form', $edit, t('Apply'));

View file

@ -31,7 +31,7 @@ class BulkFormTest extends UserTestBase {
* Tests the user bulk form.
*/
public function testBulkForm() {
// Login as a user without 'administer users'.
// Log in as a user without 'administer users'.
$this->drupalLogin($this->drupalCreateUser(array('administer permissions')));
$user_storage = $this->container->get('entity.manager')->getStorage('user');