KernelTestBase.php 22.7 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 119 120
   *
   * @throws \RuntimeException
   *   Thrown when CONFIG_ACTIVE_DIRECTORY or CONFIG_STAGING_DIRECTORY cannot
   *   be created or made writable.
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
   */
  protected function prepareConfigDirectories() {
    $this->configDirectories = array();
    include_once DRUPAL_ROOT . '/core/includes/install.inc';
    foreach (array(CONFIG_ACTIVE_DIRECTORY, CONFIG_STAGING_DIRECTORY) as $type) {
      // Assign the relative path to the global variable.
      $path = $this->siteDirectory . '/config_' . $type;
      $GLOBALS['config_directories'][$type] = $path;
      // Ensure the directory can be created and is writeable.
      if (!install_ensure_config_directory($type)) {
        throw new \RuntimeException("Failed to create '$type' config directory $path");
      }
      // Provide the already resolved path for tests.
      $this->configDirectories[$type] = $path;
    }
  }

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

144 145 146
    // Back up settings from TestBase::prepareEnvironment().
    $settings = Settings::getAll();

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

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

185
    // Bootstrap a new kernel.
186
    $class_loader = require DRUPAL_ROOT . '/autoload.php';
187
    $this->kernel = new DrupalKernel('testing', $class_loader, FALSE);
188
    $request = Request::create('/');
189 190 191 192 193
    $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);
    }
194
    $this->kernel->boot();
195

196 197 198 199 200 201
    // 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;

202 203 204 205 206
    // Restore and merge settings.
    // DrupalKernel::boot() initializes new Settings, and the containerBuild()
    // method sets additional settings.
    new Settings($settings + Settings::getAll());

207 208 209
    // Create and set new configuration directories.
    $this->prepareConfigDirectories();

210 211
    // Set the request scope.
    $this->container = $this->kernel->getContainer();
212 213
    $this->container->get('request_stack')->push($request);

214 215 216 217 218 219
    // 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);
    }
220

221 222 223 224 225
    // 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.
226
    \Drupal::service('config.storage')->write('core.extension', array('module' => array(), 'theme' => array()));
227

228 229 230 231 232 233 234 235
    // 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));
    }

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
    // 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.
252 253
    $modules = array_reverse($modules);
    $modules = call_user_func_array('array_merge_recursive', $modules);
254
    if ($modules) {
255
      $this->enableModules($modules);
256 257 258 259 260
    }

    // Tests based on this class are entitled to use Drupal's File and
    // StreamWrapper APIs.
    // @todo Move StreamWrapper management into DrupalKernel.
261
    // @see https://www.drupal.org/node/2028109
262 263
    file_prepare_directory($this->publicFilesDirectory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
    $this->settingsSet('file_public_path', $this->publicFilesDirectory);
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
    $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.
283
    // @see https://www.drupal.org/node/2028109
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    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.
306
    $this->container->setParameter('language.default_values', $this->defaultLanguageData());
307 308 309 310 311

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

    $container
312
      ->register('config.storage', 'Drupal\Core\Config\DatabaseStorage')
313 314 315
      ->addArgument(Database::getConnection())
      ->addArgument('config');

316 317 318 319 320 321 322
    if ($this->strictConfigSchema) {
      $container
        ->register('simpletest.config_schema_checker', 'Drupal\Core\Config\Testing\ConfigSchemaChecker')
        ->addArgument(new Reference('config.typed'))
        ->addTag('event_subscriber');
    }

323 324 325
    $keyvalue_options = $container->getParameter('factory.keyvalue') ?: array();
    $keyvalue_options['default'] = 'keyvalue.memory';
    $container->setParameter('factory.keyvalue', $keyvalue_options);
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    $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'))
345
        ->addArgument(new Parameter('factory.keyvalue'));
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363

      $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));
    }

364 365 366 367 368 369
    // 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')));

370
    $request = Request::create('/');
371
    $container->get('request_stack')->push($request);
372 373
  }

374 375 376 377 378 379 380 381 382 383
  /**
   * 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;
  }

384 385 386 387 388
  /**
   * Installs default configuration for a given list of modules.
   *
   * @param array $modules
   *   A list of modules for which to install default configuration.
389 390 391
   *
   * @throws \RuntimeException
   *   Thrown when any module listed in $modules is not enabled.
392 393 394 395
   */
  protected function installConfig(array $modules) {
    foreach ($modules as $module) {
      if (!$this->container->get('module_handler')->moduleExists($module)) {
396
        throw new \RuntimeException("'$module' module is not enabled");
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
      }
      \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.
412 413 414 415
   *
   * @throws \RuntimeException
   *   Thrown when $module is not enabled or when the table schema cannot be
   *   found in the module specified.
416 417
   */
  protected function installSchema($module, $tables) {
418
    // drupal_get_module_schema() is technically able to install a schema
419 420 421 422 423
    // 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)) {
424
      throw new \RuntimeException("'$module' module is not enabled");
425 426 427
    }
    $tables = (array) $tables;
    foreach ($tables as $table) {
428
      $schema = drupal_get_module_schema($module, $table);
429
      if (empty($schema)) {
430
        throw new \RuntimeException("Unknown '$table' table schema in '$module' module.");
431 432 433 434 435 436 437 438 439
      }
      $this->container->get('database')->schema()->createTable($table, $schema);
    }
    $this->pass(format_string('Installed %module tables: %tables.', array(
      '%tables' => '{' . implode('}, {', $tables) . '}',
      '%module' => $module,
    )));
  }

440 441 442


  /**
443
   * Installs the storage schema for a specific entity type.
444 445 446 447 448 449 450
   *
   * @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');
451 452
    $entity_type = $entity_manager->getDefinition($entity_type_id);
    $entity_manager->onEntityTypeCreate($entity_type);
453

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

479 480 481 482 483 484 485 486 487
  /**
   * 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) {
488 489 490 491 492 493 494 495
    // 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');
496 497 498 499 500 501 502 503 504
    // 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) {
505
      $module_handler->addModule($module, $module_list[$module]->getPath());
506 507 508 509 510 511 512 513 514 515 516 517
      // 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.
518
    $this->container->get('module_handler')->reload();
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
    $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();
537
    $extension_config = $this->config('core.extension');
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    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
567
   *   StreamWrapperInterface::NORMAL.
568
   */
569 570
  protected function registerStreamWrapper($scheme, $class, $type = StreamWrapperInterface::NORMAL) {
    $this->container->get('stream_wrapper_manager')->registerWrapper($scheme, $class, $type);
571 572
  }

573 574 575 576 577 578 579 580 581
  /**
   * Renders a render array.
   *
   * @param array $elements
   *   The elements to render.
   *
   * @return string
   *   The rendered string output (typically HTML).
   */
582
  protected function render(array &$elements) {
583
    $content = $this->container->get('renderer')->renderRoot($elements);
584
    drupal_process_attached($elements);
585
    $this->setRawContent($content);
586
    $this->verbose('<pre style="white-space: pre-wrap">' . Html::escape($content));
587 588 589
    return $content;
  }

590
}