KernelTestBase.php 23.3 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\simpletest\KernelTestBase.
 */

namespace Drupal\simpletest;

10
use Drupal\Component\Utility\Html;
11
use Drupal\Component\Utility\SafeMarkup;
12
use Drupal\Component\Utility\Variable;
13 14 15
use Drupal\Core\Database\Database;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DrupalKernel;
16
use Drupal\Core\Entity\Sql\SqlEntityStorageInterface;
17
use Drupal\Core\Extension\ExtensionDiscovery;
18 19
use Drupal\Core\KeyValueStore\KeyValueMemoryFactory;
use Drupal\Core\Language\Language;
20
use Drupal\Core\Site\Settings;
21
use Symfony\Component\DependencyInjection\Parameter;
22
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
23 24 25 26 27 28 29 30 31 32 33 34 35 36
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpFoundation\Request;

/**
 * Base class for integration tests.
 *
 * Tests extending this base class can access files and the database, but the
 * entire environment is initially empty. Drupal runs in a minimal mocked
 * environment, comparable to the one in the early installer.
 *
 * The module/hook system is functional and operates on a fixed module list.
 * Additional modules needed in a test may be loaded and added to the fixed
 * module list.
 *
37 38 39
 * @deprecated in Drupal 8.0.x, will be removed before Drupal 8.2.x. Use
 *   \Drupal\KernelTests\KernelTestBase instead.
 *
40 41
 * @see \Drupal\simpletest\KernelTestBase::$modules
 * @see \Drupal\simpletest\KernelTestBase::enableModules()
42 43
 *
 * @ingroup testing
44
 */
45
abstract class KernelTestBase extends TestBase {
46

47 48
  use AssertContentTrait;

49 50 51 52 53 54 55 56
  /**
   * Modules to enable.
   *
   * Test classes extending this class, and any classes in the hierarchy up to
   * this class, may specify individual lists of modules to enable by setting
   * this property. The values of all properties in all classes in the hierarchy
   * are merged.
   *
57 58
   * Any modules specified in the $modules property are automatically loaded and
   * set as the fixed module list.
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
   *
   * Unlike WebTestBase::setUp(), the specified modules are loaded only, but not
   * automatically installed. Modules need to be installed manually, if needed.
   *
   * @see \Drupal\simpletest\KernelTestBase::enableModules()
   * @see \Drupal\simpletest\KernelTestBase::setUp()
   *
   * @var array
   */
  public static $modules = array();

  private $moduleFiles;
  private $themeFiles;

  /**
   * The configuration directories for this test run.
   *
   * @var array
   */
  protected $configDirectories = array();

  /**
   * A KeyValueMemoryFactory instance to use when building the container.
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueMemoryFactory.
   */
  protected $keyValueFactory;

  /**
88
   * Array of registered stream wrappers.
89 90 91
   *
   * @var array
   */
92
  protected $streamWrappers = array();
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116

  /**
   * {@inheritdoc}
   */
  function __construct($test_id = NULL) {
    parent::__construct($test_id);
    $this->skipClasses[__CLASS__] = TRUE;
  }

  /**
   * {@inheritdoc}
   */
  protected function beforePrepareEnvironment() {
    // Copy/prime extension file lists once to avoid filesystem scans.
    if (!isset($this->moduleFiles)) {
      $this->moduleFiles = \Drupal::state()->get('system.module.files') ?: array();
      $this->themeFiles = \Drupal::state()->get('system.theme.files') ?: array();
    }
  }

  /**
   * Create and set new configuration directories.
   *
   * @see config_get_config_directory()
117 118
   *
   * @throws \RuntimeException
119
   *   Thrown when CONFIG_SYNC_DIRECTORY cannot be created or made writable.
120 121 122 123
   */
  protected function prepareConfigDirectories() {
    $this->configDirectories = array();
    include_once DRUPAL_ROOT . '/core/includes/install.inc';
124
    // Assign the relative path to the global variable.
125 126
    $path = $this->siteDirectory . '/config_' . CONFIG_SYNC_DIRECTORY;
    $GLOBALS['config_directories'][CONFIG_SYNC_DIRECTORY] = $path;
127
    // Ensure the directory can be created and is writeable.
128 129
    if (!install_ensure_config_directory(CONFIG_SYNC_DIRECTORY)) {
      throw new \RuntimeException("Failed to create '" . CONFIG_SYNC_DIRECTORY . "' config directory $path");
130
    }
131
    // Provide the already resolved path for tests.
132
    $this->configDirectories[CONFIG_SYNC_DIRECTORY] = $path;
133 134 135 136 137 138 139 140
  }

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    $this->keyValueFactory = new KeyValueMemoryFactory();

141 142 143
    // Back up settings from TestBase::prepareEnvironment().
    $settings = Settings::getAll();

144
    // Allow for test-specific overrides.
145
    $directory = DRUPAL_ROOT . '/' . $this->siteDirectory;
146
    $settings_services_file = DRUPAL_ROOT . '/' . $this->originalSite . '/testing.services.yml';
147
    $container_yamls = [];
148 149
    if (file_exists($settings_services_file)) {
      // Copy the testing-specific service overrides in place.
150
      $testing_services_file = $directory . '/services.yml';
151
      copy($settings_services_file, $testing_services_file);
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
      $container_yamls[] = $testing_services_file;
    }
    $settings_testing_file = DRUPAL_ROOT . '/' . $this->originalSite . '/settings.testing.php';
    if (file_exists($settings_testing_file)) {
      // Copy the testing-specific settings.php overrides in place.
      copy($settings_testing_file, $directory . '/settings.testing.php');
    }

    if (file_exists($directory . '/settings.testing.php')) {
      // Add the name of the testing class to settings.php and include the
      // testing specific overrides
      $hash_salt = Settings::getHashSalt();
      $test_class = get_class($this);
      $container_yamls_export = Variable::export($container_yamls);
      $php = <<<EOD
<?php

\$settings['hash_salt'] = '$hash_salt';
\$settings['container_yamls'] = $container_yamls_export;

\$test_class = '$test_class';
include DRUPAL_ROOT . '/' . \$site_path . '/settings.testing.php';
EOD;
      file_put_contents($directory . '/settings.php', $php);
176 177
    }

178 179
    // Add this test class as a service provider.
    // @todo Remove the indirection; implement ServiceProviderInterface instead.
180 181
    $GLOBALS['conf']['container_service_providers']['TestServiceProvider'] = 'Drupal\simpletest\TestServiceProvider';

182
    // Bootstrap a new kernel.
183
    $class_loader = require DRUPAL_ROOT . '/autoload.php';
184
    $this->kernel = new DrupalKernel('testing', $class_loader, FALSE);
185
    $request = Request::create('/');
186 187 188 189 190
    $site_path = DrupalKernel::findSitePath($request);
    $this->kernel->setSitePath($site_path);
    if (file_exists($directory . '/settings.testing.php')) {
      Settings::initialize(DRUPAL_ROOT, $site_path, $class_loader);
    }
191
    $this->kernel->boot();
192

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
    // Ensure database install 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));
    }

    // Reboot the kernel because the container might contain a connection to the
    // database that has been closed during the database install tasks. This
    // prevents any services created during the first boot from having stale
    // database connections, for example, \Drupal\Core\Config\DatabaseStorage.
    $this->kernel->shutdown();
    $this->kernel->boot();


209 210 211 212 213 214
    // Save the original site directory path, so that extensions in the
    // site-specific directory can still be discovered in the test site
    // environment.
    // @see \Drupal\Core\Extension\ExtensionDiscovery::scan()
    $settings['test_parent_site'] = $this->originalSite;

215 216 217 218 219
    // Restore and merge settings.
    // DrupalKernel::boot() initializes new Settings, and the containerBuild()
    // method sets additional settings.
    new Settings($settings + Settings::getAll());

220 221 222
    // Create and set new configuration directories.
    $this->prepareConfigDirectories();

223 224
    // Set the request scope.
    $this->container = $this->kernel->getContainer();
225 226
    $this->container->get('request_stack')->push($request);

227 228 229 230 231 232
    // Re-inject extension file listings into state, unless the key/value
    // service was overridden (in which case its storage does not exist yet).
    if ($this->container->get('keyvalue') instanceof KeyValueMemoryFactory) {
      $this->container->get('state')->set('system.module.files', $this->moduleFiles);
      $this->container->get('state')->set('system.theme.files', $this->themeFiles);
    }
233

234 235 236 237 238
    // Create a minimal core.extension configuration object so that the list of
    // enabled modules can be maintained allowing
    // \Drupal\Core\Config\ConfigInstaller::installDefaultConfig() to work.
    // Write directly to active storage to avoid early instantiation of
    // the event dispatcher which can prevent modules from registering events.
239
    \Drupal::service('config.storage')->write('core.extension', array('module' => array(), 'theme' => array()));
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256

    // Collect and set a fixed module list.
    $class = get_class($this);
    $modules = array();
    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.
257 258
    $modules = array_reverse($modules);
    $modules = call_user_func_array('array_merge_recursive', $modules);
259
    if ($modules) {
260
      $this->enableModules($modules);
261 262 263 264 265
    }

    // Tests based on this class are entitled to use Drupal's File and
    // StreamWrapper APIs.
    // @todo Move StreamWrapper management into DrupalKernel.
266
    // @see https://www.drupal.org/node/2028109
267 268
    file_prepare_directory($this->publicFilesDirectory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
    $this->settingsSet('file_public_path', $this->publicFilesDirectory);
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    $this->streamWrappers = array();
    $this->registerStreamWrapper('public', 'Drupal\Core\StreamWrapper\PublicStream');
    // The temporary stream wrapper is able to operate both with and without
    // configuration.
    $this->registerStreamWrapper('temporary', 'Drupal\Core\StreamWrapper\TemporaryStream');
  }

  /**
   * {@inheritdoc}
   */
  protected function tearDown() {
    if ($this->kernel instanceof DrupalKernel) {
      $this->kernel->shutdown();
    }
    // Before tearing down the test environment, ensure that no stream wrapper
    // of this test leaks into the parent environment. Unlike all other global
    // state variables in Drupal, stream wrappers are a global state construct
    // of PHP core, which has to be maintained manually.
    // @todo Move StreamWrapper management into DrupalKernel.
288
    // @see https://www.drupal.org/node/2028109
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    foreach ($this->streamWrappers as $scheme => $type) {
      $this->unregisterStreamWrapper($scheme, $type);
    }
    parent::tearDown();
  }

  /**
   * Sets up the base service container for this test.
   *
   * Extend this method in your test to register additional service overrides
   * that need to persist a DrupalKernel reboot. This method is called whenever
   * the kernel is rebuilt.
   *
   * @see \Drupal\simpletest\KernelTestBase::setUp()
   * @see \Drupal\simpletest\KernelTestBase::enableModules()
   * @see \Drupal\simpletest\KernelTestBase::disableModules()
   */
  public function containerBuild(ContainerBuilder $container) {
    // Keep the container object around for tests.
    $this->container = $container;

    // Set the default language on the minimal container.
311
    $this->container->setParameter('language.default_values', $this->defaultLanguageData());
312 313 314 315 316

    $container->register('lock', 'Drupal\Core\Lock\NullLockBackend');
    $container->register('cache_factory', 'Drupal\Core\Cache\MemoryBackendFactory');

    $container
317
      ->register('config.storage', 'Drupal\Core\Config\DatabaseStorage')
318 319 320
      ->addArgument(Database::getConnection())
      ->addArgument('config');

321 322 323 324
    if ($this->strictConfigSchema) {
      $container
        ->register('simpletest.config_schema_checker', 'Drupal\Core\Config\Testing\ConfigSchemaChecker')
        ->addArgument(new Reference('config.typed'))
325
        ->addArgument($this->getConfigSchemaExclusions())
326 327 328
        ->addTag('event_subscriber');
    }

329 330 331
    $keyvalue_options = $container->getParameter('factory.keyvalue') ?: array();
    $keyvalue_options['default'] = 'keyvalue.memory';
    $container->setParameter('factory.keyvalue', $keyvalue_options);
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    $container->set('keyvalue.memory', $this->keyValueFactory);
    if (!$container->has('keyvalue')) {
      // TestBase::setUp puts a completely empty container in
      // $this->container which is somewhat the mirror of the empty
      // environment being set up. Unit tests need not to waste time with
      // getting a container set up for them. Drupal Unit Tests might just get
      // away with a simple container holding the absolute bare minimum. When
      // a kernel is overridden then there's no need to re-register the keyvalue
      // service but when a test is happy with the superminimal container put
      // together here, it still might a keyvalue storage for anything using
      // \Drupal::state() -- that's why a memory service was added in the first
      // place.
      $container->register('settings', 'Drupal\Core\Site\Settings')
        ->setFactoryClass('Drupal\Core\Site\Settings')
        ->setFactoryMethod('getInstance');

      $container
        ->register('keyvalue', 'Drupal\Core\KeyValueStore\KeyValueFactory')
        ->addArgument(new Reference('service_container'))
351
        ->addArgument(new Parameter('factory.keyvalue'));
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369

      $container->register('state', 'Drupal\Core\State\State')
        ->addArgument(new Reference('keyvalue'));
    }

    if ($container->hasDefinition('path_processor_alias')) {
      // Prevent the alias-based path processor, which requires a url_alias db
      // table, from being registered to the path processor manager. We do this
      // by removing the tags that the compiler pass looks for. This means the
      // url generator can safely be used within tests.
      $definition = $container->getDefinition('path_processor_alias');
      $definition->clearTag('path_processor_inbound')->clearTag('path_processor_outbound');
    }

    if ($container->hasDefinition('password')) {
      $container->getDefinition('password')->setArguments(array(1));
    }

370 371 372 373 374 375
    // Register the stream wrapper manager.
    $container
      ->register('stream_wrapper_manager', 'Drupal\Core\StreamWrapper\StreamWrapperManager')
      ->addArgument(new Reference('module_handler'))
      ->addMethodCall('setContainer', array(new Reference('service_container')));

376
    $request = Request::create('/');
377
    $container->get('request_stack')->push($request);
378 379
  }

380 381 382 383 384 385 386 387 388 389
  /**
   * Provides the data for setting the default language on the container.
   *
   * @return array
   *   The data array for the default language.
   */
  protected function defaultLanguageData() {
    return Language::$defaultValues;
  }

390 391 392 393 394
  /**
   * Installs default configuration for a given list of modules.
   *
   * @param array $modules
   *   A list of modules for which to install default configuration.
395 396 397
   *
   * @throws \RuntimeException
   *   Thrown when any module listed in $modules is not enabled.
398 399 400 401
   */
  protected function installConfig(array $modules) {
    foreach ($modules as $module) {
      if (!$this->container->get('module_handler')->moduleExists($module)) {
402
        throw new \RuntimeException("'$module' module is not enabled");
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
      }
      \Drupal::service('config.installer')->installDefaultConfig('module', $module);
    }
    $this->pass(format_string('Installed default config: %modules.', array(
      '%modules' => implode(', ', $modules),
    )));
  }

  /**
   * Installs a specific table 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.
418 419 420 421
   *
   * @throws \RuntimeException
   *   Thrown when $module is not enabled or when the table schema cannot be
   *   found in the module specified.
422 423
   */
  protected function installSchema($module, $tables) {
424
    // drupal_get_module_schema() is technically able to install a schema
425 426 427 428 429
    // 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)) {
430
      throw new \RuntimeException("'$module' module is not enabled");
431 432 433
    }
    $tables = (array) $tables;
    foreach ($tables as $table) {
434
      $schema = drupal_get_module_schema($module, $table);
435
      if (empty($schema)) {
436
        throw new \RuntimeException("Unknown '$table' table schema in '$module' module.");
437 438 439 440 441 442 443 444 445
      }
      $this->container->get('database')->schema()->createTable($table, $schema);
    }
    $this->pass(format_string('Installed %module tables: %tables.', array(
      '%tables' => '{' . implode('}, {', $tables) . '}',
      '%module' => $module,
    )));
  }

446 447 448


  /**
449
   * Installs the storage schema for a specific entity type.
450 451 452 453 454 455 456
   *
   * @param string $entity_type_id
   *   The ID of the entity type.
   */
  protected function installEntitySchema($entity_type_id) {
    /** @var \Drupal\Core\Entity\EntityManagerInterface $entity_manager */
    $entity_manager = $this->container->get('entity.manager');
457 458
    $entity_type = $entity_manager->getDefinition($entity_type_id);
    $entity_manager->onEntityTypeCreate($entity_type);
459

460 461
    // For test runs, the most common storage backend is a SQL database. For
    // this case, ensure the tables got created.
462
    $storage = $entity_manager->getStorage($entity_type_id);
463 464 465 466 467 468
    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)) {
469
          $this->fail(SafeMarkup::format('Installed entity type table for the %entity_type entity type: %table', array(
470 471 472 473 474 475 476
            '%entity_type' => $entity_type_id,
            '%table' => $table,
          )));
          $all_tables_exist = FALSE;
        }
      }
      if ($all_tables_exist) {
477
        $this->pass(SafeMarkup::format('Installed entity type tables for the %entity_type entity type: %tables', array(
478 479 480
          '%entity_type' => $entity_type_id,
          '%tables' => '{' . implode('}, {', $tables) . '}',
        )));
481 482 483 484
      }
    }
  }

485 486 487 488 489 490 491 492 493
  /**
   * Enables modules for this test.
   *
   * @param array $modules
   *   A list of modules to enable. Dependencies are not resolved; i.e.,
   *   multiple modules have to be specified with dependent modules first.
   *   The new modules are only added to the active module list and loaded.
   */
  protected function enableModules(array $modules) {
494 495 496 497 498 499 500 501
    // 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
    $listing = new ExtensionDiscovery(\Drupal::root());
    $module_list = $listing->scan('module');
    // In ModuleHandlerTest we pass in a profile as if it were a module.
    $module_list += $listing->scan('profile');
502 503 504 505 506 507 508 509 510
    // 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 =  \Drupal::service('config.storage');
    $extensions = $active_storage->read('core.extension');

    foreach ($modules as $module) {
511
      $module_handler->addModule($module, $module_list[$module]->getPath());
512 513 514 515 516 517 518 519 520 521 522 523
      // Maintain the list of enabled modules in configuration.
      $extensions['module'][$module] = 0;
    }
    $active_storage->write('core.extension', $extensions);

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

    // Ensure isLoaded() is TRUE in order to make _theme() work.
    // Note that the kernel has rebuilt the container; this $module_handler is
    // no longer the $module_handler instance from above.
524
    $this->container->get('module_handler')->reload();
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
    $this->pass(format_string('Enabled modules: %modules.', array(
      '%modules' => implode(', ', $modules),
    )));
  }

  /**
   * Disables modules for this test.
   *
   * @param array $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 active modules is still loaded. The modules are only
   *   removed from the active module list.
   */
  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();
543
    $extension_config = $this->config('core.extension');
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
    foreach ($modules as $module) {
      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->kernel->updateModules($module_filenames, $module_filenames);

    // Ensure isLoaded() is TRUE in order to make _theme() 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();
    $this->pass(format_string('Disabled modules: %modules.', array(
      '%modules' => implode(', ', $modules),
    )));
  }

  /**
   * Registers a stream wrapper for this test.
   *
   * @param string $scheme
   *   The scheme to register.
   * @param string $class
   *   The fully qualified class name to register.
   * @param int $type
   *   The Drupal Stream Wrapper API type. Defaults to
573
   *   StreamWrapperInterface::NORMAL.
574
   */
575 576
  protected function registerStreamWrapper($scheme, $class, $type = StreamWrapperInterface::NORMAL) {
    $this->container->get('stream_wrapper_manager')->registerWrapper($scheme, $class, $type);
577 578
  }

579 580 581 582 583 584 585 586 587
  /**
   * Renders a render array.
   *
   * @param array $elements
   *   The elements to render.
   *
   * @return string
   *   The rendered string output (typically HTML).
   */
588
  protected function render(array &$elements) {
589 590 591 592 593 594 595 596
    // Use the bare HTML page renderer to render our links.
    $renderer = $this->container->get('bare_html_page_renderer');
    $response = $renderer->renderBarePage(
      $elements, '', $this->container->get('theme.manager')->getActiveTheme()->getName()
    );

    // Glean the content from the response object.
    $content = $response->getContent();
597
    $this->setRawContent($content);
598
    $this->verbose('<pre style="white-space: pre-wrap">' . Html::escape($content));
599 600 601
    return $content;
  }

602
}