Commit 31fbee70 authored by catch's avatar catch

Issue #3035825 by plach, larowlan, amateescu, jhedstrom: Make it easier to set...

Issue #3035825 by plach, larowlan, amateescu, jhedstrom: Make it easier to set up the current_user service in kernel tests
parent 825e5147
......@@ -5,6 +5,7 @@
use Drupal\KernelTests\KernelTestBase;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\Tests\user\Traits\UserCreationTrait;
/**
* @coversDefaultClass \Drupal\content_moderation\ParamConverter\EntityRevisionConverter
......@@ -13,6 +14,8 @@
*/
class EntityRevisionConverterTest extends KernelTestBase {
use UserCreationTrait;
/**
* {@inheritdoc}
*/
......@@ -29,9 +32,10 @@ class EntityRevisionConverterTest extends KernelTestBase {
*/
protected function setUp() {
parent::setUp();
$this->setUpCurrentUser();
$this->installEntitySchema('node');
$this->installEntitySchema('user');
$this->installSchema('system', 'sequences');
$this->installSchema('node', 'node_access');
}
......
......@@ -6,8 +6,9 @@
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Menu\MenuTreeParameters;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Drupal\KernelTests\KernelTestBase;
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Drupal\Tests\user\Traits\UserCreationTrait;
use Drupal\user\Entity\User;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\Request;
......@@ -21,6 +22,8 @@
*/
class MenuLinkContentCacheabilityBubblingTest extends KernelTestBase {
use UserCreationTrait;
/**
* {@inheritdoc}
*/
......@@ -32,8 +35,8 @@ class MenuLinkContentCacheabilityBubblingTest extends KernelTestBase {
protected function setUp() {
parent::setUp();
$this->setUpCurrentUser(['uid' => 0]);
$this->installEntitySchema('menu_link_content');
$this->installEntitySchema('user');
// Ensure that the weight of module_link_content is higher than system.
// @see menu_link_content_install()
......
......@@ -5,6 +5,7 @@
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Drupal\menu_link_content\MenuLinkContentInterface;
use Drupal\Tests\node\Kernel\Migrate\d6\MigrateNodeTestBase;
use Drupal\Tests\user\Traits\UserCreationTrait;
/**
* Menu link migration.
......@@ -13,6 +14,8 @@
*/
class MigrateMenuLinkTest extends MigrateNodeTestBase {
use UserCreationTrait;
/**
* {@inheritdoc}
*/
......@@ -30,6 +33,7 @@ class MigrateMenuLinkTest extends MigrateNodeTestBase {
*/
protected function setUp() {
parent::setUp();
$this->setUpCurrentUser();
$this->installEntitySchema('menu_link_content');
$this->executeMigrations([
'language',
......
......@@ -4,6 +4,7 @@
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
use Drupal\Tests\user\Traits\UserCreationTrait;
/**
* Menu link migration.
......@@ -12,6 +13,8 @@
*/
class MigrateMenuLinkTranslationTest extends MigrateDrupal6TestBase {
use UserCreationTrait;
/**
* {@inheritdoc}
*/
......@@ -30,6 +33,7 @@ class MigrateMenuLinkTranslationTest extends MigrateDrupal6TestBase {
protected function setUp() {
parent::setUp();
$this->migrateContent();
$this->setUpCurrentUser();
$this->installEntitySchema('menu_link_content');
$this->executeMigrations([
'language',
......
......@@ -6,6 +6,7 @@
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Drupal\menu_link_content\MenuLinkContentInterface;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
use Drupal\Tests\user\Traits\UserCreationTrait;
/**
* Menu link migration.
......@@ -15,6 +16,8 @@
class MigrateMenuLinkTest extends MigrateDrupal7TestBase {
const MENU_NAME = 'menu-test-menu';
use UserCreationTrait;
/**
* {@inheritdoc}
*/
......@@ -35,6 +38,8 @@ class MigrateMenuLinkTest extends MigrateDrupal7TestBase {
*/
protected function setUp() {
parent::setUp();
$this->setUpCurrentUser();
$this->installEntitySchema('menu_link_content');
$this->installSchema('node', ['node_access']);
$this->installConfig(static::$modules);
......
......@@ -2,12 +2,13 @@
namespace Drupal\Tests\menu_link_content\Kernel\Plugin\migrate\process;
use Drupal\KernelTests\KernelTestBase;
use Drupal\menu_link_content\Plugin\migrate\process\LinkUri;
use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;
use Drupal\node\Entity\Node;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\user\Traits\UserCreationTrait;
/**
* Tests \Drupal\menu_link_content\Plugin\migrate\process\LinkUri.
......@@ -18,6 +19,8 @@
*/
class LinkUriTest extends KernelTestBase {
use UserCreationTrait;
/**
* Modules to enable.
*
......@@ -30,8 +33,8 @@ class LinkUriTest extends KernelTestBase {
*/
public function setUp() {
parent::setUp();
$this->setUpCurrentUser();
$this->installEntitySchema('node');
$this->installEntitySchema('user');
}
/**
......
......@@ -3,11 +3,11 @@
namespace Drupal\Tests\migrate\Kernel\process;
use Drupal\KernelTests\KernelTestBase;
use Drupal\migrate\Plugin\migrate\process\Route;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Plugin\migrate\process\Route;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Row;
use Drupal\user\Entity\User;
use Drupal\Tests\user\Traits\UserCreationTrait;
/**
* Tests the route process plugin.
......@@ -18,6 +18,8 @@
*/
class RouteTest extends KernelTestBase {
use UserCreationTrait;
/**
* {@inheritdoc}
*/
......@@ -195,15 +197,9 @@ public function providerTestRoute() {
* @dataProvider providerTestRouteWithParamQuery
*/
public function testRouteWithParamQuery($value, $expected) {
$this->installSchema('system', ['sequences']);
$this->installEntitySchema('user');
$this->installConfig(['user']);
// Create a user so that user/1/edit is a valid path.
$adminUser = User::create([
'name' => $this->randomMachineName(),
]);
$adminUser->save();
$this->setUpCurrentUser();
$this->installConfig(['user']);
$actual = $this->doTransform($value);
$this->assertSame($expected, $actual);
......
......@@ -3,6 +3,7 @@
namespace Drupal\Tests\node\Kernel\Migrate\d6;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
use Drupal\Tests\user\Traits\UserCreationTrait;
use Symfony\Component\HttpFoundation\Request;
/**
......@@ -13,6 +14,8 @@
*/
class NodeTranslationRedirectTest extends MigrateDrupal6TestBase {
use UserCreationTrait;
/**
* {@inheritdoc}
*/
......@@ -30,6 +33,8 @@ class NodeTranslationRedirectTest extends MigrateDrupal6TestBase {
protected function setUp() {
parent::setUp();
$this->setUpCurrentUser();
$this->installEntitySchema('node');
$this->installConfig(['node']);
$this->installSchema('node', ['node_access']);
......
......@@ -3,6 +3,7 @@
namespace Drupal\Tests\node\Kernel\Migrate\d7;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
use Drupal\Tests\user\Traits\UserCreationTrait;
use Symfony\Component\HttpFoundation\Request;
/**
......@@ -13,6 +14,8 @@
*/
class NodeTranslationRedirectTest extends MigrateDrupal7TestBase {
use UserCreationTrait;
/**
* {@inheritdoc}
*/
......@@ -24,6 +27,7 @@ class NodeTranslationRedirectTest extends MigrateDrupal7TestBase {
'migrate_drupal_multilingual',
'node',
'text',
'user',
];
/**
......@@ -32,6 +36,8 @@ class NodeTranslationRedirectTest extends MigrateDrupal7TestBase {
protected function setUp() {
parent::setUp();
$this->setUpCurrentUser();
$this->installSchema('node', ['node_access']);
$this->installSchema('system', ['key_value']);
......
......@@ -3,6 +3,7 @@
namespace Drupal\Tests\node\Traits;
use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;
/**
* Provides methods to create node based on default settings.
......@@ -75,8 +76,23 @@ protected function createNode(array $settings = []) {
],
'title' => $this->randomMachineName(8),
'type' => 'page',
'uid' => \Drupal::currentUser()->id(),
];
if (!array_key_exists('uid', $settings)) {
$user = User::load(\Drupal::currentUser()->id());
if ($user) {
$settings['uid'] = $user->id();
}
elseif (method_exists($this, 'setUpCurrentUser')) {
/** @var \Drupal\user\UserInterface $user */
$user = $this->setUpCurrentUser();
$settings['uid'] = $user->id();
}
else {
$settings['uid'] = 0;
}
}
$node = Node::create($settings);
$node->save();
......
......@@ -7,6 +7,7 @@
use Drupal\Tests\field\Traits\EntityReferenceTestTrait;
use Drupal\Tests\node\Traits\ContentTypeCreationTrait;
use Drupal\Tests\node\Traits\NodeCreationTrait;
use Drupal\Tests\user\Traits\UserCreationTrait;
use Drupal\Tests\views\Kernel\ViewsKernelTestBase;
use Drupal\views\Tests\ViewTestData;
use Drupal\taxonomy\Entity\Vocabulary;
......@@ -18,6 +19,7 @@
abstract class TaxonomyTestBase extends ViewsKernelTestBase {
use EntityReferenceTestTrait;
use UserCreationTrait;
use NodeCreationTrait {
createNode as drupalCreateNode;
......
......@@ -3,7 +3,11 @@
namespace Drupal\Tests\user\Traits;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Database\DatabaseExceptionWrapper;
use Drupal\Core\Database\SchemaObjectExistsException;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Session\AccountInterface;
use Drupal\KernelTests\KernelTestBase;
use Drupal\user\Entity\Role;
use Drupal\user\Entity\User;
use Drupal\user\RoleInterface;
......@@ -16,6 +20,112 @@
*/
trait UserCreationTrait {
/**
* Creates a random user account and sets it as current user.
*
* Unless explicitly specified by setting the user ID to 1, a regular user
* account will be created and set as current, after creating user account 1.
* Additionally, this will ensure that at least the anonymous user account
* exists regardless of the specified user ID.
*
* @param array $values
* (optional) An array of initial user field values.
* @param array $permissions
* (optional) Array of permission names to assign to user. Note that the
* user always has the default permissions derived from the "authenticated
* users" role.
* @param bool $admin
* (optional) Whether the user should be an administrator with all the
* available permissions.
*
* @return \Drupal\user\UserInterface
* A user account object.
*
* @throws \LogicException
* If attempting to assign additional roles to the anonymous user account.
* @throws \Drupal\Core\Entity\EntityStorageException
* If the user could not be saved.
*/
protected function setUpCurrentUser(array $values = [], array $permissions = [], $admin = FALSE) {
$values += [
'name' => $this->randomMachineName(),
];
// In many cases the anonymous user account is fine for testing purposes,
// however, if we need to create a user with a non-empty ID, we need also
// the "sequences" table.
if (!\Drupal::moduleHandler()->moduleExists('system')) {
$values['uid'] = 0;
}
if ($this instanceof KernelTestBase && (!isset($values['uid']) || $values['uid'])) {
try {
$this->installSchema('system', ['sequences']);
}
catch (SchemaObjectExistsException $e) {
}
}
// Creating an administrator or assigning custom permissions would result in
// creating and assigning a new role to the user. This is not possible with
// the anonymous user account.
if (($admin || $permissions) && isset($values['uid']) && is_numeric($values['uid']) && $values['uid'] == 0) {
throw new \LogicException('The anonymous user account cannot have additional roles.');
}
$original_permissions = $permissions;
$original_admin = $admin;
$original_values = $values;
$autocreate_user_1 = !isset($values['uid']) || $values['uid'] > 1;
// No need to create user account 1 if it already exists.
try {
$autocreate_user_1 = $autocreate_user_1 && !User::load(1);
}
catch (DatabaseExceptionWrapper $e) {
// Missing schema, it will be created later on.
}
// Save the user entity object and created its schema if needed.
try {
if ($autocreate_user_1) {
$permissions = [];
$admin = FALSE;
$values = [];
}
$user = $this->createUser($permissions, NULL, $admin, $values);
}
catch (EntityStorageException $e) {
if ($this instanceof KernelTestBase) {
$this->installEntitySchema('user');
$user = $this->createUser($permissions, NULL, $admin, $values);
}
else {
throw $e;
}
}
// Ensure the anonymous user account exists.
if (!User::load(0)) {
$values = [
'uid' => 0,
'status' => 0,
'name' => '',
];
User::create($values)->save();
}
// If we automatically created user account 1, we need to create a regular
// user account before setting up the current user service to avoid
// potential false positives caused by access control bypass.
if ($autocreate_user_1) {
$user = $this->createUser($original_permissions, NULL, $original_admin, $original_values);
}
$this->setCurrentUser($user);
return $user;
}
/**
* Switch the current logged in user.
*
......@@ -37,12 +147,17 @@ protected function setCurrentUser(AccountInterface $account) {
* @param bool $admin
* (optional) Whether the user should be an administrator
* with all the available permissions.
* @param array $values
* (optional) An array of initial user field values.
*
* @return \Drupal\user\Entity\User|false
* A fully loaded user object with pass_raw property, or FALSE if account
* creation fails.
*
* @throws \Drupal\Core\Entity\EntityStorageException
* If the user creation fails.
*/
protected function createUser(array $permissions = [], $name = NULL, $admin = FALSE) {
protected function createUser(array $permissions = [], $name = NULL, $admin = FALSE, array $values = []) {
// Create a role with the given permission set, if any.
$rid = FALSE;
if ($permissions) {
......@@ -53,11 +168,18 @@ protected function createUser(array $permissions = [], $name = NULL, $admin = FA
}
// Create a user assigned to that role.
$edit = [];
$edit['name'] = !empty($name) ? $name : $this->randomMachineName();
$edit['mail'] = $edit['name'] . '@example.com';
$edit['pass'] = user_password();
$edit['status'] = 1;
$edit = $values;
if ($name) {
$edit['name'] = $name;
}
elseif (!isset($values['name'])) {
$edit['name'] = $this->randomMachineName();
}
$edit += [
'mail' => $edit['name'] . '@example.com',
'pass' => user_password(),
'status' => 1,
];
if ($rid) {
$edit['roles'] = [$rid];
}
......@@ -69,8 +191,9 @@ protected function createUser(array $permissions = [], $name = NULL, $admin = FA
$account = User::create($edit);
$account->save();
$this->assertTrue($account->id(), new FormattableMarkup('User created with name %name and pass %pass', ['%name' => $edit['name'], '%pass' => $edit['pass']]), 'User login');
if (!$account->id()) {
$valid_user = $account->id() !== NULL;
$this->assertTrue($valid_user, new FormattableMarkup('User created with name %name and pass %pass', ['%name' => $edit['name'], '%pass' => $edit['pass']]), 'User login');
if (!$valid_user) {
return FALSE;
}
......
......@@ -4,9 +4,9 @@
use Drupal\Core\Session\AccountInterface;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\user\Entity\Role;
use Drupal\Tests\user\Traits\UserCreationTrait;
use Drupal\Tests\views\Kernel\ViewsKernelTestBase;
use Drupal\user\Entity\Role;
use Drupal\views\Views;
/**
......@@ -45,7 +45,9 @@ class FieldEntityLinkTest extends ViewsKernelTestBase {
protected function setUpFixtures() {
parent::setUpFixtures();
$this->installEntitySchema('user');
// Create the anonymous user account and set it as current user.
$this->setUpCurrentUser(['uid' => 0]);
$this->installEntitySchema('entity_test');
$this->installConfig(['user']);
......
......@@ -59,13 +59,14 @@ class WorkspaceCRUDTest extends KernelTestBase {
protected function setUp() {
parent::setUp();
$this->installSchema('system', ['key_value_expire', 'sequences']);
$this->setUpCurrentUser();
$this->installSchema('system', ['key_value_expire']);
$this->installSchema('node', ['node_access']);
$this->installEntitySchema('workspace');
$this->installEntitySchema('workspace_association');
$this->installEntitySchema('node');
$this->installEntitySchema('user');
$this->installConfig(['filter', 'node', 'system']);
......
......@@ -5,6 +5,7 @@
use Drupal\entity_test\Entity\EntityTestAdminRoutes;
use Drupal\entity_test\Entity\EntityTestMul;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\user\Traits\UserCreationTrait;
use Drupal\user\Entity\Role;
use Drupal\user\RoleInterface;
use Symfony\Component\HttpFoundation\Request;
......@@ -17,6 +18,8 @@
*/
class RouteProviderTest extends KernelTestBase {
use UserCreationTrait;
/**
* {@inheritdoc}
*/
......@@ -28,7 +31,8 @@ class RouteProviderTest extends KernelTestBase {
protected function setUp() {
parent::setUp();
$this->installEntitySchema('user');
$this->setUpCurrentUser(['uid' => 1]);
$this->installEntitySchema('entity_test_mul');
$this->installEntitySchema('entity_test_admin_routes');
......
......@@ -6,6 +6,7 @@
use Drupal\entity_test\Entity\EntityTestMulRev;
use Drupal\KernelTests\KernelTestBase;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\Tests\user\Traits\UserCreationTrait;
/**
* Tests the entity converter when the "load_latest_revision" flag is set.
......@@ -15,6 +16,8 @@
*/
class EntityConverterLatestRevisionTest extends KernelTestBase {
use UserCreationTrait;
/**
* Modules to install.
*
......@@ -40,7 +43,8 @@ class EntityConverterLatestRevisionTest extends KernelTestBase {
protected function setUp() {
parent::setUp();
$this->installEntitySchema('user');
$this->setUpCurrentUser();
$this->installEntitySchema('entity_test_mulrev');
$this->installEntitySchema('entity_test');
$this->installConfig(['system', 'language']);
......
......@@ -6,6 +6,7 @@
use Drupal\Core\Url;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\user\Traits\UserCreationTrait;
/**
* Tests the path validator.
......@@ -16,16 +17,19 @@
*/
class PathValidatorTest extends KernelTestBase {
use UserCreationTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['path', 'entity_test', 'user'];
public static $modules = ['path', 'entity_test', 'system', 'user'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->setUpCurrentUser();
$this->installEntitySchema('entity_test');
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment