TestBase.php 56.1 KB
Newer Older
1
2
3
4
<?php

/**
 * @file
5
 * Definition of \Drupal\simpletest\TestBase.
6
7
8
9
 */

namespace Drupal\simpletest;

10
use Drupal\Component\Utility\Crypt;
11
use Drupal\Component\Utility\Random;
12
use Drupal\Component\Utility\String;
13
use Drupal\Core\Database\Database;
14
use Drupal\Core\Config\ConfigImporter;
15
use Drupal\Core\Config\StorageComparer;
16
use Drupal\Core\DependencyInjection\ContainerBuilder;
17
use Drupal\Core\Database\ConnectionNotDefinedException;
18
use Drupal\Core\Config\StorageInterface;
19
use Drupal\Core\Language\Language;
20
21
use Drupal\Core\Session\AccountProxy;
use Drupal\Core\Session\AnonymousUserSession;
22
use Drupal\Core\Site\Settings;
23
use Drupal\Core\StreamWrapper\PublicStream;
24
use Drupal\Core\Utility\Error;
25
use Symfony\Component\HttpFoundation\Request;
26
use Symfony\Component\HttpFoundation\RequestStack;
27
use Symfony\Component\DependencyInjection\Reference;
28
29
30
31

/**
 * Base class for Drupal tests.
 *
32
 * Do not extend this class directly; use either
33
 * \Drupal\simpletest\WebTestBase or \Drupal\simpletest\KernelTestBase.
34
35
36
37
38
39
40
41
42
 */
abstract class TestBase {
  /**
   * The test run ID.
   *
   * @var string
   */
  protected $testId;

43
44
45
46
47
48
49
  /**
   * The site directory of this test run.
   *
   * @var string
   */
  protected $siteDirectory = NULL;

50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
  /**
   * The database prefix of this test run.
   *
   * @var string
   */
  protected $databasePrefix = NULL;

  /**
   * Time limit for the test.
   */
  protected $timeLimit = 500;

  /**
   * Current results of this test case.
   *
   * @var Array
   */
  public $results = array(
    '#pass' => 0,
    '#fail' => 0,
    '#exception' => 0,
    '#debug' => 0,
  );

  /**
   * Assertions thrown in that test case.
   *
   * @var Array
   */
  protected $assertions = array();

  /**
   * This class is skipped when looking for the source of an assertion.
   *
   * When displaying which function an assert comes from, it's not too useful
   * to see "WebTestBase->drupalLogin()', we would like to see the test
   * that called it. So we need to skip the classes defining these helper
   * methods.
   */
  protected $skipClasses = array(__CLASS__ => TRUE);

91
92
93
94
95
  /**
   * TRUE if verbose debugging is enabled.
   *
   * @var boolean
   */
96
  public $verbose;
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120

  /**
   * Incrementing identifier for verbose output filenames.
   *
   * @var integer
   */
  protected $verboseId = 0;

  /**
   * Safe class name for use in verbose output filenames.
   *
   * Namespaces separator (\) replaced with _.
   *
   * @var string
   */
  protected $verboseClassName;

  /**
   * Directory where verbose output files are put.
   *
   * @var string
   */
  protected $verboseDirectory;

121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
  /**
   * URL to the verbose output file directory.
   *
   * @var string
   */
  protected $verboseDirectoryUrl;

  /**
   * The original configuration (variables), if available.
   *
   * @var string
   * @todo Remove all remnants of $GLOBALS['conf'].
   * @see https://drupal.org/node/2183323
   */
  protected $originalConf;

  /**
   * The original configuration (variables).
   *
   * @var string
   */
  protected $originalConfig;

  /**
   * The original configuration directories.
   *
   * An array of paths keyed by the CONFIG_*_DIRECTORY constants defined by
   * core/includes/bootstrap.inc.
   *
   * @var array
   */
  protected $originalConfigDirectories;

  /**
   * The original container.
   *
   * @var \Symfony\Component\DependencyInjection\ContainerInterface
   */
  protected $originalContainer;

  /**
   * The original file directory, before it was changed for testing purposes.
   *
   * @var string
   */
  protected $originalFileDirectory = NULL;

  /**
   * The original language.
   *
   * @var \Drupal\Core\Language\LanguageInterface
   */
  protected $originalLanguage;

175
176
177
178
179
180
181
  /**
   * The original database prefix when running inside Simpletest.
   *
   * @var string
   */
  protected $originalPrefix;

182
  /**
183
   * The original installation profile.
184
185
186
   *
   * @var string
   */
187
188
189
190
191
192
193
194
  protected $originalProfile;

  /**
   * The name of the session cookie.
   *
   * @var string
   */
  protected $originalSessionName;
195

196
197
  /**
   * The settings array.
198
199
   *
   * @var array
200
201
202
   */
  protected $originalSettings;

203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
  /**
   * The original array of shutdown function callbacks.
   *
   * @var array
   */
  protected $originalShutdownCallbacks;

  /**
   * The site directory of the original parent site.
   *
   * @var string
   */
  protected $originalSite;

  /**
   * The original user, before testing began.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $originalUser;

224
225
226
227
228
229
230
  /**
   * The public file directory for the test environment.
   *
   * This is set in TestBase::prepareEnvironment().
   *
   * @var string
   */
231
  protected $publicFilesDirectory;
232

233
234
235
236
237
238
239
  /**
   * The private file directory for the test environment.
   *
   * This is set in TestBase::prepareEnvironment().
   *
   * @var string
   */
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
  protected $privateFilesDirectory;

  /**
   * The temporary file directory for the test environment.
   *
   * This is set in TestBase::prepareEnvironment().
   *
   * @var string
   */
  protected $tempFilesDirectory;

  /**
   * The translation file directory for the test environment.
   *
   * This is set in TestBase::prepareEnvironment().
   *
   * @var string
   */
  protected $translationFilesDirectory;
259

260
  /**
261
262
   * Whether to die in case any test assertion fails.
   *
263
   * @var boolean
264
265
   *
   * @see run-tests.sh
266
   */
267
  public $dieOnFail = FALSE;
268

269
270
271
272
273
274
275
  /**
   * The DrupalKernel instance used in the test.
   *
   * @var \Drupal\Core\DrupalKernel
   */
  protected $kernel;

276
277
278
279
280
281
282
  /**
   * The dependency injection container used in the test.
   *
   * @var \Symfony\Component\DependencyInjection\ContainerInterface
   */
  protected $container;

283
284
285
286
287
288
289
  /**
   * The config importer that can used in a test.
   *
   * @var \Drupal\Core\Config\ConfigImporter
   */
  protected $configImporter;

290
291
292
293
294
295
296
  /**
   * The random generator.
   *
   * @var \Drupal\Component\Utility\Random
   */
  protected $randomGenerator;

297
298
299
300
301
302
303
  /**
   * Set to TRUE to strict check all configuration saved.
   *
   * @see \Drupal\Core\Config\Testing\ConfigSchemaChecker
   *
   * @var bool
   */
304
  protected $strictConfigSchema = TRUE;
305

306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
  /**
   * HTTP authentication method (specified as a CURLAUTH_* constant).
   *
   * @var int
   * @see http://php.net/manual/en/function.curl-setopt.php
   */
  protected $httpAuthMethod = CURLAUTH_BASIC;

  /**
   * HTTP authentication credentials (<username>:<password>).
   *
   * @var string
   */
  protected $httpAuthCredentials = NULL;

321
322
323
324
325
326
327
328
329
330
  /**
   * Constructor for Test.
   *
   * @param $test_id
   *   Tests with the same id are reported together.
   */
  public function __construct($test_id = NULL) {
    $this->testId = $test_id;
  }

331
332
333
334
335
  /**
   * Performs setup tasks before each individual test method is run.
   */
  abstract protected function setUp();

336
337
338
339
340
341
342
343
344
345
  /**
   * Checks the matching requirements for Test.
   *
   * @return
   *   Array of errors containing a list of unmet requirements.
   */
  protected function checkRequirements() {
    return array();
  }

346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
  /**
   * Helper method to store an assertion record in the configured database.
   *
   * This method decouples database access from assertion logic.
   *
   * @param array $assertion
   *   Keyed array representing an assertion, as generated by assert().
   *
   * @see self::assert()
   */
  protected function storeAssertion(array $assertion) {
    return self::getDatabaseConnection()
      ->insert('simpletest')
      ->fields($assertion)
      ->execute();
  }

363
364
365
366
  /**
   * Internal helper: stores the assert.
   *
   * @param $status
367
   *   Can be 'pass', 'fail', 'exception', 'debug'.
368
369
   *   TRUE is a synonym for 'pass', FALSE for 'fail'.
   * @param $message
370
   *   (optional) A message to display with the assertion. Do not translate
371
372
373
   *   messages: use \Drupal\Component\Utility\String::format() to embed
   *   variables in the message text, not t(). If left blank, a default message
   *   will be displayed.
374
   * @param $group
375
376
377
378
   *   (optional) The group this message is in, which is displayed in a column
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
   *   translate this string. Defaults to 'Other'; most tests do not override
   *   this default.
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
   * @param $caller
   *   By default, the assert comes from a function whose name starts with
   *   'test'. Instead, you can specify where this assert originates from
   *   by passing in an associative array as $caller. Key 'file' is
   *   the name of the source file, 'line' is the line number and 'function'
   *   is the caller function itself.
   */
  protected function assert($status, $message = '', $group = 'Other', array $caller = NULL) {
    // Convert boolean status to string status.
    if (is_bool($status)) {
      $status = $status ? 'pass' : 'fail';
    }

    // Increment summary result counter.
    $this->results['#' . $status]++;

    // Get the function information about the call to the assertion method.
    if (!$caller) {
      $caller = $this->getAssertionCall();
    }

    // Creation assertion array that can be displayed while tests are running.
    $this->assertions[] = $assertion = array(
      'test_id' => $this->testId,
      'test_class' => get_class($this),
      'status' => $status,
      'message' => $message,
      'message_group' => $group,
      'function' => $caller['function'],
      'line' => $caller['line'],
      'file' => $caller['file'],
    );

    // Store assertion for display after the test has completed.
413
    $this->storeAssertion($assertion);
414
415
416
417
418
419
420

    // We do not use a ternary operator here to allow a breakpoint on
    // test failure.
    if ($status == 'pass') {
      return TRUE;
    }
    else {
421
      if ($this->dieOnFail && ($status == 'fail' || $status == 'exception')) {
422
423
        exit(1);
      }
424
425
426
427
428
429
430
431
432
433
434
      return FALSE;
    }
  }

  /**
   * Store an assertion from outside the testing context.
   *
   * This is useful for inserting assertions that can only be recorded after
   * the test case has been destroyed, such as PHP fatal errors. The caller
   * information is not automatically gathered since the caller is most likely
   * inserting the assertion on behalf of other code. In all other respects
435
   * the method behaves just like \Drupal\simpletest\TestBase::assert() in terms
436
437
438
439
440
   * of storing the assertion.
   *
   * @return
   *   Message ID of the stored assertion.
   *
441
442
   * @see \Drupal\simpletest\TestBase::assert()
   * @see \Drupal\simpletest\TestBase::deleteAssert()
443
444
445
446
447
448
449
450
   */
  public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = array()) {
    // Convert boolean status to string status.
    if (is_bool($status)) {
      $status = $status ? 'pass' : 'fail';
    }

    $caller += array(
451
      'function' => 'Unknown',
452
      'line' => 0,
453
      'file' => 'Unknown',
454
455
456
457
458
459
460
461
462
463
464
465
466
    );

    $assertion = array(
      'test_id' => $test_id,
      'test_class' => $test_class,
      'status' => $status,
      'message' => $message,
      'message_group' => $group,
      'function' => $caller['function'],
      'line' => $caller['line'],
      'file' => $caller['file'],
    );

467
    // We can't use storeAssertion() because this method is static.
468
469
    return self::getDatabaseConnection()
      ->insert('simpletest')
470
471
472
473
474
475
476
477
478
      ->fields($assertion)
      ->execute();
  }

  /**
   * Delete an assertion record by message ID.
   *
   * @param $message_id
   *   Message ID of the assertion to delete.
479
   *
480
481
482
   * @return
   *   TRUE if the assertion was deleted, FALSE otherwise.
   *
483
   * @see \Drupal\simpletest\TestBase::insertAssert()
484
485
   */
  public static function deleteAssert($message_id) {
486
    // We can't use storeAssertion() because this method is static.
487
488
    return (bool) self::getDatabaseConnection()
      ->delete('simpletest')
489
490
491
492
      ->condition('message_id', $message_id)
      ->execute();
  }

493
494
495
  /**
   * Returns the database connection to the site running Simpletest.
   *
496
   * @return \Drupal\Core\Database\Connection
497
498
499
   *   The database connection to use for inserting assertions.
   */
  public static function getDatabaseConnection() {
500
501
502
    // Check whether there is a test runner connection.
    // @see run-tests.sh
    // @todo Convert Simpletest UI runner to create + use this connection, too.
503
    try {
504
      $connection = Database::getConnection('default', 'test-runner');
505
506
    }
    catch (ConnectionNotDefinedException $e) {
507
508
509
510
511
512
513
514
515
516
517
      // Check whether there is a backup of the original default connection.
      // @see TestBase::prepareEnvironment()
      try {
        $connection = Database::getConnection('default', 'simpletest_original_default');
      }
      catch (ConnectionNotDefinedException $e) {
        // If TestBase::prepareEnvironment() or TestBase::restoreEnvironment()
        // failed, the test-specific database connection does not exist
        // yet/anymore, so fall back to the default of the (UI) test runner.
        $connection = Database::getConnection('default', 'default');
      }
518
519
520
521
    }
    return $connection;
  }

522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
  /**
   * Cycles through backtrace until the first non-assertion method is found.
   *
   * @return
   *   Array representing the true caller.
   */
  protected function getAssertionCall() {
    $backtrace = debug_backtrace();

    // The first element is the call. The second element is the caller.
    // We skip calls that occurred in one of the methods of our base classes
    // or in an assertion function.
   while (($caller = $backtrace[1]) &&
         ((isset($caller['class']) && isset($this->skipClasses[$caller['class']])) ||
           substr($caller['function'], 0, 6) == 'assert')) {
      // We remove that call.
      array_shift($backtrace);
    }

541
    return Error::getLastCaller($backtrace);
542
543
544
  }

  /**
545
546
547
   * Check to see if a value is not false.
   *
   * False values are: empty string, 0, NULL, and FALSE.
548
549
550
551
   *
   * @param $value
   *   The value on which the assertion is to be done.
   * @param $message
552
   *   (optional) A message to display with the assertion. Do not translate
553
554
555
   *   messages: use \Drupal\Component\Utility\String::format() to embed
   *   variables in the message text, not t(). If left blank, a default message
   *   will be displayed.
556
   * @param $group
557
558
559
560
   *   (optional) The group this message is in, which is displayed in a column
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
   *   translate this string. Defaults to 'Other'; most tests do not override
   *   this default.
561
   *
562
563
564
565
   * @return
   *   TRUE if the assertion succeeded, FALSE otherwise.
   */
  protected function assertTrue($value, $message = '', $group = 'Other') {
566
    return $this->assert((bool) $value, $message ? $message : String::format('Value @value is TRUE.', array('@value' => var_export($value, TRUE))), $group);
567
568
569
  }

  /**
570
571
572
   * Check to see if a value is false.
   *
   * False values are: empty string, 0, NULL, and FALSE.
573
574
575
576
   *
   * @param $value
   *   The value on which the assertion is to be done.
   * @param $message
577
   *   (optional) A message to display with the assertion. Do not translate
578
579
580
   *   messages: use \Drupal\Component\Utility\String::format() to embed
   *   variables in the message text, not t(). If left blank, a default message
   *   will be displayed.
581
   * @param $group
582
583
584
585
   *   (optional) The group this message is in, which is displayed in a column
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
   *   translate this string. Defaults to 'Other'; most tests do not override
   *   this default.
586
   *
587
588
589
590
   * @return
   *   TRUE if the assertion succeeded, FALSE otherwise.
   */
  protected function assertFalse($value, $message = '', $group = 'Other') {
591
    return $this->assert(!$value, $message ? $message : String::format('Value @value is FALSE.', array('@value' => var_export($value, TRUE))), $group);
592
593
594
595
596
597
598
599
  }

  /**
   * Check to see if a value is NULL.
   *
   * @param $value
   *   The value on which the assertion is to be done.
   * @param $message
600
   *   (optional) A message to display with the assertion. Do not translate
601
602
603
   *   messages: use \Drupal\Component\Utility\String::format() to embed
   *   variables in the message text, not t(). If left blank, a default message
   *   will be displayed.
604
   * @param $group
605
606
607
608
   *   (optional) The group this message is in, which is displayed in a column
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
   *   translate this string. Defaults to 'Other'; most tests do not override
   *   this default.
609
   *
610
611
612
613
   * @return
   *   TRUE if the assertion succeeded, FALSE otherwise.
   */
  protected function assertNull($value, $message = '', $group = 'Other') {
614
    return $this->assert(!isset($value), $message ? $message : String::format('Value @value is NULL.', array('@value' => var_export($value, TRUE))), $group);
615
616
617
618
619
620
621
622
  }

  /**
   * Check to see if a value is not NULL.
   *
   * @param $value
   *   The value on which the assertion is to be done.
   * @param $message
623
   *   (optional) A message to display with the assertion. Do not translate
624
625
626
   *   messages: use \Drupal\Component\Utility\String::format() to embed
   *   variables in the message text, not t(). If left blank, a default message
   *   will be displayed.
627
   * @param $group
628
629
630
631
   *   (optional) The group this message is in, which is displayed in a column
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
   *   translate this string. Defaults to 'Other'; most tests do not override
   *   this default.
632
   *
633
634
635
636
   * @return
   *   TRUE if the assertion succeeded, FALSE otherwise.
   */
  protected function assertNotNull($value, $message = '', $group = 'Other') {
637
    return $this->assert(isset($value), $message ? $message : String::format('Value @value is not NULL.', array('@value' => var_export($value, TRUE))), $group);
638
639
640
641
642
643
644
645
646
647
  }

  /**
   * Check to see if two values are equal.
   *
   * @param $first
   *   The first value to check.
   * @param $second
   *   The second value to check.
   * @param $message
648
   *   (optional) A message to display with the assertion. Do not translate
649
650
651
   *   messages: use \Drupal\Component\Utility\String::format() to embed
   *   variables in the message text, not t(). If left blank, a default message
   *   will be displayed.
652
   * @param $group
653
654
655
656
   *   (optional) The group this message is in, which is displayed in a column
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
   *   translate this string. Defaults to 'Other'; most tests do not override
   *   this default.
657
   *
658
659
660
661
   * @return
   *   TRUE if the assertion succeeded, FALSE otherwise.
   */
  protected function assertEqual($first, $second, $message = '', $group = 'Other') {
662
    return $this->assert($first == $second, $message ? $message : String::format('Value @first is equal to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
663
664
665
666
667
668
669
670
671
672
  }

  /**
   * Check to see if two values are not equal.
   *
   * @param $first
   *   The first value to check.
   * @param $second
   *   The second value to check.
   * @param $message
673
   *   (optional) A message to display with the assertion. Do not translate
674
675
676
   *   messages: use \Drupal\Component\Utility\String::format() to embed
   *   variables in the message text, not t(). If left blank, a default message
   *   will be displayed.
677
   * @param $group
678
679
680
681
   *   (optional) The group this message is in, which is displayed in a column
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
   *   translate this string. Defaults to 'Other'; most tests do not override
   *   this default.
682
   *
683
684
685
686
   * @return
   *   TRUE if the assertion succeeded, FALSE otherwise.
   */
  protected function assertNotEqual($first, $second, $message = '', $group = 'Other') {
687
    return $this->assert($first != $second, $message ? $message : String::format('Value @first is not equal to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
688
689
690
691
692
693
694
695
696
697
  }

  /**
   * Check to see if two values are identical.
   *
   * @param $first
   *   The first value to check.
   * @param $second
   *   The second value to check.
   * @param $message
698
   *   (optional) A message to display with the assertion. Do not translate
699
700
701
   *   messages: use \Drupal\Component\Utility\String::format() to embed
   *   variables in the message text, not t(). If left blank, a default message
   *   will be displayed.
702
   * @param $group
703
704
705
706
   *   (optional) The group this message is in, which is displayed in a column
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
   *   translate this string. Defaults to 'Other'; most tests do not override
   *   this default.
707
   *
708
709
710
711
   * @return
   *   TRUE if the assertion succeeded, FALSE otherwise.
   */
  protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
712
    return $this->assert($first === $second, $message ? $message : String::format('Value @first is identical to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
713
714
715
716
717
718
719
720
721
722
  }

  /**
   * Check to see if two values are not identical.
   *
   * @param $first
   *   The first value to check.
   * @param $second
   *   The second value to check.
   * @param $message
723
   *   (optional) A message to display with the assertion. Do not translate
724
725
726
   *   messages: use \Drupal\Component\Utility\String::format() to embed
   *   variables in the message text, not t(). If left blank, a default message
   *   will be displayed.
727
   * @param $group
728
729
730
731
   *   (optional) The group this message is in, which is displayed in a column
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
   *   translate this string. Defaults to 'Other'; most tests do not override
   *   this default.
732
   *
733
734
735
736
   * @return
   *   TRUE if the assertion succeeded, FALSE otherwise.
   */
  protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') {
737
    return $this->assert($first !== $second, $message ? $message : String::format('Value @first is not identical to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
738
739
  }

740
741
742
743
744
745
746
747
  /**
   * Checks to see if two objects are identical.
   *
   * @param object $object1
   *   The first object to check.
   * @param object $object2
   *   The second object to check.
   * @param $message
748
   *   (optional) A message to display with the assertion. Do not translate
749
750
751
   *   messages: use \Drupal\Component\Utility\String::format() to embed
   *   variables in the message text, not t(). If left blank, a default message
   *   will be displayed.
752
   * @param $group
753
754
755
756
   *   (optional) The group this message is in, which is displayed in a column
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
   *   translate this string. Defaults to 'Other'; most tests do not override
   *   this default.
757
758
759
760
   *
   * @return
   *   TRUE if the assertion succeeded, FALSE otherwise.
   */
761
  protected function assertIdenticalObject($object1, $object2, $message = '', $group = 'Other') {
762
    $message = $message ?: String::format('!object1 is identical to !object2', array(
763
764
765
766
767
768
769
      '!object1' => var_export($object1, TRUE),
      '!object2' => var_export($object2, TRUE),
    ));
    $identical = TRUE;
    foreach ($object1 as $key => $value) {
      $identical = $identical && isset($object2->$key) && $object2->$key === $value;
    }
770
    return $this->assertTrue($identical, $message, $group);
771
772
  }

773
774
775
776
777
778
779
  /**
   * Asserts that no errors have been logged to the PHP error.log thus far.
   *
   * @return bool
   *   TRUE if the assertion succeeded, FALSE otherwise.
   *
   * @see TestBase::prepareEnvironment()
780
   * @see \Drupal\Core\DrupalKernel::bootConfiguration()
781
782
783
784
785
786
   */
  protected function assertNoErrorsLogged() {
    // Since PHP only creates the error.log file when an actual error is
    // triggered, it is sufficient to check whether the file exists.
    return $this->assertFalse(file_exists(DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log'), 'PHP error.log is empty.');
  }
787

788
789
790
791
  /**
   * Fire an assertion that is always positive.
   *
   * @param $message
792
   *   (optional) A message to display with the assertion. Do not translate
793
794
795
   *   messages: use \Drupal\Component\Utility\String::format() to embed
   *   variables in the message text, not t(). If left blank, a default message
   *   will be displayed.
796
   * @param $group
797
798
799
800
   *   (optional) The group this message is in, which is displayed in a column
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
   *   translate this string. Defaults to 'Other'; most tests do not override
   *   this default.
801
   *
802
803
804
805
806
807
808
809
810
811
812
   * @return
   *   TRUE.
   */
  protected function pass($message = NULL, $group = 'Other') {
    return $this->assert(TRUE, $message, $group);
  }

  /**
   * Fire an assertion that is always negative.
   *
   * @param $message
813
   *   (optional) A message to display with the assertion. Do not translate
814
815
816
   *   messages: use \Drupal\Component\Utility\String::format() to embed
   *   variables in the message text, not t(). If left blank, a default message
   *   will be displayed.
817
   * @param $group
818
819
820
821
   *   (optional) The group this message is in, which is displayed in a column
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
   *   translate this string. Defaults to 'Other'; most tests do not override
   *   this default.
822
   *
823
824
825
826
827
828
829
830
831
832
833
   * @return
   *   FALSE.
   */
  protected function fail($message = NULL, $group = 'Other') {
    return $this->assert(FALSE, $message, $group);
  }

  /**
   * Fire an error assertion.
   *
   * @param $message
834
   *   (optional) A message to display with the assertion. Do not translate
835
836
837
   *   messages: use \Drupal\Component\Utility\String::format() to embed
   *   variables in the message text, not t(). If left blank, a default message
   *   will be displayed.
838
   * @param $group
839
840
841
842
   *   (optional) The group this message is in, which is displayed in a column
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
   *   translate this string. Defaults to 'Other'; most tests do not override
   *   this default.
843
844
   * @param $caller
   *   The caller of the error.
845
   *
846
847
848
849
850
851
852
853
854
855
856
857
858
859
   * @return
   *   FALSE.
   */
  protected function error($message = '', $group = 'Other', array $caller = NULL) {
    if ($group == 'User notice') {
      // Since 'User notice' is set by trigger_error() which is used for debug
      // set the message to a status of 'debug'.
      return $this->assert('debug', $message, 'Debug', $caller);
    }

    return $this->assert('exception', $message, $group, $caller);
  }

  /**
860
   * Logs a verbose message in a text file.
861
   *
862
863
   * The link to the verbose message will be placed in the test results as a
   * passing assertion with the text '[verbose message]'.
864
865
866
867
868
869
870
   *
   * @param $message
   *   The verbose message to be stored.
   *
   * @see simpletest_verbose()
   */
  protected function verbose($message) {
871
872
873
874
875
    // Do nothing if verbose debugging is disabled.
    if (!$this->verbose) {
      return;
    }

876
877
878
879
    $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;
    $verbose_filename =  $this->verboseClassName . '-' . $this->verboseId . '-' . $this->testId . '.html';
    if (file_put_contents($this->verboseDirectory . '/' . $verbose_filename, $message)) {
      $url = $this->verboseDirectoryUrl . '/' . $verbose_filename;
880
      // Not using _l() to avoid invoking the theme system, so that unit tests
881
      // can use verbose() as well.
882
      $url = '<a href="' . $url . '" target="_blank">Verbose message</a>';
883
      $this->error($url, 'User notice');
884
    }
885
    $this->verboseId++;
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
  }

  /**
   * Run all tests in this class.
   *
   * Regardless of whether $methods are passed or not, only method names
   * starting with "test" are executed.
   *
   * @param $methods
   *   (optional) A list of method names in the test case class to run; e.g.,
   *   array('testFoo', 'testBar'). By default, all methods of the class are
   *   taken into account, but it can be useful to only run a few selected test
   *   methods during debugging.
   */
  public function run(array $methods = array()) {
901
902
903
904
905
906
907
908
909
910
911
912
913
    $class = get_class($this);

    if ($missing_requirements = $this->checkRequirements()) {
      $object_info = new \ReflectionObject($this);
      $caller = array(
        'file' => $object_info->getFileName(),
      );
      foreach ($missing_requirements as $missing_requirement) {
        TestBase::insertAssert($this->testId, $class, FALSE, $missing_requirement, 'Requirements check', $caller);
      }
      return;
    }

914
    TestServiceProvider::$currentTest = $this;
915
    $simpletest_config = $this->config('simpletest.settings');
916

917
918
919
920
    // Unless preset from run-tests.sh, retrieve the current verbose setting.
    if (!isset($this->verbose)) {
      $this->verbose = $simpletest_config->get('verbose');
    }
921

922
    if ($this->verbose) {
923
924
      // Initialize verbose debugging.
      $this->verbose = TRUE;
925
      $this->verboseDirectory = PublicStream::basePath() . '/simpletest/verbose';
926
      $this->verboseDirectoryUrl = file_create_url($this->verboseDirectory);
927
928
929
930
931
      if (file_prepare_directory($this->verboseDirectory, FILE_CREATE_DIRECTORY) && !file_exists($this->verboseDirectory . '/.htaccess')) {
        file_put_contents($this->verboseDirectory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
      }
      $this->verboseClassName = str_replace("\\", "_", $class);
    }
932
933
    // HTTP auth settings (<username>:<password>) for the simpletest browser
    // when sending requests to the test site.
934
    $this->httpAuthMethod = (int) $simpletest_config->get('httpauth.method');
935
936
937
    $username = $simpletest_config->get('httpauth.username');
    $password = $simpletest_config->get('httpauth.password');
    if (!empty($username) && !empty($password)) {
938
      $this->httpAuthCredentials = $username . ':' . $password;
939
940
941
942
943
    }

    set_error_handler(array($this, 'errorHandler'));
    // Iterate through all the methods in this class, unless a specific list of
    // methods to run was passed.
944
945
946
    $test_methods = array_filter(get_class_methods($class), function ($method) {
      return strpos($method, 'test') === 0;
    });
947
948
949
950
951
    if (empty($test_methods)) {
      // Call $this->assert() here because we need to pass along custom caller
      // information, lest the wrong originating code file/line be identified.
      $this->assert(FALSE, 'No test methods found.', 'Requirements', array('function' => __METHOD__ . '()', 'file' => __FILE__, 'line' => __LINE__));
    }
952
    if ($methods) {
953
954
955
956
957
958
      $test_methods = array_intersect($test_methods, $methods);
    }
    foreach ($test_methods as $method) {
      // Insert a fail record. This will be deleted on completion to ensure
      // that testing completed.
      $method_info = new \ReflectionMethod($class, $method);
959
      $caller = array(
960
961
962
        'file' => $method_info->getFileName(),
        'line' => $method_info->getStartLine(),
        'function' => $class . '->' . $method . '()',
963
      );
964
965
966
967
      $test_completion_check_id = TestBase::insertAssert($this->testId, $class, FALSE, 'The test did not complete due to a fatal error.', 'Completion check', $caller);

      try {
        $this->prepareEnvironment();
968
      }
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
      catch (\Exception $e) {
        $this->exceptionHandler($e);
        // The prepareEnvironment() method isolates the test from the parent
        // Drupal site by creating a random database prefix and test site
        // directory. If this fails, a test would possibly operate in the
        // parent site. Therefore, the entire test run for this test class
        // has to be aborted.
        // restoreEnvironment() cannot be called, because we do not know
        // where exactly the environment setup failed.
        break;
      }

      try {
        $this->setUp();
      }
      catch (\Exception $e) {
        $this->exceptionHandler($e);
        // Abort if setUp() fails, since all test methods will fail.
        // But ensure to clean up and restore the environment, since
        // prepareEnvironment() succeeded.
        $this->restoreEnvironment();
        break;
991
      }
992
993
      try {
        $this->$method();
994
      }
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
      catch (\Exception $e) {
        $this->exceptionHandler($e);
      }
      try {
        $this->tearDown();
      }
      catch (\Exception $e) {
        $this->exceptionHandler($e);
        // If a test fails to tear down, abort the entire test class, since
        // it is likely that all tests will fail in the same way and a
        // failure here only results in additional test artifacts that have
        // to be manually deleted.
        $this->restoreEnvironment();
        break;
      }

      $this->restoreEnvironment();
      // Remove the test method completion check record.
      TestBase::deleteAssert($test_completion_check_id);
1014
    }
1015

1016
    TestServiceProvider::$currentTest = NULL;
1017
1018
1019
1020
1021
    // Clear out the error messages and restore error handler.
    drupal_get_messages();
    restore_error_handler();
  }

1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
  /**
   * Generates a database prefix for running tests.
   *
   * The database prefix is used by prepareEnvironment() to setup a public files
   * directory for the test to be run, which also contains the PHP error log,
   * which is written to in case of a fatal error. Since that directory is based
   * on the database prefix, all tests (even unit tests) need to have one, in
   * order to access and read the error log.
   *
   * @see TestBase::prepareEnvironment()
   *
   * The generated database table prefix is used for the Drupal installation
   * being performed for the test. It is also used as user agent HTTP header
1035
1036
1037
1038
   * value by the cURL-based browser of WebTestBase, which is sent to the Drupal
   * installation of the test. During early Drupal bootstrap, the user agent
   * HTTP header is parsed, and if it matches, all database queries use the
   * database table prefix that has been generated here.
1039
1040
1041
1042
   *
   * @see WebTestBase::curlInitialize()
   * @see drupal_valid_test_ua()
   */
1043
  private function prepareDatabasePrefix() {
1044
1045
1046
1047
1048
1049
1050
1051
    // Ensure that the generated test site directory does not exist already,
    // which may happen with a large amount of concurrent threads and
    // long-running tests.
    do {
      $suffix = mt_rand(100000, 999999);
      $this->siteDirectory = 'sites/simpletest/' . $suffix;
      $this->databasePrefix = 'simpletest' . $suffix;
    } while (is_dir(DRUPAL_ROOT . '/' . $this->siteDirectory));
1052
1053
1054
1055

    // As soon as the database prefix is set, the test might start to execute.
    // All assertions as well as the SimpleTest batch operations are associated
    // with the testId, so the database prefix has to be associated with it.
1056
    $affected_rows = self::getDatabaseConnection()->update('simpletest_test_id')
1057
1058
1059
      ->fields(array('last_prefix' => $this->databasePrefix))
      ->condition('test_id', $this->testId)
      ->execute();
1060
1061
1062
    if (!$affected_rows) {
      throw new \RuntimeException('Failed to set up database prefix.');
    }
1063
1064
1065
1066
1067
  }

  /**
   * Changes the database connection to the prefixed one.
   *
1068
   * @see TestBase::prepareEnvironment()
1069
   */
1070
  private function changeDatabasePrefix() {
1071
1072
1073
    if (empty($this->databasePrefix)) {
      $this->prepareDatabasePrefix();
    }
1074
1075
1076
1077
1078
1079
1080
    // If the backup already exists, something went terribly wrong.
    // This case is possible, because database connection info is a static
    // global state construct on the Database class, which at least persists
    // for all test methods executed in one PHP process.
    if (Database::getConnectionInfo('simpletest_original_default')) {
      throw new \RuntimeException("Bad Database connection state: 'simpletest_original_default' connection key already exists. Broken test?");
    }
1081
1082
1083
1084
1085

    // Clone the current connection and replace the current prefix.
    $connection_info = Database::getConnectionInfo('default');
    Database::renameConnection('default', 'simpletest_original_default');
    foreach ($connection_info as $target => $value) {
1086
1087
1088
1089
1090
      // Replace the full table prefix definition to ensure that no table
      // prefixes of the test runner leak into the test.
      $connection_info[$target]['prefix'] = array(
        'default' => $value['prefix']['default'] . $this->databasePrefix,
      );
1091
1092
    }
    Database::addConnectionInfo('default', 'default', $connection_info['default']);
1093
  }
1094

1095
1096
1097
  /**
   * Act on global state information before the environment is altered for a test.
   *
1098
   * Allows e.g. KernelTestBase to prime system/extension info from the
1099
1100
1101
1102
   * parent site (and inject it into the test environment so as to improve
   * performance).
   */
  protected function beforePrepareEnvironment() {
1103
1104
1105
1106
1107
1108
1109
  }

  /**
   * Prepares the current environment for running the test.
   *
   * Backups various current environment variables and resets them, so they do
   * not interfere with the Drupal site installation in which tests are executed
1110
   * and can be restored in TestBase::restoreEnvironment().
1111
1112
1113
1114
   *
   * Also sets up new resources for the testing environment, such as the public
   * filesystem and configuration directories.
   *
1115
1116
1117
1118
1119
   * This method is private as it must only be called once by TestBase::run()
   * (multiple invocations for the same test would have unpredictable
   * consequences) and it must not be callable or overridable by test classes.
   *
   * @see TestBase::beforePrepareEnvironment()
1120
   */
1121
  private function prepareEnvironment() {
1122
    $user = \Drupal::currentUser();
1123
1124
1125
1126
1127
1128
    // Allow (base) test classes to backup global state information.
    $this->beforePrepareEnvironment();

    // Create the database prefix for this test.
    $this->prepareDatabasePrefix();

1129
    $language_interface = \Drupal::languageManager()->getCurrentLanguage();
1130

1131
    // When running the test runner within a test, back up the original database
1132
1133
    // prefix.
    if (DRUPAL_TEST_IN_CHILD_SITE) {
1134
1135
1136
      $this->originalPrefix = drupal_valid_test_ua();
    }

1137
    // Backup current in-memory configuration.
1138
    $this->originalSite = conf_path();
1139
    $this->originalSettings = Settings::getAll();
1140
    $this->originalConfig = $GLOBALS['config'];
1141
1142
1143
    // @todo Remove all remnants of $GLOBALS['conf'].
    // @see https://drupal.org/node/2183323
    $this->originalConf = isset($GLOBALS['conf']) ? $GLOBALS['conf'] : NULL;
1144
1145

    // Backup statics and globals.
1146
    $this->originalContainer = clone \Drupal::getContainer();
1147
    $this->originalLanguage = $language_interface;
1148
    $this->originalConfigDirectories = $GLOBALS['config_directories'];
1149
1150

    // Save further contextual information.
1151
1152
    // Use the original files directory to avoid nesting it within an existing
    // simpletest directory if a test is executed within a test.
1153
    $this->originalFileDirectory = Settings::get('file_public_path', conf_path() . '/files');
1154
    $this->originalProfile = drupal_get_profile();
1155
    $this->originalUser = isset($user) ? clone $user : NULL;
1156

1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
    // Prevent that session data is leaked into the UI test runner by closing
    // the session and then setting the session-name (i.e. the name of the
    // session cookie) to a random value. If a test starts a new session, then
    // it will be associated with a different session-name. After the test-run
    // it can be safely destroyed.
    // @see TestBase::restoreEnvironment()
    if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) {
      session_write_close();
    }
    $this->originalSessionName = session_name();
    session_name('SIMPLETEST' . Crypt::randomBytesBase64());
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178

    // Save and clean the shutdown callbacks array because it is static cached
    // and will be changed by the test run. Otherwise it will contain callbacks
    // from both environments and the testing environment will try to call the
    // handlers defined by the original one.
    $callbacks = &drupal_register_shutdown_function();
    $this->originalShutdownCallbacks = $callbacks;
    $callbacks = array();

    // Create test directory ahead of installation so fatal errors and debug
    // information can be logged during installation process.
1179
1180
1181
    file_prepare_directory($this->siteDirectory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);

    // Prepare filesystem directory paths.
1182
1183
1184
1185
    $this->publicFilesDirectory = $this->siteDirectory . '/files';
    $this->privateFilesDirectory = $this->siteDirectory . '/private';
    $this->tempFilesDirectory = $this->siteDirectory . '/temp';
    $this->translationFilesDirectory = $this->siteDirectory . '/translations';
1186

1187
    $this->generatedTestFiles = FALSE;
1188

1189
1190
1191
    // Ensure the configImporter is refreshed for each test.
    $this->configImporter = NULL;

1192
1193
    // Unregister all custom stream wrappers of the parent site.
    // Availability of Drupal stream wrappers varies by test base class:
1194
    // - KernelTestBase supports and maintains stream wrappers in a custom
1195
1196
1197
    //   way.
    // - WebTestBase re-initializes Drupal stream wrappers after installation.
    // The original stream wrappers are restored after the test run.
1198
    // @see TestBase::restoreEnvironment()
1199
    $this->originalContainer->get('stream_wrapper_manager')->unregister();
1200

1201
    // Reset statics.
1202
1203
    drupal_static_reset();

1204
1205
    // Ensure there is no service container.
    $this->container = NULL;
1206
    \Drupal::unsetContainer();
1207

1208
    // Unset globals.
1209
    unset($GLOBALS['config_directories']);
1210
1211
    unset($GLOBALS['config']);
    unset($GLOBALS['conf']);
1212

1213
1214
    // Log fatal errors.
    ini_set('log_errors', 1);
1215
    ini_set('error_log', DRUPAL_ROOT . '/' . $this->siteDirectory . '/error.log');
1216

1217
1218
1219
    // Change the database prefix.
    $this->changeDatabasePrefix();

1220
1221
1222
1223
    // After preparing the environment and changing the database prefix, we are
    // in a valid test environment.
    drupal_valid_test_ua($this->databasePrefix);
    conf_path(FALSE, TRUE);
1224

1225
1226
1227
1228
    // Reset settings.
    new Settings(array(
      // For performance, simply use the database prefix as hash salt.
      'hash_salt' => $this->databasePrefix,
1229
      'container_yamls' => [],
1230
1231
    ));

1232
    drupal_set_time_limit($this->timeLimit);
1233
1234
  }

1235
  /**
1236
   * Performs cleanup tasks after each individual test method has been run.
1237
1238
1239
1240
1241
1242
   */
  protected function tearDown() {
  }

  /**
   * Cleans up the test environment and restores the original environment.
1243
   *
1244
   * Deletes created files, database tables, and reverts environment changes.
1245
1246
1247
1248
1249
1250
1251
   *
   * This method needs to be invoked for both unit and integration tests.
   *
   * @see TestBase::prepareDatabasePrefix()
   * @see TestBase::changeDatabasePrefix()
   * @see TestBase::prepareEnvironment()
   */
1252
  private function restoreEnvironment() {
1253
1254
1255
1256
1257
1258
1259
1260
1261
    // Destroy the session if one was started during the test-run.
    $_SESSION = array();
    if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) {
      session_destroy();
      $params = session_get_cookie_params();
      setcookie(session_name(), '', REQUEST_TIME - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
    }
    session_name($this->originalSessionName);

1262
1263
1264
1265
1266
1267
1268
    // Reset all static variables.
    // Unsetting static variables will potentially invoke destruct methods,
    // which might call into functions that prime statics and caches again.
    // In that case, all functions are still operating on the test environment,
    // which means they may need to access its filesystem and database.
    drupal_static_reset();

1269
    if ($this->container && $this->container->has('state') && $state = $this->container->get('state')) {
1270
      $captured_emails = $state->get('system.test_mail_collector') ?: array();
1271
1272
      $emailCount = count($captured_emails);
      if ($emailCount) {
1273
1274
        $message = $emailCount == 1 ? '1 email was sent during this test.' : $emailCount . ' emails were sent during this test.';
        $this->pass($message, 'Email');
1275
1276
1277
      }
    }

1278
1279
1280
1281
    // Sleep for 50ms to allow shutdown functions and terminate events to
    // complete. Further information: https://drupal.org/node/2194357.
    usleep(50000);

1282
1283
    // Remove all prefixed tables.
    $original_connection_info = Database::getConnectionInfo('simpletest_original_default');
1284
    $original_prefix = $original_connection_info['default']['prefix']['default'];
1285
    $test_connection_info = Database::getConnectionInfo('default');
1286
    $test_prefix = $test_connection_info['default']['prefix']['default'];
1287
1288
1289
    if ($original_prefix != $test_prefix) {
      $tables = Database::getConnection()->schema()->findTables($test_prefix . '%');
      $prefix_length = strlen($test_prefix);
1290
      foreach ($tables as $table) {
1291
        if (Database::getConnection()->schema()->dropTable(substr($table, $prefix_length))) {
1292
1293
1294
1295
          unset($tables[$table]);
        }
      }
    }
1296

1297
1298
1299
1300
    // In case a fatal error occurred that was not in the test process read the
    // log to pick up any fatal errors.
    simpletest_log_read($this->testId, $this->databasePrefix, get_class($this));

1301
1302
1303
1304
    // Restore original dependency injection container.
    $this->container = $this->originalContainer;
    \Drupal::setContainer($this->originalContainer);

1305
1306
    // Delete test site directory.
    file_unmanaged_delete_recursive($this->siteDirectory, array($this, 'filePreDeleteCallback'));
1307
1308
1309
1310
1311
1312

    // Restore original database connection.
    Database::removeConnection('default');
    Database::renameConnection('simpletest_original_default', 'default');

    // Reset all static variables.
1313
    // All destructors of statically cached objects have been invoked above;
1314
    // this second reset is guaranteed to reset everything to nothing.
1315
1316
1317
    drupal_static_reset();

    // Restore original in-memory configuration.
1318
    $GLOBALS['config'] = $this->originalConfig;
1319
    $GLOBALS['conf'] = $this->originalConf;
1320
    new Settings($this->originalSettings);
1321
1322

    // Restore original statics and globals.
1323
    $GLOBALS['config_directories'] = $this->originalConfigDirectories;
alexpott's avatar