abstract class StatisticsTestBase extends WebTestBase (View source)

deprecated in drupal:8.?.? and is removed from drupal:9.0.0. Use \Drupal\Tests\statistics\Functional\StatisticsTestBase instead.

Defines a base class for testing the Statistics module.

Traits

Defines a trait for shared functional test setup functionality.

AssertContentTrait
TestFileCreationTrait

Provides test assertions for testing page-level cache contexts & tags.

BlockCreationTrait
ContentTypeCreationTrait
CronRunTrait

Provides methods for testing emails sent during test runs.

NodeCreationTrait
UserCreationTrait
XdebugRequestTrait
EntityViewTrait
SessionTestTrait

Provides a method to refresh in-memory configuration and state information.

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 shutdown handlers array, before it was cleaned for testing.

from  WebTestBase
protected object $originalUser

The original user, before it was changed to a clean uid = 1 for testing.

from  WebTestBase
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
protected AccountInterface $rootUser

The "#1" admin user.

from  FunctionalTestSetupTrait
protected Classloader $classLoader

The class loader to use for installation and initialization of setup.

from  FunctionalTestSetupTrait
protected deprecated $configDirectories

The config directories used in this test.

from  FunctionalTestSetupTrait
protected bool $apcuEnsureUniquePrefix

The flag to set 'apcu_ensure_unique_prefix' setting.

from  FunctionalTestSetupTrait
protected string $profile

The profile to install as a basis for testing.

from  WebTestBase
protected string $url

The URL currently loaded in the internal browser.

from  WebTestBase
protected resource $curlHandle

The handle of the current cURL connection.

from  WebTestBase
protected bool $assertAjaxHeader

Whether or not to assert the presence of the X-Drupal-Ajax-Token.

from  WebTestBase
protected array $headers

The headers of the page currently loaded in the internal browser.

from  WebTestBase
protected array $cookies

The cookies of the page currently loaded in the internal browser.

from  WebTestBase
protected bool $dumpHeaders

Indicates that headers should be dumped if verbose output is enabled.

from  WebTestBase
protected AccountInterface|bool $loggedInUser

The current user logged in using the internal browser.

from  WebTestBase
protected $cookieFile

The current cookie file used by cURL.

from  WebTestBase
protected $additionalCurlOptions

Additional cURL options.

from  WebTestBase
protected array $originalBatch

The original batch, before it was changed for testing purposes.

from  WebTestBase
protected $sessionId

The current session ID, if available.

from  WebTestBase
protected int $maximumRedirects

The maximum number of redirects to follow when handling responses.

from  WebTestBase
protected int $redirectCount

The number of redirects followed during the handling of a request.

from  WebTestBase
protected null|int $maximumMetaRefreshCount

The number of meta refresh redirects to follow, or NULL if unlimited.

from  WebTestBase
protected int $metaRefreshCount

The number of meta refresh redirects followed during ::drupalGet().

from  WebTestBase
protected array $curlCookies

Cookies to set on curl requests.

from  WebTestBase
protected array $customTranslations

An array of custom translations suitable for drupal_rewrite_settings().

from  WebTestBase
static array $modules

Modules to enable.

protected UserInterface $blockingUser

User with permissions to ban IP's.

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 \Drupal\simpletest\WebTestBase.

checkTestHierarchyMismatch()

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

from  TestBase
setUp()

Sets up a Drupal site for running functional and integration tests.

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.

from  TestBase
tearDown()

Cleans up after testing.

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
refreshVariables()

Refreshes in-memory configuration and state information.

prepareSettings()

Prepares site settings and services before installation.

writeSettings(array $settings)

Rewrites the settings.php file of the test site.

setContainerParameter(string $name, string $value)

Changes parameters in the services.yml file.

rebuildContainer()

Rebuilds \Drupal::getContainer().

resetAll()

Resets all data structures after having enabled new modules.

Request
prepareRequestForGenerator(bool $clean_urls = TRUE, array $override_server_vars = [])

Creates a mock request and sets it on the generator.

doInstall()

Execute the non-interactive installer.

initSettings()

Initialize settings created during install.

initConfig(ContainerInterface $container)

Initialize various configurations post-installation.

initUserSession()

Initializes user 1 for the site to be installed.

ContainerInterface
initKernel(Request $request)

Initializes the kernel after installation.

installDefaultThemeFromClassProperty(ContainerInterface $container)

Installs the default theme defined by static::$defaultTheme when needed.

installModulesFromClassProperty(ContainerInterface $container)

Install modules defined by static::$modules.

rebuildAll()

Resets and rebuilds the environment after setup.

array
installParameters()

Returns the parameters that will be used when Simpletest installs Drupal.

setupBaseUrl()

Sets up the base URL based upon the environment variable.

prepareEnvironment()

Prepares the current environment for running the test.

Tasks[]
getDatabaseTypes()

Returns all supported database driver installer objects.

string[]
getCacheHeaderValues(string $header_name)

Gets a specific header value as array.

assertCacheContext(string $expected_cache_context)

Asserts whether an expected cache context was present in the last response.

assertNoCacheContext(string $not_expected_cache_context)

Asserts that a cache context was not present in the last response.

assertPageCacheContextsAndTags(Url $url, array $expected_contexts, array $expected_tags)

Asserts page cache miss, then hit for the given URL; checks cache headers.

debugCacheTags(array $actual_tags, array $expected_tags)

Provides debug information for cache tags.

assertCacheTags(array $expected_tags, bool $include_default_tags = TRUE)

Ensures that some cache tags are present in the current response.

bool
assertCacheContexts(array $expected_contexts, string $message = NULL, bool $include_default_contexts = TRUE)

Ensures that some cache contexts are present in the current response.

assertCacheMaxAge(int $max_age)

Asserts the max age header.

array
getMails(array $filter = [])

Gets an array containing all emails sent during this test case.

bool
assertMail(string $name, string $value = '', string $message = '', string $group = 'Email')

Asserts that the most recently sent email message has the given value.

bool
assertMailString(string $field_name, string $string, int $email_depth, string $message = '', string $group = 'Other')

Asserts that the most recently sent email message has the string in it.

bool
assertMailPattern(string $field_name, string $regex, string $message = '', string $group = 'Other')

Asserts that the most recently sent email message has the pattern in it.

verboseEmail(int $count = 1)

Outputs to verbose the most recent $count emails sent.

assertBlockAppears(Block $block)

Checks to see whether a block appears on the page.

assertNoBlockAppears(Block $block)

Checks to see whether a block does not appears on the page.

array
findBlockInstance(Block $block)

Find a block instance on the page.

drupalLogin(AccountInterface $account)

Log in a user with the internal browser.

drupalUserIsLoggedIn(UserInterface $account)

Returns whether a given user account is logged in.

drupalLogout()

Logs a user out of the internal browser and confirms.

setBatch()

Preserve the original batch, and instantiate the test batch.

restoreBatch()

Restore the original batch.

addCustomTranslations(string $langcode, array $values)

Queues custom translations to be written to settings.php.

writeCustomTranslations()

Writes custom translations to the test site's settings.php.

curlInitialize()

Initializes the cURL connection.

The
curlExec($curl_options, $redirect = FALSE)

Initializes and executes a cURL request.

curlHeaderCallback($curlHandler, $header)

Reads headers and registers errors received from the tested site.

curlClose()

Close the cURL handler and unset the handler.

bool
isInChildSite()

Returns whether the test is being executed from within a test site.

string
drupalGet(Url|string $path, array $options = [], array $headers = [])

Retrieves a Drupal path or an absolute path.

array
drupalGetJSON(Url|string $path, array $options = [], array $headers = [])

Retrieves a Drupal path or an absolute path and JSON decodes the result.

mixed
drupalGetWithFormat(Url|string $path, string $format, array $options = [], array $headers = [])

Retrieves a Drupal path or an absolute path for a given format.

array
drupalGetAjax(Url|string $path, array $options = [], array $headers = [])

Requests a path or URL in drupal_ajax format and JSON-decodes the response.

string
drupalGetXHR(Url|string $path, array $options = [], array $headers = [])

Requests a Drupal path or an absolute path as if it is a XMLHttpRequest.

drupalPostForm(Url|string $path, $edit, $submit, array $options = [], array $headers = [], $form_html_id = NULL, $extra_post = NULL)

Executes a form submission.

An
drupalPostAjaxForm(Url|string $path, $edit, $triggering_element, $ajax_path = NULL, array $options = [], array $headers = [], $form_html_id = NULL, $ajax_settings = NULL)

Executes an Ajax form submission.

drupalProcessAjaxResponse(string $content, array $ajax_response, array $ajax_settings, array $drupal_settings)

Processes an AJAX response into current content.

The
drupalPost(string|Url $path, string $accept, array $post, array $options = [])

Perform a POST HTTP request.

string
drupalPostWithFormat(string|Url $path, string $format, array $post, array $options = [])

Performs a POST HTTP request with a specific format.

array
getAjaxPageStatePostData()

Get the Ajax page state from drupalSettings and prepare it for POSTing.

string
serializePostValues(array $post = [])

Serialize POST HTTP request values.

array
translatePostValues(array $values)

Transforms a nested array into a flat array suitable for WebTestBase::drupalPostForm().

Either
checkForMetaRefresh()

Checks for meta refresh tag and if found call drupalGet() recursively.

The
drupalHead($path, array $options = [], array $headers = [])

Retrieves only the headers for a Drupal path or an absolute path.

Submit
handleForm($post, $edit, $upload, $submit, $form)

Handles form input related to drupalPostForm().

string|bool
clickLink(string|MarkupInterface $label, int $index = 0)

Follows a link by complete name.

string|bool
clickLinkPartialName(string|MarkupInterface $label, int $index = 0)

Follows a link by partial name.

bool|string
clickLinkHelper(string|MarkupInterface $label, int $index, string $pattern)

Provides a helper for ::clickLink() and ::clickLinkPartialName().

string
getAbsoluteUrl(string $path)

Takes a path and returns an absolute path.

A
drupalGetHeaders($all_requests = FALSE)

Gets the HTTP response headers of the requested page.

The
drupalGetHeader($name, $all_requests = FALSE)

Gets the value of an HTTP response header.

bool
assertHeader(string $header, string $value, string $message = '', string $group = 'Browser')

Check if a HTTP response header exists and has the expected value.

true
assertUrl(Url|string $path, array $options = [], $message = '', $group = 'Other')

Passes if the internal browser's URL matches the given path.

Assertion
assertResponse($code, $message = '', $group = 'Browser')

Asserts the page responds with the specified response code.

Assertion
assertNoResponse($code, $message = '', $group = 'Browser')

Asserts the page did not return the specified response code.

string
buildUrl(string|Url $path, array $options = [])

Builds an a absolute URL from a system path or a URL object.

assertCacheTag(string $expected_cache_tag)

Asserts whether an expected cache tag was present in the last response.

assertNoCacheTag(string $cache_tag)

Asserts whether an expected cache tag was absent in the last response.

setHttpResponseDebugCacheabilityHeaders(bool $value = TRUE)

Enables/disables the cacheability headers.

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 \Drupal\simpletest\WebTestBase.

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()

Sets up a Drupal site for running functional and integration tests.

Installs Drupal with the installation profile specified in \Drupal\simpletest\WebTestBase::$profile into the prefixed database.

Afterwards, installs any additional modules specified in the static \Drupal\simpletest\WebTestBase::$modules property of each class in the class hierarchy.

After installation all caches are flushed and several configuration values are reset to the values of the parent site executing the test, since the default values may be incompatible with the environment in which tests are being executed.

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()

Cleans up after testing.

Deletes created files and temporary files directory, deletes the tables created by setUp(), and resets the database prefix.

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 refreshVariables()

Refreshes in-memory configuration and state information.

Useful after a page request is made that changes configuration or state in a different thread.

In other words calling a settings page with $this->drupalPostForm() with a changed value would update configuration to reflect that change, but in the thread that made the call (thread running the test) the changed values would not be picked up.

This method clears the cache and loads a fresh copy.

protected prepareSettings()

Prepares site settings and services before installation.

protected writeSettings(array $settings)

Rewrites the settings.php file of the test site.

Parameters

array $settings

An array of settings to write out, in the format expected by drupal_rewrite_settings().

See also

drupal_rewrite_settings()

protected setContainerParameter(string $name, string $value)

Changes parameters in the services.yml file.

Parameters

string $name

The name of the parameter.

string $value

The value of the parameter.

protected rebuildContainer()

Rebuilds \Drupal::getContainer().

Use this to update the test process's kernel with a new service container. For example, when the list of enabled modules is changed via the internal browser the test process's kernel has a service container with an out of date module list.

Fix https://www.drupal.org/node/2021959 so that module enable/disable changes are immediately reflected in \Drupal::getContainer(). Until then, tests can invoke this workaround when requiring services from newly enabled modules to be immediately available in the same request.

See also

\Drupal\Core\Test\TestBase::prepareEnvironment()
\Drupal\Core\Test\TestBase::restoreEnvironment()

protected resetAll()

Resets all data structures after having enabled new modules.

This method is called by FunctionalTestSetupTrait::rebuildAll() after enabling the requested modules. It must be called again when additional modules are enabled later.

See also

FunctionalTestSetupTrait::rebuildAll
\Drupal\Tests\BrowserTestBase::installDrupal()
WebTestBase::setUp

protected Request prepareRequestForGenerator(bool $clean_urls = TRUE, array $override_server_vars = [])

Creates a mock request and sets it on the generator.

This is used to manipulate how the generator generates paths during tests. It also ensures that calls to $this->drupalGet() will work when running from run-tests.sh because the url generator no longer looks at the global variables that are set there but relies on getting this information from a request object.

Parameters

bool $clean_urls

Whether to mock the request using clean urls.

array $override_server_vars

An array of server variables to override.

Return Value

Request

The mocked request object.

protected doInstall()

Execute the non-interactive installer.

See also

install_drupal()

protected initSettings()

Initialize settings created during install.

protected initConfig(ContainerInterface $container)

Initialize various configurations post-installation.

Parameters

ContainerInterface $container

The container.

protected initUserSession()

Initializes user 1 for the site to be installed.

protected ContainerInterface initKernel(Request $request)

Initializes the kernel after installation.

Parameters

Request $request

Request object.

Return Value

ContainerInterface

The container.

protected installDefaultThemeFromClassProperty(ContainerInterface $container)

Installs the default theme defined by static::$defaultTheme when needed.

To install a test theme outside of the testing environment, add

Parameters

ContainerInterface $container

The container.

protected installModulesFromClassProperty(ContainerInterface $container)

Install modules defined by static::$modules.

To install test modules outside of the testing environment, add

Parameters

ContainerInterface $container

The container.

protected rebuildAll()

Resets and rebuilds the environment after setup.

protected array installParameters()

Returns the parameters that will be used when Simpletest installs Drupal.

Return Value

array

Array of parameters for use in install_drupal().

See also

install_drupal()
install_state_defaults()

protected setupBaseUrl()

Sets up the base URL based upon the environment variable.

Exceptions

Exception

protected prepareEnvironment()

Prepares the current environment for running the test.

Also sets up new resources for the testing environment, such as the public filesystem and configuration directories.

This method is private as it must only be called once by BrowserTestBase::setUp() (multiple invocations for the same test would have unpredictable consequences) and it must not be callable or overridable by test classes.

protected Tasks[] getDatabaseTypes()

Returns all supported database driver installer objects.

This wraps drupal_get_database_types() for use without a current container.

Return Value

Tasks[]

An array of available database driver installer objects.

protected enablePageCaching()

Enables page caching.

protected string[] getCacheHeaderValues(string $header_name)

Gets a specific header value as array.

Parameters

string $header_name

The header name.

Return Value

string[]

The header value, potentially exploded by spaces.

protected assertCacheContext(string $expected_cache_context)

Asserts whether an expected cache context was present in the last response.

Parameters

string $expected_cache_context

The expected cache context.

protected assertNoCacheContext(string $not_expected_cache_context)

Asserts that a cache context was not present in the last response.

Parameters

string $not_expected_cache_context

The expected cache context.

protected assertPageCacheContextsAndTags(Url $url, array $expected_contexts, array $expected_tags)

Asserts page cache miss, then hit for the given URL; checks cache headers.

Parameters

Url $url

The URL to test.

array $expected_contexts

The expected cache contexts for the given URL.

array $expected_tags

The expected cache tags for the given URL.

protected debugCacheTags(array $actual_tags, array $expected_tags)

Provides debug information for cache tags.

Parameters

array $actual_tags

The actual cache tags.

array $expected_tags

The expected cache tags.

protected assertCacheTags(array $expected_tags, bool $include_default_tags = TRUE)

Ensures that some cache tags are present in the current response.

Parameters

array $expected_tags

The expected tags.

bool $include_default_tags

(optional) Whether the default cache tags should be included.

protected bool assertCacheContexts(array $expected_contexts, string $message = NULL, bool $include_default_contexts = TRUE)

Ensures that some cache contexts are present in the current response.

Parameters

array $expected_contexts

The expected cache contexts.

string $message

(optional) A verbose message to output.

bool $include_default_contexts

(optional) Whether the default contexts should automatically be included.

Return Value

bool

TRUE if the assertion succeeded, FALSE otherwise.

protected assertCacheMaxAge(int $max_age)

Asserts the max age header.

Parameters

int $max_age

protected array getMails(array $filter = [])

Gets an array containing all emails sent during this test case.

Parameters

array $filter

An array containing key/value pairs used to filter the emails that are returned.

Return Value

array

An array containing email messages captured during the current test.

protected bool assertMail(string $name, string $value = '', string $message = '', string $group = 'Email')

Asserts that the most recently sent email message has the given value.

The field in $name must have the content described in $value.

Parameters

string $name

Name of field or message property to assert. Examples: subject, body, id, ...

string $value

Value of the field to assert.

string $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.

string $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 'Email'; most tests do not override this default.

Return Value

bool

TRUE on pass, FALSE on fail.

protected bool assertMailString(string $field_name, string $string, int $email_depth, string $message = '', string $group = 'Other')

Asserts that the most recently sent email message has the string in it.

Parameters

string $field_name

Name of field or message property to assert: subject, body, id, ...

string $string

String to search for.

int $email_depth

Number of emails to search for string, starting with most recent.

string $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.

string $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

bool

TRUE on pass, FALSE on fail.

protected bool assertMailPattern(string $field_name, string $regex, string $message = '', string $group = 'Other')

Asserts that the most recently sent email message has the pattern in it.

Parameters

string $field_name

Name of field or message property to assert: subject, body, id, ...

string $regex

Pattern to search for.

string $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.

string $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

bool

TRUE on pass, FALSE on fail.

protected verboseEmail(int $count = 1)

Outputs to verbose the most recent $count emails sent.

Parameters

int $count

Optional number of emails to output.

protected assertBlockAppears(Block $block)

Checks to see whether a block appears on the page.

Parameters

Block $block

The block entity to find on the page.

protected assertNoBlockAppears(Block $block)

Checks to see whether a block does not appears on the page.

Parameters

Block $block

The block entity to find on the page.

protected array findBlockInstance(Block $block)

Find a block instance on the page.

Parameters

Block $block

The block entity to find on the page.

Return Value

array

The result from the xpath query.

protected drupalLogin(AccountInterface $account)

Log in a user with the internal browser.

If a user is already logged in, then the current user is logged out before logging in the specified user.

Please note that neither the current user nor the passed-in user object is populated with data of the logged in user. If you need full access to the user object after logging in, it must be updated manually. If you also need access to the plain-text password of the user (set by drupalCreateUser()), e.g. to log in the same user again, then it must be re-assigned manually. For example:

Parameters

AccountInterface $account

User object representing the user to log in.

See also

drupalCreateUser()

protected drupalUserIsLoggedIn(UserInterface $account)

Returns whether a given user account is logged in.

Parameters

UserInterface $account

The user account object to check.

protected drupalLogout()

Logs a user out of the internal browser and confirms.

Confirms logout by checking the login page.

protected setBatch()

Preserve the original batch, and instantiate the test batch.

protected restoreBatch()

Restore the original batch.

See also

::setBatch

protected addCustomTranslations(string $langcode, array $values)

Queues custom translations to be written to settings.php.

Use WebTestBase::writeCustomTranslations() to apply and write the queued translations.

Parameters

string $langcode

The langcode to add translations for.

array $values

Array of values containing the untranslated string and its translation. For example: @code array( '' => array('Sunday' => 'domingo'), 'Long month name' => array('March' => 'marzo'), ); @endcode Pass an empty array to remove all existing custom translations for the given $langcode.

protected writeCustomTranslations()

Writes custom translations to the test site's settings.php.

Use TestBase::addCustomTranslations() to queue custom translations before calling this method.

protected curlInitialize()

Initializes the cURL connection.

If the simpletest_httpauth_credentials variable is set, this function will add HTTP authentication headers. This is necessary for testing sites that are protected by login credentials from public access. See the description of $curl_options for other options.

protected The curlExec($curl_options, $redirect = FALSE)

Initializes and executes a cURL request.

Parameters

$curl_options

An associative array of cURL options to set, where the keys are constants defined by the cURL library. For a list of valid options, see http://php.net/manual/function.curl-setopt.php

$redirect

FALSE if this is an initial request, TRUE if this request is the result of a redirect.

Return Value

The

content returned from the call to curl_exec().

See also

curlInitialize()

protected curlHeaderCallback($curlHandler, $header)

Reads headers and registers errors received from the tested site.

Parameters

$curlHandler

The cURL handler.

$header

An header.

See also

_drupal_log_error()

protected curlClose()

Close the cURL handler and unset the handler.

protected bool isInChildSite()

Returns whether the test is being executed from within a test site.

Mainly used by recursive tests (i.e. to test the testing framework).

Return Value

bool

TRUE if this test was instantiated in a request within the test site, FALSE otherwise.

See also

\Drupal\Core\DrupalKernel::bootConfiguration()

protected string drupalGet(Url|string $path, array $options = [], array $headers = [])

Retrieves a Drupal path or an absolute path.

Parameters

Url|string $path

Drupal path or URL to load into internal browser

array $options

Options to be forwarded to the url generator.

array $headers

An array containing additional HTTP request headers, each formatted as "name: value".

Return Value

string

The retrieved HTML string, also available as $this->getRawContent()

protected array drupalGetJSON(Url|string $path, array $options = [], array $headers = [])

Retrieves a Drupal path or an absolute path and JSON decodes the result.

Parameters

Url|string $path

Drupal path or URL to request AJAX from.

array $options

Array of URL options.

array $headers

Array of headers. Eg array('Accept: application/vnd.drupal-ajax').

Return Value

array

Decoded json.

protected mixed drupalGetWithFormat(Url|string $path, string $format, array $options = [], array $headers = [])

Retrieves a Drupal path or an absolute path for a given format.

Parameters

Url|string $path

Drupal path or URL to request given format from.

string $format

The wanted request format.

array $options

Array of URL options.

array $headers

Array of headers.

Return Value

mixed

The result of the request.

protected array drupalGetAjax(Url|string $path, array $options = [], array $headers = [])

Requests a path or URL in drupal_ajax format and JSON-decodes the response.

Parameters

Url|string $path

Drupal path or URL to request from.

array $options

Array of URL options.

array $headers

Array of headers.

Return Value

array

Decoded JSON.

protected string drupalGetXHR(Url|string $path, array $options = [], array $headers = [])

Requests a Drupal path or an absolute path as if it is a XMLHttpRequest.

Parameters

Url|string $path

Drupal path or URL to request from.

array $options

Array of URL options.

array $headers

Array of headers.

Return Value

string

The retrieved content.

protected drupalPostForm(Url|string $path, $edit, $submit, array $options = [], array $headers = [], $form_html_id = NULL, $extra_post = NULL)

Executes a form submission.

It will be done as usual POST request with SimpleBrowser.

Parameters

Url|string $path

Location of the post form. Either a Drupal path or an absolute path or NULL to post to the current page. For multi-stage forms you can set the path to NULL and have it post to the last received page. Example:

@code // First step in form. $edit = array(...); $this->drupalPostForm('some_url', $edit, t('Save'));

// Second step in form. $edit = array(...); $this->drupalPostForm(NULL, $edit, t('Save')); @endcode

$edit

Field data in an associative array. Changes the current input fields (where possible) to the values indicated.

When working with form tests, the keys for an $edit element should match the 'name' parameter of the HTML of the form. For example, the 'body' field for a node has the following HTML: @code <textarea id="edit-body-und-0-value" class="text-full form-textarea resize-vertical" placeholder="" cols="60" rows="9" name="body[0][value]"> @endcode When testing this field using an $edit parameter, the code becomes: @code $edit["body[0][value]"] = 'My test value'; @endcode

A checkbox can be set to TRUE to be checked and should be set to FALSE to be unchecked. Multiple select fields can be tested using 'name[]' and setting each of the desired values in an array: @code $edit = array(); $edit['name[]'] = array('value1', 'value2'); @endcode

$submit

Value of the submit button whose click is to be emulated. For example, t('Save'). The processing of the request depends on this value. For example, a form may have one button with the value t('Save') and another button with the value t('Delete'), and execute different code depending on which one is clicked.

This function can also be called to emulate an Ajax submission. In this case, this value needs to be an array with the following keys:

  • path: A path to submit the form values to for Ajax-specific processing.
  • triggering_element: If the value for the 'path' key is a generic Ajax processing path, this needs to be set to the name of the element. If the name doesn't identify the element uniquely, then this should instead be an array with a single key/value pair, corresponding to the element name and value. The \Drupal\Core\Form\FormAjaxResponseBuilder uses this to find the #ajax information for the element, including which specific callback to use for processing the request.

This can also be set to NULL in order to emulate an Internet Explorer submission of a form with a single text field, and pressing ENTER in that textfield: under these conditions, no button information is added to the POST data.

array $options

Options to be forwarded to the url generator.

array $headers

An array containing additional HTTP request headers, each formatted as "name: value".

$form_html_id

(optional) HTML ID of the form to be submitted. On some pages there are many identical forms, so just using the value of the submit button is not enough. For example: 'trigger-node-presave-assign-form'. Note that this is not the Drupal $form_id, but rather the HTML ID of the form, which is typically the same thing but with hyphens replacing the underscores.

$extra_post

(optional) A string of additional data to append to the POST submission. This can be used to add POST data for which there are no HTML fields, as is done by drupalPostAjaxForm(). This string is literally appended to the POST data, so it must already be urlencoded and contain a leading "&" (e.g., "&extra_var1=hello+world&extra_var2=you%26me").

protected An drupalPostAjaxForm(Url|string $path, $edit, $triggering_element, $ajax_path = NULL, array $options = [], array $headers = [], $form_html_id = NULL, $ajax_settings = NULL)

Executes an Ajax form submission.

This executes a POST as ajax.js does. The returned JSON data is used to update $this->content via drupalProcessAjaxResponse(). It also returns the array of AJAX commands received.

Parameters

Url|string $path

Location of the form containing the Ajax enabled element to test. Can be either a Drupal path or an absolute path or NULL to use the current page.

$edit

Field data in an associative array. Changes the current input fields (where possible) to the values indicated.

$triggering_element

The name of the form element that is responsible for triggering the Ajax functionality to test. May be a string or, if the triggering element is a button, an associative array where the key is the name of the button and the value is the button label. i.e.) array('op' => t('Refresh')).

$ajax_path

(optional) Override the path set by the Ajax settings of the triggering element.

array $options

(optional) Options to be forwarded to the url generator.

array $headers

(optional) An array containing additional HTTP request headers, each formatted as "name: value". Forwarded to drupalPostForm().

$form_html_id

(optional) HTML ID of the form to be submitted, use when there is more than one identical form on the same page and the value of the triggering element is not enough to identify the form. Note this is not the Drupal ID of the form but rather the HTML ID of the form.

$ajax_settings

(optional) An array of Ajax settings which if specified will be used in place of the Ajax settings of the triggering element.

Return Value

An

array of Ajax commands.

See also

drupalPostForm()
drupalProcessAjaxResponse()
ajax.js

protected drupalProcessAjaxResponse(string $content, array $ajax_response, array $ajax_settings, array $drupal_settings)

Processes an AJAX response into current content.

This processes the AJAX response as ajax.js does. It uses the response's JSON data, an array of commands, to update $this->content using equivalent DOM manipulation as is used by ajax.js. It does not apply custom AJAX commands though, because emulation is only implemented for the AJAX commands that ship with Drupal core.

Parameters

string $content

The current HTML content.

array $ajax_response

An array of AJAX commands.

array $ajax_settings

An array of AJAX settings which will be used to process the response.

array $drupal_settings

An array of settings to update the value of drupalSettings for the currently-loaded page.

See also

drupalPostAjaxForm()
ajax.js

protected The drupalPost(string|Url $path, string $accept, array $post, array $options = [])

Perform a POST HTTP request.

Parameters

string|Url $path

Drupal path or absolute path where the request should be POSTed.

string $accept

The value for the "Accept" header. Usually either 'application/json' or 'application/vnd.drupal-ajax'.

array $post

The POST data. When making a 'application/vnd.drupal-ajax' request, the Ajax page state data should be included. Use getAjaxPageStatePostData() for that.

array $options

(optional) Options to be forwarded to the url generator. The 'absolute' option will automatically be enabled.

Return Value

The

content returned from the call to curl_exec().

See also

WebTestBase::getAjaxPageStatePostData
WebTestBase::curlExec

protected string drupalPostWithFormat(string|Url $path, string $format, array $post, array $options = [])

Performs a POST HTTP request with a specific format.

Parameters

string|Url $path

Drupal path or absolute path where the request should be POSTed.

string $format

The request format.

array $post

The POST data. When making a 'application/vnd.drupal-ajax' request, the Ajax page state data should be included. Use getAjaxPageStatePostData() for that.

array $options

(optional) Options to be forwarded to the url generator. The 'absolute' option will automatically be enabled.

Return Value

string

The content returned from the call to curl_exec().

See also

WebTestBase::drupalPost
WebTestBase::getAjaxPageStatePostData
WebTestBase::curlExec

protected array getAjaxPageStatePostData()

Get the Ajax page state from drupalSettings and prepare it for POSTing.

Return Value

array

The Ajax page state POST data.

protected string serializePostValues(array $post = [])

Serialize POST HTTP request values.

Encode according to application/x-www-form-urlencoded. Both names and values needs to be urlencoded, according to http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1

Parameters

array $post

The array of values to be POSTed.

Return Value

string

The serialized result.

protected array translatePostValues(array $values)

Transforms a nested array into a flat array suitable for WebTestBase::drupalPostForm().

Parameters

array $values

A multi-dimensional form values array to convert.

Return Value

array

The flattened $edit array suitable for WebTestBase::drupalPostForm().

protected Either checkForMetaRefresh()

Checks for meta refresh tag and if found call drupalGet() recursively.

This function looks for the http-equiv attribute to be set to "Refresh" and is case-sensitive.

Return Value

Either

the new page content or FALSE.

protected The drupalHead($path, array $options = [], array $headers = [])

Retrieves only the headers for a Drupal path or an absolute path.

Parameters

$path

Drupal path or URL to load into internal browser

array $options

Options to be forwarded to the url generator.

array $headers

An array containing additional HTTP request headers, each formatted as "name: value".

Return Value

The

retrieved headers, also available as $this->getRawContent()

protected Submit handleForm($post, $edit, $upload, $submit, $form)

Handles form input related to drupalPostForm().

Ensure that the specified fields exist and attempt to create POST data in the correct manner for the particular field type.

Parameters

$post

Reference to array of post values.

$edit

Reference to array of edit values to be checked against the form.

$upload
$submit

Form submit button value.

$form

Array of form elements.

Return Value

Submit

value matches a valid submit input in the form.

Follows a link by complete name.

Will click the first link found with this link text by default, or a later one if an index is given. Match is case sensitive with normalized space. The label is translated label.

If the link is discovered and clicked, the test passes. Fail otherwise.

Parameters

string|MarkupInterface $label

Text between the anchor tags.

int $index

Link position counting from zero.

Return Value

string|bool

Page contents on success, or FALSE on failure.

protected string|bool clickLinkPartialName(string|MarkupInterface $label, int $index = 0)

Follows a link by partial name.

If the link is discovered and clicked, the test passes. Fail otherwise.

Parameters

string|MarkupInterface $label

Text between the anchor tags, uses starts-with().

int $index

Link position counting from zero.

Return Value

string|bool

Page contents on success, or FALSE on failure.

See also

\Drupal\simpletest\::clickLink()

protected bool|string clickLinkHelper(string|MarkupInterface $label, int $index, string $pattern)

Provides a helper for ::clickLink() and ::clickLinkPartialName().

Parameters

string|MarkupInterface $label

Text between the anchor tags, uses starts-with().

int $index

Link position counting from zero.

string $pattern

A pattern to use for the XPath.

Return Value

bool|string

Page contents on success, or FALSE on failure.

protected string getAbsoluteUrl(string $path)

Takes a path and returns an absolute path.

This method is implemented in the way that browsers work, see https://url.spec.whatwg.org/#relative-state for more information about the possible cases.

Parameters

string $path

A path from the internal browser content.

Return Value

string

The $path with $base_url prepended, if necessary.

protected A drupalGetHeaders($all_requests = FALSE)

Gets the HTTP response headers of the requested page.

Normally we are only interested in the headers returned by the last request. However, if a page is redirected or HTTP authentication is in use, multiple requests will be required to retrieve the page. Headers from all requests may be requested by passing TRUE to this function.

Parameters

$all_requests

Boolean value specifying whether to return headers from all requests instead of just the last request. Defaults to FALSE.

Return Value

A

name/value array if headers from only the last request are requested. If headers from all requests are requested, an array of name/value arrays, one for each request.

The pseudonym ":status" is used for the HTTP status line.

Values for duplicate headers are stored as a single comma-separated list.

protected The drupalGetHeader($name, $all_requests = FALSE)

Gets the value of an HTTP response header.

If multiple requests were required to retrieve the page, only the headers from the last request will be checked by default. However, if TRUE is passed as the second argument, all requests will be processed from last to first until the header is found.

Parameters

$name

The name of the header to retrieve. Names are case-insensitive (see RFC 2616 section 4.2).

$all_requests

Boolean value specifying whether to check all requests if the header is not found in the last request. Defaults to FALSE.

Return Value

The

HTTP header value or FALSE if not found.

protected bool assertHeader(string $header, string $value, string $message = '', string $group = 'Browser')

Check if a HTTP response header exists and has the expected value.

Parameters

string $header

The header key, example: Content-Type

string $value

The header value.

string $message

(optional) A message to display with the assertion.

string $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

bool

TRUE if the assertion succeeded, FALSE otherwise.

protected true assertUrl(Url|string $path, array $options = [], $message = '', $group = 'Other')

Passes if the internal browser's URL matches the given path.

Parameters

Url|string $path

The expected system path or URL.

array $options

(optional) Any additional options to pass for $path to the url generator.

$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

on pass, FALSE on fail.

protected Assertion assertResponse($code, $message = '', $group = 'Browser')

Asserts the page responds with the specified response code.

Parameters

$code

Response code. For example 200 is a successful page request. For a list of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.

$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 'Browser'; most tests do not override this default.

Return Value

Assertion result.

protected Assertion assertNoResponse($code, $message = '', $group = 'Browser')

Asserts the page did not return the specified response code.

Parameters

$code

Response code. For example 200 is a successful page request. For a list of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.

$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 'Browser'; most tests do not override this default.

Return Value

Assertion result.

protected string buildUrl(string|Url $path, array $options = [])

Builds an a absolute URL from a system path or a URL object.

Parameters

string|Url $path

A system path or a URL.

array $options

Options to be passed to Url::fromUri().

Return Value

string

An absolute URL string.

protected assertCacheTag(string $expected_cache_tag)

Asserts whether an expected cache tag was present in the last response.

Parameters

string $expected_cache_tag

The expected cache tag.

protected assertNoCacheTag(string $cache_tag)

Asserts whether an expected cache tag was absent in the last response.

Parameters

string $cache_tag

The cache tag to check.

protected setHttpResponseDebugCacheabilityHeaders(bool $value = TRUE)

Enables/disables the cacheability headers.

Sets the http.response.debug_cacheability_headers container parameter.

Parameters

bool $value

(optional) Whether the debugging cacheability headers should be sent.