updated core and modules

This commit is contained in:
Bachir Soussi Chiadmi
2017-09-09 16:27:51 +02:00
parent 027aa99b32
commit 41863f872c
7810 changed files with 318922 additions and 83631 deletions
@@ -14,9 +14,9 @@ $connection = Database::getConnection();
// already.
$connection->delete('config')->condition('name', 'user.mail')->execute();
$connection->insert('config')
->fields(array('collection', 'name', 'data'))
->values(array(
->fields(['collection', 'name', 'data'])
->values([
'collection' => '',
'name' => 'user.mail',
'data' => "a:10:{s:14:\"cancel_confirm\";a:2:{s:4:\"body\";s:369:\"[user:name],\n\nA request to cancel your account has been made at [site:name].\n\nYou may now cancel your account on [site:url-brief] by clicking this link or copying and pasting it into your browser:\n\n[user:cancel-url]\n\nNOTE: The cancellation of your account is not reversible.\n\nThis link expires in one day and nothing will happen if it is not used.\n\n-- [site:name] team\";s:7:\"subject\";s:59:\"Account cancellation request for [user:name] at [site:name]\";}s:14:\"password_reset\";a:2:{s:4:\"body\";s:397:\"[user:name],\n\nA request to reset the password for your account has been made at [site:name].\n\nYou may now log in by clicking this link or copying and pasting it to your browser:\n\n[user:one-time-login-url]\n\nThis link can only be used once to log in and will lead you to a page where you can set your password. It expires after one day and nothing will happen if it's not used.\n\n-- [site:name] team\";s:7:\"subject\";s:60:\"Replacement login information for [user:name] at [site:name]\";}s:22:\"register_admin_created\";a:2:{s:4:\"body\";s:463:\"[user:name],\n\nA site administrator at [site:name] has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser:\n\n[user:one-time-login-url]\n\nThis link can only be used once to log in and will lead you to a page where you can set your password.\n\nAfter setting your password, you will be able to log in at [site:login-url] in the future using:\n\nusername: [user:name]\npassword: Your password\n\n-- [site:name] team\";s:7:\"subject\";s:58:\"An administrator created an account for you at [site:name]\";}s:29:\"register_no_approval_required\";a:2:{s:4:\"body\";s:437:\"[user:name],\n\nThank you for registering at [site:name]. You may now log in by clicking this link or copying and pasting it to your browser:\n\n[user:one-time-login-url]\n\nThis link can only be used once to log in and will lead you to a page where you can set your password.\n\nAfter setting your password, you will be able to log in at [site:login-url] in the future using:\n\nusername: [user:name]\npassword: Your password\n\n-- [site:name] team\";s:7:\"subject\";s:46:\"Account details for [user:name] at [site:name]\";}s:25:\"register_pending_approval\";a:2:{s:4:\"body\";s:281:\"[user:name],\n\nThank you for registering at [site:name]. Your application for an account is currently pending approval. Once it has been approved, you will receive another email containing information about how to log in, set your password, and other details.\n\n\n-- [site:name] team\";s:7:\"subject\";s:71:\"Account details for [user:name] at [site:name] (pending admin approval)\";}s:31:\"register_pending_approval_admin\";a:2:{s:4:\"body\";s:56:\"[user:name] has applied for an account.\n\n[user:edit-url]\";s:7:\"subject\";s:71:\"Account details for [user:name] at [site:name] (pending admin approval)\";}s:16:\"status_activated\";a:2:{s:4:\"body\";s:446:\"[user:name],\n\nYour account at [site:name] has been activated.\n\nYou may now log in by clicking this link or copying and pasting it into your browser:\n\n[user:one-time-login-url]\n\nThis link can only be used once to log in and will lead you to a page where you can set your password.\n\nAfter setting your password, you will be able to log in at [site:login-url] in the future using:\n\nusername: [user:name]\npassword: Your password\n\n-- [site:name] team\";s:7:\"subject\";s:57:\"Account details for [user:name] at [site:name] (approved)\";}s:14:\"status_blocked\";a:2:{s:4:\"body\";s:89:\"[user:name],\n\nYour account on [site:account-name] has been blocked.\n\n-- [site:name] team\";s:7:\"subject\";s:56:\"Account details for [user:name] at [site:name] (blocked)\";}s:15:\"status_canceled\";a:2:{s:4:\"body\";s:82:\"[user:name],\n\nYour account on [site:name] has been canceled.\n\n-- [site:name] team\";s:7:\"subject\";s:57:\"Account details for [user:name] at [site:name] (canceled)\";}s:8:\"langcode\";s:2:\"en\";}"
))->execute();
])->execute();
@@ -5,8 +5,8 @@ package: Testing
# version: VERSION
# core: 8.x
# Information added by Drupal.org packaging script on 2016-08-03
version: '8.1.8'
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
core: '8.x'
project: 'drupal'
datestamp: 1470233791
datestamp: 1502903957
@@ -5,8 +5,8 @@ package: Testing
# version: VERSION
# core: 8.x
# Information added by Drupal.org packaging script on 2016-08-03
version: '8.1.8'
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
core: '8.x'
project: 'drupal'
datestamp: 1470233791
datestamp: 1502903957
@@ -5,8 +5,8 @@ package: Testing
# version: VERSION
# core: 8.x
# Information added by Drupal.org packaging script on 2016-08-03
version: '8.1.8'
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
core: '8.x'
project: 'drupal'
datestamp: 1470233791
datestamp: 1502903957
@@ -5,8 +5,8 @@ package: Testing
# version: VERSION
# core: 8.x
# Information added by Drupal.org packaging script on 2016-08-03
version: '8.1.8'
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
core: '8.x'
project: 'drupal'
datestamp: 1470233791
datestamp: 1502903957
@@ -13,7 +13,7 @@ use Drupal\Component\Utility\SafeMarkup;
function user_hooks_test_user_format_name_alter(&$name, $account) {
if (\Drupal::state()->get('user_hooks_test_user_format_name_alter', FALSE)) {
if (\Drupal::state()->get('user_hooks_test_user_format_name_alter_safe', FALSE)) {
$name = SafeMarkup::format('<em>@uid</em>', array('@uid' => $account->id()));
$name = SafeMarkup::format('<em>@uid</em>', ['@uid' => $account->id()]);
}
else {
$name = '<em>' . $account->id() . '</em>';
@@ -0,0 +1,119 @@
langcode: en
status: true
dependencies:
module:
- user
id: test_filter_current_user
label: Users
module: views
description: ''
tag: ''
base_table: users_field_data
base_field: uid
core: 8.x
display:
default:
display_plugin: default
id: default
display_title: Master
position: 0
display_options:
access:
type: none
cache:
type: tag
query:
type: views_query
options:
disable_sql_rewrite: false
distinct: false
replica: false
query_comment: ''
exposed_form:
type: basic
options:
submit_button: Filter
reset_button: false
reset_button_label: Reset
exposed_sorts_label: 'Sort by'
expose_sort_order: true
sort_asc_label: Asc
sort_desc_label: Desc
pager:
type: none
options:
offset: 0
style:
type: default
options:
row_class: ''
default_row_class: true
uses_fields: false
row:
type: fields
options:
separator: ''
hide_empty: false
default_field_elements: true
fields:
uid:
id: uid
table: users
field: uid
relationship: none
group_type: group
admin_label: ''
label: ''
exclude: false
filters:
uid_current:
id: uid_current
table: users
field: uid_current
relationship: none
group_type: group
admin_label: ''
operator: '='
value: '1'
group: 1
exposed: false
expose:
operator_id: ''
label: ''
description: ''
use_operator: false
operator: ''
identifier: ''
required: false
remember: false
multiple: false
remember_roles:
authenticated: authenticated
is_grouped: false
group_info:
label: ''
description: ''
identifier: ''
optional: true
widget: select
multiple: false
remember: false
default_group: All
default_group_multiple: { }
group_items: { }
entity_type: user
plugin_id: user_current
sorts: { }
header: { }
footer: { }
empty: { }
relationships: { }
arguments: { }
display_extenders: { }
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- user
tags: { }
@@ -48,7 +48,7 @@ display:
group: 1
id: status
table: users_field_data
value: true
value: '1'
plugin_id: boolean
entity_type: user
entity_field: status
@@ -52,7 +52,7 @@ display:
table: users_field_data
field: status
operator: '='
value: true
value: '1'
plugin_id: boolean
entity_type: user
entity_field: status
@@ -126,7 +126,7 @@ display:
field_api_classes: false
filters:
status:
value: true
value: '1'
table: users_field_data
field: status
plugin_id: boolean
@@ -142,7 +142,7 @@ display:
plugin_id: user_roles
filters:
status:
value: true
value: '1'
table: users_field_data
field: status
id: status
@@ -8,8 +8,8 @@ dependencies:
- user
- views
# Information added by Drupal.org packaging script on 2016-08-03
version: '8.1.8'
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
core: '8.x'
project: 'drupal'
datestamp: 1470233791
datestamp: 1502903957
@@ -0,0 +1,64 @@
<?php
namespace Drupal\Tests\user\Functional;
use Drupal\Tests\views_ui\Functional\UITestBase;
use Drupal\views\Tests\ViewTestData;
/**
* Tests views role access plugin UI.
*
* @group user
* @see \Drupal\user\Plugin\views\access\Role
*/
class AccessRoleUITest extends UITestBase {
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_access_role'];
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['user', 'user_test_views'];
/**
* {@inheritdoc}
*/
protected function setUp($import_test_views = TRUE) {
parent::setUp($import_test_views);
ViewTestData::createTestViews(get_class($this), ['user_test_views']);
}
/**
* Tests the role access plugin UI.
*/
public function testAccessRoleUI() {
$entity_manager = $this->container->get('entity.manager');
$entity_manager->getStorage('user_role')->create(['id' => 'custom_role', 'label' => 'Custom role'])->save();
$access_url = "admin/structure/views/nojs/display/test_access_role/default/access_options";
$this->drupalPostForm($access_url, ['access_options[role][custom_role]' => 1], t('Apply'));
$this->assertResponse(200);
$this->drupalPostForm(NULL, [], t('Save'));
$view = $entity_manager->getStorage('view')->load('test_access_role');
$display = $view->getDisplay('default');
$this->assertEqual($display['display_options']['access']['options']['role'], ['custom_role' => 'custom_role']);
// Test changing access plugin from role to none.
$this->drupalPostForm('admin/structure/views/nojs/display/test_access_role/default/access', ['access[type]' => 'none'], t('Apply'));
$this->drupalPostForm(NULL, [], t('Save'));
// Verify that role option is not set.
$view = $entity_manager->getStorage('view')->load('test_access_role');
$display = $view->getDisplay('default');
$this->assertFalse(isset($display['display_options']['access']['options']['role']));
}
}
@@ -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'];
}
}
@@ -0,0 +1,613 @@
<?php
namespace Drupal\Tests\user\Functional;
use Drupal\comment\CommentInterface;
use Drupal\comment\Entity\Comment;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\Tests\BrowserTestBase;
use Drupal\user\Entity\User;
/**
* Ensure that account cancellation methods work as expected.
*
* @group user
*/
class UserCancelTest extends BrowserTestBase {
use CommentTestTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['node', 'comment'];
protected function setUp() {
parent::setUp();
$this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
}
/**
* Attempt to cancel account without permission.
*/
public function testUserCancelWithoutPermission() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$this->config('user.settings')->set('cancel_method', 'user_cancel_reassign')->save();
$user_storage = $this->container->get('entity.manager')->getStorage('user');
// Create a user.
$account = $this->drupalCreateUser([]);
$this->drupalLogin($account);
// Load a real user object.
$user_storage->resetCache([$account->id()]);
$account = $user_storage->load($account->id());
// Create a node.
$node = $this->drupalCreateNode(['uid' => $account->id()]);
// Attempt to cancel account.
$this->drupalGet('user/' . $account->id() . '/edit');
$this->assertNoRaw(t('Cancel account'), 'No cancel account button displayed.');
// Attempt bogus account cancellation request confirmation.
$timestamp = $account->getLastLoginTime();
$this->drupalGet("user/" . $account->id() . "/cancel/confirm/$timestamp/" . user_pass_rehash($account, $timestamp));
$this->assertResponse(403, 'Bogus cancelling request rejected.');
$user_storage->resetCache([$account->id()]);
$account = $user_storage->load($account->id());
$this->assertTrue($account->isActive(), 'User account was not canceled.');
// Confirm user's content has not been altered.
$node_storage->resetCache([$node->id()]);
$test_node = $node_storage->load($node->id());
$this->assertTrue(($test_node->getOwnerId() == $account->id() && $test_node->isPublished()), 'Node of the user has not been altered.');
}
/**
* Test ability to change the permission for canceling users.
*/
public function testUserCancelChangePermission() {
\Drupal::service('module_installer')->install(['user_form_test']);
\Drupal::service('router.builder')->rebuild();
$this->config('user.settings')->set('cancel_method', 'user_cancel_reassign')->save();
// Create a regular user.
$account = $this->drupalCreateUser([]);
$admin_user = $this->drupalCreateUser(['cancel other accounts']);
$this->drupalLogin($admin_user);
// Delete regular user.
$this->drupalPostForm('user_form_test_cancel/' . $account->id(), [], t('Cancel account'));
// Confirm deletion.
$this->assertRaw(t('%name has been deleted.', ['%name' => $account->getUsername()]), 'User deleted.');
$this->assertFalse(User::load($account->id()), 'User is not found in the database.');
}
/**
* Tests that user account for uid 1 cannot be cancelled.
*
* This should never be possible, or the site owner would become unable to
* administer the site.
*/
public function testUserCancelUid1() {
$user_storage = $this->container->get('entity.manager')->getStorage('user');
\Drupal::service('module_installer')->install(['views']);
\Drupal::service('router.builder')->rebuild();
// Update uid 1's name and password to we know it.
$password = user_password();
$account = [
'name' => 'user1',
'pass' => $this->container->get('password')->hash(trim($password)),
];
// We cannot use $account->save() here, because this would result in the
// password being hashed again.
db_update('users_field_data')
->fields($account)
->condition('uid', 1)
->execute();
// Reload and log in uid 1.
$user_storage->resetCache([1]);
$user1 = $user_storage->load(1);
$user1->pass_raw = $password;
// Try to cancel uid 1's account with a different user.
$admin_user = $this->drupalCreateUser(['administer users']);
$this->drupalLogin($admin_user);
$edit = [
'action' => 'user_cancel_user_action',
'user_bulk_form[0]' => TRUE,
];
$this->drupalPostForm('admin/people', $edit, t('Apply to selected items'));
// Verify that uid 1's account was not cancelled.
$user_storage->resetCache([1]);
$user1 = $user_storage->load(1);
$this->assertTrue($user1->isActive(), 'User #1 still exists and is not blocked.');
}
/**
* Attempt invalid account cancellations.
*/
public function testUserCancelInvalid() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$this->config('user.settings')->set('cancel_method', 'user_cancel_reassign')->save();
$user_storage = $this->container->get('entity.manager')->getStorage('user');
// Create a user.
$account = $this->drupalCreateUser(['cancel account']);
$this->drupalLogin($account);
// Load a real user object.
$user_storage->resetCache([$account->id()]);
$account = $user_storage->load($account->id());
// Create a node.
$node = $this->drupalCreateNode(['uid' => $account->id()]);
// Attempt to cancel account.
$this->drupalPostForm('user/' . $account->id() . '/edit', NULL, t('Cancel account'));
// Confirm account cancellation.
$timestamp = time();
$this->drupalPostForm(NULL, NULL, t('Cancel account'));
$this->assertText(t('A confirmation request to cancel your account has been sent to your email address.'), 'Account cancellation request mailed message displayed.');
// Attempt bogus account cancellation request confirmation.
$bogus_timestamp = $timestamp + 60;
$this->drupalGet("user/" . $account->id() . "/cancel/confirm/$bogus_timestamp/" . user_pass_rehash($account, $bogus_timestamp));
$this->assertText(t('You have tried to use an account cancellation link that has expired. Please request a new one using the form below.'), 'Bogus cancelling request rejected.');
$user_storage->resetCache([$account->id()]);
$account = $user_storage->load($account->id());
$this->assertTrue($account->isActive(), 'User account was not canceled.');
// Attempt expired account cancellation request confirmation.
$bogus_timestamp = $timestamp - 86400 - 60;
$this->drupalGet("user/" . $account->id() . "/cancel/confirm/$bogus_timestamp/" . user_pass_rehash($account, $bogus_timestamp));
$this->assertText(t('You have tried to use an account cancellation link that has expired. Please request a new one using the form below.'), 'Expired cancel account request rejected.');
$user_storage->resetCache([$account->id()]);
$account = $user_storage->load($account->id());
$this->assertTrue($account->isActive(), 'User account was not canceled.');
// Confirm user's content has not been altered.
$node_storage->resetCache([$node->id()]);
$test_node = $node_storage->load($node->id());
$this->assertTrue(($test_node->getOwnerId() == $account->id() && $test_node->isPublished()), 'Node of the user has not been altered.');
}
/**
* Disable account and keep all content.
*/
public function testUserBlock() {
$this->config('user.settings')->set('cancel_method', 'user_cancel_block')->save();
$user_storage = $this->container->get('entity.manager')->getStorage('user');
// Create a user.
$web_user = $this->drupalCreateUser(['cancel account']);
$this->drupalLogin($web_user);
// Load a real user object.
$user_storage->resetCache([$web_user->id()]);
$account = $user_storage->load($web_user->id());
// Attempt to cancel account.
$this->drupalGet('user/' . $account->id() . '/edit');
$this->drupalPostForm(NULL, NULL, t('Cancel account'));
$this->assertText(t('Are you sure you want to cancel your account?'), 'Confirmation form to cancel account displayed.');
$this->assertText(t('Your account will be blocked and you will no longer be able to log in. All of your content will remain attributed to your username.'), 'Informs that all content will be remain as is.');
$this->assertNoText(t('Select the method to cancel the account above.'), 'Does not allow user to select account cancellation method.');
// Confirm account cancellation.
$timestamp = time();
$this->drupalPostForm(NULL, NULL, t('Cancel account'));
$this->assertText(t('A confirmation request to cancel your account has been sent to your email address.'), 'Account cancellation request mailed message displayed.');
// Confirm account cancellation request.
$this->drupalGet("user/" . $account->id() . "/cancel/confirm/$timestamp/" . user_pass_rehash($account, $timestamp));
$user_storage->resetCache([$account->id()]);
$account = $user_storage->load($account->id());
$this->assertTrue($account->isBlocked(), 'User has been blocked.');
// Confirm that the confirmation message made it through to the end user.
$this->assertRaw(t('%name has been disabled.', ['%name' => $account->getUsername()]), "Confirmation message displayed to user.");
}
/**
* Disable account and unpublish all content.
*/
public function testUserBlockUnpublish() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$this->config('user.settings')->set('cancel_method', 'user_cancel_block_unpublish')->save();
// Create comment field on page.
$this->addDefaultCommentField('node', 'page');
$user_storage = $this->container->get('entity.manager')->getStorage('user');
// Create a user.
$account = $this->drupalCreateUser(['cancel account']);
$this->drupalLogin($account);
// Load a real user object.
$user_storage->resetCache([$account->id()]);
$account = $user_storage->load($account->id());
// Create a node with two revisions.
$node = $this->drupalCreateNode(['uid' => $account->id()]);
$settings = get_object_vars($node);
$settings['revision'] = 1;
$node = $this->drupalCreateNode($settings);
// Add a comment to the page.
$comment_subject = $this->randomMachineName(8);
$comment_body = $this->randomMachineName(8);
$comment = Comment::create([
'subject' => $comment_subject,
'comment_body' => $comment_body,
'entity_id' => $node->id(),
'entity_type' => 'node',
'field_name' => 'comment',
'status' => CommentInterface::PUBLISHED,
'uid' => $account->id(),
]);
$comment->save();
// Attempt to cancel account.
$this->drupalGet('user/' . $account->id() . '/edit');
$this->drupalPostForm(NULL, NULL, t('Cancel account'));
$this->assertText(t('Are you sure you want to cancel your account?'), 'Confirmation form to cancel account displayed.');
$this->assertText(t('Your account will be blocked and you will no longer be able to log in. All of your content will be hidden from everyone but administrators.'), 'Informs that all content will be unpublished.');
// Confirm account cancellation.
$timestamp = time();
$this->drupalPostForm(NULL, NULL, t('Cancel account'));
$this->assertText(t('A confirmation request to cancel your account has been sent to your email address.'), 'Account cancellation request mailed message displayed.');
// Confirm account cancellation request.
$this->drupalGet("user/" . $account->id() . "/cancel/confirm/$timestamp/" . user_pass_rehash($account, $timestamp));
$user_storage->resetCache([$account->id()]);
$account = $user_storage->load($account->id());
$this->assertTrue($account->isBlocked(), 'User has been blocked.');
// Confirm user's content has been unpublished.
$node_storage->resetCache([$node->id()]);
$test_node = $node_storage->load($node->id());
$this->assertFalse($test_node->isPublished(), 'Node of the user has been unpublished.');
$test_node = node_revision_load($node->getRevisionId());
$this->assertFalse($test_node->isPublished(), 'Node revision of the user has been unpublished.');
$storage = \Drupal::entityManager()->getStorage('comment');
$storage->resetCache([$comment->id()]);
$comment = $storage->load($comment->id());
$this->assertFalse($comment->isPublished(), 'Comment of the user has been unpublished.');
// Confirm that the confirmation message made it through to the end user.
$this->assertRaw(t('%name has been disabled.', ['%name' => $account->getUsername()]), "Confirmation message displayed to user.");
}
/**
* Delete account and anonymize all content.
*/
public function testUserAnonymize() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$this->config('user.settings')->set('cancel_method', 'user_cancel_reassign')->save();
// Create comment field on page.
$this->addDefaultCommentField('node', 'page');
$user_storage = $this->container->get('entity.manager')->getStorage('user');
// Create a user.
$account = $this->drupalCreateUser(['cancel account']);
$this->drupalLogin($account);
// Load a real user object.
$user_storage->resetCache([$account->id()]);
$account = $user_storage->load($account->id());
// Create a simple node.
$node = $this->drupalCreateNode(['uid' => $account->id()]);
// Add a comment to the page.
$comment_subject = $this->randomMachineName(8);
$comment_body = $this->randomMachineName(8);
$comment = Comment::create([
'subject' => $comment_subject,
'comment_body' => $comment_body,
'entity_id' => $node->id(),
'entity_type' => 'node',
'field_name' => 'comment',
'status' => CommentInterface::PUBLISHED,
'uid' => $account->id(),
]);
$comment->save();
// Create a node with two revisions, the initial one belonging to the
// cancelling user.
$revision_node = $this->drupalCreateNode(['uid' => $account->id()]);
$revision = $revision_node->getRevisionId();
$settings = get_object_vars($revision_node);
$settings['revision'] = 1;
$settings['uid'] = 1; // Set new/current revision to someone else.
$revision_node = $this->drupalCreateNode($settings);
// Attempt to cancel account.
$this->drupalGet('user/' . $account->id() . '/edit');
$this->drupalPostForm(NULL, NULL, t('Cancel account'));
$this->assertText(t('Are you sure you want to cancel your account?'), 'Confirmation form to cancel account displayed.');
$this->assertRaw(t('Your account will be removed and all account information deleted. All of your content will be assigned to the %anonymous-name user.', ['%anonymous-name' => $this->config('user.settings')->get('anonymous')]), 'Informs that all content will be attributed to anonymous account.');
// Confirm account cancellation.
$timestamp = time();
$this->drupalPostForm(NULL, NULL, t('Cancel account'));
$this->assertText(t('A confirmation request to cancel your account has been sent to your email address.'), 'Account cancellation request mailed message displayed.');
// Confirm account cancellation request.
$this->drupalGet("user/" . $account->id() . "/cancel/confirm/$timestamp/" . user_pass_rehash($account, $timestamp));
$user_storage->resetCache([$account->id()]);
$this->assertFalse($user_storage->load($account->id()), 'User is not found in the database.');
// Confirm that user's content has been attributed to anonymous user.
$anonymous_user = User::getAnonymousUser();
$node_storage->resetCache([$node->id()]);
$test_node = $node_storage->load($node->id());
$this->assertTrue(($test_node->getOwnerId() == 0 && $test_node->isPublished()), 'Node of the user has been attributed to anonymous user.');
$test_node = node_revision_load($revision, TRUE);
$this->assertTrue(($test_node->getRevisionUser()->id() == 0 && $test_node->isPublished()), 'Node revision of the user has been attributed to anonymous user.');
$node_storage->resetCache([$revision_node->id()]);
$test_node = $node_storage->load($revision_node->id());
$this->assertTrue(($test_node->getOwnerId() != 0 && $test_node->isPublished()), "Current revision of the user's node was not attributed to anonymous user.");
$storage = \Drupal::entityManager()->getStorage('comment');
$storage->resetCache([$comment->id()]);
$test_comment = $storage->load($comment->id());
$this->assertTrue(($test_comment->getOwnerId() == 0 && $test_comment->isPublished()), 'Comment of the user has been attributed to anonymous user.');
$this->assertEqual($test_comment->getAuthorName(), $anonymous_user->getDisplayName(), 'Comment of the user has been attributed to anonymous user name.');
// Confirm that the confirmation message made it through to the end user.
$this->assertRaw(t('%name has been deleted.', ['%name' => $account->getUsername()]), "Confirmation message displayed to user.");
}
/**
* Delete account and anonymize all content using a batch process.
*/
public function testUserAnonymizeBatch() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$this->config('user.settings')->set('cancel_method', 'user_cancel_reassign')->save();
$user_storage = $this->container->get('entity.manager')->getStorage('user');
// Create a user.
$account = $this->drupalCreateUser(['cancel account']);
$this->drupalLogin($account);
// Load a real user object.
$user_storage->resetCache([$account->id()]);
$account = $user_storage->load($account->id());
// Create 11 nodes in order to trigger batch processing in
// node_mass_update().
$nodes = [];
for ($i = 0; $i < 11; $i++) {
$node = $this->drupalCreateNode(['uid' => $account->id()]);
$nodes[$node->id()] = $node;
}
// Attempt to cancel account.
$this->drupalGet('user/' . $account->id() . '/edit');
$this->drupalPostForm(NULL, NULL, t('Cancel account'));
$this->assertText(t('Are you sure you want to cancel your account?'), 'Confirmation form to cancel account displayed.');
$this->assertRaw(t('Your account will be removed and all account information deleted. All of your content will be assigned to the %anonymous-name user.', ['%anonymous-name' => $this->config('user.settings')->get('anonymous')]), 'Informs that all content will be attributed to anonymous account.');
// Confirm account cancellation.
$timestamp = time();
$this->drupalPostForm(NULL, NULL, t('Cancel account'));
$this->assertText(t('A confirmation request to cancel your account has been sent to your email address.'), 'Account cancellation request mailed message displayed.');
// Confirm account cancellation request.
$this->drupalGet("user/" . $account->id() . "/cancel/confirm/$timestamp/" . user_pass_rehash($account, $timestamp));
$user_storage->resetCache([$account->id()]);
$this->assertFalse($user_storage->load($account->id()), 'User is not found in the database.');
// Confirm that user's content has been attributed to anonymous user.
$node_storage->resetCache(array_keys($nodes));
$test_nodes = $node_storage->loadMultiple(array_keys($nodes));
foreach ($test_nodes as $test_node) {
$this->assertTrue(($test_node->getOwnerId() == 0 && $test_node->isPublished()), 'Node ' . $test_node->id() . ' of the user has been attributed to anonymous user.');
}
}
/**
* Delete account and remove all content.
*/
public function testUserDelete() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$this->config('user.settings')->set('cancel_method', 'user_cancel_delete')->save();
\Drupal::service('module_installer')->install(['comment']);
$this->resetAll();
$this->addDefaultCommentField('node', 'page');
$user_storage = $this->container->get('entity.manager')->getStorage('user');
// Create a user.
$account = $this->drupalCreateUser(['cancel account', 'post comments', 'skip comment approval']);
$this->drupalLogin($account);
// Load a real user object.
$user_storage->resetCache([$account->id()]);
$account = $user_storage->load($account->id());
// Create a simple node.
$node = $this->drupalCreateNode(['uid' => $account->id()]);
// Create comment.
$edit = [];
$edit['subject[0][value]'] = $this->randomMachineName(8);
$edit['comment_body[0][value]'] = $this->randomMachineName(16);
$this->drupalPostForm('comment/reply/node/' . $node->id() . '/comment', $edit, t('Preview'));
$this->drupalPostForm(NULL, [], t('Save'));
$this->assertText(t('Your comment has been posted.'));
$comments = entity_load_multiple_by_properties('comment', ['subject' => $edit['subject[0][value]']]);
$comment = reset($comments);
$this->assertTrue($comment->id(), 'Comment found.');
// Create a node with two revisions, the initial one belonging to the
// cancelling user.
$revision_node = $this->drupalCreateNode(['uid' => $account->id()]);
$revision = $revision_node->getRevisionId();
$settings = get_object_vars($revision_node);
$settings['revision'] = 1;
$settings['uid'] = 1; // Set new/current revision to someone else.
$revision_node = $this->drupalCreateNode($settings);
// Attempt to cancel account.
$this->drupalGet('user/' . $account->id() . '/edit');
$this->drupalPostForm(NULL, NULL, t('Cancel account'));
$this->assertText(t('Are you sure you want to cancel your account?'), 'Confirmation form to cancel account displayed.');
$this->assertText(t('Your account will be removed and all account information deleted. All of your content will also be deleted.'), 'Informs that all content will be deleted.');
// Confirm account cancellation.
$timestamp = time();
$this->drupalPostForm(NULL, NULL, t('Cancel account'));
$this->assertText(t('A confirmation request to cancel your account has been sent to your email address.'), 'Account cancellation request mailed message displayed.');
// Confirm account cancellation request.
$this->drupalGet("user/" . $account->id() . "/cancel/confirm/$timestamp/" . user_pass_rehash($account, $timestamp));
$user_storage->resetCache([$account->id()]);
$this->assertFalse($user_storage->load($account->id()), 'User is not found in the database.');
// Confirm that user's content has been deleted.
$node_storage->resetCache([$node->id()]);
$this->assertFalse($node_storage->load($node->id()), 'Node of the user has been deleted.');
$this->assertFalse(node_revision_load($revision), 'Node revision of the user has been deleted.');
$node_storage->resetCache([$revision_node->id()]);
$this->assertTrue($node_storage->load($revision_node->id()), "Current revision of the user's node was not deleted.");
\Drupal::entityManager()->getStorage('comment')->resetCache([$comment->id()]);
$this->assertFalse(Comment::load($comment->id()), 'Comment of the user has been deleted.');
// Confirm that the confirmation message made it through to the end user.
$this->assertRaw(t('%name has been deleted.', ['%name' => $account->getUsername()]), "Confirmation message displayed to user.");
}
/**
* Create an administrative user and delete another user.
*/
public function testUserCancelByAdmin() {
$this->config('user.settings')->set('cancel_method', 'user_cancel_reassign')->save();
// Create a regular user.
$account = $this->drupalCreateUser([]);
// Create administrative user.
$admin_user = $this->drupalCreateUser(['administer users']);
$this->drupalLogin($admin_user);
// Delete regular user.
$this->drupalGet('user/' . $account->id() . '/edit');
$this->drupalPostForm(NULL, NULL, t('Cancel account'));
$this->assertRaw(t('Are you sure you want to cancel the account %name?', ['%name' => $account->getUsername()]), 'Confirmation form to cancel account displayed.');
$this->assertText(t('Select the method to cancel the account above.'), 'Allows to select account cancellation method.');
// Confirm deletion.
$this->drupalPostForm(NULL, NULL, t('Cancel account'));
$this->assertRaw(t('%name has been deleted.', ['%name' => $account->getUsername()]), 'User deleted.');
$this->assertFalse(User::load($account->id()), 'User is not found in the database.');
}
/**
* Tests deletion of a user account without an email address.
*/
public function testUserWithoutEmailCancelByAdmin() {
$this->config('user.settings')->set('cancel_method', 'user_cancel_reassign')->save();
// Create a regular user.
$account = $this->drupalCreateUser([]);
// This user has no email address.
$account->mail = '';
$account->save();
// Create administrative user.
$admin_user = $this->drupalCreateUser(['administer users']);
$this->drupalLogin($admin_user);
// Delete regular user without email address.
$this->drupalGet('user/' . $account->id() . '/edit');
$this->drupalPostForm(NULL, NULL, t('Cancel account'));
$this->assertRaw(t('Are you sure you want to cancel the account %name?', ['%name' => $account->getUsername()]), 'Confirmation form to cancel account displayed.');
$this->assertText(t('Select the method to cancel the account above.'), 'Allows to select account cancellation method.');
// Confirm deletion.
$this->drupalPostForm(NULL, NULL, t('Cancel account'));
$this->assertRaw(t('%name has been deleted.', ['%name' => $account->getUsername()]), 'User deleted.');
$this->assertFalse(User::load($account->id()), 'User is not found in the database.');
}
/**
* Create an administrative user and mass-delete other users.
*/
public function testMassUserCancelByAdmin() {
\Drupal::service('module_installer')->install(['views']);
\Drupal::service('router.builder')->rebuild();
$this->config('user.settings')->set('cancel_method', 'user_cancel_reassign')->save();
$user_storage = $this->container->get('entity.manager')->getStorage('user');
// Enable account cancellation notification.
$this->config('user.settings')->set('notify.status_canceled', TRUE)->save();
// Create administrative user.
$admin_user = $this->drupalCreateUser(['administer users']);
$this->drupalLogin($admin_user);
// Create some users.
$users = [];
for ($i = 0; $i < 3; $i++) {
$account = $this->drupalCreateUser([]);
$users[$account->id()] = $account;
}
// Cancel user accounts, including own one.
$edit = [];
$edit['action'] = 'user_cancel_user_action';
for ($i = 0; $i <= 4; $i++) {
$edit['user_bulk_form[' . $i . ']'] = TRUE;
}
$this->drupalPostForm('admin/people', $edit, t('Apply to selected items'));
$this->assertText(t('Are you sure you want to cancel these user accounts?'), 'Confirmation form to cancel accounts displayed.');
$this->assertText(t('When cancelling these accounts'), 'Allows to select account cancellation method.');
$this->assertText(t('Require email confirmation to cancel account'), 'Allows to send confirmation mail.');
$this->assertText(t('Notify user when account is canceled'), 'Allows to send notification mail.');
// Confirm deletion.
$this->drupalPostForm(NULL, NULL, t('Cancel accounts'));
$status = TRUE;
foreach ($users as $account) {
$status = $status && (strpos($this->getTextContent(), $account->getUsername() . ' has been deleted.') !== FALSE);
$user_storage->resetCache([$account->id()]);
$status = $status && !$user_storage->load($account->id());
}
$this->assertTrue($status, 'Users deleted and not found in the database.');
// Ensure that admin account was not cancelled.
$this->assertText(t('A confirmation request to cancel your account has been sent to your email address.'), 'Account cancellation request mailed message displayed.');
$admin_user = $user_storage->load($admin_user->id());
$this->assertTrue($admin_user->isActive(), 'Administrative user is found in the database and enabled.');
// Verify that uid 1's account was not cancelled.
$user_storage->resetCache([1]);
$user1 = $user_storage->load(1);
$this->assertTrue($user1->isActive(), 'User #1 still exists and is not blocked.');
}
/**
* Tests user cancel with node access.
*/
public function testUserDeleteWithContentAndNodeAccess() {
\Drupal::service('module_installer')->install(['node_access_test']);
// Rebuild node access.
node_access_rebuild();
$account = $this->drupalCreateUser(['access content']);
$node = $this->drupalCreateNode(['type' => 'page', 'uid' => $account->id()]);
$account->delete();
$load2 = \Drupal::entityTypeManager()->getStorage('node')->load($node->id());
$this->assertTrue(empty($load2));
}
}
@@ -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']]));
}
}
@@ -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()]));
}
}
@@ -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);
}
}
@@ -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.');
}
}
@@ -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();
}
}
@@ -0,0 +1,432 @@
<?php
namespace Drupal\Tests\user\Functional;
use Drupal\Core\Flood\DatabaseBackend;
use Drupal\Core\Url;
use Drupal\Tests\BrowserTestBase;
use Drupal\user\Controller\UserAuthenticationController;
use GuzzleHttp\Cookie\CookieJar;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Drupal\hal\Encoder\JsonEncoder as HALJsonEncoder;
use Symfony\Component\Serializer\Serializer;
/**
* Tests login via direct HTTP.
*
* @group user
*/
class UserLoginHttpTest extends BrowserTestBase {
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['hal'];
/**
* The cookie jar.
*
* @var \GuzzleHttp\Cookie\CookieJar
*/
protected $cookies;
/**
* The serializer.
*
* @var \Symfony\Component\Serializer\Serializer
*/
protected $serializer;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->cookies = new CookieJar();
$encoders = [new JsonEncoder(), new XmlEncoder(), new HALJsonEncoder()];
$this->serializer = new Serializer([], $encoders);
}
/**
* Executes a login HTTP request.
*
* @param string $name
* The username.
* @param string $pass
* The user password.
* @param string $format
* The format to use to make the request.
*
* @return \Psr\Http\Message\ResponseInterface The HTTP response.
* The HTTP response.
*/
protected function loginRequest($name, $pass, $format = 'json') {
$user_login_url = Url::fromRoute('user.login.http')
->setRouteParameter('_format', $format)
->setAbsolute();
$request_body = [];
if (isset($name)) {
$request_body['name'] = $name;
}
if (isset($pass)) {
$request_body['pass'] = $pass;
}
$result = \Drupal::httpClient()->post($user_login_url->toString(), [
'body' => $this->serializer->encode($request_body, $format),
'headers' => [
'Accept' => "application/$format",
],
'http_errors' => FALSE,
'cookies' => $this->cookies,
]);
return $result;
}
/**
* Tests user session life cycle.
*/
public function testLogin() {
// Without the serialization module only JSON is supported.
$this->doTestLogin('json');
// Enable serialization so we have access to additional formats.
$this->container->get('module_installer')->install(['serialization']);
$this->doTestLogin('json');
$this->doTestLogin('xml');
$this->doTestLogin('hal_json');
}
/**
* Do login testing for a given serialization format.
*
* @param string $format
* Serialization format.
*/
protected function doTestLogin($format) {
$client = \Drupal::httpClient();
// Create new user for each iteration to reset flood.
// Grant the user administer users permissions to they can see the
// 'roles' field.
$account = $this->drupalCreateUser(['administer users']);
$name = $account->getUsername();
$pass = $account->passRaw;
$login_status_url = $this->getLoginStatusUrlString($format);
$response = $client->get($login_status_url);
$this->assertHttpResponse($response, 200, UserAuthenticationController::LOGGED_OUT);
// Flooded.
$this->config('user.flood')
->set('user_limit', 3)
->save();
$response = $this->loginRequest($name, 'wrong-pass', $format);
$this->assertHttpResponseWithMessage($response, 400, 'Sorry, unrecognized username or password.', $format);
$response = $this->loginRequest($name, 'wrong-pass', $format);
$this->assertHttpResponseWithMessage($response, 400, 'Sorry, unrecognized username or password.', $format);
$response = $this->loginRequest($name, 'wrong-pass', $format);
$this->assertHttpResponseWithMessage($response, 400, 'Sorry, unrecognized username or password.', $format);
$response = $this->loginRequest($name, 'wrong-pass', $format);
$this->assertHttpResponseWithMessage($response, 403, 'Too many failed login attempts from your IP address. This IP address is temporarily blocked.', $format);
// After testing the flood control we can increase the limit.
$this->config('user.flood')
->set('user_limit', 100)
->save();
$response = $this->loginRequest(NULL, NULL, $format);
$this->assertHttpResponseWithMessage($response, 400, 'Missing credentials.', $format);
$response = $this->loginRequest(NULL, $pass, $format);
$this->assertHttpResponseWithMessage($response, 400, 'Missing credentials.name.', $format);
$response = $this->loginRequest($name, NULL, $format);
$this->assertHttpResponseWithMessage($response, 400, 'Missing credentials.pass.', $format);
// Blocked.
$account
->block()
->save();
$response = $this->loginRequest($name, $pass, $format);
$this->assertHttpResponseWithMessage($response, 400, 'The user has not been activated or is blocked.', $format);
$account
->activate()
->save();
$response = $this->loginRequest($name, 'garbage', $format);
$this->assertHttpResponseWithMessage($response, 400, 'Sorry, unrecognized username or password.', $format);
$response = $this->loginRequest('garbage', $pass, $format);
$this->assertHttpResponseWithMessage($response, 400, 'Sorry, unrecognized username or password.', $format);
$response = $this->loginRequest($name, $pass, $format);
$this->assertEquals(200, $response->getStatusCode());
$result_data = $this->serializer->decode($response->getBody(), $format);
$this->assertEquals($name, $result_data['current_user']['name']);
$this->assertEquals($account->id(), $result_data['current_user']['uid']);
$this->assertEquals($account->getRoles(), $result_data['current_user']['roles']);
$logout_token = $result_data['logout_token'];
$response = $client->get($login_status_url, ['cookies' => $this->cookies]);
$this->assertHttpResponse($response, 200, UserAuthenticationController::LOGGED_IN);
$response = $this->logoutRequest($format, $logout_token);
$this->assertEquals(204, $response->getStatusCode());
$response = $client->get($login_status_url, ['cookies' => $this->cookies]);
$this->assertHttpResponse($response, 200, UserAuthenticationController::LOGGED_OUT);
$this->resetFlood();
}
/**
* Gets a value for a given key from the response.
*
* @param \Psr\Http\Message\ResponseInterface $response
* The response object.
* @param string $key
* The key for the value.
* @param string $format
* The encoded format.
*
* @return mixed
* The value for the key.
*/
protected function getResultValue(ResponseInterface $response, $key, $format) {
$decoded = $this->serializer->decode((string) $response->getBody(), $format);
if (is_array($decoded)) {
return $decoded[$key];
}
else {
return $decoded->{$key};
}
}
/**
* Resets all flood entries.
*/
protected function resetFlood() {
$this->container->get('database')->delete(DatabaseBackend::TABLE_NAME)->execute();
}
/**
* Tests the global login flood control.
*
* @see \Drupal\basic_auth\Tests\Authentication\BasicAuthTest::testGlobalLoginFloodControl
* @see \Drupal\user\Tests\UserLoginTest::testGlobalLoginFloodControl
*/
public function testGlobalLoginFloodControl() {
$this->config('user.flood')
->set('ip_limit', 2)
// Set a high per-user limit out so that it is not relevant in the test.
->set('user_limit', 4000)
->save();
$user = $this->drupalCreateUser([]);
$incorrect_user = clone $user;
$incorrect_user->passRaw .= 'incorrect';
// Try 2 failed logins.
for ($i = 0; $i < 2; $i++) {
$response = $this->loginRequest($incorrect_user->getUsername(), $incorrect_user->passRaw);
$this->assertEquals('400', $response->getStatusCode());
}
// IP limit has reached to its limit. Even valid user credentials will fail.
$response = $this->loginRequest($user->getUsername(), $user->passRaw);
$this->assertHttpResponseWithMessage($response, '403', 'Access is blocked because of IP based flood prevention.');
}
/**
* Checks a response for status code and body.
*
* @param \Psr\Http\Message\ResponseInterface $response
* The response object.
* @param int $expected_code
* The expected status code.
* @param mixed $expected_body
* The expected response body.
*/
protected function assertHttpResponse(ResponseInterface $response, $expected_code, $expected_body) {
$this->assertEquals($expected_code, $response->getStatusCode());
$this->assertEquals($expected_body, (string) $response->getBody());
}
/**
* Checks a response for status code and message.
*
* @param \Psr\Http\Message\ResponseInterface $response
* The response object.
* @param int $expected_code
* The expected status code.
* @param string $expected_message
* The expected message encoded in response.
* @param string $format
* The format that the response is encoded in.
*/
protected function assertHttpResponseWithMessage(ResponseInterface $response, $expected_code, $expected_message, $format = 'json') {
$this->assertEquals($expected_code, $response->getStatusCode());
$this->assertEquals($expected_message, $this->getResultValue($response, 'message', $format));
}
/**
* Test the per-user login flood control.
*
* @see \Drupal\user\Tests\UserLoginTest::testPerUserLoginFloodControl
* @see \Drupal\basic_auth\Tests\Authentication\BasicAuthTest::testPerUserLoginFloodControl
*/
public function testPerUserLoginFloodControl() {
foreach ([TRUE, FALSE] as $uid_only_setting) {
$this->config('user.flood')
// Set a high global limit out so that it is not relevant in the test.
->set('ip_limit', 4000)
->set('user_limit', 3)
->set('uid_only', $uid_only_setting)
->save();
$user1 = $this->drupalCreateUser([]);
$incorrect_user1 = clone $user1;
$incorrect_user1->passRaw .= 'incorrect';
$user2 = $this->drupalCreateUser([]);
// Try 2 failed logins.
for ($i = 0; $i < 2; $i++) {
$response = $this->loginRequest($incorrect_user1->getUsername(), $incorrect_user1->passRaw);
$this->assertHttpResponseWithMessage($response, 400, 'Sorry, unrecognized username or password.');
}
// A successful login will reset the per-user flood control count.
$response = $this->loginRequest($user1->getUsername(), $user1->passRaw);
$result_data = $this->serializer->decode($response->getBody(), 'json');
$this->logoutRequest('json', $result_data['logout_token']);
// Try 3 failed logins for user 1, they will not trigger flood control.
for ($i = 0; $i < 3; $i++) {
$response = $this->loginRequest($incorrect_user1->getUsername(), $incorrect_user1->passRaw);
$this->assertHttpResponseWithMessage($response, 400, 'Sorry, unrecognized username or password.');
}
// Try one successful attempt for user 2, it should not trigger any
// flood control.
$this->drupalLogin($user2);
$this->drupalLogout();
// Try one more attempt for user 1, it should be rejected, even if the
// correct password has been used.
$response = $this->loginRequest($user1->getUsername(), $user1->passRaw);
// Depending on the uid_only setting the error message will be different.
if ($uid_only_setting) {
$excepted_message = 'There have been more than 3 failed login attempts for this account. It is temporarily blocked. Try again later or request a new password.';
}
else {
$excepted_message = 'Too many failed login attempts from your IP address. This IP address is temporarily blocked.';
}
$this->assertHttpResponseWithMessage($response, 403, $excepted_message);
}
}
/**
* Executes a logout HTTP request.
*
* @param string $format
* The format to use to make the request.
* @param string $logout_token
* The csrf token for user logout.
*
* @return \Psr\Http\Message\ResponseInterface The HTTP response.
* The HTTP response.
*/
protected function logoutRequest($format = 'json', $logout_token = '') {
/** @var \GuzzleHttp\Client $client */
$client = $this->container->get('http_client');
$user_logout_url = Url::fromRoute('user.logout.http')
->setRouteParameter('_format', $format)
->setAbsolute();
if ($logout_token) {
$user_logout_url->setOption('query', ['token' => $logout_token]);
}
$post_options = [
'headers' => [
'Accept' => "application/$format",
],
'http_errors' => FALSE,
'cookies' => $this->cookies,
];
$response = $client->post($user_logout_url->toString(), $post_options);
return $response;
}
/**
* Test csrf protection of User Logout route.
*/
public function testLogoutCsrfProtection() {
$client = \Drupal::httpClient();
$login_status_url = $this->getLoginStatusUrlString();
$account = $this->drupalCreateUser();
$name = $account->getUsername();
$pass = $account->passRaw;
$response = $this->loginRequest($name, $pass);
$this->assertEquals(200, $response->getStatusCode());
$result_data = $this->serializer->decode($response->getBody(), 'json');
$logout_token = $result_data['logout_token'];
// Test third party site posting to current site with logout request.
// This should not logout the current user because it lacks the CSRF
// token.
$response = $this->logoutRequest('json');
$this->assertEquals(403, $response->getStatusCode());
// Ensure still logged in.
$response = $client->get($login_status_url, ['cookies' => $this->cookies]);
$this->assertHttpResponse($response, 200, UserAuthenticationController::LOGGED_IN);
// Try with an incorrect token.
$response = $this->logoutRequest('json', 'not-the-correct-token');
$this->assertEquals(403, $response->getStatusCode());
// Ensure still logged in.
$response = $client->get($login_status_url, ['cookies' => $this->cookies]);
$this->assertHttpResponse($response, 200, UserAuthenticationController::LOGGED_IN);
// Try a logout request with correct token.
$response = $this->logoutRequest('json', $logout_token);
$this->assertEquals(204, $response->getStatusCode());
// Ensure actually logged out.
$response = $client->get($login_status_url, ['cookies' => $this->cookies]);
$this->assertHttpResponse($response, 200, UserAuthenticationController::LOGGED_OUT);
}
/**
* Gets the URL string for checking login.
*
* @param string $format
* The format to use to make the request.
*
* @return string
* The URL string.
*/
protected function getLoginStatusUrlString($format = 'json') {
$user_login_status_url = Url::fromRoute('user.login_status.http');
$user_login_status_url->setRouteParameter('_format', $format);
$user_login_status_url->setAbsolute();
return $user_login_status_url->toString();
}
}
@@ -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().');
}
}
@@ -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.');
}
}
}
@@ -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);
}
}
@@ -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();
}
}
@@ -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']));
}
}
@@ -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()]));
}
}
@@ -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.
@@ -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');
@@ -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');
}
}
@@ -3,6 +3,7 @@
namespace Drupal\Tests\user\Kernel\Migrate\d6;
use Drupal\file\Entity\File;
use Drupal\Tests\file\Kernel\Migrate\d6\FileMigrationTestTrait;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**
@@ -12,6 +13,8 @@ use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
*/
class MigrateUserPictureFileTest extends MigrateDrupal6TestBase {
use FileMigrationTestTrait;
/**
* {@inheritdoc}
*/
@@ -19,20 +22,14 @@ class MigrateUserPictureFileTest extends MigrateDrupal6TestBase {
parent::setUp();
$this->installEntitySchema('file');
/** @var \Drupal\migrate\Plugin\MigrationInterface $migration */
$migration = $this->getMigration('d6_user_picture_file');
$source = $migration->getSourceConfiguration();
$source['site_path'] = 'core/modules/simpletest';
$migration->set('source', $source);
$this->executeMigration($migration);
$this->executeMigration('d6_user_picture_file');
}
/**
* 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);
}
@@ -12,6 +12,11 @@ use Drupal\user\Entity\User;
*/
class MigrateUserProfileValuesTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['language'];
/**
* {@inheritdoc}
*/
@@ -19,6 +24,7 @@ class MigrateUserProfileValuesTest extends MigrateDrupal6TestBase {
parent::setUp();
$this->executeMigrations([
'language',
'user_profile_field',
'user_profile_field_instance',
'user_profile_entity_display',
@@ -3,7 +3,9 @@
namespace Drupal\Tests\user\Kernel\Migrate\d6;
use Drupal\user\Entity\Role;
use Drupal\user\RoleInterface;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
use Drupal\migrate\Plugin\MigrateIdMapInterface;
/**
* Upgrade user roles to user.role.*.yml.
@@ -21,29 +23,70 @@ class MigrateUserRoleTest extends MigrateDrupal6TestBase {
}
/**
* Tests user role migration.
* Helper function to perform assertions on a user role.
*
* @param string $id
* The role ID.
* @param string[] $permissions
* An array of user permissions.
* @param int $lookupId
* The original numeric ID of the role in the source database.
* @param \Drupal\migrate\Plugin\MigrateIdMapInterface $id_map
* The map table plugin.
*/
public function testUserRole() {
/** @var \Drupal\migrate\Plugin\MigrationInterface $migration */
$id_map = $this->getMigration('d6_user_role')->getIdMap();
$rid = 'anonymous';
$anonymous = Role::load($rid);
$this->assertIdentical($rid, $anonymous->id());
$this->assertIdentical(array('migrate test anonymous permission', 'use text format filtered_html'), $anonymous->getPermissions());
$this->assertIdentical(array($rid), $id_map->lookupDestinationId(array(1)));
$rid = 'authenticated';
$authenticated = Role::load($rid);
$this->assertIdentical($rid, $authenticated->id());
$this->assertIdentical(array('migrate test authenticated permission', 'use text format filtered_html'), $authenticated->getPermissions());
$this->assertIdentical(array($rid), $id_map->lookupDestinationId(array(2)));
$rid = 'migrate_test_role_1';
$migrate_test_role_1 = Role::load($rid);
$this->assertIdentical($rid, $migrate_test_role_1->id());
$this->assertIdentical(array('migrate test role 1 test permission', 'use text format full_html', 'use text format php_code'), $migrate_test_role_1->getPermissions());
$this->assertIdentical(array($rid), $id_map->lookupDestinationId(array(3)));
$rid = 'migrate_test_role_2';
$migrate_test_role_2 = Role::load($rid);
$this->assertIdentical(array(
protected function assertRole($id, array $permissions, $lookupId, MigrateIdMapInterface $id_map) {
/** @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]));
}
/**
* Helper function to test the migration of the user roles. The user roles
* will be re-imported and the tests here will be repeated.
*
* @param \Drupal\migrate\Plugin\MigrateIdMapInterface $id_map
* The map table plugin.
*/
protected function assertRoles(MigrateIdMapInterface $id_map) {
// The permissions for each role are found in the two tables in the Drupal 6
// source database. One is the permission table and the other is the
// filter_format table.
$permissions = [
// From permission table.
'access content',
'migrate test anonymous permission',
// From filter_format tables.
'use text format filtered_html'
];
$this->assertRole('anonymous', $permissions, 1, $id_map);
$permissions = [
// From permission table.
'access comments',
'access content',
'migrate test authenticated permission',
'post comments',
'skip comment approval',
// From filter_format.
'use text format filtered_html',
];
$this->assertRole('authenticated', $permissions, 2, $id_map);
$permissions = [
// From permission table.
'migrate test role 1 test permission',
// From filter format.
'use text format full_html',
'use text format php_code'
];
$this->assertRole('migrate_test_role_1', $permissions, 3, $id_map);
$permissions = [
// From permission table.
'migrate test role 2 test permission',
'use PHP for settings',
'administer contact forms',
@@ -59,14 +102,66 @@ class MigrateUserRoleTest extends MigrateDrupal6TestBase {
'edit own forum content',
'administer nodes',
'access content overview',
// From filter format.
'use text format php_code',
), $migrate_test_role_2->getPermissions());
$this->assertIdentical($rid, $migrate_test_role_2->id());
$this->assertIdentical(array($rid), $id_map->lookupDestinationId(array(4)));
$rid = 'migrate_test_role_3_that_is_long';
$migrate_test_role_3 = Role::load($rid);
$this->assertIdentical($rid, $migrate_test_role_3->id());
$this->assertIdentical(array($rid), $id_map->lookupDestinationId(array(5)));
];
$this->assertRole('migrate_test_role_2', $permissions, 4, $id_map);
// The only permission for this role is a filter format.
$permissions = ['use text format php_code'];
$this->assertRole('migrate_test_role_3_that_is_longer_than_thirty_two_characters', $permissions, 5, $id_map);
}
/**
* Tests user role migration.
*/
public function testUserRole() {
$id_map = $this->getMigration('d6_user_role')->getIdMap();
$this->assertRoles($id_map);
// Test there are no duplicated roles.
$roles = [
'anonymous1',
'authenticated1',
'administrator1',
'migrate_test_role_11',
'migrate_test_role_21',
'migrate_test_role_3_that_is_longer_than_thirty_two_characters1'
];
$this->assertEmpty(Role::loadMultiple($roles));
// Remove the map row for the migrate_test_role_1 role and rerun the
// migration. This will re-import the migrate_test_role_1 role migration
// again.
$this->sourceDatabase->insert('role')
->fields([
'rid' => 6,
'name' => 'migrate test role 4',
])
->execute();
$this->sourceDatabase->insert('permission')
->fields([
'pid' => 7,
'rid' => 6,
'perm' => 'access content',
'tid' => 0,
])
->execute();
$id_map->delete(['rid' => 3]);
$this->executeMigration('d6_user_role');
// Test there are no duplicated roles.
$roles[] = 'migrate_test_role_41';
$this->assertEmpty(Role::loadMultiple($roles));
// Test that the existing roles have not changed.
$this->assertRoles($id_map);
// Test the migration of the new role, migrate_test_role_4.
$permissions = ['access content'];
$this->assertRole('migrate_test_role_4', $permissions, 6, $id_map);
}
}
@@ -3,6 +3,7 @@
namespace Drupal\Tests\user\Kernel\Migrate\d6;
use Drupal\migrate\MigrateExecutable;
use Drupal\Tests\file\Kernel\Migrate\d6\FileMigrationTestTrait;
use Drupal\user\Entity\User;
use Drupal\file\Entity\File;
use Drupal\Core\Database\Database;
@@ -16,6 +17,13 @@ use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
*/
class MigrateUserTest extends MigrateDrupal6TestBase {
use FileMigrationTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['language'];
/**
* {@inheritdoc}
*/
@@ -29,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',
@@ -38,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',
@@ -52,11 +60,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-2.jpg'));
$file->save();
$this->executeMigration('language');
$this->migrateUsers();
}
@@ -75,41 +84,60 @@ 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);
}
/** @var \Drupal\user\UserInterface $user */
$user = User::load($source->uid);
$this->assertIdentical($source->uid, $user->id());
$this->assertIdentical($source->name, $user->label());
$this->assertIdentical($source->mail, $user->getEmail());
$this->assertIdentical($source->created, $user->getCreatedTime());
$this->assertIdentical($source->access, $user->getLastAccessedTime());
$this->assertIdentical($source->login, $user->getLastLoginTime());
$this->assertSame($source->uid, $user->id());
$this->assertSame($source->name, $user->label());
$this->assertSame($source->mail, $user->getEmail());
$this->assertSame($source->created, $user->getCreatedTime());
$this->assertSame($source->access, $user->getLastAccessedTime());
$this->assertSame($source->login, $user->getLastLoginTime());
$is_blocked = $source->status == 0;
$this->assertIdentical($is_blocked, $user->isBlocked());
$this->assertSame($is_blocked, $user->isBlocked());
$expected_timezone_name = $source->timezone_name ?: $this->config('system.date')->get('timezone.default');
$this->assertSame($expected_timezone_name, $user->getTimeZone());
$this->assertSame($source->init, $user->getInitialEmail());
$this->assertSame($roles, $user->getRoles());
// Ensure the user's langcode, preferred_langcode and
// preferred_admin_langcode are valid.
// $user->getPreferredLangcode() might fallback to default language if the
// user preferred language is not configured on the site. We just want to
// test if the value was imported correctly.
$this->assertIdentical($source->language, $user->preferred_langcode->value);
$expected_timezone_name = $source->timezone_name ?: $this->config('system.date')->get('timezone.default');
$this->assertIdentical($expected_timezone_name, $user->getTimeZone());
$this->assertIdentical($source->init, $user->getInitialEmail());
$this->assertIdentical($roles, $user->getRoles());
$language_manager = $this->container->get('language_manager');
$default_langcode = $language_manager->getDefaultLanguage()->getId();
if (empty($source->language)) {
$this->assertSame('en', $user->langcode->value);
$this->assertSame($default_langcode, $user->preferred_langcode->value);
$this->assertSame($default_langcode, $user->preferred_admin_langcode->value);
}
elseif ($language_manager->getLanguage($source->language) === NULL) {
$this->assertSame($default_langcode, $user->langcode->value);
$this->assertSame($default_langcode, $user->preferred_langcode->value);
$this->assertSame($default_langcode, $user->preferred_admin_langcode->value);
}
else {
$this->assertSame($source->language, $user->langcode->value);
$this->assertSame($source->language, $user->preferred_langcode->value);
$this->assertSame($source->language, $user->preferred_admin_langcode->value);
}
// We have one empty picture in the data so don't try load that.
if (!empty($source->picture)) {
// Test the user picture.
$file = File::load($user->user_picture->target_id);
$this->assertIdentical(basename($source->picture), $file->getFilename());
$this->assertSame(basename($source->picture), $file->getFilename());
}
else {
// Ensure the user does not have a picture.
@@ -29,7 +29,7 @@ class MigrateUserRoleTest extends MigrateDrupal7TestBase {
* The role ID.
* @param string $label
* The role's expected label.
* @param int|NULL $original_rid
* @param int|null $original_rid
* The original (integer) ID of the role, to check permissions.
*/
protected function assertEntity($id, $label, $original_rid) {
@@ -45,6 +45,7 @@ class MigrateUserRoleTest extends MigrateDrupal7TestBase {
->condition('rid', $original_rid)
->execute()
->fetchCol();
sort($permissions);
$this->assertIdentical($permissions, $entity->getPermissions());
}
}
@@ -56,6 +57,50 @@ class MigrateUserRoleTest extends MigrateDrupal7TestBase {
$this->assertEntity('anonymous', 'anonymous user', 1);
$this->assertEntity('authenticated', 'authenticated user', 2);
$this->assertEntity('administrator', 'administrator', 3);
// Test there are no duplicated roles.
$roles = [
'anonymous1',
'authenticated1',
'administrator1',
];
$this->assertEmpty(Role::loadMultiple($roles));
// Remove the map row for the administrator role and rerun the migration.
// This will re-import the administrator role again.
$id_map = $this->getMigration('d7_user_role')->getIdMap();
$id_map->delete(['rid' => 3]);
$this->sourceDatabase->insert('role')
->fields([
'rid' => 4,
'name' => 'test role',
'weight' => 10,
])
->execute();
$this->sourceDatabase->insert('role_permission')
->fields([
'rid' => 4,
'permission' => 'access content',
'module' => 'node',
])
->execute();
$this->executeMigration('d7_user_role');
// Test there are no duplicated roles.
$roles = [
'anonymous1',
'authenticated1',
'administrator1',
];
$this->assertEmpty(Role::loadMultiple($roles));
// Test that the existing roles have not changed.
$this->assertEntity('administrator', 'administrator', 3);
$this->assertEntity('anonymous', 'anonymous user', 1);
$this->assertEntity('authenticated', 'authenticated user', 2);
// Test the migration of the new role, test role.
$this->assertEntity('test_role', 'test role', 4);
}
}
@@ -2,6 +2,10 @@
namespace Drupal\Tests\user\Kernel\Migrate\d7;
use Drupal\comment\Entity\CommentType;
use Drupal\Core\Database\Database;
use Drupal\node\Entity\NodeType;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
use Drupal\user\Entity\User;
use Drupal\user\RoleInterface;
@@ -17,7 +21,19 @@ class MigrateUserTest extends MigrateDrupal7TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['file', 'image'];
public static $modules = [
'comment',
'datetime',
'file',
'image',
'language',
'link',
'node',
'system',
'taxonomy',
'telephone',
'text',
];
/**
* {@inheritdoc}
@@ -27,14 +43,43 @@ class MigrateUserTest extends MigrateDrupal7TestBase {
// Prepare to migrate user pictures as well.
$this->installEntitySchema('file');
$this->createType('page');
$this->createType('article');
$this->createType('blog');
$this->createType('book');
$this->createType('forum');
$this->createType('test_content_type');
Vocabulary::create(['vid' => 'test_vocabulary'])->save();
$this->executeMigrations([
'language',
'user_picture_field',
'user_picture_field_instance',
'd7_user_role',
'd7_field',
'd7_field_instance',
'd7_user',
]);
}
/**
* Creates a node type with a corresponding comment type.
*
* @param string $id
* The node type ID.
*/
protected function createType($id) {
NodeType::create([
'type' => $id,
'label' => $this->randomString(),
])->save();
CommentType::create([
'id' => 'comment_node_' . $id,
'label' => $this->randomString(),
'target_entity_type_id' => 'node',
])->save();
}
/**
* Asserts various aspects of a user account.
*
@@ -46,6 +91,8 @@ class MigrateUserTest extends MigrateDrupal7TestBase {
* The user's email address.
* @param string $password
* The password for this user.
* @param int $created
* The user's creation time.
* @param int $access
* The last access time.
* @param int $login
@@ -54,54 +101,139 @@ class MigrateUserTest extends MigrateDrupal7TestBase {
* Whether or not the account is blocked.
* @param string $langcode
* The user account's language code.
* @param string $timezone
* The user account's timezone name.
* @param string $init
* The user's initial email address.
* @param string[] $roles
* Role IDs the user account is expected to have.
* @param int $field_integer
* The value of the integer field.
* @param int|false $field_file_target_id
* (optional) The target ID of the file field.
* @param bool $has_picture
* Whether the user is expected to have a picture attached.
* (optional) Whether the user is expected to have a picture attached.
*/
protected function assertEntity($id, $label, $mail, $password, $access, $login, $blocked, $langcode, $init, array $roles = [RoleInterface::AUTHENTICATED_ID], $has_picture = FALSE) {
protected function assertEntity($id, $label, $mail, $password, $created, $access, $login, $blocked, $langcode, $timezone, $init, $roles, $field_integer, $field_file_target_id = FALSE, $has_picture = FALSE) {
/** @var \Drupal\user\UserInterface $user */
$user = User::load($id);
$this->assertTrue($user instanceof UserInterface);
$this->assertIdentical($label, $user->label());
$this->assertIdentical($mail, $user->getEmail());
$this->assertIdentical($access, $user->getLastAccessedTime());
$this->assertIdentical($login, $user->getLastLoginTime());
$this->assertIdentical($blocked, $user->isBlocked());
$this->assertSame($label, $user->label());
$this->assertSame($mail, $user->getEmail());
$this->assertSame($password, $user->getPassword());
$this->assertSame($created, $user->getCreatedTime());
$this->assertSame($access, $user->getLastAccessedTime());
$this->assertSame($login, $user->getLastLoginTime());
$this->assertNotSame($blocked, $user->isBlocked());
// Ensure the user's langcode, preferred_langcode and
// preferred_admin_langcode are valid.
// $user->getPreferredLangcode() might fallback to default language if the
// user preferred language is not configured on the site. We just want to
// test if the value was imported correctly.
$this->assertIdentical($langcode, $user->langcode->value);
$this->assertIdentical($langcode, $user->preferred_langcode->value);
$this->assertIdentical($langcode, $user->preferred_admin_langcode->value);
$this->assertIdentical($init, $user->getInitialEmail());
$this->assertIdentical($roles, $user->getRoles());
$this->assertIdentical($has_picture, !$user->user_picture->isEmpty());
$this->assertIdentical($password, $user->getPassword());
$language_manager = $this->container->get('language_manager');
$default_langcode = $language_manager->getDefaultLanguage()->getId();
if ($langcode == '') {
$this->assertSame('en', $user->langcode->value);
$this->assertSame($default_langcode, $user->preferred_langcode->value);
$this->assertSame($default_langcode, $user->preferred_admin_langcode->value);
}
elseif ($language_manager->getLanguage($langcode) === NULL) {
$this->assertSame($default_langcode, $user->langcode->value);
$this->assertSame($default_langcode, $user->preferred_langcode->value);
$this->assertSame($default_langcode, $user->preferred_admin_langcode->value);
}
else {
$this->assertSame($langcode, $user->langcode->value);
$this->assertSame($langcode, $user->preferred_langcode->value);
$this->assertSame($langcode, $user->preferred_admin_langcode->value);
}
$this->assertSame($timezone, $user->getTimeZone());
$this->assertSame($init, $user->getInitialEmail());
$this->assertSame($roles, $user->getRoles());
$this->assertSame($has_picture, !$user->user_picture->isEmpty());
if (!is_null($field_integer)) {
$this->assertTrue($user->hasField('field_integer'));
$this->assertEquals($field_integer[0], $user->field_integer->value);
}
if (!empty($field_file_target_id)) {
$this->assertTrue($user->hasField('field_file'));
$this->assertSame($field_file_target_id, $user->field_file->target_id);
}
}
/**
* Tests the Drupal 7 user to Drupal 8 migration.
*/
public function testUser() {
$password = '$S$DGFZUE.FhrXbe4y52eC7p0ZVRGD/gOPtVctDlmC89qkujnBokAlJ';
$this->assertEntity(2, 'Odo', 'odo@local.host', $password, '0', '0', FALSE, '', 'odo@local.host');
$users = Database::getConnection('default', 'migrate')
->select('users', 'u')
->fields('u')
->condition('uid', 1, '>')
->execute()
->fetchAll();
// Ensure that the user can authenticate.
$this->assertEquals(2, \Drupal::service('user.auth')->authenticate('Odo', 'a password'));
// After authenticating the password will be rehashed because the password
// stretching iteration count has changed from 15 in Drupal 7 to 16 in
// Drupal 8.
$user = User::load(2);
$rehash = $user->getPassword();
$this->assertNotEquals($password, $rehash);
foreach ($users as $source) {
$rids = Database::getConnection('default', 'migrate')
->select('users_roles', 'ur')
->fields('ur', ['rid'])
->condition('ur.uid', $source->uid)
->execute()
->fetchCol();
$roles = [RoleInterface::AUTHENTICATED_ID];
$id_map = $this->getMigration('d7_user_role')->getIdMap();
foreach ($rids as $rid) {
$role = $id_map->lookupDestinationId([$rid]);
$roles[] = reset($role);
}
// Authenticate again and there should be no re-hash.
$this->assertEquals(2, \Drupal::service('user.auth')->authenticate('Odo', 'a password'));
$user = User::load(2);
$this->assertEquals($rehash, $user->getPassword());
$field_integer = Database::getConnection('default', 'migrate')
->select('field_data_field_integer', 'fi')
->fields('fi', ['field_integer_value'])
->condition('fi.entity_id', $source->uid)
->execute()
->fetchCol();
$field_integer = !empty($field_integer) ? $field_integer : NULL;
$field_file = Database::getConnection('default', 'migrate')
->select('field_data_field_file', 'ff')
->fields('ff', ['field_file_fid'])
->condition('ff.entity_id', $source->uid)
->execute()
->fetchField();
$this->assertEntity(
$source->uid,
$source->name,
$source->mail,
$source->pass,
$source->created,
$source->access,
$source->login,
$source->status,
$source->language,
$source->timezone,
$source->init,
$roles,
$field_integer,
$field_file
);
// Ensure that the user can authenticate.
$this->assertEquals($source->uid, $this->container->get('user.auth')->authenticate($source->name, 'a password'));
// After authenticating the password will be rehashed because the password
// stretching iteration count has changed from 15 in Drupal 7 to 16 in
// Drupal 8.
$user = User::load($source->uid);
$rehash = $user->getPassword();
$this->assertNotEquals($source->pass, $rehash);
// Authenticate again and there should be no re-hash.
$this->assertEquals($source->uid, $this->container->get('user.auth')->authenticate($source->name, 'a password'));
$user = User::load($source->uid);
$this->assertEquals($rehash, $user->getPassword());
}
}
}
@@ -0,0 +1,129 @@
<?php
namespace Drupal\Tests\user\Kernel\Plugin\migrate\source;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
/**
* Tests the profile_field source plugin.
*
* @covers \Drupal\user\Plugin\migrate\source\ProfileField
* @group user
*/
class ProfileFieldTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['user', 'migrate_drupal'];
/**
* {@inheritdoc}
*/
public function providerSource() {
$tests = [
[
'source_data' => [],
'expected_data' => [],
],
];
$profile_fields = [
[
'fid' => 1,
'title' => 'First name',
'name' => 'profile_first_name',
'explanation' => 'First name user',
'category' => 'profile',
'page' => '',
'type' => 'textfield',
'weight' => 0,
'required' => 1,
'register' => 0,
'visibility' => 2,
'autocomplete' => 0,
'options' => '',
],
[
'fid' => 2,
'title' => 'Last name',
'name' => 'profile_last_name',
'explanation' => 'Last name user',
'category' => 'profile',
'page' => '',
'type' => 'textfield',
'weight' => 0,
'required' => 0,
'register' => 0,
'visibility' => 2,
'autocomplete' => 0,
'options' => '',
],
[
'fid' => 3,
'title' => 'Policy',
'name' => 'profile_policy',
'explanation' => 'A checkbox that say if you accept policy of website',
'category' => 'profile',
'page' => '',
'type' => 'checkbox',
'weight' => 0,
'required' => 1,
'register' => 1,
'visibility' => 2,
'autocomplete' => 0,
'options' => '',
],
[
'fid' => 4,
'title' => 'Color',
'name' => 'profile_color',
'explanation' => 'A selection that allows user to select a color',
'category' => 'profile',
'page' => '',
'type' => 'selection',
'weight' => 0,
'required' => 0,
'register' => 0,
'visibility' => 2,
'autocomplete' => 0,
'options' => "red\nblue\ngreen",
],
];
$tests[0]['source_data']['profile_fields'] = $profile_fields;
// Profile values are merged with pre-set options of a "selection" field.
$tests[0]['source_data']['profile_values'] = [
[
'fid' => 4,
'uid' => 1,
'value' => 'yellow',
]
];
// Expected options are:
// for "checkbox" fields - array with NULL options
// for "selection" fields - options in both keys and values
$expected_field_options = [
'',
'',
[NULL, NULL],
[
'red' => 'red',
'blue' => 'blue',
'green' => 'green',
'yellow' => 'yellow',
]
];
$tests[0]['expected_data'] = $profile_fields;
foreach ($tests[0]['expected_data'] as $delta => $row) {
$tests[0]['expected_data'][$delta]['options'] = $expected_field_options[$delta];
}
return $tests;
}
}
@@ -0,0 +1,55 @@
<?php
namespace Drupal\Tests\user\Kernel\Plugin\migrate\source;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
/**
* Tests the user_picture_instance source plugin.
*
* @covers \Drupal\user\Plugin\migrate\source\UserPictureInstance
* @group user
*/
class UserPictureInstanceTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['user', 'migrate_drupal'];
/**
* {@inheritdoc}
*/
public function providerSource() {
$tests = [];
// The source data.
$tests[0]['source_data']['variable'] = [
[
'name' => 'file_directory',
'value' => serialize(NULL),
],
[
'name' => 'user_picture_file_size',
'value' => serialize(128),
],
[
'name' => 'user_picture_dimensions',
'value' => serialize('128x128'),
],
];
// The expected results.
$tests[0]['expected_data'] = [
[
'id' => '',
'file_directory' => 'pictures',
'max_filesize' => '128KB',
'max_resolution' => '128x128',
],
];
return $tests;
}
}
@@ -0,0 +1,85 @@
<?php
namespace Drupal\Tests\user\Kernel\Plugin\migrate\source\d6;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
/**
* Tests the d6_profile_field_values source plugin.
*
* @covers \Drupal\user\Plugin\migrate\source\d6\ProfileFieldValues
* @group user
*/
class ProfileFieldValuesTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['user', 'migrate_drupal'];
/**
* {@inheritdoc}
*/
public function providerSource() {
$tests = [];
// The source data.
$tests[0]['source_data']['profile_values'] = [
[
'fid' => '8',
'uid' => '2',
'value' => 'red',
],
[
'fid' => '9',
'uid' => '2',
'value' => 'Lorem ipsum dolor sit amet...',
],
];
$tests[0]['source_data']['profile_fields'] = [
[
'fid' => '8',
'title' => 'Favorite color',
'name' => 'profile_color',
'explanation' => 'List your favorite color',
'category' => 'Personal information',
'page' => 'Peole whose favorite color is %value',
'type' => 'textfield',
'weight' => '-10',
'required' => '0',
'register' => '1',
'visibility' => '2',
'autocomplete' => '1',
'options' => '',
],
[
'fid' => '9',
'title' => 'Biography',
'name' => 'profile_biography',
'explanation' => 'Tell people a little bit about yourself',
'category' => 'Personal information',
'page' => '',
'type' => 'textarea',
'weight' => '-8',
'required' => '0',
'register' => '0',
'visibility' => '2',
'autocomplete' => '0',
'options' => '',
],
];
// The expected results.
$tests[0]['expected_data'] = [
[
'profile_color' => ['red'],
'profile_biography' => ['Lorem ipsum dolor sit amet...'],
'uid' => '2',
],
];
return $tests;
}
}
@@ -0,0 +1,87 @@
<?php
namespace Drupal\Tests\user\Kernel\Plugin\migrate\source\d6;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
/**
* Tests the d6_user_role source plugin.
*
* @covers \Drupal\user\Plugin\migrate\source\d6\Role
* @group user
*/
class RoleTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['user', 'migrate_drupal'];
/**
* {@inheritdoc}
*/
public function providerSource() {
$tests = [
[
'source_data' => [],
'expected_data' => [],
],
];
$roles = [
[
'rid' => 1,
'name' => 'anonymous user',
'permissions' => [
'access content',
],
],
[
'rid' => 2,
'name' => 'authenticated user',
'permissions' => [
'access comments',
'access content',
'post comments',
'post comments without approval',
],
],
[
'rid' => 3,
'name' => 'administrator',
'permissions' => [
'access comments',
'administer comments',
'post comments',
'post comments without approval',
'access content',
'administer content types',
'administer nodes',
],
],
];
// The source data.
foreach ($roles as $role) {
$tests[0]['source_data']['permission'][] = [
'rid' => $role['rid'],
'perm' => implode(', ', $role['permissions']),
];
unset($role['permissions']);
$tests[0]['source_data']['role'][] = $role;
}
$tests[0]['source_data']['filter_formats'] = [
[
'format' => 1,
'roles' => '',
],
];
// The expected results.
$tests[0]['expected_data'] = $roles;
return $tests;
}
}
@@ -0,0 +1,49 @@
<?php
namespace Drupal\Tests\user\Kernel\Plugin\migrate\source\d6;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
/**
* Tests the d6_user_picture_file source plugin.
*
* @covers \Drupal\user\Plugin\migrate\source\d6\UserPictureFile
* @group user
*/
class UserPictureFileTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['user', 'migrate_drupal'];
/**
* {@inheritdoc}
*/
public function providerSource() {
$tests = [];
// The source data.
$tests[0]['source_data']['users'] = [
[
'uid' => '2',
'picture' => 'core/modules/simpletest/files/image-test.jpg',
],
[
'uid' => '15',
'picture' => '',
],
];
// The expected results.
$tests[0]['expected_data'] = [
[
'uid' => '2',
'picture' => 'core/modules/simpletest/files/image-test.jpg',
],
];
return $tests;
}
}
@@ -0,0 +1,46 @@
<?php
namespace Drupal\Tests\user\Kernel\Plugin\migrate\source\d6;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
/**
* Tests the d6_user_picture source plugin.
*
* @covers \Drupal\user\Plugin\migrate\source\d6\UserPicture
* @group user
*/
class UserPictureTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['user', 'migrate_drupal'];
/**
* {@inheritdoc}
*/
public function providerSource() {
$tests = [];
// The source data.
$tests[0]['source_data']['users'] = [
[
'uid' => 1,
'access' => 1382835435,
'picture' => 'sites/default/files/pictures/picture-1.jpg',
],
[
'uid' => 2,
'access' => 1382835436,
'picture' => 'sites/default/files/pictures/picture-2.jpg',
],
];
// User picture data model is identical in source input and output.
$tests[0]['expected_data'] = $tests[0]['source_data']['users'];
return $tests;
}
}
@@ -0,0 +1,83 @@
<?php
namespace Drupal\Tests\user\Kernel\Plugin\migrate\source\d6;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
/**
* Tests the d6_user source plugin.
*
* @covers \Drupal\user\Plugin\migrate\source\d6\User
* @group user
*/
class UserTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['user', 'migrate_drupal'];
/**
* {@inheritdoc}
*/
public function providerSource() {
$tests = [];
// The source data.
$tests[0]['source_data']['users'] = [
[
'uid' => 2,
'name' => 'admin',
'pass' => '1234',
'mail' => 'admin@example.com',
'theme' => '',
'signature' => '',
'signature_format' => 0,
'created' => 1279402616,
'access' => 1322981278,
'login' => 1322699994,
'status' => 0,
'timezone' => 'America/Lima',
'language' => 'en',
// @todo Add the file when needed.
'picture' => 'sites/default/files/pictures/picture-1.jpg',
'init' => 'admin@example.com',
'data' => NULL,
],
[
'uid' => 4,
'name' => 'alice',
// @todo d6 hash?
'pass' => '1234',
'mail' => 'alice@example.com',
'theme' => '',
'signature' => '',
'signature_format' => 0,
'created' => 1322981368,
'access' => 1322982419,
'login' => 132298140,
'status' => 0,
'timezone' => 'America/Lima',
'language' => 'en',
'picture' => '',
'init' => 'alice@example.com',
'data' => NULL,
],
];
// getDatabase() will not create empty tables, so we need to insert data
// even if it's irrelevant to the test.
$tests[0]['source_data']['users_roles'] = [
[
'uid' => 99,
'rid' => 99,
],
];
// The expected results.
$tests[0]['expected_data'] = $tests[0]['source_data']['users'];
return $tests;
}
}
@@ -0,0 +1,72 @@
<?php
namespace Drupal\Tests\user\Kernel\Plugin\migrate\source\d7;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
/**
* Tests the d7_user_role source plugin.
*
* @covers \Drupal\user\Plugin\migrate\source\d7\Role
* @group user
*/
class RoleTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['migrate_drupal', 'user'];
/**
* {@inheritdoc}
*/
public function providerSource() {
$expected = [
[
'rid' => 1,
'name' => 'anonymous user',
'permissions' => [
'access content',
],
],
[
'rid' => 2,
'name' => 'authenticated user',
'permissions' => [
'access comments',
'access content',
'post comments',
'post comments without approval',
],
],
[
'rid' => 3,
'name' => 'administrator',
'permissions' => [
'access comments',
'administer comments',
'post comments',
'post comments without approval',
'access content',
'administer content types',
'administer nodes',
],
],
];
$data = [
[[], $expected],
];
foreach ($expected as $row) {
foreach ($row['permissions'] as $permission) {
$data[0][0]['role_permission'][] = [
'permission' => $permission,
'rid' => $row['rid'],
];
}
unset($row['permissions']);
$data[0][0]['role'][] = $row;
}
return $data;
}
}
@@ -0,0 +1,120 @@
<?php
namespace Drupal\Tests\user\Kernel\Plugin\migrate\source\d7;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
/**
* Tests the d7_user source plugin.
*
* @covers \Drupal\user\Plugin\migrate\source\d7\User
* @group user
*/
class UserTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['user', 'migrate_drupal'];
/**
* {@inheritdoc}
*/
public function providerSource() {
$tests = [];
// The source data.
$tests[0]['source_data']['field_config_instance'] = [
[
'id' => '33',
'field_id' => '11',
'field_name' => 'field_file',
'entity_type' => 'user',
'bundle' => 'user',
'data' => 'a:0:{}',
'deleted' => '0',
],
];
$tests[0]['source_data']['field_data_field_file'] = [
[
'entity_type' => 'user',
'bundle' => 'user',
'deleted' => 0,
'entity_id' => 2,
'revision_id' => NULL,
'language' => 'und',
'delta' => 0,
'field_file_fid' => 99,
'field_file_display' => 1,
'field_file_description' => 'None',
],
];
$tests[0]['source_data']['role'] = [
[
'rid' => 2,
'name' => 'authenticated user',
'weight' => 0,
],
];
$tests[0]['source_data']['users'] = [
[
'uid' => '2',
'name' => 'Odo',
'pass' => '$S$DVpvPItXvnsmF3giVEe7Jy2lG.SCoEs8uKwpHsyPvdeNAaNZYxZ8',
'mail' => 'odo@local.host',
'theme' => '',
'signature' => '',
'signature_format' => 'filtered_html',
'created' => '1432750741',
'access' => '0',
'login' => '0',
'status' => '1',
'timezone' => 'America/Chicago',
'language' => '',
'picture' => '0',
'init' => 'odo@local.host',
'data' => 'a:1:{s:7:"contact";i:1;}',
],
];
$tests[0]['source_data']['users_roles'] = [
[
'uid' => 2,
'rid' => 2,
],
];
// The expected results.
$tests[0]['expected_data'] = [
[
'uid' => '2',
'name' => 'Odo',
'pass' => '$S$DVpvPItXvnsmF3giVEe7Jy2lG.SCoEs8uKwpHsyPvdeNAaNZYxZ8',
'mail' => 'odo@local.host',
'signature' => '',
'signature_format' => 'filtered_html',
'created' => '1432750741',
'access' => '0',
'login' => '0',
'status' => '1',
'timezone' => 'America/Chicago',
'language' => '',
'picture' => '0',
'init' => 'odo@local.host',
'roles' => [2],
'data' => [
'contact' => 1,
],
'field_file' => [
[
'fid' => 99,
'display' => 1,
'description' => 'None',
],
],
],
];
return $tests;
}
}
@@ -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();
@@ -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,14 +128,14 @@ class UserAccountFormFieldsTest extends KernelTestBase {
protected function buildAccountForm($operation) {
// @see HtmlEntityFormController::getFormObject()
$entity_type = 'user';
$fields = array();
$fields = [];
if ($operation != 'register') {
$fields['uid'] = 2;
}
$entity = $this->container->get('entity.manager')
->getStorage($entity_type)
->create($fields);
$form_object = $this->container->get('entity.manager')
$this->container->get('entity.manager')
->getFormObject($entity_type, $operation)
->setEntity($entity);
@@ -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);
@@ -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'];
}
@@ -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());
}
}
@@ -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',
@@ -16,7 +16,7 @@ class UserInstallTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('user');
public static $modules = ['user'];
/**
* {@inheritdoc}
@@ -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());
@@ -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']);
}
}
@@ -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.
@@ -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,35 +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'),
'ᚠᛇᚻ᛫ᛒᛦᚦ' => 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);
@@ -68,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.');
@@ -83,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([
@@ -95,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());
@@ -115,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.'));
@@ -124,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));
@@ -156,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);
@@ -172,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']));
}
/**
@@ -194,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]));
}
/**
@@ -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);
@@ -0,0 +1,95 @@
<?php
namespace Drupal\Tests\user\Kernel\Views;
use Drupal\views\Views;
use Drupal\Core\Session\AnonymousUserSession;
/**
* Tests the current user filter handler.
*
* @group user
* @see \Drupal\user\Plugin\views\filter\Current
*/
class HandlerFilterCurrentUserTest extends UserKernelTestBase {
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_filter_current_user'];
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountProxy
*/
protected $currentUser;
/**
* {@inheritdoc}
*/
protected function setUp($import_test_views = TRUE) {
parent::setUp();
$this->currentUser = $this->container->get('current_user');
$this->setupPermissionTestData();
}
/**
* Tests the current user filter handler with anonymous user.
*/
public function testFilterCurrentUserAsAnonymous() {
$column_map = ['uid' => 'uid'];
$this->currentUser->setAccount(new AnonymousUserSession());
$view = Views::getView('test_filter_current_user');
$view->initHandlers();
$view->filter['uid_current']->value = 0;
$this->executeView($view);
$expected[] = ['uid' => 1];
$expected[] = ['uid' => 2];
$expected[] = ['uid' => 3];
$expected[] = ['uid' => 4];
$this->assertIdenticalResultset($view, $expected, $column_map, 'Anonymous account can view all accounts when current filter is FALSE.');
$view->destroy();
$view = Views::getView('test_filter_current_user');
$view->initHandlers();
$view->filter['uid_current']->value = 1;
$this->executeView($view);
$expected = [];
$this->assertIdenticalResultset($view, $expected, $column_map, 'Anonymous account can view zero accounts when current filter is TRUE.');
$view->destroy();
}
/**
* Tests the current user filter handler with logged-in user.
*/
public function testFilterCurrentUserAsUser() {
$column_map = ['uid' => 'uid'];
$user = reset($this->users);
$this->currentUser->setAccount($user);
$view = Views::getView('test_filter_current_user');
$view->initHandlers();
$view->filter['uid_current']->value = 0;
$this->executeView($view);
$expected = [];
$expected[] = ['uid' => 2];
$expected[] = ['uid' => 3];
$expected[] = ['uid' => 4];
$this->assertIdenticalResultset($view, $expected, $column_map, 'User can view all users except itself when current filter is FALSE.');
$view->destroy();
$view = Views::getView('test_filter_current_user');
$view->initHandlers();
$view->filter['uid_current']->value = 1;
$this->executeView($view);
$expected = [];
$expected[] = ['uid' => 1];
$this->assertIdenticalResultset($view, $expected, $column_map, 'User can only view itself when current filter is TRUE.');
$view->destroy();
}
}
@@ -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]);
@@ -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.
@@ -39,15 +39,44 @@ class HandlerFilterRolesTest extends UserKernelTestBase {
'id' => 'roles_target_id',
'table' => 'user__roles',
'field' => 'roles_target_id',
'value' => [
'test_user_role' => 'test_user_role',
],
'value' => ['test_user_role' => 'test_user_role'],
'plugin_id' => 'user_roles',
];
$view->save();
$expected['config'][] = 'user.role.test_user_role';
$this->assertEqual($expected, $view->getDependencies());
$view = View::load('test_user_name');
$display = &$view->getDisplay('default');
$display['display_options']['filters']['roles_target_id'] = [
'id' => 'roles_target_id',
'table' => 'user__roles',
'field' => 'roles_target_id',
'value' => [
'test_user_role' => 'test_user_role',
],
'operator' => 'empty',
'plugin_id' => 'user_roles',
];
$view->save();
unset($expected['config']);
$this->assertEqual($expected, $view->getDependencies());
$view = View::load('test_user_name');
$display = &$view->getDisplay('default');
$display['display_options']['filters']['roles_target_id'] = [
'id' => 'roles_target_id',
'table' => 'user__roles',
'field' => 'roles_target_id',
'value' => [
'test_user_role' => 'test_user_role',
],
'operator' => 'not empty',
'plugin_id' => 'user_roles',
];
$view->save();
$this->assertEqual($expected, $view->getDependencies());
$view = Views::getView('test_user_name');
$view->initDisplay();
$view->initHandlers();
@@ -63,7 +92,6 @@ class HandlerFilterRolesTest extends UserKernelTestBase {
'plugin_id' => 'user_roles',
];
$view->save();
unset($expected['config']);
$this->assertEqual($expected, $view->getDependencies());
}
@@ -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();
@@ -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'],
];
}
}
@@ -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')
@@ -97,43 +97,43 @@ 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');
file_put_contents($url . '/module_a/module_a.permissions.yml',
"access_module_a: single_description"
);
file_put_contents($url . '/module_a/module_a.permissions.yml', "access_module_a: single_description");
mkdir($url . '/module_b');
file_put_contents($url . '/module_b/module_b.permissions.yml',
"'access module b':
file_put_contents($url . '/module_b/module_b.permissions.yml', <<<EOF
'access module b':
title: 'Access B'
description: 'bla bla'
'access module a via module b':
title: 'Access A via B'
provider: 'module_a'
");
EOF
);
mkdir($url . '/module_c');
file_put_contents($url . '/module_c/module_c.permissions.yml',
"'access_module_c':
file_put_contents($url . '/module_c/module_c.permissions.yml', <<<EOF
'access_module_c':
title: 'Access C'
description: 'bla bla'
'restrict access': TRUE
");
$modules = array('module_a', 'module_b', 'module_c');
$extensions = array(
EOF
);
$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')
@@ -187,9 +187,10 @@ class PermissionHandlerTest extends UnitTestCase {
$url = vfsStream::url('modules');
mkdir($url . '/module_a');
file_put_contents($url . '/module_a/module_a.permissions.yml',
"access_module_a2: single_description2
access_module_a1: single_description1"
file_put_contents($url . '/module_a/module_a.permissions.yml', <<<EOF
access_module_a2: single_description2
access_module_a1: single_description1
EOF
);
mkdir($url . '/module_b');
file_put_contents($url . '/module_b/module_b.permissions.yml',
@@ -226,41 +227,44 @@ access_module_a1: single_description1"
$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');
file_put_contents($url . '/module_a/module_a.permissions.yml',
"permission_callbacks:
file_put_contents($url . '/module_a/module_a.permissions.yml', <<<EOF
permission_callbacks:
- 'Drupal\\user\\Tests\\TestPermissionCallbacks::singleDescription'
");
EOF
);
mkdir($url . '/module_b');
file_put_contents($url . '/module_b/module_b.permissions.yml',
"permission_callbacks:
file_put_contents($url . '/module_b/module_b.permissions.yml', <<<EOF
permission_callbacks:
- 'Drupal\\user\\Tests\\TestPermissionCallbacks::titleDescription'
- 'Drupal\\user\\Tests\\TestPermissionCallbacks::titleProvider'
");
EOF
);
mkdir($url . '/module_c');
file_put_contents($url . '/module_c/module_c.permissions.yml',
"permission_callbacks:
file_put_contents($url . '/module_c/module_c.permissions.yml', <<<EOF
permission_callbacks:
- 'Drupal\\user\\Tests\\TestPermissionCallbacks::titleDescriptionRestrictAccess'
");
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')
@@ -269,19 +273,19 @@ access_module_a1: single_description1"
$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);
@@ -303,29 +307,30 @@ access_module_a1: single_description1"
$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');
file_put_contents($url . '/module_a/module_a.permissions.yml',
"'access module a':
file_put_contents($url . '/module_a/module_a.permissions.yml', <<<EOF
'access module a':
title: 'Access A'
description: 'bla bla'
permission_callbacks:
- 'Drupal\\user\\Tests\\TestPermissionCallbacks::titleDescription'
");
$modules = array('module_a');
$extensions = array(
'module_a' => $this->mockModuleExtension('module_a', 'Module a'),
EOF
);
$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')
@@ -334,7 +339,7 @@ permission_callbacks:
$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);
@@ -394,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',
),
);
],
];
}
}
@@ -437,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);
}
@@ -451,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);
}
@@ -22,10 +22,10 @@ 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'];
$add_role_plugin = new AddRoleUser($config, 'user_add_role_action', ['type' => 'user'], $this->userRoleEntityType);
$remove_role_plugin->execute($this->account);
$add_role_plugin->execute($this->account);
}
/**
@@ -40,10 +40,10 @@ 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'];
$add_role_plugin = new AddRoleUser($config, 'user_add_role_action', ['type' => 'user'], $this->userRoleEntityType);
$remove_role_plugin->execute($this->account);
$add_role_plugin->execute($this->account);
}
}
@@ -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);
}
@@ -5,7 +5,7 @@ namespace Drupal\Tests\user\Unit\Plugin\Core\Entity;
use Drupal\Tests\Core\Session\UserSessionTest;
use Drupal\user\RoleInterface;
/**
/**
* @coversDefaultClass \Drupal\user\Entity\User
* @group user
*/
@@ -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));
}
}
@@ -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())
@@ -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);
@@ -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');
}
@@ -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');
}
@@ -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;
}
@@ -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')
@@ -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());
}
}
@@ -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);
}
}
@@ -4,8 +4,8 @@ description: 'Theme for testing the available fields in user twig template'
# version: VERSION
# core: 8.x
# Information added by Drupal.org packaging script on 2016-08-03
version: '8.1.8'
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
core: '8.x'
project: 'drupal'
datestamp: 1470233791
datestamp: 1502903957