annotate core/modules/simpletest/src/TestBase.php @ 4:a9cd425dd02b

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