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