KernelTestBase.php 39 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\KernelTests;

5 6 7
use Drupal\Component\FileCache\ApcuFileCacheBackend;
use Drupal\Component\FileCache\FileCache;
use Drupal\Component\FileCache\FileCacheFactory;
8
use Drupal\Component\Utility\Html;
9
use Drupal\Component\Render\FormattableMarkup;
10
use Drupal\Core\Config\Development\ConfigSchemaChecker;
11 12 13 14 15 16
use Drupal\Core\Database\Database;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
use Drupal\Core\DrupalKernel;
use Drupal\Core\Entity\Sql\SqlEntityStorageInterface;
use Drupal\Core\Extension\ExtensionDiscovery;
17
use Drupal\Core\Language\Language;
18
use Drupal\Core\Site\Settings;
19
use Drupal\Core\Test\TestDatabase;
20
use Drupal\Tests\AssertHelperTrait;
21
use Drupal\Tests\ConfigTestTrait;
22
use Drupal\Tests\PhpunitCompatibilityTrait;
23
use Drupal\Tests\RandomGeneratorTrait;
24
use Drupal\Tests\TestRequirementsTrait;
25
use PHPUnit\Framework\Exception;
26
use PHPUnit\Framework\TestCase;
27 28 29 30
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpFoundation\Request;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\visitor\vfsStreamPrintVisitor;
31 32
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\Routing\Route;
33 34 35 36

/**
 * Base class for functional integration tests.
 *
37 38 39
 * This base class should be useful for testing some types of integrations which
 * don't require the overhead of a fully-installed Drupal instance, but which
 * have many dependencies on parts of Drupal which can't or shouldn't be mocked.
40
 *
41 42 43
 * This base class partially boots a fixture Drupal. The state of the fixture
 * Drupal is comparable to the state of a system during the early part of the
 * installation process.
44
 *
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
 * Tests extending this base class can access services and the database, but the
 * system is initially empty. This Drupal runs in a minimal mocked filesystem
 * which operates within vfsStream.
 *
 * Modules specified in the $modules property are added to the service container
 * for each test. The module/hook system is functional. Additional modules
 * needed in a test should override $modules. Modules specified in this way will
 * be added to those specified in superclasses.
 *
 * Unlike \Drupal\Tests\BrowserTestBase, the modules are not installed. They are
 * loaded such that their services and hooks are available, but the install
 * process has not been performed.
 *
 * Other modules can be made available in this way using
 * KernelTestBase::enableModules().
 *
 * Some modules can be brought into a fully-installed state using
 * KernelTestBase::installConfig(), KernelTestBase::installSchema(), and
 * KernelTestBase::installEntitySchema(). Alternately, tests which need modules
 * to be fully installed could inherit from \Drupal\Tests\BrowserTestBase.
65 66 67
 *
 * @see \Drupal\Tests\KernelTestBase::$modules
 * @see \Drupal\Tests\KernelTestBase::enableModules()
68 69 70 71
 * @see \Drupal\Tests\KernelTestBase::installConfig()
 * @see \Drupal\Tests\KernelTestBase::installEntitySchema()
 * @see \Drupal\Tests\KernelTestBase::installSchema()
 * @see \Drupal\Tests\BrowserTestBase
72 73
 *
 * @ingroup testing
74
 */
75
abstract class KernelTestBase extends TestCase implements ServiceProviderInterface {
76 77 78

  use AssertLegacyTrait;
  use AssertContentTrait;
79
  use AssertHelperTrait;
80
  use RandomGeneratorTrait;
81
  use ConfigTestTrait;
82
  use TestRequirementsTrait;
83
  use PhpunitCompatibilityTrait;
84 85 86 87 88 89 90 91 92 93 94 95 96

  /**
   * {@inheritdoc}
   *
   * Back up and restore any global variables that may be changed by tests.
   *
   * @see self::runTestInSeparateProcess
   */
  protected $backupGlobals = TRUE;

  /**
   * {@inheritdoc}
   *
97 98 99 100
   * Kernel tests are run in separate processes because they allow autoloading
   * of code from extensions. Running the test in a separate process isolates
   * this behavior from other tests. Subclasses should not override this
   * property.
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 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
   */
  protected $runTestInSeparateProcess = TRUE;

  /**
   * {@inheritdoc}
   *
   * Back up and restore static class properties that may be changed by tests.
   *
   * @see self::runTestInSeparateProcess
   */
  protected $backupStaticAttributes = TRUE;

  /**
   * {@inheritdoc}
   *
   * Contains a few static class properties for performance.
   */
  protected $backupStaticAttributesBlacklist = [
    // Ignore static discovery/parser caches to speed up tests.
    'Drupal\Component\Discovery\YamlDiscovery' => ['parsedFiles'],
    'Drupal\Core\DependencyInjection\YamlFileLoader' => ['yaml'],
    'Drupal\Core\Extension\ExtensionDiscovery' => ['files'],
    'Drupal\Core\Extension\InfoParser' => ['parsedInfos'],
    // Drupal::$container cannot be serialized.
    'Drupal' => ['container'],
    // Settings cannot be serialized.
    'Drupal\Core\Site\Settings' => ['instance'],
  ];

  /**
   * {@inheritdoc}
   *
   * Do not forward any global state from the parent process to the processes
   * that run the actual tests.
   *
   * @see self::runTestInSeparateProcess
   */
  protected $preserveGlobalState = FALSE;

  /**
   * @var \Composer\Autoload\Classloader
   */
  protected $classLoader;

  /**
   * @var string
   */
  protected $siteDirectory;

  /**
   * @var string
   */
  protected $databasePrefix;

  /**
   * @var \Drupal\Core\DependencyInjection\ContainerBuilder
   */
  protected $container;

  /**
   * Modules to enable.
   *
163 164 165
   * The test runner will merge the $modules lists from this class, the class
   * it extends, and so on up the class hierarchy. It is not necessary to
   * include modules in your list that a parent class has already declared.
166
   *
167 168 169 170 171
   * The Path Alias module is always installed because the functionality has
   * moved from core to a required module in Drupal 8.8.0. If a kernel test
   * requires path alias functionality it is recommended to add the module to
   * the test's own $modules property for Drupal 9 compatibility.
   *
172 173 174 175 176
   * @see \Drupal\Tests\KernelTestBase::enableModules()
   * @see \Drupal\Tests\KernelTestBase::bootKernel()
   *
   * @var array
   */
177
  protected static $modules = ['path_alias'];
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

  /**
   * The virtual filesystem root directory.
   *
   * @var \org\bovigo\vfs\vfsStreamDirectory
   */
  protected $vfsRoot;

  /**
   * @todo Move into Config test base class.
   * @var \Drupal\Core\Config\ConfigImporter
   */
  protected $configImporter;

  /**
   * The app root.
   *
   * @var string
   */
  protected $root;

  /**
   * Set to TRUE to strict check all configuration saved.
   *
202
   * @see \Drupal\Core\Config\Development\ConfigSchemaChecker
203 204 205 206 207
   *
   * @var bool
   */
  protected $strictConfigSchema = TRUE;

208 209 210 211 212
  /**
   * An array of config object names that are excluded from schema checking.
   *
   * @var string[]
   */
213
  protected static $configSchemaCheckerExclusions = [
214 215 216 217 218 219 220 221
    // Following are used to test lack of or partial schema. Where partial
    // schema is provided, that is explicitly tested in specific tests.
    'config_schema_test.noschema',
    'config_schema_test.someschema',
    'config_schema_test.schema_data_types',
    'config_schema_test.no_schema_data_types',
    // Used to test application of schema to filtering of configuration.
    'config_test.dynamic.system',
222
  ];
223

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
  /**
   * {@inheritdoc}
   */
  public static function setUpBeforeClass() {
    parent::setUpBeforeClass();

    // Change the current dir to DRUPAL_ROOT.
    chdir(static::getDrupalRoot());
  }

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->root = static::getDrupalRoot();
241
    $this->initFileCache();
242 243 244 245 246 247 248 249 250 251
    $this->bootEnvironment();
    $this->bootKernel();
  }

  /**
   * Bootstraps a basic test environment.
   *
   * Should not be called by tests. Only visible for DrupalKernel integration
   * tests.
   *
252
   * @see \Drupal\KernelTests\Core\DrupalKernel\DrupalKernelTest
253 254 255
   * @internal
   */
  protected function bootEnvironment() {
256
    $this->streamWrappers = [];
257 258
    \Drupal::unsetContainer();

259
    $this->classLoader = require $this->root . '/autoload.php';
260 261 262 263

    require_once $this->root . '/core/includes/bootstrap.inc';

    // Set up virtual filesystem.
264 265 266
    Database::addConnectionInfo('default', 'test-runner', $this->getDatabaseConnectionInfo()['default']);
    $test_db = new TestDatabase();
    $this->siteDirectory = $test_db->getTestSitePath();
267 268 269 270

    // Ensure that all code that relies on drupal_valid_test_ua() can still be
    // safely executed. This primarily affects the (test) site directory
    // resolution (used by e.g. LocalStream and PhpStorage).
271
    $this->databasePrefix = $test_db->getDatabasePrefix();
272 273
    drupal_valid_test_ua($this->databasePrefix);

274
    $settings = [
275 276 277 278 279
      'hash_salt' => get_class($this),
      'file_public_path' => $this->siteDirectory . '/files',
      // Disable Twig template caching/dumping.
      'twig_cache' => FALSE,
      // @see \Drupal\KernelTests\KernelTestBase::register()
280
    ];
281 282
    new Settings($settings);

283
    $this->setUpFilesystem();
284 285 286 287 288 289 290

    foreach (Database::getAllConnectionInfo() as $key => $targets) {
      Database::removeConnection($key);
    }
    Database::addConnectionInfo('default', 'default', $this->getDatabaseConnectionInfo()['default']);
  }

291 292 293 294
  /**
   * Sets up the filesystem, so things like the file directory.
   */
  protected function setUpFilesystem() {
295 296 297 298 299 300
    $test_db = new TestDatabase($this->databasePrefix);
    $test_site_path = $test_db->getTestSitePath();

    $this->vfsRoot = vfsStream::setup('root');
    $this->vfsRoot->addChild(vfsStream::newDirectory($test_site_path));
    $this->siteDirectory = vfsStream::url('root/' . $test_site_path);
301 302

    mkdir($this->siteDirectory . '/files', 0775);
303
    mkdir($this->siteDirectory . '/files/config/sync', 0775, TRUE);
304 305 306

    $settings = Settings::getInstance() ? Settings::getAll() : [];
    $settings['file_public_path'] = $this->siteDirectory . '/files';
307
    $settings['config_sync_directory'] = $this->siteDirectory . '/files/config/sync';
308 309 310
    new Settings($settings);
  }

311 312 313 314 315 316 317
  /**
   * @return string
   */
  public function getDatabasePrefix() {
    return $this->databasePrefix;
  }

318 319 320
  /**
   * Bootstraps a kernel for a test.
   */
321
  private function bootKernel() {
322 323
    $this->setSetting('container_yamls', []);
    // Allow for test-specific overrides.
324
    $settings_services_file = $this->root . '/sites/default/testing.services.yml';
325 326
    if (file_exists($settings_services_file)) {
      // Copy the testing-specific service overrides in place.
327
      $testing_services_file = $this->siteDirectory . '/services.yml';
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
      copy($settings_services_file, $testing_services_file);
      $this->setSetting('container_yamls', [$testing_services_file]);
    }

    // Allow for global test environment overrides.
    if (file_exists($test_env = $this->root . '/sites/default/testing.services.yml')) {
      $GLOBALS['conf']['container_yamls']['testing'] = $test_env;
    }
    // Add this test class as a service provider.
    $GLOBALS['conf']['container_service_providers']['test'] = $this;

    $modules = self::getModulesToEnable(get_class($this));

    // Bootstrap the kernel. Do not use createFromRequest() to retain Settings.
    $kernel = new DrupalKernel('testing', $this->classLoader, FALSE);
    $kernel->setSitePath($this->siteDirectory);
    // Boot a new one-time container from scratch. Ensure to set the module list
    // upfront to avoid a subsequent rebuild.
346
    if ($modules && $extensions = $this->getExtensionsForModules($modules)) {
347 348 349 350 351
      $kernel->updateModules($extensions, $extensions);
    }
    // DrupalKernel::boot() is not sufficient as it does not invoke preHandle(),
    // which is required to initialize legacy global variables.
    $request = Request::create('/');
352 353 354 355
    $kernel->boot();
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
    $kernel->preHandle($request);
356 357 358

    $this->container = $kernel->getContainer();

359 360 361 362 363 364 365 366
    // Ensure database tasks have been run.
    require_once __DIR__ . '/../../../includes/install.inc';
    $connection = Database::getConnection();
    $errors = db_installer_object($connection->driver())->runTasks();
    if (!empty($errors)) {
      $this->fail('Failed to run installer database tasks: ' . implode(', ', $errors));
    }

367 368 369 370
    if ($modules) {
      $this->container->get('module_handler')->loadAll();
    }

371 372 373
    // Setup the destion to the be frontpage by default.
    \Drupal::destination()->set('/');

374 375
    // Write the core.extension configuration.
    // Required for ConfigInstaller::installDefaultConfig() to work.
376
    $this->container->get('config.storage')->write('core.extension', [
377
      'module' => array_fill_keys($modules, 0),
378
      'theme' => [],
379
      'profile' => '',
380
    ]);
381 382 383 384 385 386

    $settings = Settings::getAll();
    $settings['php_storage']['default'] = [
      'class' => '\Drupal\Component\PhpStorage\FileStorage',
    ];
    new Settings($settings);
387 388 389 390 391 392

    // Manually configure the test mail collector implementation to prevent
    // tests from sending out emails and collect them in state instead.
    // While this should be enforced via settings.php prior to installation,
    // some tests expect to be able to test mail system implementations.
    $GLOBALS['config']['system.mail']['interface']['default'] = 'test_mail_collector';
393 394 395 396 397

    // Manually configure the default file scheme so that modules that use file
    // functions don't have to install system and its configuration.
    // @see file_default_scheme()
    $GLOBALS['config']['system.file']['default_scheme'] = 'public';
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
  }

  /**
   * Configuration accessor for tests. Returns non-overridden configuration.
   *
   * @param string $name
   *   The configuration name.
   *
   * @return \Drupal\Core\Config\Config
   *   The configuration object with original configuration data.
   */
  protected function config($name) {
    return $this->container->get('config.factory')->getEditable($name);
  }

  /**
   * Returns the Database connection info to be used for this test.
   *
   * This method only exists for tests of the Database component itself, because
   * they require multiple database connections. Each SQLite :memory: connection
   * creates a new/separate database in memory. A shared-memory SQLite file URI
   * triggers PHP open_basedir/allow_url_fopen/allow_url_include restrictions.
   * Due to that, Database tests are running against a SQLite database that is
   * located in an actual file in the system's temporary directory.
   *
   * Other tests should not override this method.
   *
   * @return array
   *   A Database connection info array.
   *
   * @internal
   */
  protected function getDatabaseConnectionInfo() {
    // If the test is run with argument dburl then use it.
    $db_url = getenv('SIMPLETEST_DB');
433
    if (empty($db_url)) {
434
      throw new \Exception('There is no database connection so no tests can be run. You must provide a SIMPLETEST_DB environment variable to run PHPUnit based functional tests outside of run-tests.sh. See https://www.drupal.org/node/2116263#skipped-tests for more information.');
435 436
    }
    else {
437 438 439 440 441 442
      $database = Database::convertDbUrlToConnectionInfo($db_url, $this->root);
      Database::addConnectionInfo('default', 'default', $database);
    }

    // Clone the current connection and replace the current prefix.
    $connection_info = Database::getConnectionInfo('default');
443
    if (!empty($connection_info)) {
444 445 446 447
      Database::renameConnection('default', 'simpletest_original_default');
      foreach ($connection_info as $target => $value) {
        // Replace the full table prefix definition to ensure that no table
        // prefixes of the test runner leak into the test.
448
        $connection_info[$target]['prefix'] = [
449
          'default' => $this->databasePrefix,
450
        ];
451 452 453 454 455
      }
    }
    return $connection_info;
  }

456 457 458 459 460 461 462 463 464 465 466 467 468
  /**
   * Initializes the FileCache component.
   *
   * We can not use the Settings object in a component, that's why we have to do
   * it here instead of \Drupal\Component\FileCache\FileCacheFactory.
   */
  protected function initFileCache() {
    $configuration = Settings::get('file_cache');

    // Provide a default configuration, if not set.
    if (!isset($configuration['default'])) {
      // @todo Use extension_loaded('apcu') for non-testbot
      //  https://www.drupal.org/node/2447753.
469
      if (function_exists('apcu_fetch')) {
470 471 472 473 474 475 476
        $configuration['default']['cache_backend_class'] = ApcuFileCacheBackend::class;
      }
    }
    FileCacheFactory::setConfiguration($configuration);
    FileCacheFactory::setPrefix(Settings::getApcuPrefix('file_cache', $this->root));
  }

477 478 479 480 481 482 483 484 485
  /**
   * Returns Extension objects for $modules to enable.
   *
   * @param string[] $modules
   *   The list of modules to enable.
   *
   * @return \Drupal\Core\Extension\Extension[]
   *   Extension objects for $modules, keyed by module name.
   *
486
   * @throws \PHPUnit\Framework\Exception
487 488 489 490 491
   *   If a module is not available.
   *
   * @see \Drupal\Tests\KernelTestBase::enableModules()
   * @see \Drupal\Core\Extension\ModuleHandler::add()
   */
492
  private function getExtensionsForModules(array $modules) {
493
    $extensions = [];
494
    $discovery = new ExtensionDiscovery($this->root);
495
    $discovery->setProfileDirectories([]);
496 497 498
    $list = $discovery->scan('module');
    foreach ($modules as $name) {
      if (!isset($list[$name])) {
499
        throw new Exception("Unavailable module: '$name'. If this module needs to be downloaded separately, annotate the test class with '@requires module $name'.");
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
      }
      $extensions[$name] = $list[$name];
    }
    return $extensions;
  }

  /**
   * Registers test-specific services.
   *
   * Extend this method in your test to register additional services. This
   * method is called whenever the kernel is rebuilt.
   *
   * @param \Drupal\Core\DependencyInjection\ContainerBuilder $container
   *   The service container to enhance.
   *
   * @see \Drupal\Tests\KernelTestBase::bootKernel()
   */
  public function register(ContainerBuilder $container) {
    // Keep the container object around for tests.
    $this->container = $container;

    $container
      ->register('flood', 'Drupal\Core\Flood\MemoryBackend')
      ->addArgument(new Reference('request_stack'));
    $container
      ->register('lock', 'Drupal\Core\Lock\NullLockBackend');
    $container
      ->register('cache_factory', 'Drupal\Core\Cache\MemoryBackendFactory');
    $container
      ->register('keyvalue.memory', 'Drupal\Core\KeyValueStore\KeyValueMemoryFactory')
      // Must persist container rebuilds, or all data would vanish otherwise.
      ->addTag('persist');
    $container
      ->setAlias('keyvalue', 'keyvalue.memory');

535 536 537
    // Set the default language on the minimal container.
    $container->setParameter('language.default_values', Language::$defaultValues);

538 539
    if ($this->strictConfigSchema) {
      $container
540
        ->register('testing.config_schema_checker', ConfigSchemaChecker::class)
541
        ->addArgument(new Reference('config.typed'))
542
        ->addArgument($this->getConfigSchemaExclusions())
543 544 545
        ->addTag('event_subscriber');
    }

546
    if ($container->hasDefinition('path_alias.path_processor')) {
547 548 549 550
      // The alias-based processor requires the path_alias entity schema to be
      // installed, so we prevent it from being registered to the path processor
      // manager. We do this by removing the tags that the compiler pass looks
      // for. This means that the URL generator can safely be used within tests.
551
      $container->getDefinition('path_alias.path_processor')
552 553 554 555 556 557
        ->clearTag('path_processor_inbound')
        ->clearTag('path_processor_outbound');
    }

    if ($container->hasDefinition('password')) {
      $container->getDefinition('password')
558
        ->setArguments([1]);
559
    }
560
    TestServiceProvider::addRouteProvider($container);
561 562
  }

563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
  /**
   * Gets the config schema exclusions for this test.
   *
   * @return string[]
   *   An array of config object names that are excluded from schema checking.
   */
  protected function getConfigSchemaExclusions() {
    $class = get_class($this);
    $exceptions = [];
    while ($class) {
      if (property_exists($class, 'configSchemaCheckerExclusions')) {
        $exceptions = array_merge($exceptions, $class::$configSchemaCheckerExclusions);
      }
      $class = get_parent_class($class);
    }
    // Filter out any duplicates.
    return array_unique($exceptions);
  }

582 583 584 585 586 587 588 589 590 591 592 593
  /**
   * {@inheritdoc}
   */
  protected function assertPostConditions() {
    // Execute registered Drupal shutdown functions prior to tearing down.
    // @see _drupal_shutdown_function()
    $callbacks = &drupal_register_shutdown_function();
    while ($callback = array_shift($callbacks)) {
      call_user_func_array($callback['callback'], $callback['arguments']);
    }

    // Shut down the kernel (if bootKernel() was called).
594
    // @see \Drupal\KernelTests\Core\DrupalKernel\DrupalKernelTest
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
    if ($this->container) {
      $this->container->get('kernel')->shutdown();
    }

    parent::assertPostConditions();
  }

  /**
   * {@inheritdoc}
   */
  protected function tearDown() {
    // Destroy the testing kernel.
    if (isset($this->kernel)) {
      $this->kernel->shutdown();
    }

611 612 613 614 615 616 617 618 619 620 621 622 623 624
    // Remove all prefixed tables.
    $original_connection_info = Database::getConnectionInfo('simpletest_original_default');
    $original_prefix = $original_connection_info['default']['prefix']['default'];
    $test_connection_info = Database::getConnectionInfo('default');
    $test_prefix = $test_connection_info['default']['prefix']['default'];
    if ($original_prefix != $test_prefix) {
      $tables = Database::getConnection()->schema()->findTables('%');
      foreach ($tables as $table) {
        if (Database::getConnection()->schema()->dropTable($table)) {
          unset($tables[$table]);
        }
      }
    }

625 626 627 628 629 630 631 632
    // Free up memory: Own properties.
    $this->classLoader = NULL;
    $this->vfsRoot = NULL;
    $this->configImporter = NULL;

    // Free up memory: Custom test class properties.
    // Note: Private properties cannot be cleaned up.
    $rc = new \ReflectionClass(__CLASS__);
633
    $blacklist = [];
634 635 636 637 638 639 640 641 642 643
    foreach ($rc->getProperties() as $property) {
      $blacklist[$property->name] = $property->getDeclaringClass()->name;
    }
    $rc = new \ReflectionClass($this);
    foreach ($rc->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED) as $property) {
      if (!$property->isStatic() && !isset($blacklist[$property->name])) {
        $this->{$property->name} = NULL;
      }
    }

644 645 646
    // Clean FileCache cache.
    FileCache::reset();

647 648 649 650 651 652
    // Clean up statics, container, and settings.
    if (function_exists('drupal_static_reset')) {
      drupal_static_reset();
    }
    \Drupal::unsetContainer();
    $this->container = NULL;
653
    new Settings([]);
654

655 656 657 658 659 660 661 662 663
    parent::tearDown();
  }

  /**
   * @after
   *
   * Additional tear down method to close the connection at the end.
   */
  public function tearDownCloseDatabaseConnection() {
664 665 666 667 668 669 670 671 672 673 674
    // Destroy the database connection, which for example removes the memory
    // from sqlite in memory.
    foreach (Database::getAllConnectionInfo() as $key => $targets) {
      Database::removeConnection($key);
    }
  }

  /**
   * Installs default configuration for a given list of modules.
   *
   * @param string|string[] $modules
675
   *   A module or list of modules for which to install default configuration.
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
   *
   * @throws \LogicException
   *   If any module in $modules is not enabled.
   */
  protected function installConfig($modules) {
    foreach ((array) $modules as $module) {
      if (!$this->container->get('module_handler')->moduleExists($module)) {
        throw new \LogicException("$module module is not enabled.");
      }
      $this->container->get('config.installer')->installDefaultConfig('module', $module);
    }
  }

  /**
   * Installs database tables from a module schema definition.
   *
   * @param string $module
   *   The name of the module that defines the table's schema.
   * @param string|array $tables
   *   The name or an array of the names of the tables to install.
   *
   * @throws \LogicException
   *   If $module is not enabled or the table schema cannot be found.
   */
  protected function installSchema($module, $tables) {
    // drupal_get_module_schema() is technically able to install a schema
    // of a non-enabled module, but its ability to load the module's .install
    // file depends on many other factors. To prevent differences in test
    // behavior and non-reproducible test failures, we only allow the schema of
    // explicitly loaded/enabled modules to be installed.
    if (!$this->container->get('module_handler')->moduleExists($module)) {
      throw new \LogicException("$module module is not enabled.");
    }
    $tables = (array) $tables;
    foreach ($tables as $table) {
      $schema = drupal_get_module_schema($module, $table);
      if (empty($schema)) {
713 714
        // BC layer to avoid some contrib tests to fail.
        if ($module == 'system') {
715
          @trigger_error('Special handling of system module schemas in \Drupal\KernelTests\KernelTestBase::installSchema has been deprecated in Drupal 8.7.x, remove any calls to this method that use invalid schema names. See https://www.drupal.org/node/3003360.', E_USER_DEPRECATED);
716 717
          continue;
        }
718 719 720 721 722 723 724 725 726 727 728 729 730
        throw new \LogicException("$module module does not define a schema for table '$table'.");
      }
      $this->container->get('database')->schema()->createTable($table, $schema);
    }
  }

  /**
   * Installs the storage schema for a specific entity type.
   *
   * @param string $entity_type_id
   *   The ID of the entity type.
   */
  protected function installEntitySchema($entity_type_id) {
731 732 733
    $entity_type_manager = \Drupal::entityTypeManager();
    $entity_type = $entity_type_manager->getDefinition($entity_type_id);
    \Drupal::service('entity_type.listener')->onEntityTypeCreate($entity_type);
734 735 736

    // For test runs, the most common storage backend is a SQL database. For
    // this case, ensure the tables got created.
737
    $storage = $entity_type_manager->getStorage($entity_type_id);
738 739 740 741 742 743
    if ($storage instanceof SqlEntityStorageInterface) {
      $tables = $storage->getTableMapping()->getTableNames();
      $db_schema = $this->container->get('database')->schema();
      $all_tables_exist = TRUE;
      foreach ($tables as $table) {
        if (!$db_schema->tableExists($table)) {
744
          $this->fail(new FormattableMarkup('Installed entity type table for the %entity_type entity type: %table', [
745 746
            '%entity_type' => $entity_type_id,
            '%table' => $table,
747
          ]));
748 749 750 751
          $all_tables_exist = FALSE;
        }
      }
      if ($all_tables_exist) {
752
        $this->pass(new FormattableMarkup('Installed entity type tables for the %entity_type entity type: %tables', [
753 754
          '%entity_type' => $entity_type_id,
          '%tables' => '{' . implode('}, {', $tables) . '}',
755
        ]));
756 757 758 759 760 761 762
      }
    }
  }

  /**
   * Enables modules for this test.
   *
763 764 765
   * This method does not install modules fully. Services and hooks for the
   * module are available, but the install process is not performed.
   *
766 767 768
   * To install test modules outside of the testing environment, add
   * @code
   * $settings['extension_discovery_scan_tests'] = TRUE;
769
   * @endcode
770 771
   * to your settings.php.
   *
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
   * @param string[] $modules
   *   A list of modules to enable. Dependencies are not resolved; i.e.,
   *   multiple modules have to be specified individually. The modules are only
   *   added to the active module list and loaded; i.e., their database schema
   *   is not installed. hook_install() is not invoked. A custom module weight
   *   is not applied.
   *
   * @throws \LogicException
   *   If any module in $modules is already enabled.
   * @throws \RuntimeException
   *   If a module is not enabled after enabling it.
   */
  protected function enableModules(array $modules) {
    $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
    if ($trace[1]['function'] === 'setUp') {
787
      trigger_error('KernelTestBase::enableModules() should not be called from setUp(). Use the $modules property instead.', E_USER_DEPRECATED);
788 789 790 791 792 793 794
    }
    unset($trace);

    // Perform an ExtensionDiscovery scan as this function may receive a
    // profile that is not the current profile, and we don't yet have a cached
    // way to receive inactive profile information.
    // @todo Remove as part of https://www.drupal.org/node/2186491
795
    $listing = new ExtensionDiscovery($this->root);
796 797 798 799 800 801 802 803 804 805 806 807 808 809
    $module_list = $listing->scan('module');
    // In ModuleHandlerTest we pass in a profile as if it were a module.
    $module_list += $listing->scan('profile');

    // Set the list of modules in the extension handler.
    $module_handler = $this->container->get('module_handler');

    // Write directly to active storage to avoid early instantiation of
    // the event dispatcher which can prevent modules from registering events.
    $active_storage = $this->container->get('config.storage');
    $extension_config = $active_storage->read('core.extension');

    foreach ($modules as $module) {
      if ($module_handler->moduleExists($module)) {
810
        continue;
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
      }
      $module_handler->addModule($module, $module_list[$module]->getPath());
      // Maintain the list of enabled modules in configuration.
      $extension_config['module'][$module] = 0;
    }
    $active_storage->write('core.extension', $extension_config);

    // Update the kernel to make their services available.
    $extensions = $module_handler->getModuleList();
    $this->container->get('kernel')->updateModules($extensions, $extensions);

    // Ensure isLoaded() is TRUE in order to make
    // \Drupal\Core\Theme\ThemeManagerInterface::render() work.
    // Note that the kernel has rebuilt the container; this $module_handler is
    // no longer the $module_handler instance from above.
    $module_handler = $this->container->get('module_handler');
    $module_handler->reload();
    foreach ($modules as $module) {
      if (!$module_handler->moduleExists($module)) {
        throw new \RuntimeException("$module module is not enabled after enabling it.");
      }
    }
  }

  /**
   * Disables modules for this test.
   *
   * @param string[] $modules
   *   A list of modules to disable. Dependencies are not resolved; i.e.,
   *   multiple modules have to be specified with dependent modules first.
   *   Code of previously enabled modules is still loaded. The modules are only
   *   removed from the active module list.
   *
   * @throws \LogicException
   *   If any module in $modules is already disabled.
   * @throws \RuntimeException
   *   If a module is not disabled after disabling it.
   */
  protected function disableModules(array $modules) {
    // Unset the list of modules in the extension handler.
    $module_handler = $this->container->get('module_handler');
    $module_filenames = $module_handler->getModuleList();
    $extension_config = $this->config('core.extension');
    foreach ($modules as $module) {
      if (!$module_handler->moduleExists($module)) {
        throw new \LogicException("$module module cannot be disabled because it is not enabled.");
      }
      unset($module_filenames[$module]);
      $extension_config->clear('module.' . $module);
    }
    $extension_config->save();
    $module_handler->setModuleList($module_filenames);
    $module_handler->resetImplementations();
    // Update the kernel to remove their services.
    $this->container->get('kernel')->updateModules($module_filenames, $module_filenames);

867 868
    // Ensure isLoaded() is TRUE in order to make
    // \Drupal\Core\Theme\ThemeManagerInterface::render() work.
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
    // Note that the kernel has rebuilt the container; this $module_handler is
    // no longer the $module_handler instance from above.
    $module_handler = $this->container->get('module_handler');
    $module_handler->reload();
    foreach ($modules as $module) {
      if ($module_handler->moduleExists($module)) {
        throw new \RuntimeException("$module module is not disabled after disabling it.");
      }
    }
  }

  /**
   * Renders a render array.
   *
   * @param array $elements
   *   The elements to render.
   *
   * @return string
   *   The rendered string output (typically HTML).
   */
  protected function render(array &$elements) {
890 891 892 893 894 895
    // \Drupal\Core\Render\BareHtmlPageRenderer::renderBarePage calls out to
    // system_page_attachments() directly.
    if (!\Drupal::moduleHandler()->moduleExists('system')) {
      throw new \Exception(__METHOD__ . ' requires system module to be installed.');
    }

896 897
    // Use the bare HTML page renderer to render our links.
    $renderer = $this->container->get('bare_html_page_renderer');
898
    $response = $renderer->renderBarePage($elements, '', 'maintenance_page');
899 900

    // Glean the content from the response object.
901 902
    $content = $response->getContent();
    $this->setRawContent($content);
903
    $this->verbose('<pre style="white-space: pre-wrap">' . Html::escape($content));
904 905 906 907 908 909 910 911 912 913 914 915 916
    return $content;
  }

  /**
   * Sets an in-memory Settings variable.
   *
   * @param string $name
   *   The name of the setting to set.
   * @param bool|string|int|array|null $value
   *   The value to set. Note that array values are replaced entirely; use
   *   \Drupal\Core\Site\Settings::get() to perform custom merges.
   */
  protected function setSetting($name, $value) {
917 918 919 920
    if ($name === 'install_profile') {
      @trigger_error('Use \Drupal\KernelTests\KernelTestBase::setInstallProfile() to set the install profile in kernel tests. See https://www.drupal.org/node/2538996', E_USER_DEPRECATED);
      $this->setInstallProfile($value);
    }
921
    $settings = Settings::getInstance() ? Settings::getAll() : [];
922 923 924 925
    $settings[$name] = $value;
    new Settings($settings);
  }

926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
  /**
   * Sets the install profile and rebuilds the container to update it.
   *
   * @param string $profile
   *   The install profile to set.
   */
  protected function setInstallProfile($profile) {
    $this->container->get('config.factory')
      ->getEditable('core.extension')
      ->set('profile', $profile)
      ->save();

    // The installation profile is provided by a container parameter. Saving
    // the configuration doesn't automatically trigger invalidation
    $this->container->get('kernel')->rebuildContainer();
  }

943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
  /**
   * Stops test execution.
   */
  protected function stop() {
    $this->getTestResultObject()->stop();
  }

  /**
   * Dumps the current state of the virtual filesystem to STDOUT.
   */
  protected function vfsDump() {
    vfsStream::inspect(new vfsStreamPrintVisitor());
  }

  /**
   * Returns the modules to enable for this test.
   *
   * @param string $class
   *   The fully-qualified class name of this test.
   *
   * @return array
   */
965
  private static function getModulesToEnable($class) {
966
    $modules = [];
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
    while ($class) {
      if (property_exists($class, 'modules')) {
        // Only add the modules, if the $modules property was not inherited.
        $rp = new \ReflectionProperty($class, 'modules');
        if ($rp->class == $class) {
          $modules[$class] = $class::$modules;
        }
      }
      $class = get_parent_class($class);
    }
    // Modules have been collected in reverse class hierarchy order; modules
    // defined by base classes should be sorted first. Then, merge the results
    // together.
    $modules = array_reverse($modules);
    return call_user_func_array('array_merge_recursive', $modules);
  }

  /**
   * {@inheritdoc}
   */
  protected function prepareTemplate(\Text_Template $template) {
    $bootstrap_globals = '';

    // Fix missing bootstrap.php when $preserveGlobalState is FALSE.
    // @see https://github.com/sebastianbergmann/phpunit/pull/797
    $bootstrap_globals .= '$__PHPUNIT_BOOTSTRAP = ' . var_export($GLOBALS['__PHPUNIT_BOOTSTRAP'], TRUE) . ";\n";

    // Avoid repetitive test namespace discoveries to improve performance.
    // @see /core/tests/bootstrap.php
    $bootstrap_globals .= '$namespaces = ' . var_export($GLOBALS['namespaces'], TRUE) . ";\n";

998
    $template->setVar([
999 1000 1001
      'constants' => '',
      'included_files' => '',
      'globals' => $bootstrap_globals,
1002
    ]);
1003 1004 1005
  }

  /**
1006 1007 1008
   * Returns whether the current test method is running in a separate process.
   *
   * Note that KernelTestBase will run in a separate process by default.
1009 1010 1011
   *
   * @return bool
   *
1012
   * @see \Drupal\KernelTests\KernelTestBase::$runTestInSeparateProcess
1013
   * @see https://github.com/sebastianbergmann/phpunit/pull/1350
1014 1015 1016
   *
   * @deprecated in Drupal 8.4.x, for removal before the Drupal 9.0.0 release.
   *   KernelTestBase tests are always run in isolated processes.
1017 1018
   */
  protected function isTestInIsolation() {
1019
    @trigger_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated in Drupal 8.4.x, for removal before the Drupal 9.0.0 release. KernelTestBase tests are always run in isolated processes.', E_USER_DEPRECATED);
1020 1021 1022 1023 1024 1025 1026 1027 1028
    return function_exists('__phpunit_run_isolated_test');
  }

  /**
   * BC: Automatically resolve former KernelTestBase class properties.
   *
   * Test authors should follow the provided instructions and adjust their tests
   * accordingly.
   *
1029
   * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
1030 1031
   */
  public function __get($name) {
1032
    if (in_array($name, [
1033 1034 1035 1036
      'public_files_directory',
      'private_files_directory',
      'temp_files_directory',
      'translation_files_directory',
1037
    ])) {
1038 1039 1040 1041
      // @comment it in again.
      trigger_error(sprintf("KernelTestBase::\$%s no longer exists. Use the regular API method to retrieve it instead (e.g., Settings).", $name), E_USER_DEPRECATED);
      switch ($name) {
        case 'public_files_directory':
1042
          return Settings::get('file_public_path', \Drupal::service('site.path') . '/files');
1043 1044

        case 'private_files_directory':
1045
          return Settings::get('file_private_path');
1046 1047

        case 'temp_files_directory':
1048
          return \Drupal::service('file_system')->getTempDirectory();
1049 1050

        case 'translation_files_directory':
1051
          return Settings::get('file_public_path', \Drupal::service('site.path') . '/translations');
1052 1053 1054 1055
      }
    }

    if ($name === 'configDirectories') {
1056
      trigger_error(sprintf("KernelTestBase::\$%s no longer exists. Use Settings::get('config_sync_directory') directly instead.", $name), E_USER_DEPRECATED);
1057
      return [
1058
        CONFIG_SYNC_DIRECTORY => Settings::get('config_sync_directory'),
1059
      ];
1060 1061
    }

1062
    $denied = [
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
      // @see \Drupal\simpletest\TestBase
      'testId',
      'timeLimit',
      'results',
      'assertions',
      'skipClasses',
      'verbose',
      'verboseId',
      'verboseClassName',
      'verboseDirectory',
      'verboseDirectoryUrl',
      'dieOnFail',
      'kernel',
      // @see \Drupal\simpletest\TestBase::prepareEnvironment()
      'generatedTestFiles',
1078
      // Properties from the old KernelTestBase class that has been removed.
1079
      'keyValueFactory',
1080
    ];
1081 1082 1083 1084 1085
    if (in_array($name, $denied) || strpos($name, 'original') === 0) {
      throw new \RuntimeException(sprintf('TestBase::$%s property no longer exists', $name));
    }
  }

1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
  /**
   * Prevents serializing any properties.
   *
   * Kernel tests are run in a separate process. To do this PHPUnit creates a
   * script to run the test. If it fails, the test result object will contain a
   * stack trace which includes the test object. It will attempt to serialize
   * it. Returning an empty array prevents it from serializing anything it
   * should not.
   *
   * @return array
   *   An empty array.
   *
   * @see vendor/phpunit/phpunit/src/Util/PHP/Template/TestCaseMethod.tpl.dist
   */
  public function __sleep() {
    return [];
  }

1104
}