class EntityUnitTestBase
Defines an abstract test base for entity unit tests.
Hierarchy
- class \Drupal\simpletest\TestBase uses \Drupal\Tests\AssertHelperTrait, \Drupal\Core\Test\TestSetupTrait, \Drupal\Tests\RandomGeneratorTrait, \Drupal\Tests\Traits\Core\GeneratePermutationsTrait, \Drupal\Tests\ConfigTestTrait
- class \Drupal\simpletest\KernelTestBase extends \Drupal\simpletest\TestBase uses \Drupal\simpletest\AssertContentTrait
- class \Drupal\system\Tests\Entity\EntityUnitTestBase extends \Drupal\simpletest\KernelTestBase
- class \Drupal\simpletest\KernelTestBase extends \Drupal\simpletest\TestBase uses \Drupal\simpletest\AssertContentTrait
Expanded class hierarchy of EntityUnitTestBase
Deprecated
in drupal:8.1.0 and is removed from drupal:9.0.0. Use \Drupal\KernelTests\Core\Entity\EntityKernelTestBase instead.
File
-
core/
modules/ system/ src/ Tests/ Entity/ EntityUnitTestBase.php, line 18
Namespace
Drupal\system\Tests\EntityView source
abstract class EntityUnitTestBase extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'user',
'system',
'field',
'text',
'filter',
'entity_test',
];
/**
* The entity manager service.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* A list of generated identifiers.
*
* @var array
*/
protected $generatedIds = [];
/**
* The state service.
*
* @var \Drupal\Core\State\StateInterface
*/
protected $state;
protected function setUp() {
parent::setUp();
$this->entityManager = $this->container
->get('entity.manager');
$this->state = $this->container
->get('state');
$this->installSchema('system', 'sequences');
$this->installEntitySchema('user');
$this->installEntitySchema('entity_test');
// If the concrete test sub-class installs the Node or Comment modules,
// ensure that the node and comment entity schema are created before the
// field configurations are installed. This is because the entity tables
// need to be created before the body field storage tables. This prevents
// trying to create the body field tables twice.
$class = get_class($this);
while ($class) {
if (property_exists($class, 'modules')) {
// Only check the modules, if the $modules property was not inherited.
$rp = new \ReflectionProperty($class, 'modules');
if ($rp->class == $class) {
foreach (array_intersect([
'node',
'comment',
], $class::$modules) as $module) {
$this->installEntitySchema($module);
}
if (in_array('forum', $class::$modules, TRUE)) {
// Forum module is particular about the order that dependencies are
// enabled in. The comment, node and taxonomy config and the
// taxonomy_term schema need to be installed before the forum config
// which in turn needs to be installed before field config.
$this->installConfig([
'comment',
'node',
'taxonomy',
]);
$this->installEntitySchema('taxonomy_term');
$this->installConfig([
'forum',
]);
}
}
}
$class = get_parent_class($class);
}
$this->installConfig([
'field',
]);
}
/**
* Creates a user.
*
* @param array $values
* (optional) The values used to create the entity.
* @param array $permissions
* (optional) Array of permission names to assign to user.
*
* @return \Drupal\user\Entity\User
* The created user entity.
*/
protected function createUser($values = [], $permissions = []) {
if ($permissions) {
// Create a new role and apply permissions to it.
$role = Role::create([
'id' => strtolower($this->randomMachineName(8)),
'label' => $this->randomMachineName(8),
]);
$role->save();
user_role_grant_permissions($role->id(), $permissions);
$values['roles'][] = $role->id();
}
$account = User::create($values + [
'name' => $this->randomMachineName(),
'status' => 1,
]);
$account->enforceIsNew();
$account->save();
return $account;
}
/**
* Reloads the given entity from the storage and returns it.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity to be reloaded.
*
* @return \Drupal\Core\Entity\EntityInterface
* The reloaded entity.
*/
protected function reloadEntity(EntityInterface $entity) {
$controller = $this->entityManager
->getStorage($entity->getEntityTypeId());
$controller->resetCache([
$entity->id(),
]);
return $controller->load($entity->id());
}
/**
* Returns the entity_test hook invocation info.
*
* @return array
* An associative array of arbitrary hook data keyed by hook name.
*/
protected function getHooksInfo() {
$key = 'entity_test.hooks';
$hooks = $this->state
->get($key);
$this->state
->set($key, []);
return $hooks;
}
/**
* Installs a module and refreshes services.
*
* @param string $module
* The module to install.
*/
protected function installModule($module) {
$this->enableModules([
$module,
]);
$this->refreshServices();
}
/**
* Uninstalls a module and refreshes services.
*
* @param string $module
* The module to uninstall.
*/
protected function uninstallModule($module) {
$this->disableModules([
$module,
]);
$this->refreshServices();
}
/**
* Refresh services.
*/
protected function refreshServices() {
$this->container = \Drupal::getContainer();
$this->entityManager = $this->container
->get('entity.manager');
$this->state = $this->container
->get('state');
}
/**
* Generates a random ID avoiding collisions.
*
* @param bool $string
* (optional) Whether the id should have string type. Defaults to FALSE.
*
* @return int|string
* The entity identifier.
*/
protected function generateRandomEntityId($string = FALSE) {
srand(time());
do {
// 0x7FFFFFFF is the maximum allowed value for integers that works for all
// Drupal supported databases and is known to work for other databases
// like SQL Server 2014 and Oracle 10 too.
$id = $string ? $this->randomMachineName() : mt_rand(1, 0x7fffffff);
} while (isset($this->generatedIds[$id]));
$this->generatedIds[$id] = $id;
return $id;
}
}
Members
Title Sort descending | Deprecated | Modifiers | Object type | Summary | Overriden Title | Overrides |
---|---|---|---|---|---|---|
AssertHelperTrait::castSafeStrings | protected static | function | Casts MarkupInterface objects into strings. | |||
ConfigTestTrait::configImporter | protected | function | Returns a ConfigImporter object to import test configuration. | |||
ConfigTestTrait::copyConfig | protected | function | Copies configuration objects from source storage to target storage. | |||
EntityUnitTestBase::$entityManager | protected | property | The entity manager service. | |||
EntityUnitTestBase::$generatedIds | protected | property | A list of generated identifiers. | |||
EntityUnitTestBase::$modules | public static | property | Modules to enable. | Overrides KernelTestBase::$modules | ||
EntityUnitTestBase::$state | protected | property | The state service. | |||
EntityUnitTestBase::createUser | protected | function | Creates a user. | |||
EntityUnitTestBase::generateRandomEntityId | protected | function | Generates a random ID avoiding collisions. | |||
EntityUnitTestBase::getHooksInfo | protected | function | Returns the entity_test hook invocation info. | |||
EntityUnitTestBase::installModule | protected | function | Installs a module and refreshes services. | |||
EntityUnitTestBase::refreshServices | protected | function | Refresh services. | |||
EntityUnitTestBase::reloadEntity | protected | function | Reloads the given entity from the storage and returns it. | |||
EntityUnitTestBase::setUp | protected | function | Performs setup tasks before each individual test method is run. | Overrides KernelTestBase::setUp | ||
EntityUnitTestBase::uninstallModule | protected | function | Uninstalls a module and refreshes services. | |||
GeneratePermutationsTrait::generatePermutations | public static | function | Converts a list of possible parameters into a stack of permutations. | |||
KernelTestBase::$configDirectories | protected | property | The configuration directories for this test run. | |||
KernelTestBase::$keyValueFactory | protected | property | A KeyValueMemoryFactory instance to use when building the container. | |||
KernelTestBase::$moduleFiles | private | property | ||||
KernelTestBase::$streamWrappers | protected | property | Array of registered stream wrappers. | |||
KernelTestBase::$themeFiles | private | property | ||||
KernelTestBase::beforePrepareEnvironment | protected | function | Act on global state information before the environment is altered for a test. | Overrides TestBase::beforePrepareEnvironment | ||
KernelTestBase::containerBuild | public | function | Sets up the base service container for this test. | |||
KernelTestBase::defaultLanguageData | protected | function | Provides the data for setting the default language on the container. | |||
KernelTestBase::disableModules | protected | function | Disables modules for this test. | |||
KernelTestBase::enableModules | protected | function | Enables modules for this test. | |||
KernelTestBase::installConfig | protected | function | Installs default configuration for a given list of modules. | |||
KernelTestBase::installEntitySchema | protected | function | Installs the storage schema for a specific entity type. | |||
KernelTestBase::installSchema | protected | function | Installs a specific table from a module schema definition. | |||
KernelTestBase::prepareConfigDirectories | protected | function | Create and set new configuration directories. | |||
KernelTestBase::registerStreamWrapper | protected | function | Registers a stream wrapper for this test. | |||
KernelTestBase::render | protected | function | Renders a render array. | |||
KernelTestBase::tearDown | protected | function | Performs cleanup tasks after each individual test method has been run. | Overrides TestBase::tearDown | 1 | |
KernelTestBase::__construct | public | function | Constructor for Test. | Overrides TestBase::__construct | ||
RandomGeneratorTrait::$randomGenerator | protected | property | The random generator. | |||
RandomGeneratorTrait::getRandomGenerator | protected | function | Gets the random generator for the utility methods. | |||
RandomGeneratorTrait::randomMachineName | protected | function | Generates a unique random string containing letters and numbers. | 1 | ||
RandomGeneratorTrait::randomObject | public | function | Generates a random PHP object. | |||
RandomGeneratorTrait::randomString | public | function | Generates a pseudo-random string of ASCII characters of codes 32 to 126. | |||
RandomGeneratorTrait::randomStringValidate | public | function | Callback for random string validation. | |||
StorageCopyTrait::replaceStorageContents | protected static | function | Copy the configuration from one storage to another and remove stale items. | |||
TestBase::$assertions | protected | property | Assertions thrown in that test case. | |||
TestBase::$configImporter | protected | property | The config importer that can used in a test. | |||
TestBase::$databasePrefix | protected | property | The database prefix of this test run. | |||
TestBase::$dieOnFail | public | property | Whether to die in case any test assertion fails. | |||
TestBase::$httpAuthCredentials | protected | property | HTTP authentication credentials (<username>:<password>). | |||
TestBase::$httpAuthMethod | protected | property | HTTP authentication method (specified as a CURLAUTH_* constant). | |||
TestBase::$originalConf | protected | property | The original configuration (variables), if available. | |||
TestBase::$originalConfig | protected | property | The original configuration (variables). | |||
TestBase::$originalConfigDirectories | protected | property | The original configuration directories. | |||
TestBase::$originalContainer | protected | property | The original container. | |||
TestBase::$originalFileDirectory | protected | property | The original file directory, before it was changed for testing purposes. | |||
TestBase::$originalLanguage | protected | property | The original language. | |||
TestBase::$originalPrefix | protected | property | The original database prefix when running inside Simpletest. | |||
TestBase::$originalSessionName | protected | property | The name of the session cookie of the test-runner. | |||
TestBase::$originalSettings | protected | property | The settings array. | |||
TestBase::$originalShutdownCallbacks | protected | property | The original array of shutdown function callbacks. | 1 | ||
TestBase::$originalUser | protected | property | The original user, before testing began. | 1 | ||
TestBase::$results | public | property | Current results of this test case. | |||
TestBase::$skipClasses | protected | property | This class is skipped when looking for the source of an assertion. | |||
TestBase::$timeLimit | protected | property | Time limit for the test. | |||
TestBase::$translationFilesDirectory | protected | property | The translation file directory for the test environment. | |||
TestBase::$verbose | public | property | TRUE if verbose debugging is enabled. | |||
TestBase::$verboseClassName | protected | property | Safe class name for use in verbose output filenames. | |||
TestBase::$verboseDirectory | protected | property | Directory where verbose output files are put. | |||
TestBase::$verboseDirectoryUrl | protected | property | URL to the verbose output file directory. | |||
TestBase::$verboseId | protected | property | Incrementing identifier for verbose output filenames. | |||
TestBase::assert | protected | function | Internal helper: stores the assert. | |||
TestBase::assertEqual | protected | function | Check to see if two values are equal. | |||
TestBase::assertErrorLogged | protected | function | Asserts that a specific error has been logged to the PHP error log. | |||
TestBase::assertFalse | protected | function | Check to see if a value is false. | |||
TestBase::assertIdentical | protected | function | Check to see if two values are identical. | |||
TestBase::assertIdenticalObject | protected | function | Checks to see if two objects are identical. | |||
TestBase::assertNoErrorsLogged | protected | function | Asserts that no errors have been logged to the PHP error.log thus far. | |||
TestBase::assertNotEqual | protected | function | Check to see if two values are not equal. | |||
TestBase::assertNotIdentical | protected | function | Check to see if two values are not identical. | |||
TestBase::assertNotNull | protected | function | Check to see if a value is not NULL. | |||
TestBase::assertNull | protected | function | Check to see if a value is NULL. | |||
TestBase::assertTrue | protected | function | Check to see if a value is not false. | |||
TestBase::checkRequirements | protected | function | Checks the matching requirements for Test. | 1 | ||
TestBase::checkTestHierarchyMismatch | public | function | Fail the test if it belongs to a PHPUnit-based framework. | |||
TestBase::config | protected | function | Configuration accessor for tests. Returns non-overridden configuration. | |||
TestBase::deleteAssert | public static | function | Delete an assertion record by message ID. | |||
TestBase::error | protected | function | Fire an error assertion. | 1 | ||
TestBase::errorHandler | public | function | Handle errors during test runs. | |||
TestBase::exceptionHandler | protected | function | Handle exceptions. | |||
TestBase::fail | protected | function | Fire an assertion that is always negative. | |||
TestBase::filePreDeleteCallback | public static | function | Ensures test files are deletable. | |||
TestBase::getAssertionCall | protected | function | Cycles through backtrace until the first non-assertion method is found. | |||
TestBase::getDatabasePrefix | public | function | Gets the database prefix. | |||
TestBase::getTempFilesDirectory | public | function | Gets the temporary files directory. | |||
TestBase::insertAssert | Deprecated | public static | function | Store an assertion from outside the testing context. | 1 | |
TestBase::pass | protected | function | Fire an assertion that is always positive. | |||
TestBase::prepareDatabasePrefix | private | function | Generates a database prefix for running tests. | Overrides TestSetupTrait::prepareDatabasePrefix | ||
TestBase::prepareEnvironment | private | function | Prepares the current environment for running the test. | |||
TestBase::restoreEnvironment | private | function | Cleans up the test environment and restores the original environment. | |||
TestBase::run | public | function | Run all tests in this class. | 2 | ||
TestBase::settingsSet | protected | function | Changes in memory settings. | |||
TestBase::storeAssertion | protected | function | Helper method to store an assertion record in the configured database. | 1 | ||
TestBase::verbose | protected | function | Logs a verbose message in a text file. | |||
TestSetupTrait::$configSchemaCheckerExclusions | protected static | property | An array of config object names that are excluded from schema checking. | |||
TestSetupTrait::$container | protected | property | The dependency injection container used in the test. | |||
TestSetupTrait::$kernel | protected | property | The DrupalKernel instance used in the test. | |||
TestSetupTrait::$originalSite | protected | property | The site directory of the original parent site. | |||
TestSetupTrait::$privateFilesDirectory | protected | property | The private file directory for the test environment. | |||
TestSetupTrait::$publicFilesDirectory | protected | property | The public file directory for the test environment. | |||
TestSetupTrait::$siteDirectory | protected | property | The site directory of this test run. | |||
TestSetupTrait::$strictConfigSchema | protected | property | Set to TRUE to strict check all configuration saved. | 2 | ||
TestSetupTrait::$tempFilesDirectory | protected | property | The temporary file directory for the test environment. | |||
TestSetupTrait::$testId | protected | property | The test run ID. | |||
TestSetupTrait::changeDatabasePrefix | protected | function | Changes the database connection to the prefixed one. | |||
TestSetupTrait::getConfigSchemaExclusions | protected | function | Gets the config schema exclusions for this test. | |||
TestSetupTrait::getDatabaseConnection | public static | function | Returns the database connection to the site running Simpletest. |
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.