Chris@0: 0, Chris@0: '#fail' => 0, Chris@0: '#exception' => 0, Chris@0: '#debug' => 0, Chris@0: ]; Chris@0: Chris@0: /** Chris@0: * Assertions thrown in that test case. Chris@0: * Chris@17: * @var array Chris@0: */ Chris@0: protected $assertions = []; Chris@0: Chris@0: /** Chris@0: * This class is skipped when looking for the source of an assertion. Chris@0: * Chris@0: * When displaying which function an assert comes from, it's not too useful Chris@0: * to see "WebTestBase->drupalLogin()', we would like to see the test Chris@0: * that called it. So we need to skip the classes defining these helper Chris@0: * methods. Chris@0: */ Chris@0: protected $skipClasses = [__CLASS__ => TRUE]; Chris@0: Chris@0: /** Chris@0: * TRUE if verbose debugging is enabled. Chris@0: * Chris@0: * @var bool Chris@0: */ Chris@0: public $verbose; Chris@0: Chris@0: /** Chris@0: * Incrementing identifier for verbose output filenames. Chris@0: * Chris@0: * @var int Chris@0: */ Chris@0: protected $verboseId = 0; Chris@0: Chris@0: /** Chris@0: * Safe class name for use in verbose output filenames. Chris@0: * Chris@0: * Namespaces separator (\) replaced with _. Chris@0: * Chris@0: * @var string Chris@0: */ Chris@0: protected $verboseClassName; Chris@0: Chris@0: /** Chris@0: * Directory where verbose output files are put. Chris@0: * Chris@0: * @var string Chris@0: */ Chris@0: protected $verboseDirectory; Chris@0: Chris@0: /** Chris@0: * URL to the verbose output file directory. Chris@0: * Chris@0: * @var string Chris@0: */ Chris@0: protected $verboseDirectoryUrl; Chris@0: Chris@0: /** Chris@0: * The original configuration (variables), if available. Chris@0: * Chris@0: * @var string Chris@0: * @todo Remove all remnants of $GLOBALS['conf']. Chris@0: * @see https://www.drupal.org/node/2183323 Chris@0: */ Chris@0: protected $originalConf; Chris@0: Chris@0: /** Chris@0: * The original configuration (variables). Chris@0: * Chris@0: * @var string Chris@0: */ Chris@0: protected $originalConfig; Chris@0: Chris@0: /** Chris@0: * The original configuration directories. Chris@0: * Chris@0: * An array of paths keyed by the CONFIG_*_DIRECTORY constants defined by Chris@0: * core/includes/bootstrap.inc. Chris@0: * Chris@0: * @var array Chris@0: */ Chris@0: protected $originalConfigDirectories; Chris@0: Chris@0: /** Chris@0: * The original container. Chris@0: * Chris@0: * @var \Symfony\Component\DependencyInjection\ContainerInterface Chris@0: */ Chris@0: protected $originalContainer; Chris@0: Chris@0: /** Chris@0: * The original file directory, before it was changed for testing purposes. Chris@0: * Chris@0: * @var string Chris@0: */ Chris@0: protected $originalFileDirectory = NULL; Chris@0: Chris@0: /** Chris@0: * The original language. Chris@0: * Chris@0: * @var \Drupal\Core\Language\LanguageInterface Chris@0: */ Chris@0: protected $originalLanguage; Chris@0: Chris@0: /** Chris@0: * The original database prefix when running inside Simpletest. Chris@0: * Chris@0: * @var string Chris@0: */ Chris@0: protected $originalPrefix; Chris@0: Chris@0: /** Chris@0: * The name of the session cookie of the test-runner. Chris@0: * Chris@0: * @var string Chris@0: */ Chris@0: protected $originalSessionName; Chris@0: Chris@0: /** Chris@0: * The settings array. Chris@0: * Chris@0: * @var array Chris@0: */ Chris@0: protected $originalSettings; Chris@0: Chris@0: /** Chris@0: * The original array of shutdown function callbacks. Chris@0: * Chris@0: * @var array Chris@0: */ Chris@0: protected $originalShutdownCallbacks; Chris@0: Chris@0: /** Chris@0: * The original user, before testing began. Chris@0: * Chris@0: * @var \Drupal\Core\Session\AccountProxyInterface Chris@0: */ Chris@0: protected $originalUser; Chris@0: Chris@0: /** Chris@0: * The translation file directory for the test environment. Chris@0: * Chris@0: * This is set in TestBase::prepareEnvironment(). Chris@0: * Chris@0: * @var string Chris@0: */ Chris@0: protected $translationFilesDirectory; Chris@0: Chris@0: /** Chris@0: * Whether to die in case any test assertion fails. Chris@0: * Chris@0: * @var bool Chris@0: * Chris@0: * @see run-tests.sh Chris@0: */ Chris@0: public $dieOnFail = FALSE; Chris@0: Chris@0: /** Chris@0: * The config importer that can used in a test. Chris@0: * Chris@0: * @var \Drupal\Core\Config\ConfigImporter Chris@0: */ Chris@0: protected $configImporter; Chris@0: Chris@0: /** Chris@0: * HTTP authentication method (specified as a CURLAUTH_* constant). Chris@0: * Chris@0: * @var int Chris@0: * @see http://php.net/manual/function.curl-setopt.php Chris@0: */ Chris@0: protected $httpAuthMethod = CURLAUTH_BASIC; Chris@0: Chris@0: /** Chris@0: * HTTP authentication credentials (:). Chris@0: * Chris@0: * @var string Chris@0: */ Chris@0: protected $httpAuthCredentials = NULL; Chris@0: Chris@0: /** Chris@0: * Constructor for Test. Chris@0: * Chris@0: * @param $test_id Chris@0: * Tests with the same id are reported together. Chris@0: */ Chris@0: public function __construct($test_id = NULL) { Chris@0: $this->testId = $test_id; Chris@0: } Chris@0: Chris@0: /** Chris@17: * Fail the test if it belongs to a PHPUnit-based framework. Chris@17: * Chris@17: * This would probably be caused by automated test conversions such as those Chris@17: * in https://www.drupal.org/project/drupal/issues/2770921. Chris@17: */ Chris@17: public function checkTestHierarchyMismatch() { Chris@17: // We can use getPhpunitTestSuite() because it uses a regex on the class' Chris@17: // namespace to deduce the PHPUnit test suite. Chris@17: if (TestDiscovery::getPhpunitTestSuite(get_class($this)) !== FALSE) { Chris@17: $this->fail(get_class($this) . ' incorrectly subclasses ' . __CLASS__ . ', it should probably extend \Drupal\Tests\BrowserTestBase instead.'); Chris@17: } Chris@17: } Chris@17: Chris@17: /** Chris@0: * Performs setup tasks before each individual test method is run. Chris@0: */ Chris@0: abstract protected function setUp(); Chris@0: Chris@0: /** Chris@0: * Checks the matching requirements for Test. Chris@0: * Chris@0: * @return Chris@0: * Array of errors containing a list of unmet requirements. Chris@0: */ Chris@0: protected function checkRequirements() { Chris@0: return []; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Helper method to store an assertion record in the configured database. Chris@0: * Chris@0: * This method decouples database access from assertion logic. Chris@0: * Chris@0: * @param array $assertion Chris@0: * Keyed array representing an assertion, as generated by assert(). Chris@0: * Chris@0: * @see self::assert() Chris@0: * Chris@0: * @return \Drupal\Core\Database\StatementInterface|int|null Chris@0: * The message ID. Chris@0: */ Chris@0: protected function storeAssertion(array $assertion) { Chris@0: return self::getDatabaseConnection() Chris@0: ->insert('simpletest', ['return' => Database::RETURN_INSERT_ID]) Chris@0: ->fields($assertion) Chris@0: ->execute(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Internal helper: stores the assert. Chris@0: * Chris@0: * @param $status Chris@0: * Can be 'pass', 'fail', 'exception', 'debug'. Chris@0: * TRUE is a synonym for 'pass', FALSE for 'fail'. Chris@0: * @param string|\Drupal\Component\Render\MarkupInterface $message Chris@0: * (optional) A message to display with the assertion. Do not translate Chris@17: * messages: use \Drupal\Component\Render\FormattableMarkup to embed Chris@0: * variables in the message text, not t(). If left blank, a default message Chris@0: * will be displayed. Chris@0: * @param $group Chris@0: * (optional) The group this message is in, which is displayed in a column Chris@0: * in test output. Use 'Debug' to indicate this is debugging output. Do not Chris@0: * translate this string. Defaults to 'Other'; most tests do not override Chris@0: * this default. Chris@0: * @param $caller Chris@0: * By default, the assert comes from a function whose name starts with Chris@0: * 'test'. Instead, you can specify where this assert originates from Chris@0: * by passing in an associative array as $caller. Key 'file' is Chris@0: * the name of the source file, 'line' is the line number and 'function' Chris@0: * is the caller function itself. Chris@0: */ Chris@0: protected function assert($status, $message = '', $group = 'Other', array $caller = NULL) { Chris@0: if ($message instanceof MarkupInterface) { Chris@0: $message = (string) $message; Chris@0: } Chris@0: // Convert boolean status to string status. Chris@0: if (is_bool($status)) { Chris@0: $status = $status ? 'pass' : 'fail'; Chris@0: } Chris@0: Chris@0: // Increment summary result counter. Chris@0: $this->results['#' . $status]++; Chris@0: Chris@0: // Get the function information about the call to the assertion method. Chris@0: if (!$caller) { Chris@0: $caller = $this->getAssertionCall(); Chris@0: } Chris@0: Chris@0: // Creation assertion array that can be displayed while tests are running. Chris@0: $assertion = [ Chris@0: 'test_id' => $this->testId, Chris@0: 'test_class' => get_class($this), Chris@0: 'status' => $status, Chris@0: 'message' => $message, Chris@0: 'message_group' => $group, Chris@0: 'function' => $caller['function'], Chris@0: 'line' => $caller['line'], Chris@0: 'file' => $caller['file'], Chris@0: ]; Chris@0: Chris@0: // Store assertion for display after the test has completed. Chris@0: $message_id = $this->storeAssertion($assertion); Chris@0: $assertion['message_id'] = $message_id; Chris@0: $this->assertions[] = $assertion; Chris@0: Chris@0: // We do not use a ternary operator here to allow a breakpoint on Chris@0: // test failure. Chris@0: if ($status == 'pass') { Chris@0: return TRUE; Chris@0: } Chris@0: else { Chris@0: if ($this->dieOnFail && ($status == 'fail' || $status == 'exception')) { Chris@0: exit(1); Chris@0: } Chris@0: return FALSE; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Store an assertion from outside the testing context. Chris@0: * Chris@0: * This is useful for inserting assertions that can only be recorded after Chris@0: * the test case has been destroyed, such as PHP fatal errors. The caller Chris@0: * information is not automatically gathered since the caller is most likely Chris@0: * inserting the assertion on behalf of other code. In all other respects Chris@0: * the method behaves just like \Drupal\simpletest\TestBase::assert() in terms Chris@0: * of storing the assertion. Chris@0: * Chris@0: * @return Chris@0: * Message ID of the stored assertion. Chris@0: * Chris@0: * @see \Drupal\simpletest\TestBase::assert() Chris@0: * @see \Drupal\simpletest\TestBase::deleteAssert() Chris@0: */ Chris@0: public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = []) { Chris@0: // Convert boolean status to string status. Chris@0: if (is_bool($status)) { Chris@0: $status = $status ? 'pass' : 'fail'; Chris@0: } Chris@0: Chris@0: $caller += [ Chris@0: 'function' => 'Unknown', Chris@0: 'line' => 0, Chris@0: 'file' => 'Unknown', Chris@0: ]; Chris@0: Chris@0: $assertion = [ Chris@0: 'test_id' => $test_id, Chris@0: 'test_class' => $test_class, Chris@0: 'status' => $status, Chris@0: 'message' => $message, Chris@0: 'message_group' => $group, Chris@0: 'function' => $caller['function'], Chris@0: 'line' => $caller['line'], Chris@0: 'file' => $caller['file'], Chris@0: ]; Chris@0: Chris@0: // We can't use storeAssertion() because this method is static. Chris@0: return self::getDatabaseConnection() Chris@0: ->insert('simpletest') Chris@0: ->fields($assertion) Chris@0: ->execute(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Delete an assertion record by message ID. Chris@0: * Chris@0: * @param $message_id Chris@0: * Message ID of the assertion to delete. Chris@0: * Chris@0: * @return Chris@0: * TRUE if the assertion was deleted, FALSE otherwise. Chris@0: * Chris@0: * @see \Drupal\simpletest\TestBase::insertAssert() Chris@0: */ Chris@0: public static function deleteAssert($message_id) { Chris@0: // We can't use storeAssertion() because this method is static. Chris@0: return (bool) self::getDatabaseConnection() Chris@0: ->delete('simpletest') Chris@0: ->condition('message_id', $message_id) Chris@0: ->execute(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Cycles through backtrace until the first non-assertion method is found. Chris@0: * Chris@0: * @return Chris@0: * Array representing the true caller. Chris@0: */ Chris@0: protected function getAssertionCall() { Chris@0: $backtrace = debug_backtrace(); Chris@0: Chris@0: // The first element is the call. The second element is the caller. Chris@0: // We skip calls that occurred in one of the methods of our base classes Chris@0: // or in an assertion function. Chris@0: while (($caller = $backtrace[1]) && Chris@0: ((isset($caller['class']) && isset($this->skipClasses[$caller['class']])) || Chris@0: substr($caller['function'], 0, 6) == 'assert')) { Chris@0: // We remove that call. Chris@0: array_shift($backtrace); Chris@0: } Chris@0: Chris@0: return Error::getLastCaller($backtrace); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Check to see if a value is not false. Chris@0: * Chris@0: * False values are: empty string, 0, NULL, and FALSE. Chris@0: * Chris@0: * @param $value Chris@0: * The value on which the assertion is to be done. Chris@0: * @param $message Chris@0: * (optional) A message to display with the assertion. Do not translate Chris@17: * messages: use \Drupal\Component\Render\FormattableMarkup to embed Chris@0: * variables in the message text, not t(). If left blank, a default message Chris@0: * will be displayed. Chris@0: * @param $group Chris@0: * (optional) The group this message is in, which is displayed in a column Chris@0: * in test output. Use 'Debug' to indicate this is debugging output. Do not Chris@0: * translate this string. Defaults to 'Other'; most tests do not override Chris@0: * this default. Chris@0: * Chris@0: * @return Chris@0: * TRUE if the assertion succeeded, FALSE otherwise. Chris@0: */ Chris@0: protected function assertTrue($value, $message = '', $group = 'Other') { Chris@17: return $this->assert((bool) $value, $message ? $message : new FormattableMarkup('Value @value is TRUE.', ['@value' => var_export($value, TRUE)]), $group); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Check to see if a value is false. Chris@0: * Chris@0: * False values are: empty string, 0, NULL, and FALSE. Chris@0: * Chris@0: * @param $value Chris@0: * The value on which the assertion is to be done. Chris@0: * @param $message Chris@0: * (optional) A message to display with the assertion. Do not translate Chris@17: * messages: use \Drupal\Component\Render\FormattableMarkup to embed Chris@0: * variables in the message text, not t(). If left blank, a default message Chris@0: * will be displayed. Chris@0: * @param $group Chris@0: * (optional) The group this message is in, which is displayed in a column Chris@0: * in test output. Use 'Debug' to indicate this is debugging output. Do not Chris@0: * translate this string. Defaults to 'Other'; most tests do not override Chris@0: * this default. Chris@0: * Chris@0: * @return Chris@0: * TRUE if the assertion succeeded, FALSE otherwise. Chris@0: */ Chris@0: protected function assertFalse($value, $message = '', $group = 'Other') { Chris@17: return $this->assert(!$value, $message ? $message : new FormattableMarkup('Value @value is FALSE.', ['@value' => var_export($value, TRUE)]), $group); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Check to see if a value is NULL. Chris@0: * Chris@0: * @param $value Chris@0: * The value on which the assertion is to be done. Chris@0: * @param $message Chris@0: * (optional) A message to display with the assertion. Do not translate Chris@17: * messages: use \Drupal\Component\Render\FormattableMarkup to embed Chris@0: * variables in the message text, not t(). If left blank, a default message Chris@0: * will be displayed. Chris@0: * @param $group Chris@0: * (optional) The group this message is in, which is displayed in a column Chris@0: * in test output. Use 'Debug' to indicate this is debugging output. Do not Chris@0: * translate this string. Defaults to 'Other'; most tests do not override Chris@0: * this default. Chris@0: * Chris@0: * @return Chris@0: * TRUE if the assertion succeeded, FALSE otherwise. Chris@0: */ Chris@0: protected function assertNull($value, $message = '', $group = 'Other') { Chris@17: return $this->assert(!isset($value), $message ? $message : new FormattableMarkup('Value @value is NULL.', ['@value' => var_export($value, TRUE)]), $group); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Check to see if a value is not NULL. Chris@0: * Chris@0: * @param $value Chris@0: * The value on which the assertion is to be done. Chris@0: * @param $message Chris@0: * (optional) A message to display with the assertion. Do not translate Chris@17: * messages: use \Drupal\Component\Render\FormattableMarkup to embed Chris@0: * variables in the message text, not t(). If left blank, a default message Chris@0: * will be displayed. Chris@0: * @param $group Chris@0: * (optional) The group this message is in, which is displayed in a column Chris@0: * in test output. Use 'Debug' to indicate this is debugging output. Do not Chris@0: * translate this string. Defaults to 'Other'; most tests do not override Chris@0: * this default. Chris@0: * Chris@0: * @return Chris@0: * TRUE if the assertion succeeded, FALSE otherwise. Chris@0: */ Chris@0: protected function assertNotNull($value, $message = '', $group = 'Other') { Chris@17: return $this->assert(isset($value), $message ? $message : new FormattableMarkup('Value @value is not NULL.', ['@value' => var_export($value, TRUE)]), $group); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Check to see if two values are equal. Chris@0: * Chris@0: * @param $first Chris@0: * The first value to check. Chris@0: * @param $second Chris@0: * The second value to check. Chris@0: * @param $message Chris@0: * (optional) A message to display with the assertion. Do not translate Chris@17: * messages: use \Drupal\Component\Render\FormattableMarkup to embed Chris@0: * variables in the message text, not t(). If left blank, a default message Chris@0: * will be displayed. Chris@0: * @param $group Chris@0: * (optional) The group this message is in, which is displayed in a column Chris@0: * in test output. Use 'Debug' to indicate this is debugging output. Do not Chris@0: * translate this string. Defaults to 'Other'; most tests do not override Chris@0: * this default. Chris@0: * Chris@0: * @return Chris@0: * TRUE if the assertion succeeded, FALSE otherwise. Chris@0: */ Chris@0: protected function assertEqual($first, $second, $message = '', $group = 'Other') { Chris@0: // Cast objects implementing MarkupInterface to string instead of Chris@0: // relying on PHP casting them to string depending on what they are being Chris@0: // comparing with. Chris@0: $first = $this->castSafeStrings($first); Chris@0: $second = $this->castSafeStrings($second); Chris@0: $is_equal = $first == $second; Chris@0: if (!$is_equal || !$message) { Chris@17: $default_message = new FormattableMarkup('Value @first is equal to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]); Chris@0: $message = $message ? $message . PHP_EOL . $default_message : $default_message; Chris@0: } Chris@0: return $this->assert($is_equal, $message, $group); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Check to see if two values are not equal. Chris@0: * Chris@0: * @param $first Chris@0: * The first value to check. Chris@0: * @param $second Chris@0: * The second value to check. Chris@0: * @param $message Chris@0: * (optional) A message to display with the assertion. Do not translate Chris@17: * messages: use \Drupal\Component\Render\FormattableMarkup to embed Chris@0: * variables in the message text, not t(). If left blank, a default message Chris@0: * will be displayed. Chris@0: * @param $group Chris@0: * (optional) The group this message is in, which is displayed in a column Chris@0: * in test output. Use 'Debug' to indicate this is debugging output. Do not Chris@0: * translate this string. Defaults to 'Other'; most tests do not override Chris@0: * this default. Chris@0: * Chris@0: * @return Chris@0: * TRUE if the assertion succeeded, FALSE otherwise. Chris@0: */ Chris@0: protected function assertNotEqual($first, $second, $message = '', $group = 'Other') { Chris@0: // Cast objects implementing MarkupInterface to string instead of Chris@0: // relying on PHP casting them to string depending on what they are being Chris@0: // comparing with. Chris@0: $first = $this->castSafeStrings($first); Chris@0: $second = $this->castSafeStrings($second); Chris@0: $not_equal = $first != $second; Chris@0: if (!$not_equal || !$message) { Chris@17: $default_message = new FormattableMarkup('Value @first is not equal to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]); Chris@0: $message = $message ? $message . PHP_EOL . $default_message : $default_message; Chris@0: } Chris@0: return $this->assert($not_equal, $message, $group); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Check to see if two values are identical. Chris@0: * Chris@0: * @param $first Chris@0: * The first value to check. Chris@0: * @param $second Chris@0: * The second value to check. Chris@0: * @param $message Chris@0: * (optional) A message to display with the assertion. Do not translate Chris@17: * messages: use \Drupal\Component\Render\FormattableMarkup to embed Chris@0: * variables in the message text, not t(). If left blank, a default message Chris@0: * will be displayed. Chris@0: * @param $group Chris@0: * (optional) The group this message is in, which is displayed in a column Chris@0: * in test output. Use 'Debug' to indicate this is debugging output. Do not Chris@0: * translate this string. Defaults to 'Other'; most tests do not override Chris@0: * this default. Chris@0: * Chris@0: * @return Chris@0: * TRUE if the assertion succeeded, FALSE otherwise. Chris@0: */ Chris@0: protected function assertIdentical($first, $second, $message = '', $group = 'Other') { Chris@0: $is_identical = $first === $second; Chris@0: if (!$is_identical || !$message) { Chris@17: $default_message = new FormattableMarkup('Value @first is identical to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]); Chris@0: $message = $message ? $message . PHP_EOL . $default_message : $default_message; Chris@0: } Chris@0: return $this->assert($is_identical, $message, $group); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Check to see if two values are not identical. Chris@0: * Chris@0: * @param $first Chris@0: * The first value to check. Chris@0: * @param $second Chris@0: * The second value to check. Chris@0: * @param $message Chris@0: * (optional) A message to display with the assertion. Do not translate Chris@17: * messages: use \Drupal\Component\Render\FormattableMarkup to embed Chris@0: * variables in the message text, not t(). If left blank, a default message Chris@0: * will be displayed. Chris@0: * @param $group Chris@0: * (optional) The group this message is in, which is displayed in a column Chris@0: * in test output. Use 'Debug' to indicate this is debugging output. Do not Chris@0: * translate this string. Defaults to 'Other'; most tests do not override Chris@0: * this default. Chris@0: * Chris@0: * @return Chris@0: * TRUE if the assertion succeeded, FALSE otherwise. Chris@0: */ Chris@0: protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') { Chris@0: $not_identical = $first !== $second; Chris@0: if (!$not_identical || !$message) { Chris@17: $default_message = new FormattableMarkup('Value @first is not identical to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]); Chris@0: $message = $message ? $message . PHP_EOL . $default_message : $default_message; Chris@0: } Chris@0: return $this->assert($not_identical, $message, $group); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Checks to see if two objects are identical. Chris@0: * Chris@0: * @param object $object1 Chris@0: * The first object to check. Chris@0: * @param object $object2 Chris@0: * The second object to check. Chris@0: * @param $message Chris@0: * (optional) A message to display with the assertion. Do not translate Chris@17: * messages: use \Drupal\Component\Render\FormattableMarkup to embed Chris@0: * variables in the message text, not t(). If left blank, a default message Chris@0: * will be displayed. Chris@0: * @param $group Chris@0: * (optional) The group this message is in, which is displayed in a column Chris@0: * in test output. Use 'Debug' to indicate this is debugging output. Do not Chris@0: * translate this string. Defaults to 'Other'; most tests do not override Chris@0: * this default. Chris@0: * Chris@0: * @return Chris@0: * TRUE if the assertion succeeded, FALSE otherwise. Chris@0: */ Chris@0: protected function assertIdenticalObject($object1, $object2, $message = '', $group = 'Other') { Chris@17: $message = $message ?: new FormattableMarkup('@object1 is identical to @object2', [ Chris@0: '@object1' => var_export($object1, TRUE), Chris@0: '@object2' => var_export($object2, TRUE), Chris@0: ]); Chris@0: $identical = TRUE; Chris@0: foreach ($object1 as $key => $value) { Chris@0: $identical = $identical && isset($object2->$key) && $object2->$key === $value; Chris@0: } Chris@0: return $this->assertTrue($identical, $message, $group); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Asserts that no errors have been logged to the PHP error.log thus far. Chris@0: * Chris@0: * @return bool Chris@0: * TRUE if the assertion succeeded, FALSE otherwise. Chris@0: * Chris@0: * @see \Drupal\simpletest\TestBase::prepareEnvironment() Chris@0: * @see \Drupal\Core\DrupalKernel::bootConfiguration() Chris@0: */ Chris@0: protected function assertNoErrorsLogged() { Chris@0: // Since PHP only creates the error.log file when an actual error is Chris@0: // triggered, it is sufficient to check whether the file exists. Chris@0: return $this->assertFalse(file_exists(DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log'), 'PHP error.log is empty.'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Asserts that a specific error has been logged to the PHP error log. Chris@0: * Chris@0: * @param string $error_message Chris@0: * The expected error message. Chris@0: * Chris@0: * @return bool Chris@0: * TRUE if the assertion succeeded, FALSE otherwise. Chris@0: * Chris@0: * @see \Drupal\simpletest\TestBase::prepareEnvironment() Chris@0: * @see \Drupal\Core\DrupalKernel::bootConfiguration() Chris@0: */ Chris@0: protected function assertErrorLogged($error_message) { Chris@0: $error_log_filename = DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log'; Chris@0: if (!file_exists($error_log_filename)) { Chris@0: $this->error('No error logged yet.'); Chris@0: } Chris@0: Chris@0: $content = file_get_contents($error_log_filename); Chris@0: $rows = explode(PHP_EOL, $content); Chris@0: Chris@0: // We iterate over the rows in order to be able to remove the logged error Chris@0: // afterwards. Chris@0: $found = FALSE; Chris@0: foreach ($rows as $row_index => $row) { Chris@0: if (strpos($content, $error_message) !== FALSE) { Chris@0: $found = TRUE; Chris@0: unset($rows[$row_index]); Chris@0: } Chris@0: } Chris@0: Chris@0: file_put_contents($error_log_filename, implode("\n", $rows)); Chris@0: Chris@0: return $this->assertTrue($found, sprintf('The %s error message was logged.', $error_message)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Fire an assertion that is always positive. Chris@0: * Chris@0: * @param $message Chris@0: * (optional) A message to display with the assertion. Do not translate Chris@17: * messages: use \Drupal\Component\Render\FormattableMarkup to embed Chris@0: * variables in the message text, not t(). If left blank, a default message Chris@0: * will be displayed. Chris@0: * @param $group Chris@0: * (optional) The group this message is in, which is displayed in a column Chris@0: * in test output. Use 'Debug' to indicate this is debugging output. Do not Chris@0: * translate this string. Defaults to 'Other'; most tests do not override Chris@0: * this default. Chris@0: * Chris@0: * @return Chris@0: * TRUE. Chris@0: */ Chris@0: protected function pass($message = NULL, $group = 'Other') { Chris@0: return $this->assert(TRUE, $message, $group); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Fire an assertion that is always negative. Chris@0: * Chris@0: * @param $message Chris@0: * (optional) A message to display with the assertion. Do not translate Chris@17: * messages: use \Drupal\Component\Render\FormattableMarkup to embed Chris@0: * variables in the message text, not t(). If left blank, a default message Chris@0: * will be displayed. Chris@0: * @param $group Chris@0: * (optional) The group this message is in, which is displayed in a column Chris@0: * in test output. Use 'Debug' to indicate this is debugging output. Do not Chris@0: * translate this string. Defaults to 'Other'; most tests do not override Chris@0: * this default. Chris@0: * Chris@0: * @return Chris@0: * FALSE. Chris@0: */ Chris@0: protected function fail($message = NULL, $group = 'Other') { Chris@0: return $this->assert(FALSE, $message, $group); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Fire an error assertion. Chris@0: * Chris@0: * @param $message Chris@0: * (optional) A message to display with the assertion. Do not translate Chris@17: * messages: use \Drupal\Component\Render\FormattableMarkup to embed Chris@0: * variables in the message text, not t(). If left blank, a default message Chris@0: * will be displayed. Chris@0: * @param $group Chris@0: * (optional) The group this message is in, which is displayed in a column Chris@0: * in test output. Use 'Debug' to indicate this is debugging output. Do not Chris@0: * translate this string. Defaults to 'Other'; most tests do not override Chris@0: * this default. Chris@0: * @param $caller Chris@0: * The caller of the error. Chris@0: * Chris@0: * @return Chris@0: * FALSE. Chris@0: */ Chris@0: protected function error($message = '', $group = 'Other', array $caller = NULL) { Chris@0: if ($group == 'User notice') { Chris@0: // Since 'User notice' is set by trigger_error() which is used for debug Chris@0: // set the message to a status of 'debug'. Chris@0: return $this->assert('debug', $message, 'Debug', $caller); Chris@0: } Chris@0: Chris@0: return $this->assert('exception', $message, $group, $caller); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Logs a verbose message in a text file. Chris@0: * Chris@0: * The link to the verbose message will be placed in the test results as a Chris@0: * passing assertion with the text '[verbose message]'. Chris@0: * Chris@0: * @param $message Chris@0: * The verbose message to be stored. Chris@0: * Chris@0: * @see simpletest_verbose() Chris@0: */ Chris@0: protected function verbose($message) { Chris@0: // Do nothing if verbose debugging is disabled. Chris@0: if (!$this->verbose) { Chris@0: return; Chris@0: } Chris@0: Chris@0: $message = '
ID #' . $this->verboseId . ' (Previous | Next)
' . $message; Chris@0: $verbose_filename = $this->verboseClassName . '-' . $this->verboseId . '-' . $this->testId . '.html'; Chris@0: if (file_put_contents($this->verboseDirectory . '/' . $verbose_filename, $message)) { Chris@0: $url = $this->verboseDirectoryUrl . '/' . $verbose_filename; Chris@0: // Not using \Drupal\Core\Utility\LinkGeneratorInterface::generate() Chris@0: // to avoid invoking the theme system, so that unit tests Chris@0: // can use verbose() as well. Chris@0: $url = 'Verbose message'; Chris@0: $this->error($url, 'User notice'); Chris@0: } Chris@0: $this->verboseId++; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Run all tests in this class. Chris@0: * Chris@0: * Regardless of whether $methods are passed or not, only method names Chris@0: * starting with "test" are executed. Chris@0: * Chris@0: * @param $methods Chris@0: * (optional) A list of method names in the test case class to run; e.g., Chris@0: * array('testFoo', 'testBar'). By default, all methods of the class are Chris@0: * taken into account, but it can be useful to only run a few selected test Chris@0: * methods during debugging. Chris@0: */ Chris@0: public function run(array $methods = []) { Chris@17: $this->checkTestHierarchyMismatch(); Chris@0: $class = get_class($this); Chris@0: Chris@0: if ($missing_requirements = $this->checkRequirements()) { Chris@0: $object_info = new \ReflectionObject($this); Chris@0: $caller = [ Chris@0: 'file' => $object_info->getFileName(), Chris@0: ]; Chris@0: foreach ($missing_requirements as $missing_requirement) { Chris@0: TestBase::insertAssert($this->testId, $class, FALSE, $missing_requirement, 'Requirements check', $caller); Chris@0: } Chris@0: return; Chris@0: } Chris@0: Chris@0: TestServiceProvider::$currentTest = $this; Chris@0: $simpletest_config = $this->config('simpletest.settings'); Chris@0: Chris@0: // Unless preset from run-tests.sh, retrieve the current verbose setting. Chris@0: if (!isset($this->verbose)) { Chris@0: $this->verbose = $simpletest_config->get('verbose'); Chris@0: } Chris@0: Chris@0: if ($this->verbose) { Chris@0: // Initialize verbose debugging. Chris@0: $this->verbose = TRUE; Chris@0: $this->verboseDirectory = PublicStream::basePath() . '/simpletest/verbose'; Chris@0: $this->verboseDirectoryUrl = file_create_url($this->verboseDirectory); Chris@18: if (\Drupal::service('file_system')->prepareDirectory($this->verboseDirectory, FileSystemInterface::CREATE_DIRECTORY) && !file_exists($this->verboseDirectory . '/.htaccess')) { Chris@0: file_put_contents($this->verboseDirectory . '/.htaccess', "\nExpiresActive Off\n\n"); Chris@0: } Chris@0: $this->verboseClassName = str_replace("\\", "_", $class); Chris@0: } Chris@0: // HTTP auth settings (:) for the simpletest browser Chris@0: // when sending requests to the test site. Chris@0: $this->httpAuthMethod = (int) $simpletest_config->get('httpauth.method'); Chris@0: $username = $simpletest_config->get('httpauth.username'); Chris@0: $password = $simpletest_config->get('httpauth.password'); Chris@0: if (!empty($username) && !empty($password)) { Chris@0: $this->httpAuthCredentials = $username . ':' . $password; Chris@0: } Chris@0: Chris@0: // Force assertion failures to be thrown as AssertionError for PHP 5 & 7 Chris@0: // compatibility. Chris@0: Handle::register(); Chris@0: Chris@0: set_error_handler([$this, 'errorHandler']); Chris@0: // Iterate through all the methods in this class, unless a specific list of Chris@0: // methods to run was passed. Chris@0: $test_methods = array_filter(get_class_methods($class), function ($method) { Chris@0: return strpos($method, 'test') === 0; Chris@0: }); Chris@0: if (empty($test_methods)) { Chris@0: // Call $this->assert() here because we need to pass along custom caller Chris@0: // information, lest the wrong originating code file/line be identified. Chris@0: $this->assert(FALSE, 'No test methods found.', 'Requirements', ['function' => __METHOD__ . '()', 'file' => __FILE__, 'line' => __LINE__]); Chris@0: } Chris@0: if ($methods) { Chris@0: $test_methods = array_intersect($test_methods, $methods); Chris@0: } Chris@0: foreach ($test_methods as $method) { Chris@0: // Insert a fail record. This will be deleted on completion to ensure Chris@0: // that testing completed. Chris@0: $method_info = new \ReflectionMethod($class, $method); Chris@0: $caller = [ Chris@0: 'file' => $method_info->getFileName(), Chris@0: 'line' => $method_info->getStartLine(), Chris@0: 'function' => $class . '->' . $method . '()', Chris@0: ]; Chris@0: $test_completion_check_id = TestBase::insertAssert($this->testId, $class, FALSE, 'The test did not complete due to a fatal error.', 'Completion check', $caller); Chris@0: Chris@0: try { Chris@0: $this->prepareEnvironment(); Chris@0: } Chris@0: catch (\Exception $e) { Chris@0: $this->exceptionHandler($e); Chris@0: // The prepareEnvironment() method isolates the test from the parent Chris@0: // Drupal site by creating a random database prefix and test site Chris@0: // directory. If this fails, a test would possibly operate in the Chris@0: // parent site. Therefore, the entire test run for this test class Chris@0: // has to be aborted. Chris@0: // restoreEnvironment() cannot be called, because we do not know Chris@0: // where exactly the environment setup failed. Chris@0: break; Chris@0: } Chris@0: Chris@0: try { Chris@0: $this->setUp(); Chris@0: } Chris@0: catch (\Exception $e) { Chris@0: $this->exceptionHandler($e); Chris@0: // Abort if setUp() fails, since all test methods will fail. Chris@0: // But ensure to clean up and restore the environment, since Chris@0: // prepareEnvironment() succeeded. Chris@0: $this->restoreEnvironment(); Chris@0: break; Chris@0: } Chris@0: try { Chris@0: $this->$method(); Chris@0: } Chris@0: catch (\Exception $e) { Chris@0: $this->exceptionHandler($e); Chris@0: } Chris@0: try { Chris@0: $this->tearDown(); Chris@0: } Chris@0: catch (\Exception $e) { Chris@0: $this->exceptionHandler($e); Chris@0: // If a test fails to tear down, abort the entire test class, since Chris@0: // it is likely that all tests will fail in the same way and a Chris@0: // failure here only results in additional test artifacts that have Chris@0: // to be manually deleted. Chris@0: $this->restoreEnvironment(); Chris@0: break; Chris@0: } Chris@0: Chris@0: $this->restoreEnvironment(); Chris@0: // Remove the test method completion check record. Chris@0: TestBase::deleteAssert($test_completion_check_id); Chris@0: } Chris@0: Chris@0: TestServiceProvider::$currentTest = NULL; Chris@0: // Clear out the error messages and restore error handler. Chris@17: \Drupal::messenger()->deleteAll(); Chris@0: restore_error_handler(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Generates a database prefix for running tests. Chris@0: * Chris@0: * The database prefix is used by prepareEnvironment() to setup a public files Chris@0: * directory for the test to be run, which also contains the PHP error log, Chris@0: * which is written to in case of a fatal error. Since that directory is based Chris@0: * on the database prefix, all tests (even unit tests) need to have one, in Chris@0: * order to access and read the error log. Chris@0: * Chris@0: * @see TestBase::prepareEnvironment() Chris@0: * Chris@0: * The generated database table prefix is used for the Drupal installation Chris@0: * being performed for the test. It is also used as user agent HTTP header Chris@0: * value by the cURL-based browser of WebTestBase, which is sent to the Drupal Chris@0: * installation of the test. During early Drupal bootstrap, the user agent Chris@0: * HTTP header is parsed, and if it matches, all database queries use the Chris@0: * database table prefix that has been generated here. Chris@0: * Chris@0: * @see WebTestBase::curlInitialize() Chris@0: * @see drupal_valid_test_ua() Chris@0: */ Chris@0: private function prepareDatabasePrefix() { Chris@0: $test_db = new TestDatabase(); Chris@0: $this->siteDirectory = $test_db->getTestSitePath(); Chris@0: $this->databasePrefix = $test_db->getDatabasePrefix(); Chris@0: Chris@0: // As soon as the database prefix is set, the test might start to execute. Chris@0: // All assertions as well as the SimpleTest batch operations are associated Chris@0: // with the testId, so the database prefix has to be associated with it. Chris@0: $affected_rows = self::getDatabaseConnection()->update('simpletest_test_id') Chris@0: ->fields(['last_prefix' => $this->databasePrefix]) Chris@0: ->condition('test_id', $this->testId) Chris@0: ->execute(); Chris@0: if (!$affected_rows) { Chris@0: throw new \RuntimeException('Failed to set up database prefix.'); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Act on global state information before the environment is altered for a test. Chris@0: * Chris@0: * Allows e.g. KernelTestBase to prime system/extension info from the Chris@0: * parent site (and inject it into the test environment so as to improve Chris@0: * performance). Chris@0: */ Chris@0: protected function beforePrepareEnvironment() { Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares the current environment for running the test. Chris@0: * Chris@0: * Backups various current environment variables and resets them, so they do Chris@0: * not interfere with the Drupal site installation in which tests are executed Chris@0: * and can be restored in TestBase::restoreEnvironment(). Chris@0: * Chris@0: * Also sets up new resources for the testing environment, such as the public Chris@0: * filesystem and configuration directories. Chris@0: * Chris@0: * This method is private as it must only be called once by TestBase::run() Chris@0: * (multiple invocations for the same test would have unpredictable Chris@0: * consequences) and it must not be callable or overridable by test classes. Chris@0: * Chris@0: * @see TestBase::beforePrepareEnvironment() Chris@0: */ Chris@0: private function prepareEnvironment() { Chris@0: $user = \Drupal::currentUser(); Chris@0: // Allow (base) test classes to backup global state information. Chris@0: $this->beforePrepareEnvironment(); Chris@0: Chris@0: // Create the database prefix for this test. Chris@0: $this->prepareDatabasePrefix(); Chris@0: Chris@0: $language_interface = \Drupal::languageManager()->getCurrentLanguage(); Chris@0: Chris@0: // When running the test runner within a test, back up the original database Chris@0: // prefix. Chris@0: if (DRUPAL_TEST_IN_CHILD_SITE) { Chris@0: $this->originalPrefix = drupal_valid_test_ua(); Chris@0: } Chris@0: Chris@0: // Backup current in-memory configuration. Chris@0: $site_path = \Drupal::service('site.path'); Chris@0: $this->originalSite = $site_path; Chris@0: $this->originalSettings = Settings::getAll(); Chris@0: $this->originalConfig = $GLOBALS['config']; Chris@0: // @todo Remove all remnants of $GLOBALS['conf']. Chris@0: // @see https://www.drupal.org/node/2183323 Chris@0: $this->originalConf = isset($GLOBALS['conf']) ? $GLOBALS['conf'] : NULL; Chris@0: Chris@0: // Backup statics and globals. Chris@0: $this->originalContainer = \Drupal::getContainer(); Chris@0: $this->originalLanguage = $language_interface; Chris@0: $this->originalConfigDirectories = $GLOBALS['config_directories']; Chris@0: Chris@0: // Save further contextual information. Chris@0: // Use the original files directory to avoid nesting it within an existing Chris@0: // simpletest directory if a test is executed within a test. Chris@0: $this->originalFileDirectory = Settings::get('file_public_path', $site_path . '/files'); Chris@0: $this->originalProfile = drupal_get_profile(); Chris@0: $this->originalUser = isset($user) ? clone $user : NULL; Chris@0: Chris@0: // Prevent that session data is leaked into the UI test runner by closing Chris@0: // the session and then setting the session-name (i.e. the name of the Chris@0: // session cookie) to a random value. If a test starts a new session, then Chris@0: // it will be associated with a different session-name. After the test-run Chris@0: // it can be safely destroyed. Chris@0: // @see TestBase::restoreEnvironment() Chris@0: if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) { Chris@0: session_write_close(); Chris@0: } Chris@0: $this->originalSessionName = session_name(); Chris@0: session_name('SIMPLETEST' . Crypt::randomBytesBase64()); Chris@0: Chris@0: // Save and clean the shutdown callbacks array because it is static cached Chris@0: // and will be changed by the test run. Otherwise it will contain callbacks Chris@0: // from both environments and the testing environment will try to call the Chris@0: // handlers defined by the original one. Chris@0: $callbacks = &drupal_register_shutdown_function(); Chris@0: $this->originalShutdownCallbacks = $callbacks; Chris@0: $callbacks = []; Chris@0: Chris@0: // Create test directory ahead of installation so fatal errors and debug Chris@0: // information can be logged during installation process. Chris@18: \Drupal::service('file_system')->prepareDirectory($this->siteDirectory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS); Chris@0: Chris@0: // Prepare filesystem directory paths. Chris@0: $this->publicFilesDirectory = $this->siteDirectory . '/files'; Chris@0: $this->privateFilesDirectory = $this->siteDirectory . '/private'; Chris@0: $this->tempFilesDirectory = $this->siteDirectory . '/temp'; Chris@0: $this->translationFilesDirectory = $this->siteDirectory . '/translations'; Chris@0: Chris@0: $this->generatedTestFiles = FALSE; Chris@0: Chris@0: // Ensure the configImporter is refreshed for each test. Chris@0: $this->configImporter = NULL; Chris@0: Chris@0: // Unregister all custom stream wrappers of the parent site. Chris@0: // Availability of Drupal stream wrappers varies by test base class: Chris@0: // - KernelTestBase supports and maintains stream wrappers in a custom Chris@0: // way. Chris@0: // - WebTestBase re-initializes Drupal stream wrappers after installation. Chris@0: // The original stream wrappers are restored after the test run. Chris@0: // @see TestBase::restoreEnvironment() Chris@0: $this->originalContainer->get('stream_wrapper_manager')->unregister(); Chris@0: Chris@0: // Reset statics. Chris@0: drupal_static_reset(); Chris@0: Chris@0: // Ensure there is no service container. Chris@0: $this->container = NULL; Chris@0: \Drupal::unsetContainer(); Chris@0: Chris@0: // Unset globals. Chris@0: unset($GLOBALS['config_directories']); Chris@0: unset($GLOBALS['config']); Chris@0: unset($GLOBALS['conf']); Chris@0: Chris@0: // Log fatal errors. Chris@0: ini_set('log_errors', 1); Chris@0: ini_set('error_log', DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log'); Chris@0: Chris@0: // Change the database prefix. Chris@0: $this->changeDatabasePrefix(); Chris@0: Chris@0: // After preparing the environment and changing the database prefix, we are Chris@0: // in a valid test environment. Chris@0: drupal_valid_test_ua($this->databasePrefix); Chris@0: Chris@0: // Reset settings. Chris@0: new Settings([ Chris@0: // For performance, simply use the database prefix as hash salt. Chris@0: 'hash_salt' => $this->databasePrefix, Chris@0: 'container_yamls' => [], Chris@0: ]); Chris@0: Chris@18: Environment::setTimeLimit($this->timeLimit); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Performs cleanup tasks after each individual test method has been run. Chris@0: */ Chris@0: protected function tearDown() { Chris@0: } Chris@0: Chris@0: /** Chris@0: * Cleans up the test environment and restores the original environment. Chris@0: * Chris@0: * Deletes created files, database tables, and reverts environment changes. Chris@0: * Chris@0: * This method needs to be invoked for both unit and integration tests. Chris@0: * Chris@0: * @see TestBase::prepareDatabasePrefix() Chris@0: * @see TestBase::changeDatabasePrefix() Chris@0: * @see TestBase::prepareEnvironment() Chris@0: */ Chris@0: private function restoreEnvironment() { Chris@0: // Destroy the session if one was started during the test-run. Chris@0: $_SESSION = []; Chris@0: if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) { Chris@0: session_destroy(); Chris@0: $params = session_get_cookie_params(); Chris@0: setcookie(session_name(), '', REQUEST_TIME - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']); Chris@0: } Chris@0: session_name($this->originalSessionName); Chris@0: Chris@0: // Reset all static variables. Chris@0: // Unsetting static variables will potentially invoke destruct methods, Chris@0: // which might call into functions that prime statics and caches again. Chris@0: // In that case, all functions are still operating on the test environment, Chris@0: // which means they may need to access its filesystem and database. Chris@0: drupal_static_reset(); Chris@0: Chris@0: if ($this->container && $this->container->has('state') && $state = $this->container->get('state')) { Chris@0: $captured_emails = $state->get('system.test_mail_collector') ?: []; Chris@0: $emailCount = count($captured_emails); Chris@0: if ($emailCount) { Chris@0: $message = $emailCount == 1 ? '1 email was sent during this test.' : $emailCount . ' emails were sent during this test.'; Chris@0: $this->pass($message, 'Email'); Chris@0: } Chris@0: } Chris@0: Chris@0: // Sleep for 50ms to allow shutdown functions and terminate events to Chris@0: // complete. Further information: https://www.drupal.org/node/2194357. Chris@0: usleep(50000); Chris@0: Chris@0: // Remove all prefixed tables. Chris@0: $original_connection_info = Database::getConnectionInfo('simpletest_original_default'); Chris@0: $original_prefix = $original_connection_info['default']['prefix']['default']; Chris@0: $test_connection_info = Database::getConnectionInfo('default'); Chris@0: $test_prefix = $test_connection_info['default']['prefix']['default']; Chris@0: if ($original_prefix != $test_prefix) { Chris@0: $tables = Database::getConnection()->schema()->findTables('%'); Chris@0: foreach ($tables as $table) { Chris@0: if (Database::getConnection()->schema()->dropTable($table)) { Chris@0: unset($tables[$table]); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: // In case a fatal error occurred that was not in the test process read the Chris@0: // log to pick up any fatal errors. Chris@0: simpletest_log_read($this->testId, $this->databasePrefix, get_class($this)); Chris@0: Chris@0: // Restore original dependency injection container. Chris@0: $this->container = $this->originalContainer; Chris@0: \Drupal::setContainer($this->originalContainer); Chris@0: Chris@0: // Delete test site directory. Chris@18: \Drupal::service('file_system')->deleteRecursive($this->siteDirectory, [$this, 'filePreDeleteCallback']); Chris@0: Chris@0: // Restore original database connection. Chris@0: Database::removeConnection('default'); Chris@0: Database::renameConnection('simpletest_original_default', 'default'); Chris@0: Chris@0: // Reset all static variables. Chris@0: // All destructors of statically cached objects have been invoked above; Chris@0: // this second reset is guaranteed to reset everything to nothing. Chris@0: drupal_static_reset(); Chris@0: Chris@0: // Restore original in-memory configuration. Chris@0: $GLOBALS['config'] = $this->originalConfig; Chris@0: $GLOBALS['conf'] = $this->originalConf; Chris@0: new Settings($this->originalSettings); Chris@0: Chris@0: // Restore original statics and globals. Chris@0: $GLOBALS['config_directories'] = $this->originalConfigDirectories; Chris@0: Chris@0: // Re-initialize original stream wrappers of the parent site. Chris@0: // This must happen after static variables have been reset and the original Chris@0: // container and $config_directories are restored, as simpletest_log_read() Chris@0: // uses the public stream wrapper to locate the error.log. Chris@0: $this->originalContainer->get('stream_wrapper_manager')->register(); Chris@0: Chris@0: if (isset($this->originalPrefix)) { Chris@0: drupal_valid_test_ua($this->originalPrefix); Chris@0: } Chris@0: else { Chris@0: drupal_valid_test_ua(FALSE); Chris@0: } Chris@0: Chris@0: // Restore original shutdown callbacks. Chris@0: $callbacks = &drupal_register_shutdown_function(); Chris@0: $callbacks = $this->originalShutdownCallbacks; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Handle errors during test runs. Chris@0: * Chris@0: * Because this is registered in set_error_handler(), it has to be public. Chris@0: * Chris@0: * @see set_error_handler Chris@0: */ Chris@0: public function errorHandler($severity, $message, $file = NULL, $line = NULL) { Chris@0: if ($severity & error_reporting()) { Chris@0: $error_map = [ Chris@0: E_STRICT => 'Run-time notice', Chris@0: E_WARNING => 'Warning', Chris@0: E_NOTICE => 'Notice', Chris@0: E_CORE_ERROR => 'Core error', Chris@0: E_CORE_WARNING => 'Core warning', Chris@0: E_USER_ERROR => 'User error', Chris@0: E_USER_WARNING => 'User warning', Chris@0: E_USER_NOTICE => 'User notice', Chris@0: E_RECOVERABLE_ERROR => 'Recoverable error', Chris@0: E_DEPRECATED => 'Deprecated', Chris@0: E_USER_DEPRECATED => 'User deprecated', Chris@0: ]; Chris@0: Chris@0: $backtrace = debug_backtrace(); Chris@0: Chris@0: // Add verbose backtrace for errors, but not for debug() messages. Chris@0: if ($severity !== E_USER_NOTICE) { Chris@0: $verbose_backtrace = $backtrace; Chris@0: array_shift($verbose_backtrace); Chris@0: $message .= '
' . Error::formatBacktrace($verbose_backtrace) . '
'; Chris@0: } Chris@0: Chris@0: $this->error($message, $error_map[$severity], Error::getLastCaller($backtrace)); Chris@0: } Chris@0: return TRUE; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Handle exceptions. Chris@0: * Chris@0: * @see set_exception_handler Chris@0: */ Chris@0: protected function exceptionHandler($exception) { Chris@0: $backtrace = $exception->getTrace(); Chris@0: $verbose_backtrace = $backtrace; Chris@0: // Push on top of the backtrace the call that generated the exception. Chris@0: array_unshift($backtrace, [ Chris@0: 'line' => $exception->getLine(), Chris@0: 'file' => $exception->getFile(), Chris@0: ]); Chris@0: $decoded_exception = Error::decodeException($exception); Chris@0: unset($decoded_exception['backtrace']); Chris@17: $message = new FormattableMarkup('%type: @message in %function (line %line of %file).
@backtrace
', $decoded_exception + [ Chris@0: '@backtrace' => Error::formatBacktrace($verbose_backtrace), Chris@0: ]); Chris@0: $this->error($message, 'Uncaught exception', Error::getLastCaller($backtrace)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Changes in memory settings. Chris@0: * Chris@0: * @param $name Chris@0: * The name of the setting to return. Chris@0: * @param $value Chris@0: * The value of the setting. Chris@0: * Chris@0: * @see \Drupal\Core\Site\Settings::get() Chris@0: */ Chris@0: protected function settingsSet($name, $value) { Chris@0: $settings = Settings::getAll(); Chris@0: $settings[$name] = $value; Chris@0: new Settings($settings); Chris@0: } Chris@0: Chris@0: /** Chris@18: * Ensures test files are deletable. Chris@0: * Chris@0: * Some tests chmod generated files to be read only. During Chris@0: * TestBase::restoreEnvironment() and other cleanup operations, these files Chris@0: * need to get deleted too. Chris@18: * Chris@18: * @see \Drupal\Core\File\FileSystemInterface::deleteRecursive() Chris@0: */ Chris@0: public static function filePreDeleteCallback($path) { Chris@0: // When the webserver runs with the same system user as the test runner, we Chris@0: // can make read-only files writable again. If not, chmod will fail while Chris@0: // the file deletion still works if file permissions have been configured Chris@0: // correctly. Thus, we ignore any problems while running chmod. Chris@0: @chmod($path, 0700); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Configuration accessor for tests. Returns non-overridden configuration. Chris@0: * Chris@0: * @param $name Chris@0: * Configuration name. Chris@0: * Chris@0: * @return \Drupal\Core\Config\Config Chris@0: * The configuration object with original configuration data. Chris@0: */ Chris@0: protected function config($name) { Chris@0: return \Drupal::configFactory()->getEditable($name); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the database prefix. Chris@0: * Chris@0: * @return string Chris@0: * The database prefix Chris@0: */ Chris@0: public function getDatabasePrefix() { Chris@0: return $this->databasePrefix; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the temporary files directory. Chris@0: * Chris@0: * @return string Chris@0: * The temporary files directory. Chris@0: */ Chris@0: public function getTempFilesDirectory() { Chris@0: return $this->tempFilesDirectory; Chris@0: } Chris@0: Chris@0: }