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\ConfigTestTrait;
16 use Drupal\Tests\RandomGeneratorTrait;
17 use Drupal\Tests\SessionTestTrait;
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 {
29 use RandomGeneratorTrait;
30 use AssertHelperTrait;
31 use GeneratePermutationsTrait;
32 // For backwards compatibility switch the visbility of the methods to public.
34 configImporter as public;
39 * The database prefix of this test run.
43 protected $databasePrefix = NULL;
46 * Time limit for the test.
48 protected $timeLimit = 500;
51 * Current results of this test case.
63 * Assertions thrown in that test case.
67 protected $assertions = [];
70 * This class is skipped when looking for the source of an assertion.
72 * When displaying which function an assert comes from, it's not too useful
73 * to see "WebTestBase->drupalLogin()', we would like to see the test
74 * that called it. So we need to skip the classes defining these helper
77 protected $skipClasses = [__CLASS__ => TRUE];
80 * TRUE if verbose debugging is enabled.
87 * Incrementing identifier for verbose output filenames.
91 protected $verboseId = 0;
94 * Safe class name for use in verbose output filenames.
96 * Namespaces separator (\) replaced with _.
100 protected $verboseClassName;
103 * Directory where verbose output files are put.
107 protected $verboseDirectory;
110 * URL to the verbose output file directory.
114 protected $verboseDirectoryUrl;
117 * The original configuration (variables), if available.
120 * @todo Remove all remnants of $GLOBALS['conf'].
121 * @see https://www.drupal.org/node/2183323
123 protected $originalConf;
126 * The original configuration (variables).
130 protected $originalConfig;
133 * The original configuration directories.
135 * An array of paths keyed by the CONFIG_*_DIRECTORY constants defined by
136 * core/includes/bootstrap.inc.
140 protected $originalConfigDirectories;
143 * The original container.
145 * @var \Symfony\Component\DependencyInjection\ContainerInterface
147 protected $originalContainer;
150 * The original file directory, before it was changed for testing purposes.
154 protected $originalFileDirectory = NULL;
157 * The original language.
159 * @var \Drupal\Core\Language\LanguageInterface
161 protected $originalLanguage;
164 * The original database prefix when running inside Simpletest.
168 protected $originalPrefix;
171 * The name of the session cookie of the test-runner.
175 protected $originalSessionName;
178 * The settings array.
182 protected $originalSettings;
185 * The original array of shutdown function callbacks.
189 protected $originalShutdownCallbacks;
192 * The original user, before testing began.
194 * @var \Drupal\Core\Session\AccountProxyInterface
196 protected $originalUser;
199 * The translation file directory for the test environment.
201 * This is set in TestBase::prepareEnvironment().
205 protected $translationFilesDirectory;
208 * Whether to die in case any test assertion fails.
214 public $dieOnFail = FALSE;
217 * The config importer that can used in a test.
219 * @var \Drupal\Core\Config\ConfigImporter
221 protected $configImporter;
224 * HTTP authentication method (specified as a CURLAUTH_* constant).
227 * @see http://php.net/manual/function.curl-setopt.php
229 protected $httpAuthMethod = CURLAUTH_BASIC;
232 * HTTP authentication credentials (<username>:<password>).
236 protected $httpAuthCredentials = NULL;
239 * Constructor for Test.
242 * Tests with the same id are reported together.
244 public function __construct($test_id = NULL) {
245 $this->testId = $test_id;
249 * Performs setup tasks before each individual test method is run.
251 abstract protected function setUp();
254 * Checks the matching requirements for Test.
257 * Array of errors containing a list of unmet requirements.
259 protected function checkRequirements() {
264 * Helper method to store an assertion record in the configured database.
266 * This method decouples database access from assertion logic.
268 * @param array $assertion
269 * Keyed array representing an assertion, as generated by assert().
271 * @see self::assert()
273 * @return \Drupal\Core\Database\StatementInterface|int|null
276 protected function storeAssertion(array $assertion) {
277 return self::getDatabaseConnection()
278 ->insert('simpletest', ['return' => Database::RETURN_INSERT_ID])
284 * Internal helper: stores the assert.
287 * Can be 'pass', 'fail', 'exception', 'debug'.
288 * TRUE is a synonym for 'pass', FALSE for 'fail'.
289 * @param string|\Drupal\Component\Render\MarkupInterface $message
290 * (optional) A message to display with the assertion. Do not translate
291 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
292 * variables in the message text, not t(). If left blank, a default message
295 * (optional) The group this message is in, which is displayed in a column
296 * in test output. Use 'Debug' to indicate this is debugging output. Do not
297 * translate this string. Defaults to 'Other'; most tests do not override
300 * By default, the assert comes from a function whose name starts with
301 * 'test'. Instead, you can specify where this assert originates from
302 * by passing in an associative array as $caller. Key 'file' is
303 * the name of the source file, 'line' is the line number and 'function'
304 * is the caller function itself.
306 protected function assert($status, $message = '', $group = 'Other', array $caller = NULL) {
307 if ($message instanceof MarkupInterface) {
308 $message = (string) $message;
310 // Convert boolean status to string status.
311 if (is_bool($status)) {
312 $status = $status ? 'pass' : 'fail';
315 // Increment summary result counter.
316 $this->results['#' . $status]++;
318 // Get the function information about the call to the assertion method.
320 $caller = $this->getAssertionCall();
323 // Creation assertion array that can be displayed while tests are running.
325 'test_id' => $this->testId,
326 'test_class' => get_class($this),
328 'message' => $message,
329 'message_group' => $group,
330 'function' => $caller['function'],
331 'line' => $caller['line'],
332 'file' => $caller['file'],
335 // Store assertion for display after the test has completed.
336 $message_id = $this->storeAssertion($assertion);
337 $assertion['message_id'] = $message_id;
338 $this->assertions[] = $assertion;
340 // We do not use a ternary operator here to allow a breakpoint on
342 if ($status == 'pass') {
346 if ($this->dieOnFail && ($status == 'fail' || $status == 'exception')) {
354 * Store an assertion from outside the testing context.
356 * This is useful for inserting assertions that can only be recorded after
357 * the test case has been destroyed, such as PHP fatal errors. The caller
358 * information is not automatically gathered since the caller is most likely
359 * inserting the assertion on behalf of other code. In all other respects
360 * the method behaves just like \Drupal\simpletest\TestBase::assert() in terms
361 * of storing the assertion.
364 * Message ID of the stored assertion.
366 * @see \Drupal\simpletest\TestBase::assert()
367 * @see \Drupal\simpletest\TestBase::deleteAssert()
369 public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = []) {
370 // Convert boolean status to string status.
371 if (is_bool($status)) {
372 $status = $status ? 'pass' : 'fail';
376 'function' => 'Unknown',
382 'test_id' => $test_id,
383 'test_class' => $test_class,
385 'message' => $message,
386 'message_group' => $group,
387 'function' => $caller['function'],
388 'line' => $caller['line'],
389 'file' => $caller['file'],
392 // We can't use storeAssertion() because this method is static.
393 return self::getDatabaseConnection()
394 ->insert('simpletest')
400 * Delete an assertion record by message ID.
403 * Message ID of the assertion to delete.
406 * TRUE if the assertion was deleted, FALSE otherwise.
408 * @see \Drupal\simpletest\TestBase::insertAssert()
410 public static function deleteAssert($message_id) {
411 // We can't use storeAssertion() because this method is static.
412 return (bool) self::getDatabaseConnection()
413 ->delete('simpletest')
414 ->condition('message_id', $message_id)
419 * Cycles through backtrace until the first non-assertion method is found.
422 * Array representing the true caller.
424 protected function getAssertionCall() {
425 $backtrace = debug_backtrace();
427 // The first element is the call. The second element is the caller.
428 // We skip calls that occurred in one of the methods of our base classes
429 // or in an assertion function.
430 while (($caller = $backtrace[1]) &&
431 ((isset($caller['class']) && isset($this->skipClasses[$caller['class']])) ||
432 substr($caller['function'], 0, 6) == 'assert')) {
433 // We remove that call.
434 array_shift($backtrace);
437 return Error::getLastCaller($backtrace);
441 * Check to see if a value is not false.
443 * False values are: empty string, 0, NULL, and FALSE.
446 * The value on which the assertion is to be done.
448 * (optional) A message to display with the assertion. Do not translate
449 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
450 * variables in the message text, not t(). If left blank, a default message
453 * (optional) The group this message is in, which is displayed in a column
454 * in test output. Use 'Debug' to indicate this is debugging output. Do not
455 * translate this string. Defaults to 'Other'; most tests do not override
459 * TRUE if the assertion succeeded, FALSE otherwise.
461 protected function assertTrue($value, $message = '', $group = 'Other') {
462 return $this->assert((bool) $value, $message ? $message : SafeMarkup::format('Value @value is TRUE.', ['@value' => var_export($value, TRUE)]), $group);
466 * Check to see if a value is false.
468 * False values are: empty string, 0, NULL, and FALSE.
471 * The value on which the assertion is to be done.
473 * (optional) A message to display with the assertion. Do not translate
474 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
475 * variables in the message text, not t(). If left blank, a default message
478 * (optional) The group this message is in, which is displayed in a column
479 * in test output. Use 'Debug' to indicate this is debugging output. Do not
480 * translate this string. Defaults to 'Other'; most tests do not override
484 * TRUE if the assertion succeeded, FALSE otherwise.
486 protected function assertFalse($value, $message = '', $group = 'Other') {
487 return $this->assert(!$value, $message ? $message : SafeMarkup::format('Value @value is FALSE.', ['@value' => var_export($value, TRUE)]), $group);
491 * Check to see if a value is NULL.
494 * The value on which the assertion is to be done.
496 * (optional) A message to display with the assertion. Do not translate
497 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
498 * variables in the message text, not t(). If left blank, a default message
501 * (optional) The group this message is in, which is displayed in a column
502 * in test output. Use 'Debug' to indicate this is debugging output. Do not
503 * translate this string. Defaults to 'Other'; most tests do not override
507 * TRUE if the assertion succeeded, FALSE otherwise.
509 protected function assertNull($value, $message = '', $group = 'Other') {
510 return $this->assert(!isset($value), $message ? $message : SafeMarkup::format('Value @value is NULL.', ['@value' => var_export($value, TRUE)]), $group);
514 * Check to see if a value is not NULL.
517 * The value on which the assertion is to be done.
519 * (optional) A message to display with the assertion. Do not translate
520 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
521 * variables in the message text, not t(). If left blank, a default message
524 * (optional) The group this message is in, which is displayed in a column
525 * in test output. Use 'Debug' to indicate this is debugging output. Do not
526 * translate this string. Defaults to 'Other'; most tests do not override
530 * TRUE if the assertion succeeded, FALSE otherwise.
532 protected function assertNotNull($value, $message = '', $group = 'Other') {
533 return $this->assert(isset($value), $message ? $message : SafeMarkup::format('Value @value is not NULL.', ['@value' => var_export($value, TRUE)]), $group);
537 * Check to see if two values are equal.
540 * The first value to check.
542 * The second value to check.
544 * (optional) A message to display with the assertion. Do not translate
545 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
546 * variables in the message text, not t(). If left blank, a default message
549 * (optional) The group this message is in, which is displayed in a column
550 * in test output. Use 'Debug' to indicate this is debugging output. Do not
551 * translate this string. Defaults to 'Other'; most tests do not override
555 * TRUE if the assertion succeeded, FALSE otherwise.
557 protected function assertEqual($first, $second, $message = '', $group = 'Other') {
558 // Cast objects implementing MarkupInterface to string instead of
559 // relying on PHP casting them to string depending on what they are being
561 $first = $this->castSafeStrings($first);
562 $second = $this->castSafeStrings($second);
563 $is_equal = $first == $second;
564 if (!$is_equal || !$message) {
565 $default_message = SafeMarkup::format('Value @first is equal to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
566 $message = $message ? $message . PHP_EOL . $default_message : $default_message;
568 return $this->assert($is_equal, $message, $group);
572 * Check to see if two values are not equal.
575 * The first value to check.
577 * The second value to check.
579 * (optional) A message to display with the assertion. Do not translate
580 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
581 * variables in the message text, not t(). If left blank, a default message
584 * (optional) The group this message is in, which is displayed in a column
585 * in test output. Use 'Debug' to indicate this is debugging output. Do not
586 * translate this string. Defaults to 'Other'; most tests do not override
590 * TRUE if the assertion succeeded, FALSE otherwise.
592 protected function assertNotEqual($first, $second, $message = '', $group = 'Other') {
593 // Cast objects implementing MarkupInterface to string instead of
594 // relying on PHP casting them to string depending on what they are being
596 $first = $this->castSafeStrings($first);
597 $second = $this->castSafeStrings($second);
598 $not_equal = $first != $second;
599 if (!$not_equal || !$message) {
600 $default_message = SafeMarkup::format('Value @first is not equal to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
601 $message = $message ? $message . PHP_EOL . $default_message : $default_message;
603 return $this->assert($not_equal, $message, $group);
607 * Check to see if two values are identical.
610 * The first value to check.
612 * The second value to check.
614 * (optional) A message to display with the assertion. Do not translate
615 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
616 * variables in the message text, not t(). If left blank, a default message
619 * (optional) The group this message is in, which is displayed in a column
620 * in test output. Use 'Debug' to indicate this is debugging output. Do not
621 * translate this string. Defaults to 'Other'; most tests do not override
625 * TRUE if the assertion succeeded, FALSE otherwise.
627 protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
628 $is_identical = $first === $second;
629 if (!$is_identical || !$message) {
630 $default_message = SafeMarkup::format('Value @first is identical to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
631 $message = $message ? $message . PHP_EOL . $default_message : $default_message;
633 return $this->assert($is_identical, $message, $group);
637 * Check to see if two values are not identical.
640 * The first value to check.
642 * The second value to check.
644 * (optional) A message to display with the assertion. Do not translate
645 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
646 * variables in the message text, not t(). If left blank, a default message
649 * (optional) The group this message is in, which is displayed in a column
650 * in test output. Use 'Debug' to indicate this is debugging output. Do not
651 * translate this string. Defaults to 'Other'; most tests do not override
655 * TRUE if the assertion succeeded, FALSE otherwise.
657 protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') {
658 $not_identical = $first !== $second;
659 if (!$not_identical || !$message) {
660 $default_message = SafeMarkup::format('Value @first is not identical to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
661 $message = $message ? $message . PHP_EOL . $default_message : $default_message;
663 return $this->assert($not_identical, $message, $group);
667 * Checks to see if two objects are identical.
669 * @param object $object1
670 * The first object to check.
671 * @param object $object2
672 * The second object to check.
674 * (optional) A message to display with the assertion. Do not translate
675 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
676 * variables in the message text, not t(). If left blank, a default message
679 * (optional) The group this message is in, which is displayed in a column
680 * in test output. Use 'Debug' to indicate this is debugging output. Do not
681 * translate this string. Defaults to 'Other'; most tests do not override
685 * TRUE if the assertion succeeded, FALSE otherwise.
687 protected function assertIdenticalObject($object1, $object2, $message = '', $group = 'Other') {
688 $message = $message ?: SafeMarkup::format('@object1 is identical to @object2', [
689 '@object1' => var_export($object1, TRUE),
690 '@object2' => var_export($object2, TRUE),
693 foreach ($object1 as $key => $value) {
694 $identical = $identical && isset($object2->$key) && $object2->$key === $value;
696 return $this->assertTrue($identical, $message, $group);
700 * Asserts that no errors have been logged to the PHP error.log thus far.
703 * TRUE if the assertion succeeded, FALSE otherwise.
705 * @see \Drupal\simpletest\TestBase::prepareEnvironment()
706 * @see \Drupal\Core\DrupalKernel::bootConfiguration()
708 protected function assertNoErrorsLogged() {
709 // Since PHP only creates the error.log file when an actual error is
710 // triggered, it is sufficient to check whether the file exists.
711 return $this->assertFalse(file_exists(DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log'), 'PHP error.log is empty.');
715 * Asserts that a specific error has been logged to the PHP error log.
717 * @param string $error_message
718 * The expected error message.
721 * TRUE if the assertion succeeded, FALSE otherwise.
723 * @see \Drupal\simpletest\TestBase::prepareEnvironment()
724 * @see \Drupal\Core\DrupalKernel::bootConfiguration()
726 protected function assertErrorLogged($error_message) {
727 $error_log_filename = DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log';
728 if (!file_exists($error_log_filename)) {
729 $this->error('No error logged yet.');
732 $content = file_get_contents($error_log_filename);
733 $rows = explode(PHP_EOL, $content);
735 // We iterate over the rows in order to be able to remove the logged error
738 foreach ($rows as $row_index => $row) {
739 if (strpos($content, $error_message) !== FALSE) {
741 unset($rows[$row_index]);
745 file_put_contents($error_log_filename, implode("\n", $rows));
747 return $this->assertTrue($found, sprintf('The %s error message was logged.', $error_message));
751 * Fire an assertion that is always positive.
754 * (optional) A message to display with the assertion. Do not translate
755 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
756 * variables in the message text, not t(). If left blank, a default message
759 * (optional) The group this message is in, which is displayed in a column
760 * in test output. Use 'Debug' to indicate this is debugging output. Do not
761 * translate this string. Defaults to 'Other'; most tests do not override
767 protected function pass($message = NULL, $group = 'Other') {
768 return $this->assert(TRUE, $message, $group);
772 * Fire an assertion that is always negative.
775 * (optional) A message to display with the assertion. Do not translate
776 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
777 * variables in the message text, not t(). If left blank, a default message
780 * (optional) The group this message is in, which is displayed in a column
781 * in test output. Use 'Debug' to indicate this is debugging output. Do not
782 * translate this string. Defaults to 'Other'; most tests do not override
788 protected function fail($message = NULL, $group = 'Other') {
789 return $this->assert(FALSE, $message, $group);
793 * Fire an error assertion.
796 * (optional) A message to display with the assertion. Do not translate
797 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
798 * variables in the message text, not t(). If left blank, a default message
801 * (optional) The group this message is in, which is displayed in a column
802 * in test output. Use 'Debug' to indicate this is debugging output. Do not
803 * translate this string. Defaults to 'Other'; most tests do not override
806 * The caller of the error.
811 protected function error($message = '', $group = 'Other', array $caller = NULL) {
812 if ($group == 'User notice') {
813 // Since 'User notice' is set by trigger_error() which is used for debug
814 // set the message to a status of 'debug'.
815 return $this->assert('debug', $message, 'Debug', $caller);
818 return $this->assert('exception', $message, $group, $caller);
822 * Logs a verbose message in a text file.
824 * The link to the verbose message will be placed in the test results as a
825 * passing assertion with the text '[verbose message]'.
828 * The verbose message to be stored.
830 * @see simpletest_verbose()
832 protected function verbose($message) {
833 // Do nothing if verbose debugging is disabled.
834 if (!$this->verbose) {
838 $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;
839 $verbose_filename = $this->verboseClassName . '-' . $this->verboseId . '-' . $this->testId . '.html';
840 if (file_put_contents($this->verboseDirectory . '/' . $verbose_filename, $message)) {
841 $url = $this->verboseDirectoryUrl . '/' . $verbose_filename;
842 // Not using \Drupal\Core\Utility\LinkGeneratorInterface::generate()
843 // to avoid invoking the theme system, so that unit tests
844 // can use verbose() as well.
845 $url = '<a href="' . $url . '" target="_blank">Verbose message</a>';
846 $this->error($url, 'User notice');
852 * Run all tests in this class.
854 * Regardless of whether $methods are passed or not, only method names
855 * starting with "test" are executed.
858 * (optional) A list of method names in the test case class to run; e.g.,
859 * array('testFoo', 'testBar'). By default, all methods of the class are
860 * taken into account, but it can be useful to only run a few selected test
861 * methods during debugging.
863 public function run(array $methods = []) {
864 $class = get_class($this);
866 if ($missing_requirements = $this->checkRequirements()) {
867 $object_info = new \ReflectionObject($this);
869 'file' => $object_info->getFileName(),
871 foreach ($missing_requirements as $missing_requirement) {
872 TestBase::insertAssert($this->testId, $class, FALSE, $missing_requirement, 'Requirements check', $caller);
877 TestServiceProvider::$currentTest = $this;
878 $simpletest_config = $this->config('simpletest.settings');
880 // Unless preset from run-tests.sh, retrieve the current verbose setting.
881 if (!isset($this->verbose)) {
882 $this->verbose = $simpletest_config->get('verbose');
885 if ($this->verbose) {
886 // Initialize verbose debugging.
887 $this->verbose = TRUE;
888 $this->verboseDirectory = PublicStream::basePath() . '/simpletest/verbose';
889 $this->verboseDirectoryUrl = file_create_url($this->verboseDirectory);
890 if (file_prepare_directory($this->verboseDirectory, FILE_CREATE_DIRECTORY) && !file_exists($this->verboseDirectory . '/.htaccess')) {
891 file_put_contents($this->verboseDirectory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
893 $this->verboseClassName = str_replace("\\", "_", $class);
895 // HTTP auth settings (<username>:<password>) for the simpletest browser
896 // when sending requests to the test site.
897 $this->httpAuthMethod = (int) $simpletest_config->get('httpauth.method');
898 $username = $simpletest_config->get('httpauth.username');
899 $password = $simpletest_config->get('httpauth.password');
900 if (!empty($username) && !empty($password)) {
901 $this->httpAuthCredentials = $username . ':' . $password;
904 // Force assertion failures to be thrown as AssertionError for PHP 5 & 7
908 set_error_handler([$this, 'errorHandler']);
909 // Iterate through all the methods in this class, unless a specific list of
910 // methods to run was passed.
911 $test_methods = array_filter(get_class_methods($class), function ($method) {
912 return strpos($method, 'test') === 0;
914 if (empty($test_methods)) {
915 // Call $this->assert() here because we need to pass along custom caller
916 // information, lest the wrong originating code file/line be identified.
917 $this->assert(FALSE, 'No test methods found.', 'Requirements', ['function' => __METHOD__ . '()', 'file' => __FILE__, 'line' => __LINE__]);
920 $test_methods = array_intersect($test_methods, $methods);
922 foreach ($test_methods as $method) {
923 // Insert a fail record. This will be deleted on completion to ensure
924 // that testing completed.
925 $method_info = new \ReflectionMethod($class, $method);
927 'file' => $method_info->getFileName(),
928 'line' => $method_info->getStartLine(),
929 'function' => $class . '->' . $method . '()',
931 $test_completion_check_id = TestBase::insertAssert($this->testId, $class, FALSE, 'The test did not complete due to a fatal error.', 'Completion check', $caller);
934 $this->prepareEnvironment();
936 catch (\Exception $e) {
937 $this->exceptionHandler($e);
938 // The prepareEnvironment() method isolates the test from the parent
939 // Drupal site by creating a random database prefix and test site
940 // directory. If this fails, a test would possibly operate in the
941 // parent site. Therefore, the entire test run for this test class
942 // has to be aborted.
943 // restoreEnvironment() cannot be called, because we do not know
944 // where exactly the environment setup failed.
951 catch (\Exception $e) {
952 $this->exceptionHandler($e);
953 // Abort if setUp() fails, since all test methods will fail.
954 // But ensure to clean up and restore the environment, since
955 // prepareEnvironment() succeeded.
956 $this->restoreEnvironment();
962 catch (\Exception $e) {
963 $this->exceptionHandler($e);
968 catch (\Exception $e) {
969 $this->exceptionHandler($e);
970 // If a test fails to tear down, abort the entire test class, since
971 // it is likely that all tests will fail in the same way and a
972 // failure here only results in additional test artifacts that have
973 // to be manually deleted.
974 $this->restoreEnvironment();
978 $this->restoreEnvironment();
979 // Remove the test method completion check record.
980 TestBase::deleteAssert($test_completion_check_id);
983 TestServiceProvider::$currentTest = NULL;
984 // Clear out the error messages and restore error handler.
985 drupal_get_messages();
986 restore_error_handler();
990 * Generates a database prefix for running tests.
992 * The database prefix is used by prepareEnvironment() to setup a public files
993 * directory for the test to be run, which also contains the PHP error log,
994 * which is written to in case of a fatal error. Since that directory is based
995 * on the database prefix, all tests (even unit tests) need to have one, in
996 * order to access and read the error log.
998 * @see TestBase::prepareEnvironment()
1000 * The generated database table prefix is used for the Drupal installation
1001 * being performed for the test. It is also used as user agent HTTP header
1002 * value by the cURL-based browser of WebTestBase, which is sent to the Drupal
1003 * installation of the test. During early Drupal bootstrap, the user agent
1004 * HTTP header is parsed, and if it matches, all database queries use the
1005 * database table prefix that has been generated here.
1007 * @see WebTestBase::curlInitialize()
1008 * @see drupal_valid_test_ua()
1010 private function prepareDatabasePrefix() {
1011 $test_db = new TestDatabase();
1012 $this->siteDirectory = $test_db->getTestSitePath();
1013 $this->databasePrefix = $test_db->getDatabasePrefix();
1015 // As soon as the database prefix is set, the test might start to execute.
1016 // All assertions as well as the SimpleTest batch operations are associated
1017 // with the testId, so the database prefix has to be associated with it.
1018 $affected_rows = self::getDatabaseConnection()->update('simpletest_test_id')
1019 ->fields(['last_prefix' => $this->databasePrefix])
1020 ->condition('test_id', $this->testId)
1022 if (!$affected_rows) {
1023 throw new \RuntimeException('Failed to set up database prefix.');
1028 * Act on global state information before the environment is altered for a test.
1030 * Allows e.g. KernelTestBase to prime system/extension info from the
1031 * parent site (and inject it into the test environment so as to improve
1034 protected function beforePrepareEnvironment() {
1038 * Prepares the current environment for running the test.
1040 * Backups various current environment variables and resets them, so they do
1041 * not interfere with the Drupal site installation in which tests are executed
1042 * and can be restored in TestBase::restoreEnvironment().
1044 * Also sets up new resources for the testing environment, such as the public
1045 * filesystem and configuration directories.
1047 * This method is private as it must only be called once by TestBase::run()
1048 * (multiple invocations for the same test would have unpredictable
1049 * consequences) and it must not be callable or overridable by test classes.
1051 * @see TestBase::beforePrepareEnvironment()
1053 private function prepareEnvironment() {
1054 $user = \Drupal::currentUser();
1055 // Allow (base) test classes to backup global state information.
1056 $this->beforePrepareEnvironment();
1058 // Create the database prefix for this test.
1059 $this->prepareDatabasePrefix();
1061 $language_interface = \Drupal::languageManager()->getCurrentLanguage();
1063 // When running the test runner within a test, back up the original database
1065 if (DRUPAL_TEST_IN_CHILD_SITE) {
1066 $this->originalPrefix = drupal_valid_test_ua();
1069 // Backup current in-memory configuration.
1070 $site_path = \Drupal::service('site.path');
1071 $this->originalSite = $site_path;
1072 $this->originalSettings = Settings::getAll();
1073 $this->originalConfig = $GLOBALS['config'];
1074 // @todo Remove all remnants of $GLOBALS['conf'].
1075 // @see https://www.drupal.org/node/2183323
1076 $this->originalConf = isset($GLOBALS['conf']) ? $GLOBALS['conf'] : NULL;
1078 // Backup statics and globals.
1079 $this->originalContainer = \Drupal::getContainer();
1080 $this->originalLanguage = $language_interface;
1081 $this->originalConfigDirectories = $GLOBALS['config_directories'];
1083 // Save further contextual information.
1084 // Use the original files directory to avoid nesting it within an existing
1085 // simpletest directory if a test is executed within a test.
1086 $this->originalFileDirectory = Settings::get('file_public_path', $site_path . '/files');
1087 $this->originalProfile = drupal_get_profile();
1088 $this->originalUser = isset($user) ? clone $user : NULL;
1090 // Prevent that session data is leaked into the UI test runner by closing
1091 // the session and then setting the session-name (i.e. the name of the
1092 // session cookie) to a random value. If a test starts a new session, then
1093 // it will be associated with a different session-name. After the test-run
1094 // it can be safely destroyed.
1095 // @see TestBase::restoreEnvironment()
1096 if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) {
1097 session_write_close();
1099 $this->originalSessionName = session_name();
1100 session_name('SIMPLETEST' . Crypt::randomBytesBase64());
1102 // Save and clean the shutdown callbacks array because it is static cached
1103 // and will be changed by the test run. Otherwise it will contain callbacks
1104 // from both environments and the testing environment will try to call the
1105 // handlers defined by the original one.
1106 $callbacks = &drupal_register_shutdown_function();
1107 $this->originalShutdownCallbacks = $callbacks;
1110 // Create test directory ahead of installation so fatal errors and debug
1111 // information can be logged during installation process.
1112 file_prepare_directory($this->siteDirectory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
1114 // Prepare filesystem directory paths.
1115 $this->publicFilesDirectory = $this->siteDirectory . '/files';
1116 $this->privateFilesDirectory = $this->siteDirectory . '/private';
1117 $this->tempFilesDirectory = $this->siteDirectory . '/temp';
1118 $this->translationFilesDirectory = $this->siteDirectory . '/translations';
1120 $this->generatedTestFiles = FALSE;
1122 // Ensure the configImporter is refreshed for each test.
1123 $this->configImporter = NULL;
1125 // Unregister all custom stream wrappers of the parent site.
1126 // Availability of Drupal stream wrappers varies by test base class:
1127 // - KernelTestBase supports and maintains stream wrappers in a custom
1129 // - WebTestBase re-initializes Drupal stream wrappers after installation.
1130 // The original stream wrappers are restored after the test run.
1131 // @see TestBase::restoreEnvironment()
1132 $this->originalContainer->get('stream_wrapper_manager')->unregister();
1135 drupal_static_reset();
1137 // Ensure there is no service container.
1138 $this->container = NULL;
1139 \Drupal::unsetContainer();
1142 unset($GLOBALS['config_directories']);
1143 unset($GLOBALS['config']);
1144 unset($GLOBALS['conf']);
1146 // Log fatal errors.
1147 ini_set('log_errors', 1);
1148 ini_set('error_log', DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log');
1150 // Change the database prefix.
1151 $this->changeDatabasePrefix();
1153 // After preparing the environment and changing the database prefix, we are
1154 // in a valid test environment.
1155 drupal_valid_test_ua($this->databasePrefix);
1159 // For performance, simply use the database prefix as hash salt.
1160 'hash_salt' => $this->databasePrefix,
1161 'container_yamls' => [],
1164 drupal_set_time_limit($this->timeLimit);
1168 * Performs cleanup tasks after each individual test method has been run.
1170 protected function tearDown() {
1174 * Cleans up the test environment and restores the original environment.
1176 * Deletes created files, database tables, and reverts environment changes.
1178 * This method needs to be invoked for both unit and integration tests.
1180 * @see TestBase::prepareDatabasePrefix()
1181 * @see TestBase::changeDatabasePrefix()
1182 * @see TestBase::prepareEnvironment()
1184 private function restoreEnvironment() {
1185 // Destroy the session if one was started during the test-run.
1187 if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) {
1189 $params = session_get_cookie_params();
1190 setcookie(session_name(), '', REQUEST_TIME - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
1192 session_name($this->originalSessionName);
1194 // Reset all static variables.
1195 // Unsetting static variables will potentially invoke destruct methods,
1196 // which might call into functions that prime statics and caches again.
1197 // In that case, all functions are still operating on the test environment,
1198 // which means they may need to access its filesystem and database.
1199 drupal_static_reset();
1201 if ($this->container && $this->container->has('state') && $state = $this->container->get('state')) {
1202 $captured_emails = $state->get('system.test_mail_collector') ?: [];
1203 $emailCount = count($captured_emails);
1205 $message = $emailCount == 1 ? '1 email was sent during this test.' : $emailCount . ' emails were sent during this test.';
1206 $this->pass($message, 'Email');
1210 // Sleep for 50ms to allow shutdown functions and terminate events to
1211 // complete. Further information: https://www.drupal.org/node/2194357.
1214 // Remove all prefixed tables.
1215 $original_connection_info = Database::getConnectionInfo('simpletest_original_default');
1216 $original_prefix = $original_connection_info['default']['prefix']['default'];
1217 $test_connection_info = Database::getConnectionInfo('default');
1218 $test_prefix = $test_connection_info['default']['prefix']['default'];
1219 if ($original_prefix != $test_prefix) {
1220 $tables = Database::getConnection()->schema()->findTables('%');
1221 foreach ($tables as $table) {
1222 if (Database::getConnection()->schema()->dropTable($table)) {
1223 unset($tables[$table]);
1228 // In case a fatal error occurred that was not in the test process read the
1229 // log to pick up any fatal errors.
1230 simpletest_log_read($this->testId, $this->databasePrefix, get_class($this));
1232 // Restore original dependency injection container.
1233 $this->container = $this->originalContainer;
1234 \Drupal::setContainer($this->originalContainer);
1236 // Delete test site directory.
1237 file_unmanaged_delete_recursive($this->siteDirectory, [$this, 'filePreDeleteCallback']);
1239 // Restore original database connection.
1240 Database::removeConnection('default');
1241 Database::renameConnection('simpletest_original_default', 'default');
1243 // Reset all static variables.
1244 // All destructors of statically cached objects have been invoked above;
1245 // this second reset is guaranteed to reset everything to nothing.
1246 drupal_static_reset();
1248 // Restore original in-memory configuration.
1249 $GLOBALS['config'] = $this->originalConfig;
1250 $GLOBALS['conf'] = $this->originalConf;
1251 new Settings($this->originalSettings);
1253 // Restore original statics and globals.
1254 $GLOBALS['config_directories'] = $this->originalConfigDirectories;
1256 // Re-initialize original stream wrappers of the parent site.
1257 // This must happen after static variables have been reset and the original
1258 // container and $config_directories are restored, as simpletest_log_read()
1259 // uses the public stream wrapper to locate the error.log.
1260 $this->originalContainer->get('stream_wrapper_manager')->register();
1262 if (isset($this->originalPrefix)) {
1263 drupal_valid_test_ua($this->originalPrefix);
1266 drupal_valid_test_ua(FALSE);
1269 // Restore original shutdown callbacks.
1270 $callbacks = &drupal_register_shutdown_function();
1271 $callbacks = $this->originalShutdownCallbacks;
1275 * Handle errors during test runs.
1277 * Because this is registered in set_error_handler(), it has to be public.
1279 * @see set_error_handler
1281 public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
1282 if ($severity & error_reporting()) {
1284 E_STRICT => 'Run-time notice',
1285 E_WARNING => 'Warning',
1286 E_NOTICE => 'Notice',
1287 E_CORE_ERROR => 'Core error',
1288 E_CORE_WARNING => 'Core warning',
1289 E_USER_ERROR => 'User error',
1290 E_USER_WARNING => 'User warning',
1291 E_USER_NOTICE => 'User notice',
1292 E_RECOVERABLE_ERROR => 'Recoverable error',
1293 E_DEPRECATED => 'Deprecated',
1294 E_USER_DEPRECATED => 'User deprecated',
1297 $backtrace = debug_backtrace();
1299 // Add verbose backtrace for errors, but not for debug() messages.
1300 if ($severity !== E_USER_NOTICE) {
1301 $verbose_backtrace = $backtrace;
1302 array_shift($verbose_backtrace);
1303 $message .= '<pre class="backtrace">' . Error::formatBacktrace($verbose_backtrace) . '</pre>';
1306 $this->error($message, $error_map[$severity], Error::getLastCaller($backtrace));
1312 * Handle exceptions.
1314 * @see set_exception_handler
1316 protected function exceptionHandler($exception) {
1317 $backtrace = $exception->getTrace();
1318 $verbose_backtrace = $backtrace;
1319 // Push on top of the backtrace the call that generated the exception.
1320 array_unshift($backtrace, [
1321 'line' => $exception->getLine(),
1322 'file' => $exception->getFile(),
1324 $decoded_exception = Error::decodeException($exception);
1325 unset($decoded_exception['backtrace']);
1326 $message = SafeMarkup::format('%type: @message in %function (line %line of %file). <pre class="backtrace">@backtrace</pre>', $decoded_exception + [
1327 '@backtrace' => Error::formatBacktrace($verbose_backtrace),
1329 $this->error($message, 'Uncaught exception', Error::getLastCaller($backtrace));
1333 * Changes in memory settings.
1336 * The name of the setting to return.
1338 * The value of the setting.
1340 * @see \Drupal\Core\Site\Settings::get()
1342 protected function settingsSet($name, $value) {
1343 $settings = Settings::getAll();
1344 $settings[$name] = $value;
1345 new Settings($settings);
1349 * Ensures test files are deletable within file_unmanaged_delete_recursive().
1351 * Some tests chmod generated files to be read only. During
1352 * TestBase::restoreEnvironment() and other cleanup operations, these files
1353 * need to get deleted too.
1355 public static function filePreDeleteCallback($path) {
1356 // When the webserver runs with the same system user as the test runner, we
1357 // can make read-only files writable again. If not, chmod will fail while
1358 // the file deletion still works if file permissions have been configured
1359 // correctly. Thus, we ignore any problems while running chmod.
1360 @chmod($path, 0700);
1364 * Configuration accessor for tests. Returns non-overridden configuration.
1367 * Configuration name.
1369 * @return \Drupal\Core\Config\Config
1370 * The configuration object with original configuration data.
1372 protected function config($name) {
1373 return \Drupal::configFactory()->getEditable($name);
1377 * Gets the database prefix.
1380 * The database prefix
1382 public function getDatabasePrefix() {
1383 return $this->databasePrefix;
1387 * Gets the temporary files directory.
1390 * The temporary files directory.
1392 public function getTempFilesDirectory() {
1393 return $this->tempFilesDirectory;