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\Utility\SafeMarkup;
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\SessionTestTrait;
19 use Drupal\Tests\Traits\Core\GeneratePermutationsTrait;
22 * Base class for Drupal tests.
24 * Do not extend this class directly; use \Drupal\simpletest\WebTestBase.
26 abstract class TestBase {
28 use BaseAssertHelperTrait;
31 use RandomGeneratorTrait;
32 use GeneratePermutationsTrait;
33 // For backwards compatibility switch the visbility of the methods to public.
35 configImporter as public;
40 * The database prefix of this test run.
44 protected $databasePrefix = NULL;
47 * Time limit for the test.
51 protected $timeLimit = 500;
54 * Current results of this test case.
66 * Assertions thrown in that test case.
70 protected $assertions = [];
73 * This class is skipped when looking for the source of an assertion.
75 * When displaying which function an assert comes from, it's not too useful
76 * to see "WebTestBase->drupalLogin()', we would like to see the test
77 * that called it. So we need to skip the classes defining these helper
80 protected $skipClasses = [__CLASS__ => TRUE];
83 * TRUE if verbose debugging is enabled.
90 * Incrementing identifier for verbose output filenames.
94 protected $verboseId = 0;
97 * Safe class name for use in verbose output filenames.
99 * Namespaces separator (\) replaced with _.
103 protected $verboseClassName;
106 * Directory where verbose output files are put.
110 protected $verboseDirectory;
113 * URL to the verbose output file directory.
117 protected $verboseDirectoryUrl;
120 * The original configuration (variables), if available.
123 * @todo Remove all remnants of $GLOBALS['conf'].
124 * @see https://www.drupal.org/node/2183323
126 protected $originalConf;
129 * The original configuration (variables).
133 protected $originalConfig;
136 * The original configuration directories.
138 * An array of paths keyed by the CONFIG_*_DIRECTORY constants defined by
139 * core/includes/bootstrap.inc.
143 protected $originalConfigDirectories;
146 * The original container.
148 * @var \Symfony\Component\DependencyInjection\ContainerInterface
150 protected $originalContainer;
153 * The original file directory, before it was changed for testing purposes.
157 protected $originalFileDirectory = NULL;
160 * The original language.
162 * @var \Drupal\Core\Language\LanguageInterface
164 protected $originalLanguage;
167 * The original database prefix when running inside Simpletest.
171 protected $originalPrefix;
174 * The name of the session cookie of the test-runner.
178 protected $originalSessionName;
181 * The settings array.
185 protected $originalSettings;
188 * The original array of shutdown function callbacks.
192 protected $originalShutdownCallbacks;
195 * The original user, before testing began.
197 * @var \Drupal\Core\Session\AccountProxyInterface
199 protected $originalUser;
202 * The translation file directory for the test environment.
204 * This is set in TestBase::prepareEnvironment().
208 protected $translationFilesDirectory;
211 * Whether to die in case any test assertion fails.
217 public $dieOnFail = FALSE;
220 * The config importer that can used in a test.
222 * @var \Drupal\Core\Config\ConfigImporter
224 protected $configImporter;
227 * HTTP authentication method (specified as a CURLAUTH_* constant).
230 * @see http://php.net/manual/function.curl-setopt.php
232 protected $httpAuthMethod = CURLAUTH_BASIC;
235 * HTTP authentication credentials (<username>:<password>).
239 protected $httpAuthCredentials = NULL;
242 * Constructor for Test.
245 * Tests with the same id are reported together.
247 public function __construct($test_id = NULL) {
248 $this->testId = $test_id;
252 * Performs setup tasks before each individual test method is run.
254 abstract protected function setUp();
257 * Checks the matching requirements for Test.
260 * Array of errors containing a list of unmet requirements.
262 protected function checkRequirements() {
267 * Helper method to store an assertion record in the configured database.
269 * This method decouples database access from assertion logic.
271 * @param array $assertion
272 * Keyed array representing an assertion, as generated by assert().
274 * @see self::assert()
276 * @return \Drupal\Core\Database\StatementInterface|int|null
279 protected function storeAssertion(array $assertion) {
280 return self::getDatabaseConnection()
281 ->insert('simpletest', ['return' => Database::RETURN_INSERT_ID])
287 * Internal helper: stores the assert.
290 * Can be 'pass', 'fail', 'exception', 'debug'.
291 * TRUE is a synonym for 'pass', FALSE for 'fail'.
292 * @param string|\Drupal\Component\Render\MarkupInterface $message
293 * (optional) A message to display with the assertion. Do not translate
294 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
295 * variables in the message text, not t(). If left blank, a default message
298 * (optional) The group this message is in, which is displayed in a column
299 * in test output. Use 'Debug' to indicate this is debugging output. Do not
300 * translate this string. Defaults to 'Other'; most tests do not override
303 * By default, the assert comes from a function whose name starts with
304 * 'test'. Instead, you can specify where this assert originates from
305 * by passing in an associative array as $caller. Key 'file' is
306 * the name of the source file, 'line' is the line number and 'function'
307 * is the caller function itself.
309 protected function assert($status, $message = '', $group = 'Other', array $caller = NULL) {
310 if ($message instanceof MarkupInterface) {
311 $message = (string) $message;
313 // Convert boolean status to string status.
314 if (is_bool($status)) {
315 $status = $status ? 'pass' : 'fail';
318 // Increment summary result counter.
319 $this->results['#' . $status]++;
321 // Get the function information about the call to the assertion method.
323 $caller = $this->getAssertionCall();
326 // Creation assertion array that can be displayed while tests are running.
328 'test_id' => $this->testId,
329 'test_class' => get_class($this),
331 'message' => $message,
332 'message_group' => $group,
333 'function' => $caller['function'],
334 'line' => $caller['line'],
335 'file' => $caller['file'],
338 // Store assertion for display after the test has completed.
339 $message_id = $this->storeAssertion($assertion);
340 $assertion['message_id'] = $message_id;
341 $this->assertions[] = $assertion;
343 // We do not use a ternary operator here to allow a breakpoint on
345 if ($status == 'pass') {
349 if ($this->dieOnFail && ($status == 'fail' || $status == 'exception')) {
357 * Store an assertion from outside the testing context.
359 * This is useful for inserting assertions that can only be recorded after
360 * the test case has been destroyed, such as PHP fatal errors. The caller
361 * information is not automatically gathered since the caller is most likely
362 * inserting the assertion on behalf of other code. In all other respects
363 * the method behaves just like \Drupal\simpletest\TestBase::assert() in terms
364 * of storing the assertion.
367 * Message ID of the stored assertion.
369 * @see \Drupal\simpletest\TestBase::assert()
370 * @see \Drupal\simpletest\TestBase::deleteAssert()
372 public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = []) {
373 // Convert boolean status to string status.
374 if (is_bool($status)) {
375 $status = $status ? 'pass' : 'fail';
379 'function' => 'Unknown',
385 'test_id' => $test_id,
386 'test_class' => $test_class,
388 'message' => $message,
389 'message_group' => $group,
390 'function' => $caller['function'],
391 'line' => $caller['line'],
392 'file' => $caller['file'],
395 // We can't use storeAssertion() because this method is static.
396 return self::getDatabaseConnection()
397 ->insert('simpletest')
403 * Delete an assertion record by message ID.
406 * Message ID of the assertion to delete.
409 * TRUE if the assertion was deleted, FALSE otherwise.
411 * @see \Drupal\simpletest\TestBase::insertAssert()
413 public static function deleteAssert($message_id) {
414 // We can't use storeAssertion() because this method is static.
415 return (bool) self::getDatabaseConnection()
416 ->delete('simpletest')
417 ->condition('message_id', $message_id)
422 * Cycles through backtrace until the first non-assertion method is found.
425 * Array representing the true caller.
427 protected function getAssertionCall() {
428 $backtrace = debug_backtrace();
430 // The first element is the call. The second element is the caller.
431 // We skip calls that occurred in one of the methods of our base classes
432 // or in an assertion function.
433 while (($caller = $backtrace[1]) &&
434 ((isset($caller['class']) && isset($this->skipClasses[$caller['class']])) ||
435 substr($caller['function'], 0, 6) == 'assert')) {
436 // We remove that call.
437 array_shift($backtrace);
440 return Error::getLastCaller($backtrace);
444 * Check to see if a value is not false.
446 * False values are: empty string, 0, NULL, and FALSE.
449 * The value on which the assertion is to be done.
451 * (optional) A message to display with the assertion. Do not translate
452 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
453 * variables in the message text, not t(). If left blank, a default message
456 * (optional) The group this message is in, which is displayed in a column
457 * in test output. Use 'Debug' to indicate this is debugging output. Do not
458 * translate this string. Defaults to 'Other'; most tests do not override
462 * TRUE if the assertion succeeded, FALSE otherwise.
464 protected function assertTrue($value, $message = '', $group = 'Other') {
465 return $this->assert((bool) $value, $message ? $message : SafeMarkup::format('Value @value is TRUE.', ['@value' => var_export($value, TRUE)]), $group);
469 * Check to see if a value is false.
471 * False values are: empty string, 0, NULL, and FALSE.
474 * The value on which the assertion is to be done.
476 * (optional) A message to display with the assertion. Do not translate
477 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
478 * variables in the message text, not t(). If left blank, a default message
481 * (optional) The group this message is in, which is displayed in a column
482 * in test output. Use 'Debug' to indicate this is debugging output. Do not
483 * translate this string. Defaults to 'Other'; most tests do not override
487 * TRUE if the assertion succeeded, FALSE otherwise.
489 protected function assertFalse($value, $message = '', $group = 'Other') {
490 return $this->assert(!$value, $message ? $message : SafeMarkup::format('Value @value is FALSE.', ['@value' => var_export($value, TRUE)]), $group);
494 * Check to see if a value is NULL.
497 * The value on which the assertion is to be done.
499 * (optional) A message to display with the assertion. Do not translate
500 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
501 * variables in the message text, not t(). If left blank, a default message
504 * (optional) The group this message is in, which is displayed in a column
505 * in test output. Use 'Debug' to indicate this is debugging output. Do not
506 * translate this string. Defaults to 'Other'; most tests do not override
510 * TRUE if the assertion succeeded, FALSE otherwise.
512 protected function assertNull($value, $message = '', $group = 'Other') {
513 return $this->assert(!isset($value), $message ? $message : SafeMarkup::format('Value @value is NULL.', ['@value' => var_export($value, TRUE)]), $group);
517 * Check to see if a value is not NULL.
520 * The value on which the assertion is to be done.
522 * (optional) A message to display with the assertion. Do not translate
523 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
524 * variables in the message text, not t(). If left blank, a default message
527 * (optional) The group this message is in, which is displayed in a column
528 * in test output. Use 'Debug' to indicate this is debugging output. Do not
529 * translate this string. Defaults to 'Other'; most tests do not override
533 * TRUE if the assertion succeeded, FALSE otherwise.
535 protected function assertNotNull($value, $message = '', $group = 'Other') {
536 return $this->assert(isset($value), $message ? $message : SafeMarkup::format('Value @value is not NULL.', ['@value' => var_export($value, TRUE)]), $group);
540 * Check to see if two values are equal.
543 * The first value to check.
545 * The second value to check.
547 * (optional) A message to display with the assertion. Do not translate
548 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
549 * variables in the message text, not t(). If left blank, a default message
552 * (optional) The group this message is in, which is displayed in a column
553 * in test output. Use 'Debug' to indicate this is debugging output. Do not
554 * translate this string. Defaults to 'Other'; most tests do not override
558 * TRUE if the assertion succeeded, FALSE otherwise.
560 protected function assertEqual($first, $second, $message = '', $group = 'Other') {
561 // Cast objects implementing MarkupInterface to string instead of
562 // relying on PHP casting them to string depending on what they are being
564 $first = $this->castSafeStrings($first);
565 $second = $this->castSafeStrings($second);
566 $is_equal = $first == $second;
567 if (!$is_equal || !$message) {
568 $default_message = SafeMarkup::format('Value @first is equal to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
569 $message = $message ? $message . PHP_EOL . $default_message : $default_message;
571 return $this->assert($is_equal, $message, $group);
575 * Check to see if two values are not equal.
578 * The first value to check.
580 * The second value to check.
582 * (optional) A message to display with the assertion. Do not translate
583 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
584 * variables in the message text, not t(). If left blank, a default message
587 * (optional) The group this message is in, which is displayed in a column
588 * in test output. Use 'Debug' to indicate this is debugging output. Do not
589 * translate this string. Defaults to 'Other'; most tests do not override
593 * TRUE if the assertion succeeded, FALSE otherwise.
595 protected function assertNotEqual($first, $second, $message = '', $group = 'Other') {
596 // Cast objects implementing MarkupInterface to string instead of
597 // relying on PHP casting them to string depending on what they are being
599 $first = $this->castSafeStrings($first);
600 $second = $this->castSafeStrings($second);
601 $not_equal = $first != $second;
602 if (!$not_equal || !$message) {
603 $default_message = SafeMarkup::format('Value @first is not equal to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
604 $message = $message ? $message . PHP_EOL . $default_message : $default_message;
606 return $this->assert($not_equal, $message, $group);
610 * Check to see if two values are identical.
613 * The first value to check.
615 * The second value to check.
617 * (optional) A message to display with the assertion. Do not translate
618 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
619 * variables in the message text, not t(). If left blank, a default message
622 * (optional) The group this message is in, which is displayed in a column
623 * in test output. Use 'Debug' to indicate this is debugging output. Do not
624 * translate this string. Defaults to 'Other'; most tests do not override
628 * TRUE if the assertion succeeded, FALSE otherwise.
630 protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
631 $is_identical = $first === $second;
632 if (!$is_identical || !$message) {
633 $default_message = SafeMarkup::format('Value @first is identical to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
634 $message = $message ? $message . PHP_EOL . $default_message : $default_message;
636 return $this->assert($is_identical, $message, $group);
640 * Check to see if two values are not identical.
643 * The first value to check.
645 * The second value to check.
647 * (optional) A message to display with the assertion. Do not translate
648 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
649 * variables in the message text, not t(). If left blank, a default message
652 * (optional) The group this message is in, which is displayed in a column
653 * in test output. Use 'Debug' to indicate this is debugging output. Do not
654 * translate this string. Defaults to 'Other'; most tests do not override
658 * TRUE if the assertion succeeded, FALSE otherwise.
660 protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') {
661 $not_identical = $first !== $second;
662 if (!$not_identical || !$message) {
663 $default_message = SafeMarkup::format('Value @first is not identical to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
664 $message = $message ? $message . PHP_EOL . $default_message : $default_message;
666 return $this->assert($not_identical, $message, $group);
670 * Checks to see if two objects are identical.
672 * @param object $object1
673 * The first object to check.
674 * @param object $object2
675 * The second object to check.
677 * (optional) A message to display with the assertion. Do not translate
678 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
679 * variables in the message text, not t(). If left blank, a default message
682 * (optional) The group this message is in, which is displayed in a column
683 * in test output. Use 'Debug' to indicate this is debugging output. Do not
684 * translate this string. Defaults to 'Other'; most tests do not override
688 * TRUE if the assertion succeeded, FALSE otherwise.
690 protected function assertIdenticalObject($object1, $object2, $message = '', $group = 'Other') {
691 $message = $message ?: SafeMarkup::format('@object1 is identical to @object2', [
692 '@object1' => var_export($object1, TRUE),
693 '@object2' => var_export($object2, TRUE),
696 foreach ($object1 as $key => $value) {
697 $identical = $identical && isset($object2->$key) && $object2->$key === $value;
699 return $this->assertTrue($identical, $message, $group);
703 * Asserts that no errors have been logged to the PHP error.log thus far.
706 * TRUE if the assertion succeeded, FALSE otherwise.
708 * @see \Drupal\simpletest\TestBase::prepareEnvironment()
709 * @see \Drupal\Core\DrupalKernel::bootConfiguration()
711 protected function assertNoErrorsLogged() {
712 // Since PHP only creates the error.log file when an actual error is
713 // triggered, it is sufficient to check whether the file exists.
714 return $this->assertFalse(file_exists(DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log'), 'PHP error.log is empty.');
718 * Asserts that a specific error has been logged to the PHP error log.
720 * @param string $error_message
721 * The expected error message.
724 * TRUE if the assertion succeeded, FALSE otherwise.
726 * @see \Drupal\simpletest\TestBase::prepareEnvironment()
727 * @see \Drupal\Core\DrupalKernel::bootConfiguration()
729 protected function assertErrorLogged($error_message) {
730 $error_log_filename = DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log';
731 if (!file_exists($error_log_filename)) {
732 $this->error('No error logged yet.');
735 $content = file_get_contents($error_log_filename);
736 $rows = explode(PHP_EOL, $content);
738 // We iterate over the rows in order to be able to remove the logged error
741 foreach ($rows as $row_index => $row) {
742 if (strpos($content, $error_message) !== FALSE) {
744 unset($rows[$row_index]);
748 file_put_contents($error_log_filename, implode("\n", $rows));
750 return $this->assertTrue($found, sprintf('The %s error message was logged.', $error_message));
754 * Fire an assertion that is always positive.
757 * (optional) A message to display with the assertion. Do not translate
758 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
759 * variables in the message text, not t(). If left blank, a default message
762 * (optional) The group this message is in, which is displayed in a column
763 * in test output. Use 'Debug' to indicate this is debugging output. Do not
764 * translate this string. Defaults to 'Other'; most tests do not override
770 protected function pass($message = NULL, $group = 'Other') {
771 return $this->assert(TRUE, $message, $group);
775 * Fire an assertion that is always negative.
778 * (optional) A message to display with the assertion. Do not translate
779 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
780 * variables in the message text, not t(). If left blank, a default message
783 * (optional) The group this message is in, which is displayed in a column
784 * in test output. Use 'Debug' to indicate this is debugging output. Do not
785 * translate this string. Defaults to 'Other'; most tests do not override
791 protected function fail($message = NULL, $group = 'Other') {
792 return $this->assert(FALSE, $message, $group);
796 * Fire an error assertion.
799 * (optional) A message to display with the assertion. Do not translate
800 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
801 * variables in the message text, not t(). If left blank, a default message
804 * (optional) The group this message is in, which is displayed in a column
805 * in test output. Use 'Debug' to indicate this is debugging output. Do not
806 * translate this string. Defaults to 'Other'; most tests do not override
809 * The caller of the error.
814 protected function error($message = '', $group = 'Other', array $caller = NULL) {
815 if ($group == 'User notice') {
816 // Since 'User notice' is set by trigger_error() which is used for debug
817 // set the message to a status of 'debug'.
818 return $this->assert('debug', $message, 'Debug', $caller);
821 return $this->assert('exception', $message, $group, $caller);
825 * Logs a verbose message in a text file.
827 * The link to the verbose message will be placed in the test results as a
828 * passing assertion with the text '[verbose message]'.
831 * The verbose message to be stored.
833 * @see simpletest_verbose()
835 protected function verbose($message) {
836 // Do nothing if verbose debugging is disabled.
837 if (!$this->verbose) {
841 $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;
842 $verbose_filename = $this->verboseClassName . '-' . $this->verboseId . '-' . $this->testId . '.html';
843 if (file_put_contents($this->verboseDirectory . '/' . $verbose_filename, $message)) {
844 $url = $this->verboseDirectoryUrl . '/' . $verbose_filename;
845 // Not using \Drupal\Core\Utility\LinkGeneratorInterface::generate()
846 // to avoid invoking the theme system, so that unit tests
847 // can use verbose() as well.
848 $url = '<a href="' . $url . '" target="_blank">Verbose message</a>';
849 $this->error($url, 'User notice');
855 * Run all tests in this class.
857 * Regardless of whether $methods are passed or not, only method names
858 * starting with "test" are executed.
861 * (optional) A list of method names in the test case class to run; e.g.,
862 * array('testFoo', 'testBar'). By default, all methods of the class are
863 * taken into account, but it can be useful to only run a few selected test
864 * methods during debugging.
866 public function run(array $methods = []) {
867 $class = get_class($this);
869 if ($missing_requirements = $this->checkRequirements()) {
870 $object_info = new \ReflectionObject($this);
872 'file' => $object_info->getFileName(),
874 foreach ($missing_requirements as $missing_requirement) {
875 TestBase::insertAssert($this->testId, $class, FALSE, $missing_requirement, 'Requirements check', $caller);
880 TestServiceProvider::$currentTest = $this;
881 $simpletest_config = $this->config('simpletest.settings');
883 // Unless preset from run-tests.sh, retrieve the current verbose setting.
884 if (!isset($this->verbose)) {
885 $this->verbose = $simpletest_config->get('verbose');
888 if ($this->verbose) {
889 // Initialize verbose debugging.
890 $this->verbose = TRUE;
891 $this->verboseDirectory = PublicStream::basePath() . '/simpletest/verbose';
892 $this->verboseDirectoryUrl = file_create_url($this->verboseDirectory);
893 if (file_prepare_directory($this->verboseDirectory, FILE_CREATE_DIRECTORY) && !file_exists($this->verboseDirectory . '/.htaccess')) {
894 file_put_contents($this->verboseDirectory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
896 $this->verboseClassName = str_replace("\\", "_", $class);
898 // HTTP auth settings (<username>:<password>) for the simpletest browser
899 // when sending requests to the test site.
900 $this->httpAuthMethod = (int) $simpletest_config->get('httpauth.method');
901 $username = $simpletest_config->get('httpauth.username');
902 $password = $simpletest_config->get('httpauth.password');
903 if (!empty($username) && !empty($password)) {
904 $this->httpAuthCredentials = $username . ':' . $password;
907 // Force assertion failures to be thrown as AssertionError for PHP 5 & 7
911 set_error_handler([$this, 'errorHandler']);
912 // Iterate through all the methods in this class, unless a specific list of
913 // methods to run was passed.
914 $test_methods = array_filter(get_class_methods($class), function ($method) {
915 return strpos($method, 'test') === 0;
917 if (empty($test_methods)) {
918 // Call $this->assert() here because we need to pass along custom caller
919 // information, lest the wrong originating code file/line be identified.
920 $this->assert(FALSE, 'No test methods found.', 'Requirements', ['function' => __METHOD__ . '()', 'file' => __FILE__, 'line' => __LINE__]);
923 $test_methods = array_intersect($test_methods, $methods);
925 foreach ($test_methods as $method) {
926 // Insert a fail record. This will be deleted on completion to ensure
927 // that testing completed.
928 $method_info = new \ReflectionMethod($class, $method);
930 'file' => $method_info->getFileName(),
931 'line' => $method_info->getStartLine(),
932 'function' => $class . '->' . $method . '()',
934 $test_completion_check_id = TestBase::insertAssert($this->testId, $class, FALSE, 'The test did not complete due to a fatal error.', 'Completion check', $caller);
937 $this->prepareEnvironment();
939 catch (\Exception $e) {
940 $this->exceptionHandler($e);
941 // The prepareEnvironment() method isolates the test from the parent
942 // Drupal site by creating a random database prefix and test site
943 // directory. If this fails, a test would possibly operate in the
944 // parent site. Therefore, the entire test run for this test class
945 // has to be aborted.
946 // restoreEnvironment() cannot be called, because we do not know
947 // where exactly the environment setup failed.
954 catch (\Exception $e) {
955 $this->exceptionHandler($e);
956 // Abort if setUp() fails, since all test methods will fail.
957 // But ensure to clean up and restore the environment, since
958 // prepareEnvironment() succeeded.
959 $this->restoreEnvironment();
965 catch (\Exception $e) {
966 $this->exceptionHandler($e);
971 catch (\Exception $e) {
972 $this->exceptionHandler($e);
973 // If a test fails to tear down, abort the entire test class, since
974 // it is likely that all tests will fail in the same way and a
975 // failure here only results in additional test artifacts that have
976 // to be manually deleted.
977 $this->restoreEnvironment();
981 $this->restoreEnvironment();
982 // Remove the test method completion check record.
983 TestBase::deleteAssert($test_completion_check_id);
986 TestServiceProvider::$currentTest = NULL;
987 // Clear out the error messages and restore error handler.
988 drupal_get_messages();
989 restore_error_handler();
993 * Generates a database prefix for running tests.
995 * The database prefix is used by prepareEnvironment() to setup a public files
996 * directory for the test to be run, which also contains the PHP error log,
997 * which is written to in case of a fatal error. Since that directory is based
998 * on the database prefix, all tests (even unit tests) need to have one, in
999 * order to access and read the error log.
1001 * @see TestBase::prepareEnvironment()
1003 * The generated database table prefix is used for the Drupal installation
1004 * being performed for the test. It is also used as user agent HTTP header
1005 * value by the cURL-based browser of WebTestBase, which is sent to the Drupal
1006 * installation of the test. During early Drupal bootstrap, the user agent
1007 * HTTP header is parsed, and if it matches, all database queries use the
1008 * database table prefix that has been generated here.
1010 * @see WebTestBase::curlInitialize()
1011 * @see drupal_valid_test_ua()
1013 private function prepareDatabasePrefix() {
1014 $test_db = new TestDatabase();
1015 $this->siteDirectory = $test_db->getTestSitePath();
1016 $this->databasePrefix = $test_db->getDatabasePrefix();
1018 // As soon as the database prefix is set, the test might start to execute.
1019 // All assertions as well as the SimpleTest batch operations are associated
1020 // with the testId, so the database prefix has to be associated with it.
1021 $affected_rows = self::getDatabaseConnection()->update('simpletest_test_id')
1022 ->fields(['last_prefix' => $this->databasePrefix])
1023 ->condition('test_id', $this->testId)
1025 if (!$affected_rows) {
1026 throw new \RuntimeException('Failed to set up database prefix.');
1031 * Act on global state information before the environment is altered for a test.
1033 * Allows e.g. KernelTestBase to prime system/extension info from the
1034 * parent site (and inject it into the test environment so as to improve
1037 protected function beforePrepareEnvironment() {
1041 * Prepares the current environment for running the test.
1043 * Backups various current environment variables and resets them, so they do
1044 * not interfere with the Drupal site installation in which tests are executed
1045 * and can be restored in TestBase::restoreEnvironment().
1047 * Also sets up new resources for the testing environment, such as the public
1048 * filesystem and configuration directories.
1050 * This method is private as it must only be called once by TestBase::run()
1051 * (multiple invocations for the same test would have unpredictable
1052 * consequences) and it must not be callable or overridable by test classes.
1054 * @see TestBase::beforePrepareEnvironment()
1056 private function prepareEnvironment() {
1057 $user = \Drupal::currentUser();
1058 // Allow (base) test classes to backup global state information.
1059 $this->beforePrepareEnvironment();
1061 // Create the database prefix for this test.
1062 $this->prepareDatabasePrefix();
1064 $language_interface = \Drupal::languageManager()->getCurrentLanguage();
1066 // When running the test runner within a test, back up the original database
1068 if (DRUPAL_TEST_IN_CHILD_SITE) {
1069 $this->originalPrefix = drupal_valid_test_ua();
1072 // Backup current in-memory configuration.
1073 $site_path = \Drupal::service('site.path');
1074 $this->originalSite = $site_path;
1075 $this->originalSettings = Settings::getAll();
1076 $this->originalConfig = $GLOBALS['config'];
1077 // @todo Remove all remnants of $GLOBALS['conf'].
1078 // @see https://www.drupal.org/node/2183323
1079 $this->originalConf = isset($GLOBALS['conf']) ? $GLOBALS['conf'] : NULL;
1081 // Backup statics and globals.
1082 $this->originalContainer = \Drupal::getContainer();
1083 $this->originalLanguage = $language_interface;
1084 $this->originalConfigDirectories = $GLOBALS['config_directories'];
1086 // Save further contextual information.
1087 // Use the original files directory to avoid nesting it within an existing
1088 // simpletest directory if a test is executed within a test.
1089 $this->originalFileDirectory = Settings::get('file_public_path', $site_path . '/files');
1090 $this->originalProfile = drupal_get_profile();
1091 $this->originalUser = isset($user) ? clone $user : NULL;
1093 // Prevent that session data is leaked into the UI test runner by closing
1094 // the session and then setting the session-name (i.e. the name of the
1095 // session cookie) to a random value. If a test starts a new session, then
1096 // it will be associated with a different session-name. After the test-run
1097 // it can be safely destroyed.
1098 // @see TestBase::restoreEnvironment()
1099 if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) {
1100 session_write_close();
1102 $this->originalSessionName = session_name();
1103 session_name('SIMPLETEST' . Crypt::randomBytesBase64());
1105 // Save and clean the shutdown callbacks array because it is static cached
1106 // and will be changed by the test run. Otherwise it will contain callbacks
1107 // from both environments and the testing environment will try to call the
1108 // handlers defined by the original one.
1109 $callbacks = &drupal_register_shutdown_function();
1110 $this->originalShutdownCallbacks = $callbacks;
1113 // Create test directory ahead of installation so fatal errors and debug
1114 // information can be logged during installation process.
1115 file_prepare_directory($this->siteDirectory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
1117 // Prepare filesystem directory paths.
1118 $this->publicFilesDirectory = $this->siteDirectory . '/files';
1119 $this->privateFilesDirectory = $this->siteDirectory . '/private';
1120 $this->tempFilesDirectory = $this->siteDirectory . '/temp';
1121 $this->translationFilesDirectory = $this->siteDirectory . '/translations';
1123 $this->generatedTestFiles = FALSE;
1125 // Ensure the configImporter is refreshed for each test.
1126 $this->configImporter = NULL;
1128 // Unregister all custom stream wrappers of the parent site.
1129 // Availability of Drupal stream wrappers varies by test base class:
1130 // - KernelTestBase supports and maintains stream wrappers in a custom
1132 // - WebTestBase re-initializes Drupal stream wrappers after installation.
1133 // The original stream wrappers are restored after the test run.
1134 // @see TestBase::restoreEnvironment()
1135 $this->originalContainer->get('stream_wrapper_manager')->unregister();
1138 drupal_static_reset();
1140 // Ensure there is no service container.
1141 $this->container = NULL;
1142 \Drupal::unsetContainer();
1145 unset($GLOBALS['config_directories']);
1146 unset($GLOBALS['config']);
1147 unset($GLOBALS['conf']);
1149 // Log fatal errors.
1150 ini_set('log_errors', 1);
1151 ini_set('error_log', DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log');
1153 // Change the database prefix.
1154 $this->changeDatabasePrefix();
1156 // After preparing the environment and changing the database prefix, we are
1157 // in a valid test environment.
1158 drupal_valid_test_ua($this->databasePrefix);
1162 // For performance, simply use the database prefix as hash salt.
1163 'hash_salt' => $this->databasePrefix,
1164 'container_yamls' => [],
1167 drupal_set_time_limit($this->timeLimit);
1171 * Performs cleanup tasks after each individual test method has been run.
1173 protected function tearDown() {
1177 * Cleans up the test environment and restores the original environment.
1179 * Deletes created files, database tables, and reverts environment changes.
1181 * This method needs to be invoked for both unit and integration tests.
1183 * @see TestBase::prepareDatabasePrefix()
1184 * @see TestBase::changeDatabasePrefix()
1185 * @see TestBase::prepareEnvironment()
1187 private function restoreEnvironment() {
1188 // Destroy the session if one was started during the test-run.
1190 if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) {
1192 $params = session_get_cookie_params();
1193 setcookie(session_name(), '', REQUEST_TIME - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
1195 session_name($this->originalSessionName);
1197 // Reset all static variables.
1198 // Unsetting static variables will potentially invoke destruct methods,
1199 // which might call into functions that prime statics and caches again.
1200 // In that case, all functions are still operating on the test environment,
1201 // which means they may need to access its filesystem and database.
1202 drupal_static_reset();
1204 if ($this->container && $this->container->has('state') && $state = $this->container->get('state')) {
1205 $captured_emails = $state->get('system.test_mail_collector') ?: [];
1206 $emailCount = count($captured_emails);
1208 $message = $emailCount == 1 ? '1 email was sent during this test.' : $emailCount . ' emails were sent during this test.';
1209 $this->pass($message, 'Email');
1213 // Sleep for 50ms to allow shutdown functions and terminate events to
1214 // complete. Further information: https://www.drupal.org/node/2194357.
1217 // Remove all prefixed tables.
1218 $original_connection_info = Database::getConnectionInfo('simpletest_original_default');
1219 $original_prefix = $original_connection_info['default']['prefix']['default'];
1220 $test_connection_info = Database::getConnectionInfo('default');
1221 $test_prefix = $test_connection_info['default']['prefix']['default'];
1222 if ($original_prefix != $test_prefix) {
1223 $tables = Database::getConnection()->schema()->findTables('%');
1224 foreach ($tables as $table) {
1225 if (Database::getConnection()->schema()->dropTable($table)) {
1226 unset($tables[$table]);
1231 // In case a fatal error occurred that was not in the test process read the
1232 // log to pick up any fatal errors.
1233 simpletest_log_read($this->testId, $this->databasePrefix, get_class($this));
1235 // Restore original dependency injection container.
1236 $this->container = $this->originalContainer;
1237 \Drupal::setContainer($this->originalContainer);
1239 // Delete test site directory.
1240 file_unmanaged_delete_recursive($this->siteDirectory, [$this, 'filePreDeleteCallback']);
1242 // Restore original database connection.
1243 Database::removeConnection('default');
1244 Database::renameConnection('simpletest_original_default', 'default');
1246 // Reset all static variables.
1247 // All destructors of statically cached objects have been invoked above;
1248 // this second reset is guaranteed to reset everything to nothing.
1249 drupal_static_reset();
1251 // Restore original in-memory configuration.
1252 $GLOBALS['config'] = $this->originalConfig;
1253 $GLOBALS['conf'] = $this->originalConf;
1254 new Settings($this->originalSettings);
1256 // Restore original statics and globals.
1257 $GLOBALS['config_directories'] = $this->originalConfigDirectories;
1259 // Re-initialize original stream wrappers of the parent site.
1260 // This must happen after static variables have been reset and the original
1261 // container and $config_directories are restored, as simpletest_log_read()
1262 // uses the public stream wrapper to locate the error.log.
1263 $this->originalContainer->get('stream_wrapper_manager')->register();
1265 if (isset($this->originalPrefix)) {
1266 drupal_valid_test_ua($this->originalPrefix);
1269 drupal_valid_test_ua(FALSE);
1272 // Restore original shutdown callbacks.
1273 $callbacks = &drupal_register_shutdown_function();
1274 $callbacks = $this->originalShutdownCallbacks;
1278 * Handle errors during test runs.
1280 * Because this is registered in set_error_handler(), it has to be public.
1282 * @see set_error_handler
1284 public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
1285 if ($severity & error_reporting()) {
1287 E_STRICT => 'Run-time notice',
1288 E_WARNING => 'Warning',
1289 E_NOTICE => 'Notice',
1290 E_CORE_ERROR => 'Core error',
1291 E_CORE_WARNING => 'Core warning',
1292 E_USER_ERROR => 'User error',
1293 E_USER_WARNING => 'User warning',
1294 E_USER_NOTICE => 'User notice',
1295 E_RECOVERABLE_ERROR => 'Recoverable error',
1296 E_DEPRECATED => 'Deprecated',
1297 E_USER_DEPRECATED => 'User deprecated',
1300 $backtrace = debug_backtrace();
1302 // Add verbose backtrace for errors, but not for debug() messages.
1303 if ($severity !== E_USER_NOTICE) {
1304 $verbose_backtrace = $backtrace;
1305 array_shift($verbose_backtrace);
1306 $message .= '<pre class="backtrace">' . Error::formatBacktrace($verbose_backtrace) . '</pre>';
1309 $this->error($message, $error_map[$severity], Error::getLastCaller($backtrace));
1315 * Handle exceptions.
1317 * @see set_exception_handler
1319 protected function exceptionHandler($exception) {
1320 $backtrace = $exception->getTrace();
1321 $verbose_backtrace = $backtrace;
1322 // Push on top of the backtrace the call that generated the exception.
1323 array_unshift($backtrace, [
1324 'line' => $exception->getLine(),
1325 'file' => $exception->getFile(),
1327 $decoded_exception = Error::decodeException($exception);
1328 unset($decoded_exception['backtrace']);
1329 $message = SafeMarkup::format('%type: @message in %function (line %line of %file). <pre class="backtrace">@backtrace</pre>', $decoded_exception + [
1330 '@backtrace' => Error::formatBacktrace($verbose_backtrace),
1332 $this->error($message, 'Uncaught exception', Error::getLastCaller($backtrace));
1336 * Changes in memory settings.
1339 * The name of the setting to return.
1341 * The value of the setting.
1343 * @see \Drupal\Core\Site\Settings::get()
1345 protected function settingsSet($name, $value) {
1346 $settings = Settings::getAll();
1347 $settings[$name] = $value;
1348 new Settings($settings);
1352 * Ensures test files are deletable within file_unmanaged_delete_recursive().
1354 * Some tests chmod generated files to be read only. During
1355 * TestBase::restoreEnvironment() and other cleanup operations, these files
1356 * need to get deleted too.
1358 public static function filePreDeleteCallback($path) {
1359 // When the webserver runs with the same system user as the test runner, we
1360 // can make read-only files writable again. If not, chmod will fail while
1361 // the file deletion still works if file permissions have been configured
1362 // correctly. Thus, we ignore any problems while running chmod.
1363 @chmod($path, 0700);
1367 * Configuration accessor for tests. Returns non-overridden configuration.
1370 * Configuration name.
1372 * @return \Drupal\Core\Config\Config
1373 * The configuration object with original configuration data.
1375 protected function config($name) {
1376 return \Drupal::configFactory()->getEditable($name);
1380 * Gets the database prefix.
1383 * The database prefix
1385 public function getDatabasePrefix() {
1386 return $this->databasePrefix;
1390 * Gets the temporary files directory.
1393 * The temporary files directory.
1395 public function getTempFilesDirectory() {
1396 return $this->tempFilesDirectory;