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