annotate core/modules/simpletest/src/TestBase.php @ 0:c75dbcec494b

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