comparison core/modules/simpletest/src/TestBase.php @ 0:4c8ae668cc8c

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