3 namespace Drupal\simpletest;
5 use Drupal\Component\Assertion\Handle;
6 use Drupal\Component\Render\MarkupInterface;
7 use Drupal\Component\Utility\Crypt;
8 use Drupal\Component\Render\FormattableMarkup;
9 use Drupal\Core\Database\Database;
10 use Drupal\Core\Site\Settings;
11 use Drupal\Core\StreamWrapper\PublicStream;
12 use Drupal\Core\Test\TestDatabase;
13 use Drupal\Core\Test\TestSetupTrait;
14 use Drupal\Core\Utility\Error;
15 use Drupal\Tests\AssertHelperTrait as BaseAssertHelperTrait;
16 use Drupal\Tests\ConfigTestTrait;
17 use Drupal\Tests\RandomGeneratorTrait;
18 use Drupal\Tests\Traits\Core\GeneratePermutationsTrait;
21 * Base class for Drupal tests.
23 * Do not extend this class directly; use \Drupal\simpletest\WebTestBase.
25 abstract class TestBase {
27 use BaseAssertHelperTrait;
29 use RandomGeneratorTrait;
30 use GeneratePermutationsTrait;
31 // For backwards compatibility switch the visibility of the methods to public.
33 configImporter as public;
38 * The database prefix of this test run.
42 protected $databasePrefix = NULL;
45 * Time limit for the test.
49 protected $timeLimit = 500;
52 * Current results of this test case.
64 * Assertions thrown in that test case.
68 protected $assertions = [];
71 * This class is skipped when looking for the source of an assertion.
73 * When displaying which function an assert comes from, it's not too useful
74 * to see "WebTestBase->drupalLogin()', we would like to see the test
75 * that called it. So we need to skip the classes defining these helper
78 protected $skipClasses = [__CLASS__ => TRUE];
81 * TRUE if verbose debugging is enabled.
88 * Incrementing identifier for verbose output filenames.
92 protected $verboseId = 0;
95 * Safe class name for use in verbose output filenames.
97 * Namespaces separator (\) replaced with _.
101 protected $verboseClassName;
104 * Directory where verbose output files are put.
108 protected $verboseDirectory;
111 * URL to the verbose output file directory.
115 protected $verboseDirectoryUrl;
118 * The original configuration (variables), if available.
121 * @todo Remove all remnants of $GLOBALS['conf'].
122 * @see https://www.drupal.org/node/2183323
124 protected $originalConf;
127 * The original configuration (variables).
131 protected $originalConfig;
134 * The original configuration directories.
136 * An array of paths keyed by the CONFIG_*_DIRECTORY constants defined by
137 * core/includes/bootstrap.inc.
141 protected $originalConfigDirectories;
144 * The original container.
146 * @var \Symfony\Component\DependencyInjection\ContainerInterface
148 protected $originalContainer;
151 * The original file directory, before it was changed for testing purposes.
155 protected $originalFileDirectory = NULL;
158 * The original language.
160 * @var \Drupal\Core\Language\LanguageInterface
162 protected $originalLanguage;
165 * The original database prefix when running inside Simpletest.
169 protected $originalPrefix;
172 * The name of the session cookie of the test-runner.
176 protected $originalSessionName;
179 * The settings array.
183 protected $originalSettings;
186 * The original array of shutdown function callbacks.
190 protected $originalShutdownCallbacks;
193 * The original user, before testing began.
195 * @var \Drupal\Core\Session\AccountProxyInterface
197 protected $originalUser;
200 * The translation file directory for the test environment.
202 * This is set in TestBase::prepareEnvironment().
206 protected $translationFilesDirectory;
209 * Whether to die in case any test assertion fails.
215 public $dieOnFail = FALSE;
218 * The config importer that can used in a test.
220 * @var \Drupal\Core\Config\ConfigImporter
222 protected $configImporter;
225 * HTTP authentication method (specified as a CURLAUTH_* constant).
228 * @see http://php.net/manual/function.curl-setopt.php
230 protected $httpAuthMethod = CURLAUTH_BASIC;
233 * HTTP authentication credentials (<username>:<password>).
237 protected $httpAuthCredentials = NULL;
240 * Constructor for Test.
243 * Tests with the same id are reported together.
245 public function __construct($test_id = NULL) {
246 $this->testId = $test_id;
250 * Fail the test if it belongs to a PHPUnit-based framework.
252 * This would probably be caused by automated test conversions such as those
253 * in https://www.drupal.org/project/drupal/issues/2770921.
255 public function checkTestHierarchyMismatch() {
256 // We can use getPhpunitTestSuite() because it uses a regex on the class'
257 // namespace to deduce the PHPUnit test suite.
258 if (TestDiscovery::getPhpunitTestSuite(get_class($this)) !== FALSE) {
259 $this->fail(get_class($this) . ' incorrectly subclasses ' . __CLASS__ . ', it should probably extend \Drupal\Tests\BrowserTestBase instead.');
264 * Performs setup tasks before each individual test method is run.
266 abstract protected function setUp();
269 * Checks the matching requirements for Test.
272 * Array of errors containing a list of unmet requirements.
274 protected function checkRequirements() {
279 * Helper method to store an assertion record in the configured database.
281 * This method decouples database access from assertion logic.
283 * @param array $assertion
284 * Keyed array representing an assertion, as generated by assert().
286 * @see self::assert()
288 * @return \Drupal\Core\Database\StatementInterface|int|null
291 protected function storeAssertion(array $assertion) {
292 return self::getDatabaseConnection()
293 ->insert('simpletest', ['return' => Database::RETURN_INSERT_ID])
299 * Internal helper: stores the assert.
302 * Can be 'pass', 'fail', 'exception', 'debug'.
303 * TRUE is a synonym for 'pass', FALSE for 'fail'.
304 * @param string|\Drupal\Component\Render\MarkupInterface $message
305 * (optional) A message to display with the assertion. Do not translate
306 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
307 * variables in the message text, not t(). If left blank, a default message
310 * (optional) The group this message is in, which is displayed in a column
311 * in test output. Use 'Debug' to indicate this is debugging output. Do not
312 * translate this string. Defaults to 'Other'; most tests do not override
315 * By default, the assert comes from a function whose name starts with
316 * 'test'. Instead, you can specify where this assert originates from
317 * by passing in an associative array as $caller. Key 'file' is
318 * the name of the source file, 'line' is the line number and 'function'
319 * is the caller function itself.
321 protected function assert($status, $message = '', $group = 'Other', array $caller = NULL) {
322 if ($message instanceof MarkupInterface) {
323 $message = (string) $message;
325 // Convert boolean status to string status.
326 if (is_bool($status)) {
327 $status = $status ? 'pass' : 'fail';
330 // Increment summary result counter.
331 $this->results['#' . $status]++;
333 // Get the function information about the call to the assertion method.
335 $caller = $this->getAssertionCall();
338 // Creation assertion array that can be displayed while tests are running.
340 'test_id' => $this->testId,
341 'test_class' => get_class($this),
343 'message' => $message,
344 'message_group' => $group,
345 'function' => $caller['function'],
346 'line' => $caller['line'],
347 'file' => $caller['file'],
350 // Store assertion for display after the test has completed.
351 $message_id = $this->storeAssertion($assertion);
352 $assertion['message_id'] = $message_id;
353 $this->assertions[] = $assertion;
355 // We do not use a ternary operator here to allow a breakpoint on
357 if ($status == 'pass') {
361 if ($this->dieOnFail && ($status == 'fail' || $status == 'exception')) {
369 * Store an assertion from outside the testing context.
371 * This is useful for inserting assertions that can only be recorded after
372 * the test case has been destroyed, such as PHP fatal errors. The caller
373 * information is not automatically gathered since the caller is most likely
374 * inserting the assertion on behalf of other code. In all other respects
375 * the method behaves just like \Drupal\simpletest\TestBase::assert() in terms
376 * of storing the assertion.
379 * Message ID of the stored assertion.
381 * @see \Drupal\simpletest\TestBase::assert()
382 * @see \Drupal\simpletest\TestBase::deleteAssert()
384 public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = []) {
385 // Convert boolean status to string status.
386 if (is_bool($status)) {
387 $status = $status ? 'pass' : 'fail';
391 'function' => 'Unknown',
397 'test_id' => $test_id,
398 'test_class' => $test_class,
400 'message' => $message,
401 'message_group' => $group,
402 'function' => $caller['function'],
403 'line' => $caller['line'],
404 'file' => $caller['file'],
407 // We can't use storeAssertion() because this method is static.
408 return self::getDatabaseConnection()
409 ->insert('simpletest')
415 * Delete an assertion record by message ID.
418 * Message ID of the assertion to delete.
421 * TRUE if the assertion was deleted, FALSE otherwise.
423 * @see \Drupal\simpletest\TestBase::insertAssert()
425 public static function deleteAssert($message_id) {
426 // We can't use storeAssertion() because this method is static.
427 return (bool) self::getDatabaseConnection()
428 ->delete('simpletest')
429 ->condition('message_id', $message_id)
434 * Cycles through backtrace until the first non-assertion method is found.
437 * Array representing the true caller.
439 protected function getAssertionCall() {
440 $backtrace = debug_backtrace();
442 // The first element is the call. The second element is the caller.
443 // We skip calls that occurred in one of the methods of our base classes
444 // or in an assertion function.
445 while (($caller = $backtrace[1]) &&
446 ((isset($caller['class']) && isset($this->skipClasses[$caller['class']])) ||
447 substr($caller['function'], 0, 6) == 'assert')) {
448 // We remove that call.
449 array_shift($backtrace);
452 return Error::getLastCaller($backtrace);
456 * Check to see if a value is not false.
458 * False values are: empty string, 0, NULL, and FALSE.
461 * The value on which the assertion is to be done.
463 * (optional) A message to display with the assertion. Do not translate
464 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
465 * variables in the message text, not t(). If left blank, a default message
468 * (optional) The group this message is in, which is displayed in a column
469 * in test output. Use 'Debug' to indicate this is debugging output. Do not
470 * translate this string. Defaults to 'Other'; most tests do not override
474 * TRUE if the assertion succeeded, FALSE otherwise.
476 protected function assertTrue($value, $message = '', $group = 'Other') {
477 return $this->assert((bool) $value, $message ? $message : new FormattableMarkup('Value @value is TRUE.', ['@value' => var_export($value, TRUE)]), $group);
481 * Check to see if a value is false.
483 * False values are: empty string, 0, NULL, and FALSE.
486 * The value on which the assertion is to be done.
488 * (optional) A message to display with the assertion. Do not translate
489 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
490 * variables in the message text, not t(). If left blank, a default message
493 * (optional) The group this message is in, which is displayed in a column
494 * in test output. Use 'Debug' to indicate this is debugging output. Do not
495 * translate this string. Defaults to 'Other'; most tests do not override
499 * TRUE if the assertion succeeded, FALSE otherwise.
501 protected function assertFalse($value, $message = '', $group = 'Other') {
502 return $this->assert(!$value, $message ? $message : new FormattableMarkup('Value @value is FALSE.', ['@value' => var_export($value, TRUE)]), $group);
506 * Check to see if a value is NULL.
509 * The value on which the assertion is to be done.
511 * (optional) A message to display with the assertion. Do not translate
512 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
513 * variables in the message text, not t(). If left blank, a default message
516 * (optional) The group this message is in, which is displayed in a column
517 * in test output. Use 'Debug' to indicate this is debugging output. Do not
518 * translate this string. Defaults to 'Other'; most tests do not override
522 * TRUE if the assertion succeeded, FALSE otherwise.
524 protected function assertNull($value, $message = '', $group = 'Other') {
525 return $this->assert(!isset($value), $message ? $message : new FormattableMarkup('Value @value is NULL.', ['@value' => var_export($value, TRUE)]), $group);
529 * Check to see if a value is not NULL.
532 * The value on which the assertion is to be done.
534 * (optional) A message to display with the assertion. Do not translate
535 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
536 * variables in the message text, not t(). If left blank, a default message
539 * (optional) The group this message is in, which is displayed in a column
540 * in test output. Use 'Debug' to indicate this is debugging output. Do not
541 * translate this string. Defaults to 'Other'; most tests do not override
545 * TRUE if the assertion succeeded, FALSE otherwise.
547 protected function assertNotNull($value, $message = '', $group = 'Other') {
548 return $this->assert(isset($value), $message ? $message : new FormattableMarkup('Value @value is not NULL.', ['@value' => var_export($value, TRUE)]), $group);
552 * Check to see if two values are equal.
555 * The first value to check.
557 * The second value to check.
559 * (optional) A message to display with the assertion. Do not translate
560 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
561 * variables in the message text, not t(). If left blank, a default message
564 * (optional) The group this message is in, which is displayed in a column
565 * in test output. Use 'Debug' to indicate this is debugging output. Do not
566 * translate this string. Defaults to 'Other'; most tests do not override
570 * TRUE if the assertion succeeded, FALSE otherwise.
572 protected function assertEqual($first, $second, $message = '', $group = 'Other') {
573 // Cast objects implementing MarkupInterface to string instead of
574 // relying on PHP casting them to string depending on what they are being
576 $first = $this->castSafeStrings($first);
577 $second = $this->castSafeStrings($second);
578 $is_equal = $first == $second;
579 if (!$is_equal || !$message) {
580 $default_message = new FormattableMarkup('Value @first is equal to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
581 $message = $message ? $message . PHP_EOL . $default_message : $default_message;
583 return $this->assert($is_equal, $message, $group);
587 * Check to see if two values are not equal.
590 * The first value to check.
592 * The second value to check.
594 * (optional) A message to display with the assertion. Do not translate
595 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
596 * variables in the message text, not t(). If left blank, a default message
599 * (optional) The group this message is in, which is displayed in a column
600 * in test output. Use 'Debug' to indicate this is debugging output. Do not
601 * translate this string. Defaults to 'Other'; most tests do not override
605 * TRUE if the assertion succeeded, FALSE otherwise.
607 protected function assertNotEqual($first, $second, $message = '', $group = 'Other') {
608 // Cast objects implementing MarkupInterface to string instead of
609 // relying on PHP casting them to string depending on what they are being
611 $first = $this->castSafeStrings($first);
612 $second = $this->castSafeStrings($second);
613 $not_equal = $first != $second;
614 if (!$not_equal || !$message) {
615 $default_message = new FormattableMarkup('Value @first is not equal to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
616 $message = $message ? $message . PHP_EOL . $default_message : $default_message;
618 return $this->assert($not_equal, $message, $group);
622 * Check to see if two values are identical.
625 * The first value to check.
627 * The second value to check.
629 * (optional) A message to display with the assertion. Do not translate
630 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
631 * variables in the message text, not t(). If left blank, a default message
634 * (optional) The group this message is in, which is displayed in a column
635 * in test output. Use 'Debug' to indicate this is debugging output. Do not
636 * translate this string. Defaults to 'Other'; most tests do not override
640 * TRUE if the assertion succeeded, FALSE otherwise.
642 protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
643 $is_identical = $first === $second;
644 if (!$is_identical || !$message) {
645 $default_message = new FormattableMarkup('Value @first is identical to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
646 $message = $message ? $message . PHP_EOL . $default_message : $default_message;
648 return $this->assert($is_identical, $message, $group);
652 * Check to see if two values are not identical.
655 * The first value to check.
657 * The second value to check.
659 * (optional) A message to display with the assertion. Do not translate
660 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
661 * variables in the message text, not t(). If left blank, a default message
664 * (optional) The group this message is in, which is displayed in a column
665 * in test output. Use 'Debug' to indicate this is debugging output. Do not
666 * translate this string. Defaults to 'Other'; most tests do not override
670 * TRUE if the assertion succeeded, FALSE otherwise.
672 protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') {
673 $not_identical = $first !== $second;
674 if (!$not_identical || !$message) {
675 $default_message = new FormattableMarkup('Value @first is not identical to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
676 $message = $message ? $message . PHP_EOL . $default_message : $default_message;
678 return $this->assert($not_identical, $message, $group);
682 * Checks to see if two objects are identical.
684 * @param object $object1
685 * The first object to check.
686 * @param object $object2
687 * The second object to check.
689 * (optional) A message to display with the assertion. Do not translate
690 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
691 * variables in the message text, not t(). If left blank, a default message
694 * (optional) The group this message is in, which is displayed in a column
695 * in test output. Use 'Debug' to indicate this is debugging output. Do not
696 * translate this string. Defaults to 'Other'; most tests do not override
700 * TRUE if the assertion succeeded, FALSE otherwise.
702 protected function assertIdenticalObject($object1, $object2, $message = '', $group = 'Other') {
703 $message = $message ?: new FormattableMarkup('@object1 is identical to @object2', [
704 '@object1' => var_export($object1, TRUE),
705 '@object2' => var_export($object2, TRUE),
708 foreach ($object1 as $key => $value) {
709 $identical = $identical && isset($object2->$key) && $object2->$key === $value;
711 return $this->assertTrue($identical, $message, $group);
715 * Asserts that no errors have been logged to the PHP error.log thus far.
718 * TRUE if the assertion succeeded, FALSE otherwise.
720 * @see \Drupal\simpletest\TestBase::prepareEnvironment()
721 * @see \Drupal\Core\DrupalKernel::bootConfiguration()
723 protected function assertNoErrorsLogged() {
724 // Since PHP only creates the error.log file when an actual error is
725 // triggered, it is sufficient to check whether the file exists.
726 return $this->assertFalse(file_exists(DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log'), 'PHP error.log is empty.');
730 * Asserts that a specific error has been logged to the PHP error log.
732 * @param string $error_message
733 * The expected error message.
736 * TRUE if the assertion succeeded, FALSE otherwise.
738 * @see \Drupal\simpletest\TestBase::prepareEnvironment()
739 * @see \Drupal\Core\DrupalKernel::bootConfiguration()
741 protected function assertErrorLogged($error_message) {
742 $error_log_filename = DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log';
743 if (!file_exists($error_log_filename)) {
744 $this->error('No error logged yet.');
747 $content = file_get_contents($error_log_filename);
748 $rows = explode(PHP_EOL, $content);
750 // We iterate over the rows in order to be able to remove the logged error
753 foreach ($rows as $row_index => $row) {
754 if (strpos($content, $error_message) !== FALSE) {
756 unset($rows[$row_index]);
760 file_put_contents($error_log_filename, implode("\n", $rows));
762 return $this->assertTrue($found, sprintf('The %s error message was logged.', $error_message));
766 * Fire an assertion that is always positive.
769 * (optional) A message to display with the assertion. Do not translate
770 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
771 * variables in the message text, not t(). If left blank, a default message
774 * (optional) The group this message is in, which is displayed in a column
775 * in test output. Use 'Debug' to indicate this is debugging output. Do not
776 * translate this string. Defaults to 'Other'; most tests do not override
782 protected function pass($message = NULL, $group = 'Other') {
783 return $this->assert(TRUE, $message, $group);
787 * Fire an assertion that is always negative.
790 * (optional) A message to display with the assertion. Do not translate
791 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
792 * variables in the message text, not t(). If left blank, a default message
795 * (optional) The group this message is in, which is displayed in a column
796 * in test output. Use 'Debug' to indicate this is debugging output. Do not
797 * translate this string. Defaults to 'Other'; most tests do not override
803 protected function fail($message = NULL, $group = 'Other') {
804 return $this->assert(FALSE, $message, $group);
808 * Fire an error assertion.
811 * (optional) A message to display with the assertion. Do not translate
812 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
813 * variables in the message text, not t(). If left blank, a default message
816 * (optional) The group this message is in, which is displayed in a column
817 * in test output. Use 'Debug' to indicate this is debugging output. Do not
818 * translate this string. Defaults to 'Other'; most tests do not override
821 * The caller of the error.
826 protected function error($message = '', $group = 'Other', array $caller = NULL) {
827 if ($group == 'User notice') {
828 // Since 'User notice' is set by trigger_error() which is used for debug
829 // set the message to a status of 'debug'.
830 return $this->assert('debug', $message, 'Debug', $caller);
833 return $this->assert('exception', $message, $group, $caller);
837 * Logs a verbose message in a text file.
839 * The link to the verbose message will be placed in the test results as a
840 * passing assertion with the text '[verbose message]'.
843 * The verbose message to be stored.
845 * @see simpletest_verbose()
847 protected function verbose($message) {
848 // Do nothing if verbose debugging is disabled.
849 if (!$this->verbose) {
853 $message = '<hr />ID #' . $this->verboseId . ' (<a href="' . $this->verboseClassName . '-' . ($this->verboseId - 1) . '-' . $this->testId . '.html">Previous</a> | <a href="' . $this->verboseClassName . '-' . ($this->verboseId + 1) . '-' . $this->testId . '.html">Next</a>)<hr />' . $message;
854 $verbose_filename = $this->verboseClassName . '-' . $this->verboseId . '-' . $this->testId . '.html';
855 if (file_put_contents($this->verboseDirectory . '/' . $verbose_filename, $message)) {
856 $url = $this->verboseDirectoryUrl . '/' . $verbose_filename;
857 // Not using \Drupal\Core\Utility\LinkGeneratorInterface::generate()
858 // to avoid invoking the theme system, so that unit tests
859 // can use verbose() as well.
860 $url = '<a href="' . $url . '" target="_blank">Verbose message</a>';
861 $this->error($url, 'User notice');
867 * Run all tests in this class.
869 * Regardless of whether $methods are passed or not, only method names
870 * starting with "test" are executed.
873 * (optional) A list of method names in the test case class to run; e.g.,
874 * array('testFoo', 'testBar'). By default, all methods of the class are
875 * taken into account, but it can be useful to only run a few selected test
876 * methods during debugging.
878 public function run(array $methods = []) {
879 $this->checkTestHierarchyMismatch();
880 $class = get_class($this);
882 if ($missing_requirements = $this->checkRequirements()) {
883 $object_info = new \ReflectionObject($this);
885 'file' => $object_info->getFileName(),
887 foreach ($missing_requirements as $missing_requirement) {
888 TestBase::insertAssert($this->testId, $class, FALSE, $missing_requirement, 'Requirements check', $caller);
893 TestServiceProvider::$currentTest = $this;
894 $simpletest_config = $this->config('simpletest.settings');
896 // Unless preset from run-tests.sh, retrieve the current verbose setting.
897 if (!isset($this->verbose)) {
898 $this->verbose = $simpletest_config->get('verbose');
901 if ($this->verbose) {
902 // Initialize verbose debugging.
903 $this->verbose = TRUE;
904 $this->verboseDirectory = PublicStream::basePath() . '/simpletest/verbose';
905 $this->verboseDirectoryUrl = file_create_url($this->verboseDirectory);
906 if (file_prepare_directory($this->verboseDirectory, FILE_CREATE_DIRECTORY) && !file_exists($this->verboseDirectory . '/.htaccess')) {
907 file_put_contents($this->verboseDirectory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
909 $this->verboseClassName = str_replace("\\", "_", $class);
911 // HTTP auth settings (<username>:<password>) for the simpletest browser
912 // when sending requests to the test site.
913 $this->httpAuthMethod = (int) $simpletest_config->get('httpauth.method');
914 $username = $simpletest_config->get('httpauth.username');
915 $password = $simpletest_config->get('httpauth.password');
916 if (!empty($username) && !empty($password)) {
917 $this->httpAuthCredentials = $username . ':' . $password;
920 // Force assertion failures to be thrown as AssertionError for PHP 5 & 7
924 set_error_handler([$this, 'errorHandler']);
925 // Iterate through all the methods in this class, unless a specific list of
926 // methods to run was passed.
927 $test_methods = array_filter(get_class_methods($class), function ($method) {
928 return strpos($method, 'test') === 0;
930 if (empty($test_methods)) {
931 // Call $this->assert() here because we need to pass along custom caller
932 // information, lest the wrong originating code file/line be identified.
933 $this->assert(FALSE, 'No test methods found.', 'Requirements', ['function' => __METHOD__ . '()', 'file' => __FILE__, 'line' => __LINE__]);
936 $test_methods = array_intersect($test_methods, $methods);
938 foreach ($test_methods as $method) {
939 // Insert a fail record. This will be deleted on completion to ensure
940 // that testing completed.
941 $method_info = new \ReflectionMethod($class, $method);
943 'file' => $method_info->getFileName(),
944 'line' => $method_info->getStartLine(),
945 'function' => $class . '->' . $method . '()',
947 $test_completion_check_id = TestBase::insertAssert($this->testId, $class, FALSE, 'The test did not complete due to a fatal error.', 'Completion check', $caller);
950 $this->prepareEnvironment();
952 catch (\Exception $e) {
953 $this->exceptionHandler($e);
954 // The prepareEnvironment() method isolates the test from the parent
955 // Drupal site by creating a random database prefix and test site
956 // directory. If this fails, a test would possibly operate in the
957 // parent site. Therefore, the entire test run for this test class
958 // has to be aborted.
959 // restoreEnvironment() cannot be called, because we do not know
960 // where exactly the environment setup failed.
967 catch (\Exception $e) {
968 $this->exceptionHandler($e);
969 // Abort if setUp() fails, since all test methods will fail.
970 // But ensure to clean up and restore the environment, since
971 // prepareEnvironment() succeeded.
972 $this->restoreEnvironment();
978 catch (\Exception $e) {
979 $this->exceptionHandler($e);
984 catch (\Exception $e) {
985 $this->exceptionHandler($e);
986 // If a test fails to tear down, abort the entire test class, since
987 // it is likely that all tests will fail in the same way and a
988 // failure here only results in additional test artifacts that have
989 // to be manually deleted.
990 $this->restoreEnvironment();
994 $this->restoreEnvironment();
995 // Remove the test method completion check record.
996 TestBase::deleteAssert($test_completion_check_id);
999 TestServiceProvider::$currentTest = NULL;
1000 // Clear out the error messages and restore error handler.
1001 \Drupal::messenger()->deleteAll();
1002 restore_error_handler();
1006 * Generates a database prefix for running tests.
1008 * The database prefix is used by prepareEnvironment() to setup a public files
1009 * directory for the test to be run, which also contains the PHP error log,
1010 * which is written to in case of a fatal error. Since that directory is based
1011 * on the database prefix, all tests (even unit tests) need to have one, in
1012 * order to access and read the error log.
1014 * @see TestBase::prepareEnvironment()
1016 * The generated database table prefix is used for the Drupal installation
1017 * being performed for the test. It is also used as user agent HTTP header
1018 * value by the cURL-based browser of WebTestBase, which is sent to the Drupal
1019 * installation of the test. During early Drupal bootstrap, the user agent
1020 * HTTP header is parsed, and if it matches, all database queries use the
1021 * database table prefix that has been generated here.
1023 * @see WebTestBase::curlInitialize()
1024 * @see drupal_valid_test_ua()
1026 private function prepareDatabasePrefix() {
1027 $test_db = new TestDatabase();
1028 $this->siteDirectory = $test_db->getTestSitePath();
1029 $this->databasePrefix = $test_db->getDatabasePrefix();
1031 // As soon as the database prefix is set, the test might start to execute.
1032 // All assertions as well as the SimpleTest batch operations are associated
1033 // with the testId, so the database prefix has to be associated with it.
1034 $affected_rows = self::getDatabaseConnection()->update('simpletest_test_id')
1035 ->fields(['last_prefix' => $this->databasePrefix])
1036 ->condition('test_id', $this->testId)
1038 if (!$affected_rows) {
1039 throw new \RuntimeException('Failed to set up database prefix.');
1044 * Act on global state information before the environment is altered for a test.
1046 * Allows e.g. KernelTestBase to prime system/extension info from the
1047 * parent site (and inject it into the test environment so as to improve
1050 protected function beforePrepareEnvironment() {
1054 * Prepares the current environment for running the test.
1056 * Backups various current environment variables and resets them, so they do
1057 * not interfere with the Drupal site installation in which tests are executed
1058 * and can be restored in TestBase::restoreEnvironment().
1060 * Also sets up new resources for the testing environment, such as the public
1061 * filesystem and configuration directories.
1063 * This method is private as it must only be called once by TestBase::run()
1064 * (multiple invocations for the same test would have unpredictable
1065 * consequences) and it must not be callable or overridable by test classes.
1067 * @see TestBase::beforePrepareEnvironment()
1069 private function prepareEnvironment() {
1070 $user = \Drupal::currentUser();
1071 // Allow (base) test classes to backup global state information.
1072 $this->beforePrepareEnvironment();
1074 // Create the database prefix for this test.
1075 $this->prepareDatabasePrefix();
1077 $language_interface = \Drupal::languageManager()->getCurrentLanguage();
1079 // When running the test runner within a test, back up the original database
1081 if (DRUPAL_TEST_IN_CHILD_SITE) {
1082 $this->originalPrefix = drupal_valid_test_ua();
1085 // Backup current in-memory configuration.
1086 $site_path = \Drupal::service('site.path');
1087 $this->originalSite = $site_path;
1088 $this->originalSettings = Settings::getAll();
1089 $this->originalConfig = $GLOBALS['config'];
1090 // @todo Remove all remnants of $GLOBALS['conf'].
1091 // @see https://www.drupal.org/node/2183323
1092 $this->originalConf = isset($GLOBALS['conf']) ? $GLOBALS['conf'] : NULL;
1094 // Backup statics and globals.
1095 $this->originalContainer = \Drupal::getContainer();
1096 $this->originalLanguage = $language_interface;
1097 $this->originalConfigDirectories = $GLOBALS['config_directories'];
1099 // Save further contextual information.
1100 // Use the original files directory to avoid nesting it within an existing
1101 // simpletest directory if a test is executed within a test.
1102 $this->originalFileDirectory = Settings::get('file_public_path', $site_path . '/files');
1103 $this->originalProfile = drupal_get_profile();
1104 $this->originalUser = isset($user) ? clone $user : NULL;
1106 // Prevent that session data is leaked into the UI test runner by closing
1107 // the session and then setting the session-name (i.e. the name of the
1108 // session cookie) to a random value. If a test starts a new session, then
1109 // it will be associated with a different session-name. After the test-run
1110 // it can be safely destroyed.
1111 // @see TestBase::restoreEnvironment()
1112 if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) {
1113 session_write_close();
1115 $this->originalSessionName = session_name();
1116 session_name('SIMPLETEST' . Crypt::randomBytesBase64());
1118 // Save and clean the shutdown callbacks array because it is static cached
1119 // and will be changed by the test run. Otherwise it will contain callbacks
1120 // from both environments and the testing environment will try to call the
1121 // handlers defined by the original one.
1122 $callbacks = &drupal_register_shutdown_function();
1123 $this->originalShutdownCallbacks = $callbacks;
1126 // Create test directory ahead of installation so fatal errors and debug
1127 // information can be logged during installation process.
1128 file_prepare_directory($this->siteDirectory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
1130 // Prepare filesystem directory paths.
1131 $this->publicFilesDirectory = $this->siteDirectory . '/files';
1132 $this->privateFilesDirectory = $this->siteDirectory . '/private';
1133 $this->tempFilesDirectory = $this->siteDirectory . '/temp';
1134 $this->translationFilesDirectory = $this->siteDirectory . '/translations';
1136 $this->generatedTestFiles = FALSE;
1138 // Ensure the configImporter is refreshed for each test.
1139 $this->configImporter = NULL;
1141 // Unregister all custom stream wrappers of the parent site.
1142 // Availability of Drupal stream wrappers varies by test base class:
1143 // - KernelTestBase supports and maintains stream wrappers in a custom
1145 // - WebTestBase re-initializes Drupal stream wrappers after installation.
1146 // The original stream wrappers are restored after the test run.
1147 // @see TestBase::restoreEnvironment()
1148 $this->originalContainer->get('stream_wrapper_manager')->unregister();
1151 drupal_static_reset();
1153 // Ensure there is no service container.
1154 $this->container = NULL;
1155 \Drupal::unsetContainer();
1158 unset($GLOBALS['config_directories']);
1159 unset($GLOBALS['config']);
1160 unset($GLOBALS['conf']);
1162 // Log fatal errors.
1163 ini_set('log_errors', 1);
1164 ini_set('error_log', DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log');
1166 // Change the database prefix.
1167 $this->changeDatabasePrefix();
1169 // After preparing the environment and changing the database prefix, we are
1170 // in a valid test environment.
1171 drupal_valid_test_ua($this->databasePrefix);
1175 // For performance, simply use the database prefix as hash salt.
1176 'hash_salt' => $this->databasePrefix,
1177 'container_yamls' => [],
1180 drupal_set_time_limit($this->timeLimit);
1184 * Performs cleanup tasks after each individual test method has been run.
1186 protected function tearDown() {
1190 * Cleans up the test environment and restores the original environment.
1192 * Deletes created files, database tables, and reverts environment changes.
1194 * This method needs to be invoked for both unit and integration tests.
1196 * @see TestBase::prepareDatabasePrefix()
1197 * @see TestBase::changeDatabasePrefix()
1198 * @see TestBase::prepareEnvironment()
1200 private function restoreEnvironment() {
1201 // Destroy the session if one was started during the test-run.
1203 if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) {
1205 $params = session_get_cookie_params();
1206 setcookie(session_name(), '', REQUEST_TIME - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
1208 session_name($this->originalSessionName);
1210 // Reset all static variables.
1211 // Unsetting static variables will potentially invoke destruct methods,
1212 // which might call into functions that prime statics and caches again.
1213 // In that case, all functions are still operating on the test environment,
1214 // which means they may need to access its filesystem and database.
1215 drupal_static_reset();
1217 if ($this->container && $this->container->has('state') && $state = $this->container->get('state')) {
1218 $captured_emails = $state->get('system.test_mail_collector') ?: [];
1219 $emailCount = count($captured_emails);
1221 $message = $emailCount == 1 ? '1 email was sent during this test.' : $emailCount . ' emails were sent during this test.';
1222 $this->pass($message, 'Email');
1226 // Sleep for 50ms to allow shutdown functions and terminate events to
1227 // complete. Further information: https://www.drupal.org/node/2194357.
1230 // Remove all prefixed tables.
1231 $original_connection_info = Database::getConnectionInfo('simpletest_original_default');
1232 $original_prefix = $original_connection_info['default']['prefix']['default'];
1233 $test_connection_info = Database::getConnectionInfo('default');
1234 $test_prefix = $test_connection_info['default']['prefix']['default'];
1235 if ($original_prefix != $test_prefix) {
1236 $tables = Database::getConnection()->schema()->findTables('%');
1237 foreach ($tables as $table) {
1238 if (Database::getConnection()->schema()->dropTable($table)) {
1239 unset($tables[$table]);
1244 // In case a fatal error occurred that was not in the test process read the
1245 // log to pick up any fatal errors.
1246 simpletest_log_read($this->testId, $this->databasePrefix, get_class($this));
1248 // Restore original dependency injection container.
1249 $this->container = $this->originalContainer;
1250 \Drupal::setContainer($this->originalContainer);
1252 // Delete test site directory.
1253 file_unmanaged_delete_recursive($this->siteDirectory, [$this, 'filePreDeleteCallback']);
1255 // Restore original database connection.
1256 Database::removeConnection('default');
1257 Database::renameConnection('simpletest_original_default', 'default');
1259 // Reset all static variables.
1260 // All destructors of statically cached objects have been invoked above;
1261 // this second reset is guaranteed to reset everything to nothing.
1262 drupal_static_reset();
1264 // Restore original in-memory configuration.
1265 $GLOBALS['config'] = $this->originalConfig;
1266 $GLOBALS['conf'] = $this->originalConf;
1267 new Settings($this->originalSettings);
1269 // Restore original statics and globals.
1270 $GLOBALS['config_directories'] = $this->originalConfigDirectories;
1272 // Re-initialize original stream wrappers of the parent site.
1273 // This must happen after static variables have been reset and the original
1274 // container and $config_directories are restored, as simpletest_log_read()
1275 // uses the public stream wrapper to locate the error.log.
1276 $this->originalContainer->get('stream_wrapper_manager')->register();
1278 if (isset($this->originalPrefix)) {
1279 drupal_valid_test_ua($this->originalPrefix);
1282 drupal_valid_test_ua(FALSE);
1285 // Restore original shutdown callbacks.
1286 $callbacks = &drupal_register_shutdown_function();
1287 $callbacks = $this->originalShutdownCallbacks;
1291 * Handle errors during test runs.
1293 * Because this is registered in set_error_handler(), it has to be public.
1295 * @see set_error_handler
1297 public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
1298 if ($severity & error_reporting()) {
1300 E_STRICT => 'Run-time notice',
1301 E_WARNING => 'Warning',
1302 E_NOTICE => 'Notice',
1303 E_CORE_ERROR => 'Core error',
1304 E_CORE_WARNING => 'Core warning',
1305 E_USER_ERROR => 'User error',
1306 E_USER_WARNING => 'User warning',
1307 E_USER_NOTICE => 'User notice',
1308 E_RECOVERABLE_ERROR => 'Recoverable error',
1309 E_DEPRECATED => 'Deprecated',
1310 E_USER_DEPRECATED => 'User deprecated',
1313 $backtrace = debug_backtrace();
1315 // Add verbose backtrace for errors, but not for debug() messages.
1316 if ($severity !== E_USER_NOTICE) {
1317 $verbose_backtrace = $backtrace;
1318 array_shift($verbose_backtrace);
1319 $message .= '<pre class="backtrace">' . Error::formatBacktrace($verbose_backtrace) . '</pre>';
1322 $this->error($message, $error_map[$severity], Error::getLastCaller($backtrace));
1328 * Handle exceptions.
1330 * @see set_exception_handler
1332 protected function exceptionHandler($exception) {
1333 $backtrace = $exception->getTrace();
1334 $verbose_backtrace = $backtrace;
1335 // Push on top of the backtrace the call that generated the exception.
1336 array_unshift($backtrace, [
1337 'line' => $exception->getLine(),
1338 'file' => $exception->getFile(),
1340 $decoded_exception = Error::decodeException($exception);
1341 unset($decoded_exception['backtrace']);
1342 $message = new FormattableMarkup('%type: @message in %function (line %line of %file). <pre class="backtrace">@backtrace</pre>', $decoded_exception + [
1343 '@backtrace' => Error::formatBacktrace($verbose_backtrace),
1345 $this->error($message, 'Uncaught exception', Error::getLastCaller($backtrace));
1349 * Changes in memory settings.
1352 * The name of the setting to return.
1354 * The value of the setting.
1356 * @see \Drupal\Core\Site\Settings::get()
1358 protected function settingsSet($name, $value) {
1359 $settings = Settings::getAll();
1360 $settings[$name] = $value;
1361 new Settings($settings);
1365 * Ensures test files are deletable within file_unmanaged_delete_recursive().
1367 * Some tests chmod generated files to be read only. During
1368 * TestBase::restoreEnvironment() and other cleanup operations, these files
1369 * need to get deleted too.
1371 public static function filePreDeleteCallback($path) {
1372 // When the webserver runs with the same system user as the test runner, we
1373 // can make read-only files writable again. If not, chmod will fail while
1374 // the file deletion still works if file permissions have been configured
1375 // correctly. Thus, we ignore any problems while running chmod.
1376 @chmod($path, 0700);
1380 * Configuration accessor for tests. Returns non-overridden configuration.
1383 * Configuration name.
1385 * @return \Drupal\Core\Config\Config
1386 * The configuration object with original configuration data.
1388 protected function config($name) {
1389 return \Drupal::configFactory()->getEditable($name);
1393 * Gets the database prefix.
1396 * The database prefix
1398 public function getDatabasePrefix() {
1399 return $this->databasePrefix;
1403 * Gets the temporary files directory.
1406 * The temporary files directory.
1408 public function getTempFilesDirectory() {
1409 return $this->tempFilesDirectory;