annotate core/modules/simpletest/src/TestBase.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents af1871eacc83
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\simpletest;
Chris@0 4
Chris@0 5 use Drupal\Component\Assertion\Handle;
Chris@18 6 use Drupal\Component\Render\FormattableMarkup;
Chris@0 7 use Drupal\Component\Render\MarkupInterface;
Chris@0 8 use Drupal\Component\Utility\Crypt;
Chris@18 9 use Drupal\Component\Utility\Environment;
Chris@0 10 use Drupal\Core\Database\Database;
Chris@18 11 use Drupal\Core\File\FileSystemInterface;
Chris@0 12 use Drupal\Core\Site\Settings;
Chris@0 13 use Drupal\Core\StreamWrapper\PublicStream;
Chris@0 14 use Drupal\Core\Test\TestDatabase;
Chris@0 15 use Drupal\Core\Test\TestSetupTrait;
Chris@0 16 use Drupal\Core\Utility\Error;
Chris@0 17 use Drupal\Tests\AssertHelperTrait as BaseAssertHelperTrait;
Chris@0 18 use Drupal\Tests\ConfigTestTrait;
Chris@0 19 use Drupal\Tests\RandomGeneratorTrait;
Chris@0 20 use Drupal\Tests\Traits\Core\GeneratePermutationsTrait;
Chris@0 21
Chris@0 22 /**
Chris@0 23 * Base class for Drupal tests.
Chris@0 24 *
Chris@0 25 * Do not extend this class directly; use \Drupal\simpletest\WebTestBase.
Chris@0 26 */
Chris@0 27 abstract class TestBase {
Chris@0 28
Chris@0 29 use BaseAssertHelperTrait;
Chris@0 30 use TestSetupTrait;
Chris@0 31 use RandomGeneratorTrait;
Chris@0 32 use GeneratePermutationsTrait;
Chris@17 33 // For backwards compatibility switch the visibility of the methods to public.
Chris@0 34 use ConfigTestTrait {
Chris@0 35 configImporter as public;
Chris@0 36 copyConfig as public;
Chris@0 37 }
Chris@0 38
Chris@0 39 /**
Chris@0 40 * The database prefix of this test run.
Chris@0 41 *
Chris@0 42 * @var string
Chris@0 43 */
Chris@0 44 protected $databasePrefix = NULL;
Chris@0 45
Chris@0 46 /**
Chris@0 47 * Time limit for the test.
Chris@12 48 *
Chris@12 49 * @var int
Chris@0 50 */
Chris@0 51 protected $timeLimit = 500;
Chris@0 52
Chris@0 53 /**
Chris@0 54 * Current results of this test case.
Chris@0 55 *
Chris@17 56 * @var array
Chris@0 57 */
Chris@0 58 public $results = [
Chris@0 59 '#pass' => 0,
Chris@0 60 '#fail' => 0,
Chris@0 61 '#exception' => 0,
Chris@0 62 '#debug' => 0,
Chris@0 63 ];
Chris@0 64
Chris@0 65 /**
Chris@0 66 * Assertions thrown in that test case.
Chris@0 67 *
Chris@17 68 * @var array
Chris@0 69 */
Chris@0 70 protected $assertions = [];
Chris@0 71
Chris@0 72 /**
Chris@0 73 * This class is skipped when looking for the source of an assertion.
Chris@0 74 *
Chris@0 75 * When displaying which function an assert comes from, it's not too useful
Chris@0 76 * to see "WebTestBase->drupalLogin()', we would like to see the test
Chris@0 77 * that called it. So we need to skip the classes defining these helper
Chris@0 78 * methods.
Chris@0 79 */
Chris@0 80 protected $skipClasses = [__CLASS__ => TRUE];
Chris@0 81
Chris@0 82 /**
Chris@0 83 * TRUE if verbose debugging is enabled.
Chris@0 84 *
Chris@0 85 * @var bool
Chris@0 86 */
Chris@0 87 public $verbose;
Chris@0 88
Chris@0 89 /**
Chris@0 90 * Incrementing identifier for verbose output filenames.
Chris@0 91 *
Chris@0 92 * @var int
Chris@0 93 */
Chris@0 94 protected $verboseId = 0;
Chris@0 95
Chris@0 96 /**
Chris@0 97 * Safe class name for use in verbose output filenames.
Chris@0 98 *
Chris@0 99 * Namespaces separator (\) replaced with _.
Chris@0 100 *
Chris@0 101 * @var string
Chris@0 102 */
Chris@0 103 protected $verboseClassName;
Chris@0 104
Chris@0 105 /**
Chris@0 106 * Directory where verbose output files are put.
Chris@0 107 *
Chris@0 108 * @var string
Chris@0 109 */
Chris@0 110 protected $verboseDirectory;
Chris@0 111
Chris@0 112 /**
Chris@0 113 * URL to the verbose output file directory.
Chris@0 114 *
Chris@0 115 * @var string
Chris@0 116 */
Chris@0 117 protected $verboseDirectoryUrl;
Chris@0 118
Chris@0 119 /**
Chris@0 120 * The original configuration (variables), if available.
Chris@0 121 *
Chris@0 122 * @var string
Chris@0 123 * @todo Remove all remnants of $GLOBALS['conf'].
Chris@0 124 * @see https://www.drupal.org/node/2183323
Chris@0 125 */
Chris@0 126 protected $originalConf;
Chris@0 127
Chris@0 128 /**
Chris@0 129 * The original configuration (variables).
Chris@0 130 *
Chris@0 131 * @var string
Chris@0 132 */
Chris@0 133 protected $originalConfig;
Chris@0 134
Chris@0 135 /**
Chris@0 136 * The original configuration directories.
Chris@0 137 *
Chris@0 138 * An array of paths keyed by the CONFIG_*_DIRECTORY constants defined by
Chris@0 139 * core/includes/bootstrap.inc.
Chris@0 140 *
Chris@0 141 * @var array
Chris@0 142 */
Chris@0 143 protected $originalConfigDirectories;
Chris@0 144
Chris@0 145 /**
Chris@0 146 * The original container.
Chris@0 147 *
Chris@0 148 * @var \Symfony\Component\DependencyInjection\ContainerInterface
Chris@0 149 */
Chris@0 150 protected $originalContainer;
Chris@0 151
Chris@0 152 /**
Chris@0 153 * The original file directory, before it was changed for testing purposes.
Chris@0 154 *
Chris@0 155 * @var string
Chris@0 156 */
Chris@0 157 protected $originalFileDirectory = NULL;
Chris@0 158
Chris@0 159 /**
Chris@0 160 * The original language.
Chris@0 161 *
Chris@0 162 * @var \Drupal\Core\Language\LanguageInterface
Chris@0 163 */
Chris@0 164 protected $originalLanguage;
Chris@0 165
Chris@0 166 /**
Chris@0 167 * The original database prefix when running inside Simpletest.
Chris@0 168 *
Chris@0 169 * @var string
Chris@0 170 */
Chris@0 171 protected $originalPrefix;
Chris@0 172
Chris@0 173 /**
Chris@0 174 * The name of the session cookie of the test-runner.
Chris@0 175 *
Chris@0 176 * @var string
Chris@0 177 */
Chris@0 178 protected $originalSessionName;
Chris@0 179
Chris@0 180 /**
Chris@0 181 * The settings array.
Chris@0 182 *
Chris@0 183 * @var array
Chris@0 184 */
Chris@0 185 protected $originalSettings;
Chris@0 186
Chris@0 187 /**
Chris@0 188 * The original array of shutdown function callbacks.
Chris@0 189 *
Chris@0 190 * @var array
Chris@0 191 */
Chris@0 192 protected $originalShutdownCallbacks;
Chris@0 193
Chris@0 194 /**
Chris@0 195 * The original user, before testing began.
Chris@0 196 *
Chris@0 197 * @var \Drupal\Core\Session\AccountProxyInterface
Chris@0 198 */
Chris@0 199 protected $originalUser;
Chris@0 200
Chris@0 201 /**
Chris@0 202 * The translation file directory for the test environment.
Chris@0 203 *
Chris@0 204 * This is set in TestBase::prepareEnvironment().
Chris@0 205 *
Chris@0 206 * @var string
Chris@0 207 */
Chris@0 208 protected $translationFilesDirectory;
Chris@0 209
Chris@0 210 /**
Chris@0 211 * Whether to die in case any test assertion fails.
Chris@0 212 *
Chris@0 213 * @var bool
Chris@0 214 *
Chris@0 215 * @see run-tests.sh
Chris@0 216 */
Chris@0 217 public $dieOnFail = FALSE;
Chris@0 218
Chris@0 219 /**
Chris@0 220 * The config importer that can used in a test.
Chris@0 221 *
Chris@0 222 * @var \Drupal\Core\Config\ConfigImporter
Chris@0 223 */
Chris@0 224 protected $configImporter;
Chris@0 225
Chris@0 226 /**
Chris@0 227 * HTTP authentication method (specified as a CURLAUTH_* constant).
Chris@0 228 *
Chris@0 229 * @var int
Chris@0 230 * @see http://php.net/manual/function.curl-setopt.php
Chris@0 231 */
Chris@0 232 protected $httpAuthMethod = CURLAUTH_BASIC;
Chris@0 233
Chris@0 234 /**
Chris@0 235 * HTTP authentication credentials (<username>:<password>).
Chris@0 236 *
Chris@0 237 * @var string
Chris@0 238 */
Chris@0 239 protected $httpAuthCredentials = NULL;
Chris@0 240
Chris@0 241 /**
Chris@0 242 * Constructor for Test.
Chris@0 243 *
Chris@0 244 * @param $test_id
Chris@0 245 * Tests with the same id are reported together.
Chris@0 246 */
Chris@0 247 public function __construct($test_id = NULL) {
Chris@0 248 $this->testId = $test_id;
Chris@0 249 }
Chris@0 250
Chris@0 251 /**
Chris@17 252 * Fail the test if it belongs to a PHPUnit-based framework.
Chris@17 253 *
Chris@17 254 * This would probably be caused by automated test conversions such as those
Chris@17 255 * in https://www.drupal.org/project/drupal/issues/2770921.
Chris@17 256 */
Chris@17 257 public function checkTestHierarchyMismatch() {
Chris@17 258 // We can use getPhpunitTestSuite() because it uses a regex on the class'
Chris@17 259 // namespace to deduce the PHPUnit test suite.
Chris@17 260 if (TestDiscovery::getPhpunitTestSuite(get_class($this)) !== FALSE) {
Chris@17 261 $this->fail(get_class($this) . ' incorrectly subclasses ' . __CLASS__ . ', it should probably extend \Drupal\Tests\BrowserTestBase instead.');
Chris@17 262 }
Chris@17 263 }
Chris@17 264
Chris@17 265 /**
Chris@0 266 * Performs setup tasks before each individual test method is run.
Chris@0 267 */
Chris@0 268 abstract protected function setUp();
Chris@0 269
Chris@0 270 /**
Chris@0 271 * Checks the matching requirements for Test.
Chris@0 272 *
Chris@0 273 * @return
Chris@0 274 * Array of errors containing a list of unmet requirements.
Chris@0 275 */
Chris@0 276 protected function checkRequirements() {
Chris@0 277 return [];
Chris@0 278 }
Chris@0 279
Chris@0 280 /**
Chris@0 281 * Helper method to store an assertion record in the configured database.
Chris@0 282 *
Chris@0 283 * This method decouples database access from assertion logic.
Chris@0 284 *
Chris@0 285 * @param array $assertion
Chris@0 286 * Keyed array representing an assertion, as generated by assert().
Chris@0 287 *
Chris@0 288 * @see self::assert()
Chris@0 289 *
Chris@0 290 * @return \Drupal\Core\Database\StatementInterface|int|null
Chris@0 291 * The message ID.
Chris@0 292 */
Chris@0 293 protected function storeAssertion(array $assertion) {
Chris@0 294 return self::getDatabaseConnection()
Chris@0 295 ->insert('simpletest', ['return' => Database::RETURN_INSERT_ID])
Chris@0 296 ->fields($assertion)
Chris@0 297 ->execute();
Chris@0 298 }
Chris@0 299
Chris@0 300 /**
Chris@0 301 * Internal helper: stores the assert.
Chris@0 302 *
Chris@0 303 * @param $status
Chris@0 304 * Can be 'pass', 'fail', 'exception', 'debug'.
Chris@0 305 * TRUE is a synonym for 'pass', FALSE for 'fail'.
Chris@0 306 * @param string|\Drupal\Component\Render\MarkupInterface $message
Chris@0 307 * (optional) A message to display with the assertion. Do not translate
Chris@17 308 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
Chris@0 309 * variables in the message text, not t(). If left blank, a default message
Chris@0 310 * will be displayed.
Chris@0 311 * @param $group
Chris@0 312 * (optional) The group this message is in, which is displayed in a column
Chris@0 313 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 314 * translate this string. Defaults to 'Other'; most tests do not override
Chris@0 315 * this default.
Chris@0 316 * @param $caller
Chris@0 317 * By default, the assert comes from a function whose name starts with
Chris@0 318 * 'test'. Instead, you can specify where this assert originates from
Chris@0 319 * by passing in an associative array as $caller. Key 'file' is
Chris@0 320 * the name of the source file, 'line' is the line number and 'function'
Chris@0 321 * is the caller function itself.
Chris@0 322 */
Chris@0 323 protected function assert($status, $message = '', $group = 'Other', array $caller = NULL) {
Chris@0 324 if ($message instanceof MarkupInterface) {
Chris@0 325 $message = (string) $message;
Chris@0 326 }
Chris@0 327 // Convert boolean status to string status.
Chris@0 328 if (is_bool($status)) {
Chris@0 329 $status = $status ? 'pass' : 'fail';
Chris@0 330 }
Chris@0 331
Chris@0 332 // Increment summary result counter.
Chris@0 333 $this->results['#' . $status]++;
Chris@0 334
Chris@0 335 // Get the function information about the call to the assertion method.
Chris@0 336 if (!$caller) {
Chris@0 337 $caller = $this->getAssertionCall();
Chris@0 338 }
Chris@0 339
Chris@0 340 // Creation assertion array that can be displayed while tests are running.
Chris@0 341 $assertion = [
Chris@0 342 'test_id' => $this->testId,
Chris@0 343 'test_class' => get_class($this),
Chris@0 344 'status' => $status,
Chris@0 345 'message' => $message,
Chris@0 346 'message_group' => $group,
Chris@0 347 'function' => $caller['function'],
Chris@0 348 'line' => $caller['line'],
Chris@0 349 'file' => $caller['file'],
Chris@0 350 ];
Chris@0 351
Chris@0 352 // Store assertion for display after the test has completed.
Chris@0 353 $message_id = $this->storeAssertion($assertion);
Chris@0 354 $assertion['message_id'] = $message_id;
Chris@0 355 $this->assertions[] = $assertion;
Chris@0 356
Chris@0 357 // We do not use a ternary operator here to allow a breakpoint on
Chris@0 358 // test failure.
Chris@0 359 if ($status == 'pass') {
Chris@0 360 return TRUE;
Chris@0 361 }
Chris@0 362 else {
Chris@0 363 if ($this->dieOnFail && ($status == 'fail' || $status == 'exception')) {
Chris@0 364 exit(1);
Chris@0 365 }
Chris@0 366 return FALSE;
Chris@0 367 }
Chris@0 368 }
Chris@0 369
Chris@0 370 /**
Chris@0 371 * Store an assertion from outside the testing context.
Chris@0 372 *
Chris@0 373 * This is useful for inserting assertions that can only be recorded after
Chris@0 374 * the test case has been destroyed, such as PHP fatal errors. The caller
Chris@0 375 * information is not automatically gathered since the caller is most likely
Chris@0 376 * inserting the assertion on behalf of other code. In all other respects
Chris@0 377 * the method behaves just like \Drupal\simpletest\TestBase::assert() in terms
Chris@0 378 * of storing the assertion.
Chris@0 379 *
Chris@0 380 * @return
Chris@0 381 * Message ID of the stored assertion.
Chris@0 382 *
Chris@0 383 * @see \Drupal\simpletest\TestBase::assert()
Chris@0 384 * @see \Drupal\simpletest\TestBase::deleteAssert()
Chris@0 385 */
Chris@0 386 public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = []) {
Chris@0 387 // Convert boolean status to string status.
Chris@0 388 if (is_bool($status)) {
Chris@0 389 $status = $status ? 'pass' : 'fail';
Chris@0 390 }
Chris@0 391
Chris@0 392 $caller += [
Chris@0 393 'function' => 'Unknown',
Chris@0 394 'line' => 0,
Chris@0 395 'file' => 'Unknown',
Chris@0 396 ];
Chris@0 397
Chris@0 398 $assertion = [
Chris@0 399 'test_id' => $test_id,
Chris@0 400 'test_class' => $test_class,
Chris@0 401 'status' => $status,
Chris@0 402 'message' => $message,
Chris@0 403 'message_group' => $group,
Chris@0 404 'function' => $caller['function'],
Chris@0 405 'line' => $caller['line'],
Chris@0 406 'file' => $caller['file'],
Chris@0 407 ];
Chris@0 408
Chris@0 409 // We can't use storeAssertion() because this method is static.
Chris@0 410 return self::getDatabaseConnection()
Chris@0 411 ->insert('simpletest')
Chris@0 412 ->fields($assertion)
Chris@0 413 ->execute();
Chris@0 414 }
Chris@0 415
Chris@0 416 /**
Chris@0 417 * Delete an assertion record by message ID.
Chris@0 418 *
Chris@0 419 * @param $message_id
Chris@0 420 * Message ID of the assertion to delete.
Chris@0 421 *
Chris@0 422 * @return
Chris@0 423 * TRUE if the assertion was deleted, FALSE otherwise.
Chris@0 424 *
Chris@0 425 * @see \Drupal\simpletest\TestBase::insertAssert()
Chris@0 426 */
Chris@0 427 public static function deleteAssert($message_id) {
Chris@0 428 // We can't use storeAssertion() because this method is static.
Chris@0 429 return (bool) self::getDatabaseConnection()
Chris@0 430 ->delete('simpletest')
Chris@0 431 ->condition('message_id', $message_id)
Chris@0 432 ->execute();
Chris@0 433 }
Chris@0 434
Chris@0 435 /**
Chris@0 436 * Cycles through backtrace until the first non-assertion method is found.
Chris@0 437 *
Chris@0 438 * @return
Chris@0 439 * Array representing the true caller.
Chris@0 440 */
Chris@0 441 protected function getAssertionCall() {
Chris@0 442 $backtrace = debug_backtrace();
Chris@0 443
Chris@0 444 // The first element is the call. The second element is the caller.
Chris@0 445 // We skip calls that occurred in one of the methods of our base classes
Chris@0 446 // or in an assertion function.
Chris@0 447 while (($caller = $backtrace[1]) &&
Chris@0 448 ((isset($caller['class']) && isset($this->skipClasses[$caller['class']])) ||
Chris@0 449 substr($caller['function'], 0, 6) == 'assert')) {
Chris@0 450 // We remove that call.
Chris@0 451 array_shift($backtrace);
Chris@0 452 }
Chris@0 453
Chris@0 454 return Error::getLastCaller($backtrace);
Chris@0 455 }
Chris@0 456
Chris@0 457 /**
Chris@0 458 * Check to see if a value is not false.
Chris@0 459 *
Chris@0 460 * False values are: empty string, 0, NULL, and FALSE.
Chris@0 461 *
Chris@0 462 * @param $value
Chris@0 463 * The value on which the assertion is to be done.
Chris@0 464 * @param $message
Chris@0 465 * (optional) A message to display with the assertion. Do not translate
Chris@17 466 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
Chris@0 467 * variables in the message text, not t(). If left blank, a default message
Chris@0 468 * will be displayed.
Chris@0 469 * @param $group
Chris@0 470 * (optional) The group this message is in, which is displayed in a column
Chris@0 471 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 472 * translate this string. Defaults to 'Other'; most tests do not override
Chris@0 473 * this default.
Chris@0 474 *
Chris@0 475 * @return
Chris@0 476 * TRUE if the assertion succeeded, FALSE otherwise.
Chris@0 477 */
Chris@0 478 protected function assertTrue($value, $message = '', $group = 'Other') {
Chris@17 479 return $this->assert((bool) $value, $message ? $message : new FormattableMarkup('Value @value is TRUE.', ['@value' => var_export($value, TRUE)]), $group);
Chris@0 480 }
Chris@0 481
Chris@0 482 /**
Chris@0 483 * Check to see if a value is false.
Chris@0 484 *
Chris@0 485 * False values are: empty string, 0, NULL, and FALSE.
Chris@0 486 *
Chris@0 487 * @param $value
Chris@0 488 * The value on which the assertion is to be done.
Chris@0 489 * @param $message
Chris@0 490 * (optional) A message to display with the assertion. Do not translate
Chris@17 491 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
Chris@0 492 * variables in the message text, not t(). If left blank, a default message
Chris@0 493 * will be displayed.
Chris@0 494 * @param $group
Chris@0 495 * (optional) The group this message is in, which is displayed in a column
Chris@0 496 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 497 * translate this string. Defaults to 'Other'; most tests do not override
Chris@0 498 * this default.
Chris@0 499 *
Chris@0 500 * @return
Chris@0 501 * TRUE if the assertion succeeded, FALSE otherwise.
Chris@0 502 */
Chris@0 503 protected function assertFalse($value, $message = '', $group = 'Other') {
Chris@17 504 return $this->assert(!$value, $message ? $message : new FormattableMarkup('Value @value is FALSE.', ['@value' => var_export($value, TRUE)]), $group);
Chris@0 505 }
Chris@0 506
Chris@0 507 /**
Chris@0 508 * Check to see if a value is NULL.
Chris@0 509 *
Chris@0 510 * @param $value
Chris@0 511 * The value on which the assertion is to be done.
Chris@0 512 * @param $message
Chris@0 513 * (optional) A message to display with the assertion. Do not translate
Chris@17 514 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
Chris@0 515 * variables in the message text, not t(). If left blank, a default message
Chris@0 516 * will be displayed.
Chris@0 517 * @param $group
Chris@0 518 * (optional) The group this message is in, which is displayed in a column
Chris@0 519 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 520 * translate this string. Defaults to 'Other'; most tests do not override
Chris@0 521 * this default.
Chris@0 522 *
Chris@0 523 * @return
Chris@0 524 * TRUE if the assertion succeeded, FALSE otherwise.
Chris@0 525 */
Chris@0 526 protected function assertNull($value, $message = '', $group = 'Other') {
Chris@17 527 return $this->assert(!isset($value), $message ? $message : new FormattableMarkup('Value @value is NULL.', ['@value' => var_export($value, TRUE)]), $group);
Chris@0 528 }
Chris@0 529
Chris@0 530 /**
Chris@0 531 * Check to see if a value is not NULL.
Chris@0 532 *
Chris@0 533 * @param $value
Chris@0 534 * The value on which the assertion is to be done.
Chris@0 535 * @param $message
Chris@0 536 * (optional) A message to display with the assertion. Do not translate
Chris@17 537 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
Chris@0 538 * variables in the message text, not t(). If left blank, a default message
Chris@0 539 * will be displayed.
Chris@0 540 * @param $group
Chris@0 541 * (optional) The group this message is in, which is displayed in a column
Chris@0 542 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 543 * translate this string. Defaults to 'Other'; most tests do not override
Chris@0 544 * this default.
Chris@0 545 *
Chris@0 546 * @return
Chris@0 547 * TRUE if the assertion succeeded, FALSE otherwise.
Chris@0 548 */
Chris@0 549 protected function assertNotNull($value, $message = '', $group = 'Other') {
Chris@17 550 return $this->assert(isset($value), $message ? $message : new FormattableMarkup('Value @value is not NULL.', ['@value' => var_export($value, TRUE)]), $group);
Chris@0 551 }
Chris@0 552
Chris@0 553 /**
Chris@0 554 * Check to see if two values are equal.
Chris@0 555 *
Chris@0 556 * @param $first
Chris@0 557 * The first value to check.
Chris@0 558 * @param $second
Chris@0 559 * The second value to check.
Chris@0 560 * @param $message
Chris@0 561 * (optional) A message to display with the assertion. Do not translate
Chris@17 562 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
Chris@0 563 * variables in the message text, not t(). If left blank, a default message
Chris@0 564 * will be displayed.
Chris@0 565 * @param $group
Chris@0 566 * (optional) The group this message is in, which is displayed in a column
Chris@0 567 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 568 * translate this string. Defaults to 'Other'; most tests do not override
Chris@0 569 * this default.
Chris@0 570 *
Chris@0 571 * @return
Chris@0 572 * TRUE if the assertion succeeded, FALSE otherwise.
Chris@0 573 */
Chris@0 574 protected function assertEqual($first, $second, $message = '', $group = 'Other') {
Chris@0 575 // Cast objects implementing MarkupInterface to string instead of
Chris@0 576 // relying on PHP casting them to string depending on what they are being
Chris@0 577 // comparing with.
Chris@0 578 $first = $this->castSafeStrings($first);
Chris@0 579 $second = $this->castSafeStrings($second);
Chris@0 580 $is_equal = $first == $second;
Chris@0 581 if (!$is_equal || !$message) {
Chris@17 582 $default_message = new FormattableMarkup('Value @first is equal to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
Chris@0 583 $message = $message ? $message . PHP_EOL . $default_message : $default_message;
Chris@0 584 }
Chris@0 585 return $this->assert($is_equal, $message, $group);
Chris@0 586 }
Chris@0 587
Chris@0 588 /**
Chris@0 589 * Check to see if two values are not equal.
Chris@0 590 *
Chris@0 591 * @param $first
Chris@0 592 * The first value to check.
Chris@0 593 * @param $second
Chris@0 594 * The second value to check.
Chris@0 595 * @param $message
Chris@0 596 * (optional) A message to display with the assertion. Do not translate
Chris@17 597 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
Chris@0 598 * variables in the message text, not t(). If left blank, a default message
Chris@0 599 * will be displayed.
Chris@0 600 * @param $group
Chris@0 601 * (optional) The group this message is in, which is displayed in a column
Chris@0 602 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 603 * translate this string. Defaults to 'Other'; most tests do not override
Chris@0 604 * this default.
Chris@0 605 *
Chris@0 606 * @return
Chris@0 607 * TRUE if the assertion succeeded, FALSE otherwise.
Chris@0 608 */
Chris@0 609 protected function assertNotEqual($first, $second, $message = '', $group = 'Other') {
Chris@0 610 // Cast objects implementing MarkupInterface to string instead of
Chris@0 611 // relying on PHP casting them to string depending on what they are being
Chris@0 612 // comparing with.
Chris@0 613 $first = $this->castSafeStrings($first);
Chris@0 614 $second = $this->castSafeStrings($second);
Chris@0 615 $not_equal = $first != $second;
Chris@0 616 if (!$not_equal || !$message) {
Chris@17 617 $default_message = new FormattableMarkup('Value @first is not equal to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
Chris@0 618 $message = $message ? $message . PHP_EOL . $default_message : $default_message;
Chris@0 619 }
Chris@0 620 return $this->assert($not_equal, $message, $group);
Chris@0 621 }
Chris@0 622
Chris@0 623 /**
Chris@0 624 * Check to see if two values are identical.
Chris@0 625 *
Chris@0 626 * @param $first
Chris@0 627 * The first value to check.
Chris@0 628 * @param $second
Chris@0 629 * The second value to check.
Chris@0 630 * @param $message
Chris@0 631 * (optional) A message to display with the assertion. Do not translate
Chris@17 632 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
Chris@0 633 * variables in the message text, not t(). If left blank, a default message
Chris@0 634 * will be displayed.
Chris@0 635 * @param $group
Chris@0 636 * (optional) The group this message is in, which is displayed in a column
Chris@0 637 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 638 * translate this string. Defaults to 'Other'; most tests do not override
Chris@0 639 * this default.
Chris@0 640 *
Chris@0 641 * @return
Chris@0 642 * TRUE if the assertion succeeded, FALSE otherwise.
Chris@0 643 */
Chris@0 644 protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
Chris@0 645 $is_identical = $first === $second;
Chris@0 646 if (!$is_identical || !$message) {
Chris@17 647 $default_message = new FormattableMarkup('Value @first is identical to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
Chris@0 648 $message = $message ? $message . PHP_EOL . $default_message : $default_message;
Chris@0 649 }
Chris@0 650 return $this->assert($is_identical, $message, $group);
Chris@0 651 }
Chris@0 652
Chris@0 653 /**
Chris@0 654 * Check to see if two values are not identical.
Chris@0 655 *
Chris@0 656 * @param $first
Chris@0 657 * The first value to check.
Chris@0 658 * @param $second
Chris@0 659 * The second value to check.
Chris@0 660 * @param $message
Chris@0 661 * (optional) A message to display with the assertion. Do not translate
Chris@17 662 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
Chris@0 663 * variables in the message text, not t(). If left blank, a default message
Chris@0 664 * will be displayed.
Chris@0 665 * @param $group
Chris@0 666 * (optional) The group this message is in, which is displayed in a column
Chris@0 667 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 668 * translate this string. Defaults to 'Other'; most tests do not override
Chris@0 669 * this default.
Chris@0 670 *
Chris@0 671 * @return
Chris@0 672 * TRUE if the assertion succeeded, FALSE otherwise.
Chris@0 673 */
Chris@0 674 protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') {
Chris@0 675 $not_identical = $first !== $second;
Chris@0 676 if (!$not_identical || !$message) {
Chris@17 677 $default_message = new FormattableMarkup('Value @first is not identical to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
Chris@0 678 $message = $message ? $message . PHP_EOL . $default_message : $default_message;
Chris@0 679 }
Chris@0 680 return $this->assert($not_identical, $message, $group);
Chris@0 681 }
Chris@0 682
Chris@0 683 /**
Chris@0 684 * Checks to see if two objects are identical.
Chris@0 685 *
Chris@0 686 * @param object $object1
Chris@0 687 * The first object to check.
Chris@0 688 * @param object $object2
Chris@0 689 * The second object to check.
Chris@0 690 * @param $message
Chris@0 691 * (optional) A message to display with the assertion. Do not translate
Chris@17 692 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
Chris@0 693 * variables in the message text, not t(). If left blank, a default message
Chris@0 694 * will be displayed.
Chris@0 695 * @param $group
Chris@0 696 * (optional) The group this message is in, which is displayed in a column
Chris@0 697 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 698 * translate this string. Defaults to 'Other'; most tests do not override
Chris@0 699 * this default.
Chris@0 700 *
Chris@0 701 * @return
Chris@0 702 * TRUE if the assertion succeeded, FALSE otherwise.
Chris@0 703 */
Chris@0 704 protected function assertIdenticalObject($object1, $object2, $message = '', $group = 'Other') {
Chris@17 705 $message = $message ?: new FormattableMarkup('@object1 is identical to @object2', [
Chris@0 706 '@object1' => var_export($object1, TRUE),
Chris@0 707 '@object2' => var_export($object2, TRUE),
Chris@0 708 ]);
Chris@0 709 $identical = TRUE;
Chris@0 710 foreach ($object1 as $key => $value) {
Chris@0 711 $identical = $identical && isset($object2->$key) && $object2->$key === $value;
Chris@0 712 }
Chris@0 713 return $this->assertTrue($identical, $message, $group);
Chris@0 714 }
Chris@0 715
Chris@0 716 /**
Chris@0 717 * Asserts that no errors have been logged to the PHP error.log thus far.
Chris@0 718 *
Chris@0 719 * @return bool
Chris@0 720 * TRUE if the assertion succeeded, FALSE otherwise.
Chris@0 721 *
Chris@0 722 * @see \Drupal\simpletest\TestBase::prepareEnvironment()
Chris@0 723 * @see \Drupal\Core\DrupalKernel::bootConfiguration()
Chris@0 724 */
Chris@0 725 protected function assertNoErrorsLogged() {
Chris@0 726 // Since PHP only creates the error.log file when an actual error is
Chris@0 727 // triggered, it is sufficient to check whether the file exists.
Chris@0 728 return $this->assertFalse(file_exists(DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log'), 'PHP error.log is empty.');
Chris@0 729 }
Chris@0 730
Chris@0 731 /**
Chris@0 732 * Asserts that a specific error has been logged to the PHP error log.
Chris@0 733 *
Chris@0 734 * @param string $error_message
Chris@0 735 * The expected error message.
Chris@0 736 *
Chris@0 737 * @return bool
Chris@0 738 * TRUE if the assertion succeeded, FALSE otherwise.
Chris@0 739 *
Chris@0 740 * @see \Drupal\simpletest\TestBase::prepareEnvironment()
Chris@0 741 * @see \Drupal\Core\DrupalKernel::bootConfiguration()
Chris@0 742 */
Chris@0 743 protected function assertErrorLogged($error_message) {
Chris@0 744 $error_log_filename = DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log';
Chris@0 745 if (!file_exists($error_log_filename)) {
Chris@0 746 $this->error('No error logged yet.');
Chris@0 747 }
Chris@0 748
Chris@0 749 $content = file_get_contents($error_log_filename);
Chris@0 750 $rows = explode(PHP_EOL, $content);
Chris@0 751
Chris@0 752 // We iterate over the rows in order to be able to remove the logged error
Chris@0 753 // afterwards.
Chris@0 754 $found = FALSE;
Chris@0 755 foreach ($rows as $row_index => $row) {
Chris@0 756 if (strpos($content, $error_message) !== FALSE) {
Chris@0 757 $found = TRUE;
Chris@0 758 unset($rows[$row_index]);
Chris@0 759 }
Chris@0 760 }
Chris@0 761
Chris@0 762 file_put_contents($error_log_filename, implode("\n", $rows));
Chris@0 763
Chris@0 764 return $this->assertTrue($found, sprintf('The %s error message was logged.', $error_message));
Chris@0 765 }
Chris@0 766
Chris@0 767 /**
Chris@0 768 * Fire an assertion that is always positive.
Chris@0 769 *
Chris@0 770 * @param $message
Chris@0 771 * (optional) A message to display with the assertion. Do not translate
Chris@17 772 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
Chris@0 773 * variables in the message text, not t(). If left blank, a default message
Chris@0 774 * will be displayed.
Chris@0 775 * @param $group
Chris@0 776 * (optional) The group this message is in, which is displayed in a column
Chris@0 777 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 778 * translate this string. Defaults to 'Other'; most tests do not override
Chris@0 779 * this default.
Chris@0 780 *
Chris@0 781 * @return
Chris@0 782 * TRUE.
Chris@0 783 */
Chris@0 784 protected function pass($message = NULL, $group = 'Other') {
Chris@0 785 return $this->assert(TRUE, $message, $group);
Chris@0 786 }
Chris@0 787
Chris@0 788 /**
Chris@0 789 * Fire an assertion that is always negative.
Chris@0 790 *
Chris@0 791 * @param $message
Chris@0 792 * (optional) A message to display with the assertion. Do not translate
Chris@17 793 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
Chris@0 794 * variables in the message text, not t(). If left blank, a default message
Chris@0 795 * will be displayed.
Chris@0 796 * @param $group
Chris@0 797 * (optional) The group this message is in, which is displayed in a column
Chris@0 798 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 799 * translate this string. Defaults to 'Other'; most tests do not override
Chris@0 800 * this default.
Chris@0 801 *
Chris@0 802 * @return
Chris@0 803 * FALSE.
Chris@0 804 */
Chris@0 805 protected function fail($message = NULL, $group = 'Other') {
Chris@0 806 return $this->assert(FALSE, $message, $group);
Chris@0 807 }
Chris@0 808
Chris@0 809 /**
Chris@0 810 * Fire an error assertion.
Chris@0 811 *
Chris@0 812 * @param $message
Chris@0 813 * (optional) A message to display with the assertion. Do not translate
Chris@17 814 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
Chris@0 815 * variables in the message text, not t(). If left blank, a default message
Chris@0 816 * will be displayed.
Chris@0 817 * @param $group
Chris@0 818 * (optional) The group this message is in, which is displayed in a column
Chris@0 819 * in test output. Use 'Debug' to indicate this is debugging output. Do not
Chris@0 820 * translate this string. Defaults to 'Other'; most tests do not override
Chris@0 821 * this default.
Chris@0 822 * @param $caller
Chris@0 823 * The caller of the error.
Chris@0 824 *
Chris@0 825 * @return
Chris@0 826 * FALSE.
Chris@0 827 */
Chris@0 828 protected function error($message = '', $group = 'Other', array $caller = NULL) {
Chris@0 829 if ($group == 'User notice') {
Chris@0 830 // Since 'User notice' is set by trigger_error() which is used for debug
Chris@0 831 // set the message to a status of 'debug'.
Chris@0 832 return $this->assert('debug', $message, 'Debug', $caller);
Chris@0 833 }
Chris@0 834
Chris@0 835 return $this->assert('exception', $message, $group, $caller);
Chris@0 836 }
Chris@0 837
Chris@0 838 /**
Chris@0 839 * Logs a verbose message in a text file.
Chris@0 840 *
Chris@0 841 * The link to the verbose message will be placed in the test results as a
Chris@0 842 * passing assertion with the text '[verbose message]'.
Chris@0 843 *
Chris@0 844 * @param $message
Chris@0 845 * The verbose message to be stored.
Chris@0 846 *
Chris@0 847 * @see simpletest_verbose()
Chris@0 848 */
Chris@0 849 protected function verbose($message) {
Chris@0 850 // Do nothing if verbose debugging is disabled.
Chris@0 851 if (!$this->verbose) {
Chris@0 852 return;
Chris@0 853 }
Chris@0 854
Chris@0 855 $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;
Chris@0 856 $verbose_filename = $this->verboseClassName . '-' . $this->verboseId . '-' . $this->testId . '.html';
Chris@0 857 if (file_put_contents($this->verboseDirectory . '/' . $verbose_filename, $message)) {
Chris@0 858 $url = $this->verboseDirectoryUrl . '/' . $verbose_filename;
Chris@0 859 // Not using \Drupal\Core\Utility\LinkGeneratorInterface::generate()
Chris@0 860 // to avoid invoking the theme system, so that unit tests
Chris@0 861 // can use verbose() as well.
Chris@0 862 $url = '<a href="' . $url . '" target="_blank">Verbose message</a>';
Chris@0 863 $this->error($url, 'User notice');
Chris@0 864 }
Chris@0 865 $this->verboseId++;
Chris@0 866 }
Chris@0 867
Chris@0 868 /**
Chris@0 869 * Run all tests in this class.
Chris@0 870 *
Chris@0 871 * Regardless of whether $methods are passed or not, only method names
Chris@0 872 * starting with "test" are executed.
Chris@0 873 *
Chris@0 874 * @param $methods
Chris@0 875 * (optional) A list of method names in the test case class to run; e.g.,
Chris@0 876 * array('testFoo', 'testBar'). By default, all methods of the class are
Chris@0 877 * taken into account, but it can be useful to only run a few selected test
Chris@0 878 * methods during debugging.
Chris@0 879 */
Chris@0 880 public function run(array $methods = []) {
Chris@17 881 $this->checkTestHierarchyMismatch();
Chris@0 882 $class = get_class($this);
Chris@0 883
Chris@0 884 if ($missing_requirements = $this->checkRequirements()) {
Chris@0 885 $object_info = new \ReflectionObject($this);
Chris@0 886 $caller = [
Chris@0 887 'file' => $object_info->getFileName(),
Chris@0 888 ];
Chris@0 889 foreach ($missing_requirements as $missing_requirement) {
Chris@0 890 TestBase::insertAssert($this->testId, $class, FALSE, $missing_requirement, 'Requirements check', $caller);
Chris@0 891 }
Chris@0 892 return;
Chris@0 893 }
Chris@0 894
Chris@0 895 TestServiceProvider::$currentTest = $this;
Chris@0 896 $simpletest_config = $this->config('simpletest.settings');
Chris@0 897
Chris@0 898 // Unless preset from run-tests.sh, retrieve the current verbose setting.
Chris@0 899 if (!isset($this->verbose)) {
Chris@0 900 $this->verbose = $simpletest_config->get('verbose');
Chris@0 901 }
Chris@0 902
Chris@0 903 if ($this->verbose) {
Chris@0 904 // Initialize verbose debugging.
Chris@0 905 $this->verbose = TRUE;
Chris@0 906 $this->verboseDirectory = PublicStream::basePath() . '/simpletest/verbose';
Chris@0 907 $this->verboseDirectoryUrl = file_create_url($this->verboseDirectory);
Chris@18 908 if (\Drupal::service('file_system')->prepareDirectory($this->verboseDirectory, FileSystemInterface::CREATE_DIRECTORY) && !file_exists($this->verboseDirectory . '/.htaccess')) {
Chris@0 909 file_put_contents($this->verboseDirectory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
Chris@0 910 }
Chris@0 911 $this->verboseClassName = str_replace("\\", "_", $class);
Chris@0 912 }
Chris@0 913 // HTTP auth settings (<username>:<password>) for the simpletest browser
Chris@0 914 // when sending requests to the test site.
Chris@0 915 $this->httpAuthMethod = (int) $simpletest_config->get('httpauth.method');
Chris@0 916 $username = $simpletest_config->get('httpauth.username');
Chris@0 917 $password = $simpletest_config->get('httpauth.password');
Chris@0 918 if (!empty($username) && !empty($password)) {
Chris@0 919 $this->httpAuthCredentials = $username . ':' . $password;
Chris@0 920 }
Chris@0 921
Chris@0 922 // Force assertion failures to be thrown as AssertionError for PHP 5 & 7
Chris@0 923 // compatibility.
Chris@0 924 Handle::register();
Chris@0 925
Chris@0 926 set_error_handler([$this, 'errorHandler']);
Chris@0 927 // Iterate through all the methods in this class, unless a specific list of
Chris@0 928 // methods to run was passed.
Chris@0 929 $test_methods = array_filter(get_class_methods($class), function ($method) {
Chris@0 930 return strpos($method, 'test') === 0;
Chris@0 931 });
Chris@0 932 if (empty($test_methods)) {
Chris@0 933 // Call $this->assert() here because we need to pass along custom caller
Chris@0 934 // information, lest the wrong originating code file/line be identified.
Chris@0 935 $this->assert(FALSE, 'No test methods found.', 'Requirements', ['function' => __METHOD__ . '()', 'file' => __FILE__, 'line' => __LINE__]);
Chris@0 936 }
Chris@0 937 if ($methods) {
Chris@0 938 $test_methods = array_intersect($test_methods, $methods);
Chris@0 939 }
Chris@0 940 foreach ($test_methods as $method) {
Chris@0 941 // Insert a fail record. This will be deleted on completion to ensure
Chris@0 942 // that testing completed.
Chris@0 943 $method_info = new \ReflectionMethod($class, $method);
Chris@0 944 $caller = [
Chris@0 945 'file' => $method_info->getFileName(),
Chris@0 946 'line' => $method_info->getStartLine(),
Chris@0 947 'function' => $class . '->' . $method . '()',
Chris@0 948 ];
Chris@0 949 $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 950
Chris@0 951 try {
Chris@0 952 $this->prepareEnvironment();
Chris@0 953 }
Chris@0 954 catch (\Exception $e) {
Chris@0 955 $this->exceptionHandler($e);
Chris@0 956 // The prepareEnvironment() method isolates the test from the parent
Chris@0 957 // Drupal site by creating a random database prefix and test site
Chris@0 958 // directory. If this fails, a test would possibly operate in the
Chris@0 959 // parent site. Therefore, the entire test run for this test class
Chris@0 960 // has to be aborted.
Chris@0 961 // restoreEnvironment() cannot be called, because we do not know
Chris@0 962 // where exactly the environment setup failed.
Chris@0 963 break;
Chris@0 964 }
Chris@0 965
Chris@0 966 try {
Chris@0 967 $this->setUp();
Chris@0 968 }
Chris@0 969 catch (\Exception $e) {
Chris@0 970 $this->exceptionHandler($e);
Chris@0 971 // Abort if setUp() fails, since all test methods will fail.
Chris@0 972 // But ensure to clean up and restore the environment, since
Chris@0 973 // prepareEnvironment() succeeded.
Chris@0 974 $this->restoreEnvironment();
Chris@0 975 break;
Chris@0 976 }
Chris@0 977 try {
Chris@0 978 $this->$method();
Chris@0 979 }
Chris@0 980 catch (\Exception $e) {
Chris@0 981 $this->exceptionHandler($e);
Chris@0 982 }
Chris@0 983 try {
Chris@0 984 $this->tearDown();
Chris@0 985 }
Chris@0 986 catch (\Exception $e) {
Chris@0 987 $this->exceptionHandler($e);
Chris@0 988 // If a test fails to tear down, abort the entire test class, since
Chris@0 989 // it is likely that all tests will fail in the same way and a
Chris@0 990 // failure here only results in additional test artifacts that have
Chris@0 991 // to be manually deleted.
Chris@0 992 $this->restoreEnvironment();
Chris@0 993 break;
Chris@0 994 }
Chris@0 995
Chris@0 996 $this->restoreEnvironment();
Chris@0 997 // Remove the test method completion check record.
Chris@0 998 TestBase::deleteAssert($test_completion_check_id);
Chris@0 999 }
Chris@0 1000
Chris@0 1001 TestServiceProvider::$currentTest = NULL;
Chris@0 1002 // Clear out the error messages and restore error handler.
Chris@17 1003 \Drupal::messenger()->deleteAll();
Chris@0 1004 restore_error_handler();
Chris@0 1005 }
Chris@0 1006
Chris@0 1007 /**
Chris@0 1008 * Generates a database prefix for running tests.
Chris@0 1009 *
Chris@0 1010 * The database prefix is used by prepareEnvironment() to setup a public files
Chris@0 1011 * directory for the test to be run, which also contains the PHP error log,
Chris@0 1012 * which is written to in case of a fatal error. Since that directory is based
Chris@0 1013 * on the database prefix, all tests (even unit tests) need to have one, in
Chris@0 1014 * order to access and read the error log.
Chris@0 1015 *
Chris@0 1016 * @see TestBase::prepareEnvironment()
Chris@0 1017 *
Chris@0 1018 * The generated database table prefix is used for the Drupal installation
Chris@0 1019 * being performed for the test. It is also used as user agent HTTP header
Chris@0 1020 * value by the cURL-based browser of WebTestBase, which is sent to the Drupal
Chris@0 1021 * installation of the test. During early Drupal bootstrap, the user agent
Chris@0 1022 * HTTP header is parsed, and if it matches, all database queries use the
Chris@0 1023 * database table prefix that has been generated here.
Chris@0 1024 *
Chris@0 1025 * @see WebTestBase::curlInitialize()
Chris@0 1026 * @see drupal_valid_test_ua()
Chris@0 1027 */
Chris@0 1028 private function prepareDatabasePrefix() {
Chris@0 1029 $test_db = new TestDatabase();
Chris@0 1030 $this->siteDirectory = $test_db->getTestSitePath();
Chris@0 1031 $this->databasePrefix = $test_db->getDatabasePrefix();
Chris@0 1032
Chris@0 1033 // As soon as the database prefix is set, the test might start to execute.
Chris@0 1034 // All assertions as well as the SimpleTest batch operations are associated
Chris@0 1035 // with the testId, so the database prefix has to be associated with it.
Chris@0 1036 $affected_rows = self::getDatabaseConnection()->update('simpletest_test_id')
Chris@0 1037 ->fields(['last_prefix' => $this->databasePrefix])
Chris@0 1038 ->condition('test_id', $this->testId)
Chris@0 1039 ->execute();
Chris@0 1040 if (!$affected_rows) {
Chris@0 1041 throw new \RuntimeException('Failed to set up database prefix.');
Chris@0 1042 }
Chris@0 1043 }
Chris@0 1044
Chris@0 1045 /**
Chris@0 1046 * Act on global state information before the environment is altered for a test.
Chris@0 1047 *
Chris@0 1048 * Allows e.g. KernelTestBase to prime system/extension info from the
Chris@0 1049 * parent site (and inject it into the test environment so as to improve
Chris@0 1050 * performance).
Chris@0 1051 */
Chris@0 1052 protected function beforePrepareEnvironment() {
Chris@0 1053 }
Chris@0 1054
Chris@0 1055 /**
Chris@0 1056 * Prepares the current environment for running the test.
Chris@0 1057 *
Chris@0 1058 * Backups various current environment variables and resets them, so they do
Chris@0 1059 * not interfere with the Drupal site installation in which tests are executed
Chris@0 1060 * and can be restored in TestBase::restoreEnvironment().
Chris@0 1061 *
Chris@0 1062 * Also sets up new resources for the testing environment, such as the public
Chris@0 1063 * filesystem and configuration directories.
Chris@0 1064 *
Chris@0 1065 * This method is private as it must only be called once by TestBase::run()
Chris@0 1066 * (multiple invocations for the same test would have unpredictable
Chris@0 1067 * consequences) and it must not be callable or overridable by test classes.
Chris@0 1068 *
Chris@0 1069 * @see TestBase::beforePrepareEnvironment()
Chris@0 1070 */
Chris@0 1071 private function prepareEnvironment() {
Chris@0 1072 $user = \Drupal::currentUser();
Chris@0 1073 // Allow (base) test classes to backup global state information.
Chris@0 1074 $this->beforePrepareEnvironment();
Chris@0 1075
Chris@0 1076 // Create the database prefix for this test.
Chris@0 1077 $this->prepareDatabasePrefix();
Chris@0 1078
Chris@0 1079 $language_interface = \Drupal::languageManager()->getCurrentLanguage();
Chris@0 1080
Chris@0 1081 // When running the test runner within a test, back up the original database
Chris@0 1082 // prefix.
Chris@0 1083 if (DRUPAL_TEST_IN_CHILD_SITE) {
Chris@0 1084 $this->originalPrefix = drupal_valid_test_ua();
Chris@0 1085 }
Chris@0 1086
Chris@0 1087 // Backup current in-memory configuration.
Chris@0 1088 $site_path = \Drupal::service('site.path');
Chris@0 1089 $this->originalSite = $site_path;
Chris@0 1090 $this->originalSettings = Settings::getAll();
Chris@0 1091 $this->originalConfig = $GLOBALS['config'];
Chris@0 1092 // @todo Remove all remnants of $GLOBALS['conf'].
Chris@0 1093 // @see https://www.drupal.org/node/2183323
Chris@0 1094 $this->originalConf = isset($GLOBALS['conf']) ? $GLOBALS['conf'] : NULL;
Chris@0 1095
Chris@0 1096 // Backup statics and globals.
Chris@0 1097 $this->originalContainer = \Drupal::getContainer();
Chris@0 1098 $this->originalLanguage = $language_interface;
Chris@0 1099 $this->originalConfigDirectories = $GLOBALS['config_directories'];
Chris@0 1100
Chris@0 1101 // Save further contextual information.
Chris@0 1102 // Use the original files directory to avoid nesting it within an existing
Chris@0 1103 // simpletest directory if a test is executed within a test.
Chris@0 1104 $this->originalFileDirectory = Settings::get('file_public_path', $site_path . '/files');
Chris@0 1105 $this->originalProfile = drupal_get_profile();
Chris@0 1106 $this->originalUser = isset($user) ? clone $user : NULL;
Chris@0 1107
Chris@0 1108 // Prevent that session data is leaked into the UI test runner by closing
Chris@0 1109 // the session and then setting the session-name (i.e. the name of the
Chris@0 1110 // session cookie) to a random value. If a test starts a new session, then
Chris@0 1111 // it will be associated with a different session-name. After the test-run
Chris@0 1112 // it can be safely destroyed.
Chris@0 1113 // @see TestBase::restoreEnvironment()
Chris@0 1114 if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) {
Chris@0 1115 session_write_close();
Chris@0 1116 }
Chris@0 1117 $this->originalSessionName = session_name();
Chris@0 1118 session_name('SIMPLETEST' . Crypt::randomBytesBase64());
Chris@0 1119
Chris@0 1120 // Save and clean the shutdown callbacks array because it is static cached
Chris@0 1121 // and will be changed by the test run. Otherwise it will contain callbacks
Chris@0 1122 // from both environments and the testing environment will try to call the
Chris@0 1123 // handlers defined by the original one.
Chris@0 1124 $callbacks = &drupal_register_shutdown_function();
Chris@0 1125 $this->originalShutdownCallbacks = $callbacks;
Chris@0 1126 $callbacks = [];
Chris@0 1127
Chris@0 1128 // Create test directory ahead of installation so fatal errors and debug
Chris@0 1129 // information can be logged during installation process.
Chris@18 1130 \Drupal::service('file_system')->prepareDirectory($this->siteDirectory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
Chris@0 1131
Chris@0 1132 // Prepare filesystem directory paths.
Chris@0 1133 $this->publicFilesDirectory = $this->siteDirectory . '/files';
Chris@0 1134 $this->privateFilesDirectory = $this->siteDirectory . '/private';
Chris@0 1135 $this->tempFilesDirectory = $this->siteDirectory . '/temp';
Chris@0 1136 $this->translationFilesDirectory = $this->siteDirectory . '/translations';
Chris@0 1137
Chris@0 1138 $this->generatedTestFiles = FALSE;
Chris@0 1139
Chris@0 1140 // Ensure the configImporter is refreshed for each test.
Chris@0 1141 $this->configImporter = NULL;
Chris@0 1142
Chris@0 1143 // Unregister all custom stream wrappers of the parent site.
Chris@0 1144 // Availability of Drupal stream wrappers varies by test base class:
Chris@0 1145 // - KernelTestBase supports and maintains stream wrappers in a custom
Chris@0 1146 // way.
Chris@0 1147 // - WebTestBase re-initializes Drupal stream wrappers after installation.
Chris@0 1148 // The original stream wrappers are restored after the test run.
Chris@0 1149 // @see TestBase::restoreEnvironment()
Chris@0 1150 $this->originalContainer->get('stream_wrapper_manager')->unregister();
Chris@0 1151
Chris@0 1152 // Reset statics.
Chris@0 1153 drupal_static_reset();
Chris@0 1154
Chris@0 1155 // Ensure there is no service container.
Chris@0 1156 $this->container = NULL;
Chris@0 1157 \Drupal::unsetContainer();
Chris@0 1158
Chris@0 1159 // Unset globals.
Chris@0 1160 unset($GLOBALS['config_directories']);
Chris@0 1161 unset($GLOBALS['config']);
Chris@0 1162 unset($GLOBALS['conf']);
Chris@0 1163
Chris@0 1164 // Log fatal errors.
Chris@0 1165 ini_set('log_errors', 1);
Chris@0 1166 ini_set('error_log', DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log');
Chris@0 1167
Chris@0 1168 // Change the database prefix.
Chris@0 1169 $this->changeDatabasePrefix();
Chris@0 1170
Chris@0 1171 // After preparing the environment and changing the database prefix, we are
Chris@0 1172 // in a valid test environment.
Chris@0 1173 drupal_valid_test_ua($this->databasePrefix);
Chris@0 1174
Chris@0 1175 // Reset settings.
Chris@0 1176 new Settings([
Chris@0 1177 // For performance, simply use the database prefix as hash salt.
Chris@0 1178 'hash_salt' => $this->databasePrefix,
Chris@0 1179 'container_yamls' => [],
Chris@0 1180 ]);
Chris@0 1181
Chris@18 1182 Environment::setTimeLimit($this->timeLimit);
Chris@0 1183 }
Chris@0 1184
Chris@0 1185 /**
Chris@0 1186 * Performs cleanup tasks after each individual test method has been run.
Chris@0 1187 */
Chris@0 1188 protected function tearDown() {
Chris@0 1189 }
Chris@0 1190
Chris@0 1191 /**
Chris@0 1192 * Cleans up the test environment and restores the original environment.
Chris@0 1193 *
Chris@0 1194 * Deletes created files, database tables, and reverts environment changes.
Chris@0 1195 *
Chris@0 1196 * This method needs to be invoked for both unit and integration tests.
Chris@0 1197 *
Chris@0 1198 * @see TestBase::prepareDatabasePrefix()
Chris@0 1199 * @see TestBase::changeDatabasePrefix()
Chris@0 1200 * @see TestBase::prepareEnvironment()
Chris@0 1201 */
Chris@0 1202 private function restoreEnvironment() {
Chris@0 1203 // Destroy the session if one was started during the test-run.
Chris@0 1204 $_SESSION = [];
Chris@0 1205 if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) {
Chris@0 1206 session_destroy();
Chris@0 1207 $params = session_get_cookie_params();
Chris@0 1208 setcookie(session_name(), '', REQUEST_TIME - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
Chris@0 1209 }
Chris@0 1210 session_name($this->originalSessionName);
Chris@0 1211
Chris@0 1212 // Reset all static variables.
Chris@0 1213 // Unsetting static variables will potentially invoke destruct methods,
Chris@0 1214 // which might call into functions that prime statics and caches again.
Chris@0 1215 // In that case, all functions are still operating on the test environment,
Chris@0 1216 // which means they may need to access its filesystem and database.
Chris@0 1217 drupal_static_reset();
Chris@0 1218
Chris@0 1219 if ($this->container && $this->container->has('state') && $state = $this->container->get('state')) {
Chris@0 1220 $captured_emails = $state->get('system.test_mail_collector') ?: [];
Chris@0 1221 $emailCount = count($captured_emails);
Chris@0 1222 if ($emailCount) {
Chris@0 1223 $message = $emailCount == 1 ? '1 email was sent during this test.' : $emailCount . ' emails were sent during this test.';
Chris@0 1224 $this->pass($message, 'Email');
Chris@0 1225 }
Chris@0 1226 }
Chris@0 1227
Chris@0 1228 // Sleep for 50ms to allow shutdown functions and terminate events to
Chris@0 1229 // complete. Further information: https://www.drupal.org/node/2194357.
Chris@0 1230 usleep(50000);
Chris@0 1231
Chris@0 1232 // Remove all prefixed tables.
Chris@0 1233 $original_connection_info = Database::getConnectionInfo('simpletest_original_default');
Chris@0 1234 $original_prefix = $original_connection_info['default']['prefix']['default'];
Chris@0 1235 $test_connection_info = Database::getConnectionInfo('default');
Chris@0 1236 $test_prefix = $test_connection_info['default']['prefix']['default'];
Chris@0 1237 if ($original_prefix != $test_prefix) {
Chris@0 1238 $tables = Database::getConnection()->schema()->findTables('%');
Chris@0 1239 foreach ($tables as $table) {
Chris@0 1240 if (Database::getConnection()->schema()->dropTable($table)) {
Chris@0 1241 unset($tables[$table]);
Chris@0 1242 }
Chris@0 1243 }
Chris@0 1244 }
Chris@0 1245
Chris@0 1246 // In case a fatal error occurred that was not in the test process read the
Chris@0 1247 // log to pick up any fatal errors.
Chris@0 1248 simpletest_log_read($this->testId, $this->databasePrefix, get_class($this));
Chris@0 1249
Chris@0 1250 // Restore original dependency injection container.
Chris@0 1251 $this->container = $this->originalContainer;
Chris@0 1252 \Drupal::setContainer($this->originalContainer);
Chris@0 1253
Chris@0 1254 // Delete test site directory.
Chris@18 1255 \Drupal::service('file_system')->deleteRecursive($this->siteDirectory, [$this, 'filePreDeleteCallback']);
Chris@0 1256
Chris@0 1257 // Restore original database connection.
Chris@0 1258 Database::removeConnection('default');
Chris@0 1259 Database::renameConnection('simpletest_original_default', 'default');
Chris@0 1260
Chris@0 1261 // Reset all static variables.
Chris@0 1262 // All destructors of statically cached objects have been invoked above;
Chris@0 1263 // this second reset is guaranteed to reset everything to nothing.
Chris@0 1264 drupal_static_reset();
Chris@0 1265
Chris@0 1266 // Restore original in-memory configuration.
Chris@0 1267 $GLOBALS['config'] = $this->originalConfig;
Chris@0 1268 $GLOBALS['conf'] = $this->originalConf;
Chris@0 1269 new Settings($this->originalSettings);
Chris@0 1270
Chris@0 1271 // Restore original statics and globals.
Chris@0 1272 $GLOBALS['config_directories'] = $this->originalConfigDirectories;
Chris@0 1273
Chris@0 1274 // Re-initialize original stream wrappers of the parent site.
Chris@0 1275 // This must happen after static variables have been reset and the original
Chris@0 1276 // container and $config_directories are restored, as simpletest_log_read()
Chris@0 1277 // uses the public stream wrapper to locate the error.log.
Chris@0 1278 $this->originalContainer->get('stream_wrapper_manager')->register();
Chris@0 1279
Chris@0 1280 if (isset($this->originalPrefix)) {
Chris@0 1281 drupal_valid_test_ua($this->originalPrefix);
Chris@0 1282 }
Chris@0 1283 else {
Chris@0 1284 drupal_valid_test_ua(FALSE);
Chris@0 1285 }
Chris@0 1286
Chris@0 1287 // Restore original shutdown callbacks.
Chris@0 1288 $callbacks = &drupal_register_shutdown_function();
Chris@0 1289 $callbacks = $this->originalShutdownCallbacks;
Chris@0 1290 }
Chris@0 1291
Chris@0 1292 /**
Chris@0 1293 * Handle errors during test runs.
Chris@0 1294 *
Chris@0 1295 * Because this is registered in set_error_handler(), it has to be public.
Chris@0 1296 *
Chris@0 1297 * @see set_error_handler
Chris@0 1298 */
Chris@0 1299 public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
Chris@0 1300 if ($severity & error_reporting()) {
Chris@0 1301 $error_map = [
Chris@0 1302 E_STRICT => 'Run-time notice',
Chris@0 1303 E_WARNING => 'Warning',
Chris@0 1304 E_NOTICE => 'Notice',
Chris@0 1305 E_CORE_ERROR => 'Core error',
Chris@0 1306 E_CORE_WARNING => 'Core warning',
Chris@0 1307 E_USER_ERROR => 'User error',
Chris@0 1308 E_USER_WARNING => 'User warning',
Chris@0 1309 E_USER_NOTICE => 'User notice',
Chris@0 1310 E_RECOVERABLE_ERROR => 'Recoverable error',
Chris@0 1311 E_DEPRECATED => 'Deprecated',
Chris@0 1312 E_USER_DEPRECATED => 'User deprecated',
Chris@0 1313 ];
Chris@0 1314
Chris@0 1315 $backtrace = debug_backtrace();
Chris@0 1316
Chris@0 1317 // Add verbose backtrace for errors, but not for debug() messages.
Chris@0 1318 if ($severity !== E_USER_NOTICE) {
Chris@0 1319 $verbose_backtrace = $backtrace;
Chris@0 1320 array_shift($verbose_backtrace);
Chris@0 1321 $message .= '<pre class="backtrace">' . Error::formatBacktrace($verbose_backtrace) . '</pre>';
Chris@0 1322 }
Chris@0 1323
Chris@0 1324 $this->error($message, $error_map[$severity], Error::getLastCaller($backtrace));
Chris@0 1325 }
Chris@0 1326 return TRUE;
Chris@0 1327 }
Chris@0 1328
Chris@0 1329 /**
Chris@0 1330 * Handle exceptions.
Chris@0 1331 *
Chris@0 1332 * @see set_exception_handler
Chris@0 1333 */
Chris@0 1334 protected function exceptionHandler($exception) {
Chris@0 1335 $backtrace = $exception->getTrace();
Chris@0 1336 $verbose_backtrace = $backtrace;
Chris@0 1337 // Push on top of the backtrace the call that generated the exception.
Chris@0 1338 array_unshift($backtrace, [
Chris@0 1339 'line' => $exception->getLine(),
Chris@0 1340 'file' => $exception->getFile(),
Chris@0 1341 ]);
Chris@0 1342 $decoded_exception = Error::decodeException($exception);
Chris@0 1343 unset($decoded_exception['backtrace']);
Chris@17 1344 $message = new FormattableMarkup('%type: @message in %function (line %line of %file). <pre class="backtrace">@backtrace</pre>', $decoded_exception + [
Chris@0 1345 '@backtrace' => Error::formatBacktrace($verbose_backtrace),
Chris@0 1346 ]);
Chris@0 1347 $this->error($message, 'Uncaught exception', Error::getLastCaller($backtrace));
Chris@0 1348 }
Chris@0 1349
Chris@0 1350 /**
Chris@0 1351 * Changes in memory settings.
Chris@0 1352 *
Chris@0 1353 * @param $name
Chris@0 1354 * The name of the setting to return.
Chris@0 1355 * @param $value
Chris@0 1356 * The value of the setting.
Chris@0 1357 *
Chris@0 1358 * @see \Drupal\Core\Site\Settings::get()
Chris@0 1359 */
Chris@0 1360 protected function settingsSet($name, $value) {
Chris@0 1361 $settings = Settings::getAll();
Chris@0 1362 $settings[$name] = $value;
Chris@0 1363 new Settings($settings);
Chris@0 1364 }
Chris@0 1365
Chris@0 1366 /**
Chris@18 1367 * Ensures test files are deletable.
Chris@0 1368 *
Chris@0 1369 * Some tests chmod generated files to be read only. During
Chris@0 1370 * TestBase::restoreEnvironment() and other cleanup operations, these files
Chris@0 1371 * need to get deleted too.
Chris@18 1372 *
Chris@18 1373 * @see \Drupal\Core\File\FileSystemInterface::deleteRecursive()
Chris@0 1374 */
Chris@0 1375 public static function filePreDeleteCallback($path) {
Chris@0 1376 // When the webserver runs with the same system user as the test runner, we
Chris@0 1377 // can make read-only files writable again. If not, chmod will fail while
Chris@0 1378 // the file deletion still works if file permissions have been configured
Chris@0 1379 // correctly. Thus, we ignore any problems while running chmod.
Chris@0 1380 @chmod($path, 0700);
Chris@0 1381 }
Chris@0 1382
Chris@0 1383 /**
Chris@0 1384 * Configuration accessor for tests. Returns non-overridden configuration.
Chris@0 1385 *
Chris@0 1386 * @param $name
Chris@0 1387 * Configuration name.
Chris@0 1388 *
Chris@0 1389 * @return \Drupal\Core\Config\Config
Chris@0 1390 * The configuration object with original configuration data.
Chris@0 1391 */
Chris@0 1392 protected function config($name) {
Chris@0 1393 return \Drupal::configFactory()->getEditable($name);
Chris@0 1394 }
Chris@0 1395
Chris@0 1396 /**
Chris@0 1397 * Gets the database prefix.
Chris@0 1398 *
Chris@0 1399 * @return string
Chris@0 1400 * The database prefix
Chris@0 1401 */
Chris@0 1402 public function getDatabasePrefix() {
Chris@0 1403 return $this->databasePrefix;
Chris@0 1404 }
Chris@0 1405
Chris@0 1406 /**
Chris@0 1407 * Gets the temporary files directory.
Chris@0 1408 *
Chris@0 1409 * @return string
Chris@0 1410 * The temporary files directory.
Chris@0 1411 */
Chris@0 1412 public function getTempFilesDirectory() {
Chris@0 1413 return $this->tempFilesDirectory;
Chris@0 1414 }
Chris@0 1415
Chris@0 1416 }