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