abstract class KernelTestBase extends TestBase (View source)

deprecated in drupal:8.0.0 and is removed from drupal:9.0.0. Use \Drupal\KernelTests\KernelTestBase instead.

Base class for functional integration tests.

This base class should be useful for testing some types of integrations which don't require the overhead of a fully-installed Drupal instance, but which have many dependencies on parts of Drupal which can't or shouldn't be mocked.

This base class partially boots a fixture Drupal. The state of the fixture Drupal is comparable to the state of a system during the early part of the installation process.

Tests extending this base class can access services and the database, but the system is initially empty. This Drupal runs in a minimal mocked filesystem which operates within vfsStream.

Modules specified in the $modules property are added to the service container for each test. The module/hook system is functional. Additional modules needed in a test should override $modules. Modules specified in this way will be added to those specified in superclasses.

Unlike \Drupal\Tests\BrowserTestBase, the modules are not installed. They are loaded such that their services and hooks are available, but the install process has not been performed.

Other modules can be made available in this way using KernelTestBase::enableModules().

Some modules can be brought into a fully-installed state using KernelTestBase::installConfig(), KernelTestBase::installSchema(), and KernelTestBase::installEntitySchema(). Alternately, tests which need modules to be fully installed could inherit from \Drupal\Tests\BrowserTestBase.

Traits

AssertContentTrait deprecated

Provides test methods to assert content.

AssertContentTrait
AssertHelperTrait

Provides a trait for shared test setup functionality.

RandomGeneratorTrait
GeneratePermutationsTrait
ConfigTestTrait

Properties

static protected string[] $configSchemaCheckerExclusions

An array of config object names that are excluded from schema checking.

from  TestSetupTrait
protected ContainerInterface $container

The dependency injection container used in the test.

from  TestSetupTrait
protected string $siteDirectory

The site directory of this test run.

from  TestSetupTrait
protected string $publicFilesDirectory

The public file directory for the test environment.

from  TestSetupTrait
protected string $originalSite

The site directory of the original parent site.

from  TestSetupTrait
protected string $privateFilesDirectory

The private file directory for the test environment.

from  TestSetupTrait
protected bool $strictConfigSchema

Set to TRUE to strict check all configuration saved.

from  TestSetupTrait
protected DrupalKernel $kernel

The DrupalKernel instance used in the test.

from  TestSetupTrait
protected string $tempFilesDirectory

The temporary file directory for the test environment.

from  TestSetupTrait
protected string $testId

The test run ID.

from  TestSetupTrait
protected string $databasePrefix

The database prefix of this test run.

from  TestBase
protected int $timeLimit

Time limit for the test.

from  TestBase
array $results

Current results of this test case.

from  TestBase
protected array $assertions

Assertions thrown in that test case.

from  TestBase
protected $skipClasses

This class is skipped when looking for the source of an assertion.

from  TestBase
bool $verbose

TRUE if verbose debugging is enabled.

from  TestBase
protected int $verboseId

Incrementing identifier for verbose output filenames.

from  TestBase
protected string $verboseClassName

Safe class name for use in verbose output filenames.

from  TestBase
protected string $verboseDirectory

Directory where verbose output files are put.

from  TestBase
protected string $verboseDirectoryUrl

URL to the verbose output file directory.

from  TestBase
protected string $originalConf

The original configuration (variables), if available.

from  TestBase
protected string $originalConfig

The original configuration (variables).

from  TestBase
protected array $originalConfigDirectories

The original configuration directories.

from  TestBase
protected ContainerInterface $originalContainer

The original container.

from  TestBase
protected string $originalFileDirectory

The original file directory, before it was changed for testing purposes.

from  TestBase
protected LanguageInterface $originalLanguage

The original language.

from  TestBase
protected string $originalPrefix

The original database prefix when running inside Simpletest.

from  TestBase
protected string $originalSessionName

The name of the session cookie of the test-runner.

from  TestBase
protected array $originalSettings

The settings array.

from  TestBase
protected array $originalShutdownCallbacks

The original array of shutdown function callbacks.

from  TestBase
protected AccountProxyInterface $originalUser

The original user, before testing began.

from  TestBase
protected string $translationFilesDirectory

The translation file directory for the test environment.

from  TestBase
bool $dieOnFail

Whether to die in case any test assertion fails.

from  TestBase
protected ConfigImporter $configImporter

The config importer that can used in a test.

from  TestBase
protected int $httpAuthMethod

HTTP authentication method (specified as a CURLAUTH_* constant).

from  TestBase
protected string $httpAuthCredentials

HTTP authentication credentials (:).

from  TestBase
static array $modules

Modules to enable.

protected array $configDirectories

The configuration directories for this test run.

protected KeyValueMemoryFactory $keyValueFactory

A KeyValueMemoryFactory instance to use when building the container.

protected array $streamWrappers

Array of registered stream wrappers.

Methods

static Connection
getDatabaseConnection()

Returns the database connection to the site running Simpletest.

prepareDatabasePrefix()

Generates a database prefix for running tests.

changeDatabasePrefix()

Changes the database connection to the prefixed one.

string[]
getConfigSchemaExclusions()

Gets the config schema exclusions for this test.

__construct($test_id = NULL)

Constructor for Test.

checkTestHierarchyMismatch()

Fail the test if it belongs to a PHPUnit-based framework.

from  TestBase
setUp()

Performs setup tasks before each individual test method is run.

array
checkRequirements()

Checks the matching requirements for Test.

from  TestBase
storeAssertion(array $assertion)

Helper method to store an assertion record in the configured database.

from  TestBase
assert($status, string|MarkupInterface $message = '', $group = 'Other', array $caller = NULL)

Internal helper: stores the assert.

from  TestBase
static Message
insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = []) deprecated

Store an assertion from outside the testing context.

from  TestBase
static true
deleteAssert($message_id)

Delete an assertion record by message ID.

from  TestBase
array
getAssertionCall()

Cycles through backtrace until the first non-assertion method is found.

from  TestBase
true
assertTrue($value, $message = '', $group = 'Other')

Check to see if a value is not false.

from  TestBase
true
assertFalse($value, $message = '', $group = 'Other')

Check to see if a value is false.

from  TestBase
true
assertNull($value, $message = '', $group = 'Other')

Check to see if a value is NULL.

from  TestBase
true
assertNotNull($value, $message = '', $group = 'Other')

Check to see if a value is not NULL.

from  TestBase
true
assertEqual($first, $second, $message = '', $group = 'Other')

Check to see if two values are equal.

from  TestBase
true
assertNotEqual($first, $second, $message = '', $group = 'Other')

Check to see if two values are not equal.

from  TestBase
true
assertIdentical($first, $second, $message = '', $group = 'Other')

Check to see if two values are identical.

from  TestBase
true
assertNotIdentical($first, $second, $message = '', $group = 'Other')

Check to see if two values are not identical.

from  TestBase
true
assertIdenticalObject(object $object1, object $object2, $message = '', $group = 'Other')

Checks to see if two objects are identical.

from  TestBase
bool
assertNoErrorsLogged()

Asserts that no errors have been logged to the PHP error.log thus far.

from  TestBase
bool
assertErrorLogged(string $error_message)

Asserts that a specific error has been logged to the PHP error log.

from  TestBase
pass($message = NULL, $group = 'Other')

Fire an assertion that is always positive.

from  TestBase
fail($message = NULL, $group = 'Other')

Fire an assertion that is always negative.

from  TestBase
error($message = '', $group = 'Other', array $caller = NULL)

Fire an error assertion.

from  TestBase
verbose($message)

Logs a verbose message in a text file.

from  TestBase
run(array $methods = [])

Run all tests in this class.

from  TestBase
beforePrepareEnvironment()

Act on global state information before the environment is altered for a test.

tearDown()

Performs cleanup tasks after each individual test method has been run.

errorHandler($severity, $message, $file = NULL, $line = NULL)

Handle errors during test runs.

from  TestBase
exceptionHandler($exception)

Handle exceptions.

from  TestBase
settingsSet($name, $value)

Changes in memory settings.

from  TestBase
static 
filePreDeleteCallback($path)

Ensures test files are deletable.

from  TestBase
config($name)

Configuration accessor for tests. Returns non-overridden configuration.

from  TestBase
string
getDatabasePrefix()

Gets the database prefix.

from  TestBase
string
getTempFilesDirectory()

Gets the temporary files directory.

from  TestBase
string
prepareConfigDirectories()

Create and set new configuration directories.

containerBuild(ContainerBuilder $container)

Sets up the base service container for this test.

array
defaultLanguageData()

Provides the data for setting the default language on the container.

installConfig(array $modules)

Installs default configuration for a given list of modules.

installSchema(string $module, string|array $tables)

Installs a specific table from a module schema definition.

installEntitySchema(string $entity_type_id)

Installs the storage schema for a specific entity type.

enableModules(array $modules)

Enables modules for this test.

disableModules(array $modules)

Disables modules for this test.

registerStreamWrapper(string $scheme, string $class, int $type = StreamWrapperInterface::NORMAL)

Registers a stream wrapper for this test.

string
render(array $elements)

Renders a render array.

Details

static Connection getDatabaseConnection()

Returns the database connection to the site running Simpletest.

Return Value

Connection

The database connection to use for inserting assertions.

protected prepareDatabasePrefix()

Generates a database prefix for running tests.

The database prefix is used by prepareEnvironment() to setup a public files directory for the test to be run, which also contains the PHP error log, which is written to in case of a fatal error. Since that directory is based on the database prefix, all tests (even unit tests) need to have one, in order to access and read the error log.

The generated database table prefix is used for the Drupal installation being performed for the test. It is also used as user agent HTTP header value by the cURL-based browser of WebTestBase, which is sent to the Drupal installation of the test. During early Drupal bootstrap, the user agent HTTP header is parsed, and if it matches, all database queries use the database table prefix that has been generated here.

See also

\Drupal\Tests\BrowserTestBase::prepareEnvironment()
WebTestBase::curlInitialize
\Drupal\simpletest\TestBase::prepareEnvironment()
drupal_valid_test_ua()

protected changeDatabasePrefix()

Changes the database connection to the prefixed one.

protected string[] getConfigSchemaExclusions()

Gets the config schema exclusions for this test.

Return Value

string[]

An array of config object names that are excluded from schema checking.

__construct($test_id = NULL)

Constructor for Test.

Parameters

$test_id

Tests with the same id are reported together.

checkTestHierarchyMismatch()

Fail the test if it belongs to a PHPUnit-based framework.

This would probably be caused by automated test conversions such as those in https://www.drupal.org/project/drupal/issues/2770921.

protected setUp()

Performs setup tasks before each individual test method is run.

protected array checkRequirements()

Checks the matching requirements for Test.

Return Value

array

of errors containing a list of unmet requirements.

protected StatementInterface|int|null storeAssertion(array $assertion)

Helper method to store an assertion record in the configured database.

This method decouples database access from assertion logic.

Parameters

array $assertion

Keyed array representing an assertion, as generated by assert().

Return Value

StatementInterface|int|null

The message ID.

See also

\Drupal\simpletest\self::assert()

protected assert($status, string|MarkupInterface $message = '', $group = 'Other', array $caller = NULL)

Internal helper: stores the assert.

Parameters

$status

Can be 'pass', 'fail', 'exception', 'debug'. TRUE is a synonym for 'pass', FALSE for 'fail'.

string|MarkupInterface $message

(optional) A message to display with the assertion. Do not translate messages: use \Drupal\Component\Render\FormattableMarkup to embed variables in the message text, not t(). If left blank, a default message will be displayed.

$group

(optional) The group this message is in, which is displayed in a column in test output. Use 'Debug' to indicate this is debugging output. Do not translate this string. Defaults to 'Other'; most tests do not override this default.

array $caller

By default, the assert comes from a function whose name starts with 'test'. Instead, you can specify where this assert originates from by passing in an associative array as $caller. Key 'file' is the name of the source file, 'line' is the line number and 'function' is the caller function itself.

static Message insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = []) deprecated

deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use simpletest_insert_assert() instead.

Store an assertion from outside the testing context.

This is useful for inserting assertions that can only be recorded after the test case has been destroyed, such as PHP fatal errors. The caller information is not automatically gathered since the caller is most likely inserting the assertion on behalf of other code. In all other respects the method behaves just like \Drupal\simpletest\TestBase::assert() in terms of storing the assertion.

Parameters

$test_id
$test_class
$status
$message
$group
array $caller

Return Value

Message

ID of the stored assertion.

See also

https://www.drupal.org/node/3030340
TestBase::assert
TestBase::deleteAssert

static true deleteAssert($message_id)

Delete an assertion record by message ID.

Parameters

$message_id

Message ID of the assertion to delete.

Return Value

true

if the assertion was deleted, FALSE otherwise.

See also

TestBase::insertAssert

protected array getAssertionCall()

Cycles through backtrace until the first non-assertion method is found.

Return Value

array

representing the true caller.

protected true assertTrue($value, $message = '', $group = 'Other')

Check to see if a value is not false.

False values are: empty string, 0, NULL, and FALSE.

Parameters

$value

The value on which the assertion is to be done.

$message

(optional) A message to display with the assertion. Do not translate messages: use \Drupal\Component\Render\FormattableMarkup to embed variables in the message text, not t(). If left blank, a default message will be displayed.

$group

(optional) The group this message is in, which is displayed in a column in test output. Use 'Debug' to indicate this is debugging output. Do not translate this string. Defaults to 'Other'; most tests do not override this default.

Return Value

true

if the assertion succeeded, FALSE otherwise.

protected true assertFalse($value, $message = '', $group = 'Other')

Check to see if a value is false.

False values are: empty string, 0, NULL, and FALSE.

Parameters

$value

The value on which the assertion is to be done.

$message

(optional) A message to display with the assertion. Do not translate messages: use \Drupal\Component\Render\FormattableMarkup to embed variables in the message text, not t(). If left blank, a default message will be displayed.

$group

(optional) The group this message is in, which is displayed in a column in test output. Use 'Debug' to indicate this is debugging output. Do not translate this string. Defaults to 'Other'; most tests do not override this default.

Return Value

true

if the assertion succeeded, FALSE otherwise.

protected true assertNull($value, $message = '', $group = 'Other')

Check to see if a value is NULL.

Parameters

$value

The value on which the assertion is to be done.

$message

(optional) A message to display with the assertion. Do not translate messages: use \Drupal\Component\Render\FormattableMarkup to embed variables in the message text, not t(). If left blank, a default message will be displayed.

$group

(optional) The group this message is in, which is displayed in a column in test output. Use 'Debug' to indicate this is debugging output. Do not translate this string. Defaults to 'Other'; most tests do not override this default.

Return Value

true

if the assertion succeeded, FALSE otherwise.

protected true assertNotNull($value, $message = '', $group = 'Other')

Check to see if a value is not NULL.

Parameters

$value

The value on which the assertion is to be done.

$message

(optional) A message to display with the assertion. Do not translate messages: use \Drupal\Component\Render\FormattableMarkup to embed variables in the message text, not t(). If left blank, a default message will be displayed.

$group

(optional) The group this message is in, which is displayed in a column in test output. Use 'Debug' to indicate this is debugging output. Do not translate this string. Defaults to 'Other'; most tests do not override this default.

Return Value

true

if the assertion succeeded, FALSE otherwise.

protected true assertEqual($first, $second, $message = '', $group = 'Other')

Check to see if two values are equal.

Parameters

$first

The first value to check.

$second

The second value to check.

$message

(optional) A message to display with the assertion. Do not translate messages: use \Drupal\Component\Render\FormattableMarkup to embed variables in the message text, not t(). If left blank, a default message will be displayed.

$group

(optional) The group this message is in, which is displayed in a column in test output. Use 'Debug' to indicate this is debugging output. Do not translate this string. Defaults to 'Other'; most tests do not override this default.

Return Value

true

if the assertion succeeded, FALSE otherwise.

protected true assertNotEqual($first, $second, $message = '', $group = 'Other')

Check to see if two values are not equal.

Parameters

$first

The first value to check.

$second

The second value to check.

$message

(optional) A message to display with the assertion. Do not translate messages: use \Drupal\Component\Render\FormattableMarkup to embed variables in the message text, not t(). If left blank, a default message will be displayed.

$group

(optional) The group this message is in, which is displayed in a column in test output. Use 'Debug' to indicate this is debugging output. Do not translate this string. Defaults to 'Other'; most tests do not override this default.

Return Value

true

if the assertion succeeded, FALSE otherwise.

protected true assertIdentical($first, $second, $message = '', $group = 'Other')

Check to see if two values are identical.

Parameters

$first

The first value to check.

$second

The second value to check.

$message

(optional) A message to display with the assertion. Do not translate messages: use \Drupal\Component\Render\FormattableMarkup to embed variables in the message text, not t(). If left blank, a default message will be displayed.

$group

(optional) The group this message is in, which is displayed in a column in test output. Use 'Debug' to indicate this is debugging output. Do not translate this string. Defaults to 'Other'; most tests do not override this default.

Return Value

true

if the assertion succeeded, FALSE otherwise.

protected true assertNotIdentical($first, $second, $message = '', $group = 'Other')

Check to see if two values are not identical.

Parameters

$first

The first value to check.

$second

The second value to check.

$message

(optional) A message to display with the assertion. Do not translate messages: use \Drupal\Component\Render\FormattableMarkup to embed variables in the message text, not t(). If left blank, a default message will be displayed.

$group

(optional) The group this message is in, which is displayed in a column in test output. Use 'Debug' to indicate this is debugging output. Do not translate this string. Defaults to 'Other'; most tests do not override this default.

Return Value

true

if the assertion succeeded, FALSE otherwise.

protected true assertIdenticalObject(object $object1, object $object2, $message = '', $group = 'Other')

Checks to see if two objects are identical.

Parameters

object $object1

The first object to check.

object $object2

The second object to check.

$message

(optional) A message to display with the assertion. Do not translate messages: use \Drupal\Component\Render\FormattableMarkup to embed variables in the message text, not t(). If left blank, a default message will be displayed.

$group

(optional) The group this message is in, which is displayed in a column in test output. Use 'Debug' to indicate this is debugging output. Do not translate this string. Defaults to 'Other'; most tests do not override this default.

Return Value

true

if the assertion succeeded, FALSE otherwise.

protected bool assertNoErrorsLogged()

Asserts that no errors have been logged to the PHP error.log thus far.

Return Value

bool

TRUE if the assertion succeeded, FALSE otherwise.

See also

\Drupal\simpletest\TestBase::prepareEnvironment()
\Drupal\Core\DrupalKernel::bootConfiguration()

protected bool assertErrorLogged(string $error_message)

Asserts that a specific error has been logged to the PHP error log.

Parameters

string $error_message

The expected error message.

Return Value

bool

TRUE if the assertion succeeded, FALSE otherwise.

See also

\Drupal\simpletest\TestBase::prepareEnvironment()
\Drupal\Core\DrupalKernel::bootConfiguration()

protected pass($message = NULL, $group = 'Other')

Fire an assertion that is always positive.

Parameters

$message

(optional) A message to display with the assertion. Do not translate messages: use \Drupal\Component\Render\FormattableMarkup to embed variables in the message text, not t(). If left blank, a default message will be displayed.

$group

(optional) The group this message is in, which is displayed in a column in test output. Use 'Debug' to indicate this is debugging output. Do not translate this string. Defaults to 'Other'; most tests do not override this default.

protected fail($message = NULL, $group = 'Other')

Fire an assertion that is always negative.

Parameters

$message

(optional) A message to display with the assertion. Do not translate messages: use \Drupal\Component\Render\FormattableMarkup to embed variables in the message text, not t(). If left blank, a default message will be displayed.

$group

(optional) The group this message is in, which is displayed in a column in test output. Use 'Debug' to indicate this is debugging output. Do not translate this string. Defaults to 'Other'; most tests do not override this default.

protected error($message = '', $group = 'Other', array $caller = NULL)

Fire an error assertion.

Parameters

$message

(optional) A message to display with the assertion. Do not translate messages: use \Drupal\Component\Render\FormattableMarkup to embed variables in the message text, not t(). If left blank, a default message will be displayed.

$group

(optional) The group this message is in, which is displayed in a column in test output. Use 'Debug' to indicate this is debugging output. Do not translate this string. Defaults to 'Other'; most tests do not override this default.

array $caller

The caller of the error.

protected verbose($message)

Logs a verbose message in a text file.

The link to the verbose message will be placed in the test results as a passing assertion with the text '[verbose message]'.

Parameters

$message

The verbose message to be stored.

See also

simpletest_verbose()

run(array $methods = [])

Run all tests in this class.

Regardless of whether $methods are passed or not, only method names starting with "test" are executed.

Parameters

array $methods

(optional) A list of method names in the test case class to run; e.g., array('testFoo', 'testBar'). By default, all methods of the class are taken into account, but it can be useful to only run a few selected test methods during debugging.

protected beforePrepareEnvironment()

Act on global state information before the environment is altered for a test.

Allows e.g. KernelTestBase to prime system/extension info from the parent site (and inject it into the test environment so as to improve performance).

protected tearDown()

Performs cleanup tasks after each individual test method has been run.

errorHandler($severity, $message, $file = NULL, $line = NULL)

Handle errors during test runs.

Because this is registered in set_error_handler(), it has to be public.

Parameters

$severity
$message
$file
$line

See also

set_error_handler

protected exceptionHandler($exception)

Handle exceptions.

Parameters

$exception

See also

set_exception_handler

protected settingsSet($name, $value)

Changes in memory settings.

Parameters

$name

The name of the setting to return.

$value

The value of the setting.

See also

Settings::get

static filePreDeleteCallback($path)

Ensures test files are deletable.

Some tests chmod generated files to be read only. During TestBase::restoreEnvironment() and other cleanup operations, these files need to get deleted too.

Parameters

$path

See also

FileSystemInterface::deleteRecursive

protected Config config($name)

Configuration accessor for tests. Returns non-overridden configuration.

Parameters

$name

Configuration name.

Return Value

Config

The configuration object with original configuration data.

string getDatabasePrefix()

Gets the database prefix.

Return Value

string

The database prefix

string getTempFilesDirectory()

Gets the temporary files directory.

Return Value

string

The temporary files directory.

protected string prepareConfigDirectories()

Create and set new configuration directories.

Return Value

string

The config sync directory path.

Exceptions

RuntimeException

See also

\Drupal\Core\Site\Settings::getConfigDirectory()

containerBuild(ContainerBuilder $container)

Sets up the base service container for this test.

Extend this method in your test to register additional service overrides that need to persist a DrupalKernel reboot. This method is called whenever the kernel is rebuilt.

protected array defaultLanguageData()

Provides the data for setting the default language on the container.

Return Value

array

The data array for the default language.

protected installConfig(array $modules)

Installs default configuration for a given list of modules.

Parameters

array $modules

A list of modules for which to install default configuration.

Exceptions

RuntimeException

protected installSchema(string $module, string|array $tables)

Installs a specific table from a module schema definition.

Parameters

string $module

The name of the module that defines the table's schema.

string|array $tables

The name or an array of the names of the tables to install.

Exceptions

RuntimeException

protected installEntitySchema(string $entity_type_id)

Installs the storage schema for a specific entity type.

Parameters

string $entity_type_id

The ID of the entity type.

protected enableModules(array $modules)

Enables modules for this test.

To install test modules outside of the testing environment, add

Parameters

array $modules

A list of modules to enable. Dependencies are not resolved; i.e., multiple modules have to be specified with dependent modules first. The new modules are only added to the active module list and loaded.

protected disableModules(array $modules)

Disables modules for this test.

Parameters

array $modules

A list of modules to disable. Dependencies are not resolved; i.e., multiple modules have to be specified with dependent modules first. Code of previously active modules is still loaded. The modules are only removed from the active module list.

protected registerStreamWrapper(string $scheme, string $class, int $type = StreamWrapperInterface::NORMAL)

Registers a stream wrapper for this test.

Parameters

string $scheme

The scheme to register.

string $class

The fully qualified class name to register.

int $type

The Drupal Stream Wrapper API type. Defaults to StreamWrapperInterface::NORMAL.

protected string render(array $elements)

Renders a render array.

Parameters

array $elements

The elements to render.

Return Value

string

The rendered string output (typically HTML).