KernelTestBase.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  1. <?php
  2. namespace Drupal\KernelTests;
  3. use Drupal\Component\FileCache\ApcuFileCacheBackend;
  4. use Drupal\Component\FileCache\FileCache;
  5. use Drupal\Component\FileCache\FileCacheFactory;
  6. use Drupal\Component\Utility\Html;
  7. use Drupal\Component\Utility\SafeMarkup;
  8. use Drupal\Core\Config\Development\ConfigSchemaChecker;
  9. use Drupal\Core\Database\Database;
  10. use Drupal\Core\DependencyInjection\ContainerBuilder;
  11. use Drupal\Core\DependencyInjection\ServiceProviderInterface;
  12. use Drupal\Core\DrupalKernel;
  13. use Drupal\Core\Entity\Sql\SqlEntityStorageInterface;
  14. use Drupal\Core\Extension\ExtensionDiscovery;
  15. use Drupal\Core\Language\Language;
  16. use Drupal\Core\Site\Settings;
  17. use Drupal\Core\Test\TestDatabase;
  18. use Drupal\simpletest\AssertContentTrait;
  19. use Drupal\simpletest\AssertHelperTrait;
  20. use Drupal\Tests\ConfigTestTrait;
  21. use Drupal\Tests\RandomGeneratorTrait;
  22. use Drupal\simpletest\TestServiceProvider;
  23. use Symfony\Component\DependencyInjection\Reference;
  24. use Symfony\Component\HttpFoundation\Request;
  25. use org\bovigo\vfs\vfsStream;
  26. use org\bovigo\vfs\visitor\vfsStreamPrintVisitor;
  27. /**
  28. * Base class for functional integration tests.
  29. *
  30. * Tests extending this base class can access files and the database, but the
  31. * entire environment is initially empty. Drupal runs in a minimal mocked
  32. * environment, comparable to the one in the early installer.
  33. *
  34. * Unlike \Drupal\Tests\UnitTestCase, modules specified in the $modules
  35. * property are automatically added to the service container for each test.
  36. * The module/hook system is functional and operates on a fixed module list.
  37. * Additional modules needed in a test may be loaded and added to the fixed
  38. * module list.
  39. *
  40. * Unlike \Drupal\simpletest\WebTestBase, the modules are only loaded, but not
  41. * installed. Modules have to be installed manually, if needed.
  42. *
  43. * @see \Drupal\Tests\KernelTestBase::$modules
  44. * @see \Drupal\Tests\KernelTestBase::enableModules()
  45. *
  46. * @todo Extend ::setRequirementsFromAnnotation() and ::checkRequirements() to
  47. * account for '@requires module'.
  48. */
  49. abstract class KernelTestBase extends \PHPUnit_Framework_TestCase implements ServiceProviderInterface {
  50. use AssertLegacyTrait;
  51. use AssertContentTrait;
  52. use AssertHelperTrait;
  53. use RandomGeneratorTrait;
  54. use ConfigTestTrait;
  55. /**
  56. * {@inheritdoc}
  57. *
  58. * Back up and restore any global variables that may be changed by tests.
  59. *
  60. * @see self::runTestInSeparateProcess
  61. */
  62. protected $backupGlobals = TRUE;
  63. /**
  64. * {@inheritdoc}
  65. *
  66. * Kernel tests are run in separate processes because they allow autoloading
  67. * of code from extensions. Running the test in a separate process isolates
  68. * this behavior from other tests. Subclasses should not override this
  69. * property.
  70. */
  71. protected $runTestInSeparateProcess = TRUE;
  72. /**
  73. * {@inheritdoc}
  74. *
  75. * Back up and restore static class properties that may be changed by tests.
  76. *
  77. * @see self::runTestInSeparateProcess
  78. */
  79. protected $backupStaticAttributes = TRUE;
  80. /**
  81. * {@inheritdoc}
  82. *
  83. * Contains a few static class properties for performance.
  84. */
  85. protected $backupStaticAttributesBlacklist = [
  86. // Ignore static discovery/parser caches to speed up tests.
  87. 'Drupal\Component\Discovery\YamlDiscovery' => ['parsedFiles'],
  88. 'Drupal\Core\DependencyInjection\YamlFileLoader' => ['yaml'],
  89. 'Drupal\Core\Extension\ExtensionDiscovery' => ['files'],
  90. 'Drupal\Core\Extension\InfoParser' => ['parsedInfos'],
  91. // Drupal::$container cannot be serialized.
  92. 'Drupal' => ['container'],
  93. // Settings cannot be serialized.
  94. 'Drupal\Core\Site\Settings' => ['instance'],
  95. ];
  96. /**
  97. * {@inheritdoc}
  98. *
  99. * Do not forward any global state from the parent process to the processes
  100. * that run the actual tests.
  101. *
  102. * @see self::runTestInSeparateProcess
  103. */
  104. protected $preserveGlobalState = FALSE;
  105. /**
  106. * @var \Composer\Autoload\Classloader
  107. */
  108. protected $classLoader;
  109. /**
  110. * @var string
  111. */
  112. protected $siteDirectory;
  113. /**
  114. * @var string
  115. */
  116. protected $databasePrefix;
  117. /**
  118. * @var \Drupal\Core\DependencyInjection\ContainerBuilder
  119. */
  120. protected $container;
  121. /**
  122. * Modules to enable.
  123. *
  124. * The test runner will merge the $modules lists from this class, the class
  125. * it extends, and so on up the class hierarchy. It is not necessary to
  126. * include modules in your list that a parent class has already declared.
  127. *
  128. * @see \Drupal\Tests\KernelTestBase::enableModules()
  129. * @see \Drupal\Tests\KernelTestBase::bootKernel()
  130. *
  131. * @var array
  132. */
  133. protected static $modules = [];
  134. /**
  135. * The virtual filesystem root directory.
  136. *
  137. * @var \org\bovigo\vfs\vfsStreamDirectory
  138. */
  139. protected $vfsRoot;
  140. /**
  141. * @var int
  142. */
  143. protected $expectedLogSeverity;
  144. /**
  145. * @var string
  146. */
  147. protected $expectedLogMessage;
  148. /**
  149. * @todo Move into Config test base class.
  150. * @var \Drupal\Core\Config\ConfigImporter
  151. */
  152. protected $configImporter;
  153. /**
  154. * The app root.
  155. *
  156. * @var string
  157. */
  158. protected $root;
  159. /**
  160. * Set to TRUE to strict check all configuration saved.
  161. *
  162. * @see \Drupal\Core\Config\Development\ConfigSchemaChecker
  163. *
  164. * @var bool
  165. */
  166. protected $strictConfigSchema = TRUE;
  167. /**
  168. * An array of config object names that are excluded from schema checking.
  169. *
  170. * @var string[]
  171. */
  172. protected static $configSchemaCheckerExclusions = [
  173. // Following are used to test lack of or partial schema. Where partial
  174. // schema is provided, that is explicitly tested in specific tests.
  175. 'config_schema_test.noschema',
  176. 'config_schema_test.someschema',
  177. 'config_schema_test.schema_data_types',
  178. 'config_schema_test.no_schema_data_types',
  179. // Used to test application of schema to filtering of configuration.
  180. 'config_test.dynamic.system',
  181. ];
  182. /**
  183. * {@inheritdoc}
  184. */
  185. public static function setUpBeforeClass() {
  186. parent::setUpBeforeClass();
  187. // Change the current dir to DRUPAL_ROOT.
  188. chdir(static::getDrupalRoot());
  189. }
  190. /**
  191. * Returns the drupal root directory.
  192. *
  193. * @return string
  194. */
  195. protected static function getDrupalRoot() {
  196. return dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
  197. }
  198. /**
  199. * {@inheritdoc}
  200. */
  201. protected function setUp() {
  202. parent::setUp();
  203. $this->root = static::getDrupalRoot();
  204. $this->initFileCache();
  205. $this->bootEnvironment();
  206. $this->bootKernel();
  207. }
  208. /**
  209. * Bootstraps a basic test environment.
  210. *
  211. * Should not be called by tests. Only visible for DrupalKernel integration
  212. * tests.
  213. *
  214. * @see \Drupal\system\Tests\DrupalKernel\DrupalKernelTest
  215. * @internal
  216. */
  217. protected function bootEnvironment() {
  218. $this->streamWrappers = [];
  219. \Drupal::unsetContainer();
  220. $this->classLoader = require $this->root . '/autoload.php';
  221. require_once $this->root . '/core/includes/bootstrap.inc';
  222. // Set up virtual filesystem.
  223. Database::addConnectionInfo('default', 'test-runner', $this->getDatabaseConnectionInfo()['default']);
  224. $test_db = new TestDatabase();
  225. $this->siteDirectory = $test_db->getTestSitePath();
  226. // Ensure that all code that relies on drupal_valid_test_ua() can still be
  227. // safely executed. This primarily affects the (test) site directory
  228. // resolution (used by e.g. LocalStream and PhpStorage).
  229. $this->databasePrefix = $test_db->getDatabasePrefix();
  230. drupal_valid_test_ua($this->databasePrefix);
  231. $settings = [
  232. 'hash_salt' => get_class($this),
  233. 'file_public_path' => $this->siteDirectory . '/files',
  234. // Disable Twig template caching/dumping.
  235. 'twig_cache' => FALSE,
  236. // @see \Drupal\KernelTests\KernelTestBase::register()
  237. ];
  238. new Settings($settings);
  239. $this->setUpFilesystem();
  240. foreach (Database::getAllConnectionInfo() as $key => $targets) {
  241. Database::removeConnection($key);
  242. }
  243. Database::addConnectionInfo('default', 'default', $this->getDatabaseConnectionInfo()['default']);
  244. }
  245. /**
  246. * Sets up the filesystem, so things like the file directory.
  247. */
  248. protected function setUpFilesystem() {
  249. $test_db = new TestDatabase($this->databasePrefix);
  250. $test_site_path = $test_db->getTestSitePath();
  251. $this->vfsRoot = vfsStream::setup('root');
  252. $this->vfsRoot->addChild(vfsStream::newDirectory($test_site_path));
  253. $this->siteDirectory = vfsStream::url('root/' . $test_site_path);
  254. mkdir($this->siteDirectory . '/files', 0775);
  255. mkdir($this->siteDirectory . '/files/config/' . CONFIG_SYNC_DIRECTORY, 0775, TRUE);
  256. $settings = Settings::getInstance() ? Settings::getAll() : [];
  257. $settings['file_public_path'] = $this->siteDirectory . '/files';
  258. new Settings($settings);
  259. $GLOBALS['config_directories'] = [
  260. CONFIG_SYNC_DIRECTORY => $this->siteDirectory . '/files/config/sync',
  261. ];
  262. }
  263. /**
  264. * @return string
  265. */
  266. public function getDatabasePrefix() {
  267. return $this->databasePrefix;
  268. }
  269. /**
  270. * Bootstraps a kernel for a test.
  271. */
  272. private function bootKernel() {
  273. $this->setSetting('container_yamls', []);
  274. // Allow for test-specific overrides.
  275. $settings_services_file = $this->root . '/sites/default' . '/testing.services.yml';
  276. if (file_exists($settings_services_file)) {
  277. // Copy the testing-specific service overrides in place.
  278. $testing_services_file = $this->root . '/' . $this->siteDirectory . '/services.yml';
  279. copy($settings_services_file, $testing_services_file);
  280. $this->setSetting('container_yamls', [$testing_services_file]);
  281. }
  282. // Allow for global test environment overrides.
  283. if (file_exists($test_env = $this->root . '/sites/default/testing.services.yml')) {
  284. $GLOBALS['conf']['container_yamls']['testing'] = $test_env;
  285. }
  286. // Add this test class as a service provider.
  287. $GLOBALS['conf']['container_service_providers']['test'] = $this;
  288. $modules = self::getModulesToEnable(get_class($this));
  289. // Prepare a precompiled container for all tests of this class.
  290. // Substantially improves performance, since ContainerBuilder::compile()
  291. // is very expensive. Encourages testing best practices (small tests).
  292. // Normally a setUpBeforeClass() operation, but object scope is required to
  293. // inject $this test class instance as a service provider (see above).
  294. $rc = new \ReflectionClass(get_class($this));
  295. $test_method_count = count(array_filter($rc->getMethods(), function ($method) {
  296. // PHPUnit's @test annotations are intentionally ignored/not supported.
  297. return strpos($method->getName(), 'test') === 0;
  298. }));
  299. // Bootstrap the kernel. Do not use createFromRequest() to retain Settings.
  300. $kernel = new DrupalKernel('testing', $this->classLoader, FALSE);
  301. $kernel->setSitePath($this->siteDirectory);
  302. // Boot a new one-time container from scratch. Ensure to set the module list
  303. // upfront to avoid a subsequent rebuild.
  304. if ($modules && $extensions = $this->getExtensionsForModules($modules)) {
  305. $kernel->updateModules($extensions, $extensions);
  306. }
  307. // DrupalKernel::boot() is not sufficient as it does not invoke preHandle(),
  308. // which is required to initialize legacy global variables.
  309. $request = Request::create('/');
  310. $kernel->prepareLegacyRequest($request);
  311. // register() is only called if a new container was built/compiled.
  312. $this->container = $kernel->getContainer();
  313. // Ensure database tasks have been run.
  314. require_once __DIR__ . '/../../../includes/install.inc';
  315. $connection = Database::getConnection();
  316. $errors = db_installer_object($connection->driver())->runTasks();
  317. if (!empty($errors)) {
  318. $this->fail('Failed to run installer database tasks: ' . implode(', ', $errors));
  319. }
  320. if ($modules) {
  321. $this->container->get('module_handler')->loadAll();
  322. }
  323. $this->container->get('request_stack')->push($request);
  324. // Setup the destion to the be frontpage by default.
  325. \Drupal::destination()->set('/');
  326. // Write the core.extension configuration.
  327. // Required for ConfigInstaller::installDefaultConfig() to work.
  328. $this->container->get('config.storage')->write('core.extension', [
  329. 'module' => array_fill_keys($modules, 0),
  330. 'theme' => [],
  331. 'profile' => '',
  332. ]);
  333. $settings = Settings::getAll();
  334. $settings['php_storage']['default'] = [
  335. 'class' => '\Drupal\Component\PhpStorage\FileStorage',
  336. ];
  337. new Settings($settings);
  338. // Manually configure the test mail collector implementation to prevent
  339. // tests from sending out emails and collect them in state instead.
  340. // While this should be enforced via settings.php prior to installation,
  341. // some tests expect to be able to test mail system implementations.
  342. $GLOBALS['config']['system.mail']['interface']['default'] = 'test_mail_collector';
  343. // Manually configure the default file scheme so that modules that use file
  344. // functions don't have to install system and its configuration.
  345. // @see file_default_scheme()
  346. $GLOBALS['config']['system.file']['default_scheme'] = 'public';
  347. }
  348. /**
  349. * Configuration accessor for tests. Returns non-overridden configuration.
  350. *
  351. * @param string $name
  352. * The configuration name.
  353. *
  354. * @return \Drupal\Core\Config\Config
  355. * The configuration object with original configuration data.
  356. */
  357. protected function config($name) {
  358. return $this->container->get('config.factory')->getEditable($name);
  359. }
  360. /**
  361. * Returns the Database connection info to be used for this test.
  362. *
  363. * This method only exists for tests of the Database component itself, because
  364. * they require multiple database connections. Each SQLite :memory: connection
  365. * creates a new/separate database in memory. A shared-memory SQLite file URI
  366. * triggers PHP open_basedir/allow_url_fopen/allow_url_include restrictions.
  367. * Due to that, Database tests are running against a SQLite database that is
  368. * located in an actual file in the system's temporary directory.
  369. *
  370. * Other tests should not override this method.
  371. *
  372. * @return array
  373. * A Database connection info array.
  374. *
  375. * @internal
  376. */
  377. protected function getDatabaseConnectionInfo() {
  378. // If the test is run with argument dburl then use it.
  379. $db_url = getenv('SIMPLETEST_DB');
  380. if (empty($db_url)) {
  381. 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.');
  382. }
  383. else {
  384. $database = Database::convertDbUrlToConnectionInfo($db_url, $this->root);
  385. Database::addConnectionInfo('default', 'default', $database);
  386. }
  387. // Clone the current connection and replace the current prefix.
  388. $connection_info = Database::getConnectionInfo('default');
  389. if (!empty($connection_info)) {
  390. Database::renameConnection('default', 'simpletest_original_default');
  391. foreach ($connection_info as $target => $value) {
  392. // Replace the full table prefix definition to ensure that no table
  393. // prefixes of the test runner leak into the test.
  394. $connection_info[$target]['prefix'] = [
  395. 'default' => $value['prefix']['default'] . $this->databasePrefix,
  396. ];
  397. }
  398. }
  399. return $connection_info;
  400. }
  401. /**
  402. * Initializes the FileCache component.
  403. *
  404. * We can not use the Settings object in a component, that's why we have to do
  405. * it here instead of \Drupal\Component\FileCache\FileCacheFactory.
  406. */
  407. protected function initFileCache() {
  408. $configuration = Settings::get('file_cache');
  409. // Provide a default configuration, if not set.
  410. if (!isset($configuration['default'])) {
  411. // @todo Use extension_loaded('apcu') for non-testbot
  412. // https://www.drupal.org/node/2447753.
  413. if (function_exists('apcu_fetch')) {
  414. $configuration['default']['cache_backend_class'] = ApcuFileCacheBackend::class;
  415. }
  416. }
  417. FileCacheFactory::setConfiguration($configuration);
  418. FileCacheFactory::setPrefix(Settings::getApcuPrefix('file_cache', $this->root));
  419. }
  420. /**
  421. * Returns Extension objects for $modules to enable.
  422. *
  423. * @param string[] $modules
  424. * The list of modules to enable.
  425. *
  426. * @return \Drupal\Core\Extension\Extension[]
  427. * Extension objects for $modules, keyed by module name.
  428. *
  429. * @throws \PHPUnit_Framework_Exception
  430. * If a module is not available.
  431. *
  432. * @see \Drupal\Tests\KernelTestBase::enableModules()
  433. * @see \Drupal\Core\Extension\ModuleHandler::add()
  434. */
  435. private function getExtensionsForModules(array $modules) {
  436. $extensions = [];
  437. $discovery = new ExtensionDiscovery($this->root);
  438. $discovery->setProfileDirectories([]);
  439. $list = $discovery->scan('module');
  440. foreach ($modules as $name) {
  441. if (!isset($list[$name])) {
  442. throw new \PHPUnit_Framework_Exception("Unavailable module: '$name'. If this module needs to be downloaded separately, annotate the test class with '@requires module $name'.");
  443. }
  444. $extensions[$name] = $list[$name];
  445. }
  446. return $extensions;
  447. }
  448. /**
  449. * Registers test-specific services.
  450. *
  451. * Extend this method in your test to register additional services. This
  452. * method is called whenever the kernel is rebuilt.
  453. *
  454. * @param \Drupal\Core\DependencyInjection\ContainerBuilder $container
  455. * The service container to enhance.
  456. *
  457. * @see \Drupal\Tests\KernelTestBase::bootKernel()
  458. */
  459. public function register(ContainerBuilder $container) {
  460. // Keep the container object around for tests.
  461. $this->container = $container;
  462. $container
  463. ->register('flood', 'Drupal\Core\Flood\MemoryBackend')
  464. ->addArgument(new Reference('request_stack'));
  465. $container
  466. ->register('lock', 'Drupal\Core\Lock\NullLockBackend');
  467. $container
  468. ->register('cache_factory', 'Drupal\Core\Cache\MemoryBackendFactory');
  469. $container
  470. ->register('keyvalue.memory', 'Drupal\Core\KeyValueStore\KeyValueMemoryFactory')
  471. // Must persist container rebuilds, or all data would vanish otherwise.
  472. ->addTag('persist');
  473. $container
  474. ->setAlias('keyvalue', 'keyvalue.memory');
  475. // Set the default language on the minimal container.
  476. $container->setParameter('language.default_values', Language::$defaultValues);
  477. if ($this->strictConfigSchema) {
  478. $container
  479. ->register('simpletest.config_schema_checker', ConfigSchemaChecker::class)
  480. ->addArgument(new Reference('config.typed'))
  481. ->addArgument($this->getConfigSchemaExclusions())
  482. ->addTag('event_subscriber');
  483. }
  484. if ($container->hasDefinition('path_processor_alias')) {
  485. // Prevent the alias-based path processor, which requires a url_alias db
  486. // table, from being registered to the path processor manager. We do this
  487. // by removing the tags that the compiler pass looks for. This means the
  488. // url generator can safely be used within tests.
  489. $container->getDefinition('path_processor_alias')
  490. ->clearTag('path_processor_inbound')
  491. ->clearTag('path_processor_outbound');
  492. }
  493. if ($container->hasDefinition('password')) {
  494. $container->getDefinition('password')
  495. ->setArguments([1]);
  496. }
  497. TestServiceProvider::addRouteProvider($container);
  498. }
  499. /**
  500. * Gets the config schema exclusions for this test.
  501. *
  502. * @return string[]
  503. * An array of config object names that are excluded from schema checking.
  504. */
  505. protected function getConfigSchemaExclusions() {
  506. $class = get_class($this);
  507. $exceptions = [];
  508. while ($class) {
  509. if (property_exists($class, 'configSchemaCheckerExclusions')) {
  510. $exceptions = array_merge($exceptions, $class::$configSchemaCheckerExclusions);
  511. }
  512. $class = get_parent_class($class);
  513. }
  514. // Filter out any duplicates.
  515. return array_unique($exceptions);
  516. }
  517. /**
  518. * {@inheritdoc}
  519. */
  520. protected function assertPostConditions() {
  521. // Execute registered Drupal shutdown functions prior to tearing down.
  522. // @see _drupal_shutdown_function()
  523. $callbacks = &drupal_register_shutdown_function();
  524. while ($callback = array_shift($callbacks)) {
  525. call_user_func_array($callback['callback'], $callback['arguments']);
  526. }
  527. // Shut down the kernel (if bootKernel() was called).
  528. // @see \Drupal\KernelTests\Core\DrupalKernel\DrupalKernelTest
  529. if ($this->container) {
  530. $this->container->get('kernel')->shutdown();
  531. }
  532. // Fail in case any (new) shutdown functions exist.
  533. $this->assertCount(0, drupal_register_shutdown_function(), 'Unexpected Drupal shutdown callbacks exist after running shutdown functions.');
  534. parent::assertPostConditions();
  535. }
  536. /**
  537. * {@inheritdoc}
  538. */
  539. protected function tearDown() {
  540. // Destroy the testing kernel.
  541. if (isset($this->kernel)) {
  542. $this->kernel->shutdown();
  543. }
  544. // Remove all prefixed tables.
  545. $original_connection_info = Database::getConnectionInfo('simpletest_original_default');
  546. $original_prefix = $original_connection_info['default']['prefix']['default'];
  547. $test_connection_info = Database::getConnectionInfo('default');
  548. $test_prefix = $test_connection_info['default']['prefix']['default'];
  549. if ($original_prefix != $test_prefix) {
  550. $tables = Database::getConnection()->schema()->findTables('%');
  551. foreach ($tables as $table) {
  552. if (Database::getConnection()->schema()->dropTable($table)) {
  553. unset($tables[$table]);
  554. }
  555. }
  556. }
  557. // Free up memory: Own properties.
  558. $this->classLoader = NULL;
  559. $this->vfsRoot = NULL;
  560. $this->configImporter = NULL;
  561. // Free up memory: Custom test class properties.
  562. // Note: Private properties cannot be cleaned up.
  563. $rc = new \ReflectionClass(__CLASS__);
  564. $blacklist = [];
  565. foreach ($rc->getProperties() as $property) {
  566. $blacklist[$property->name] = $property->getDeclaringClass()->name;
  567. }
  568. $rc = new \ReflectionClass($this);
  569. foreach ($rc->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED) as $property) {
  570. if (!$property->isStatic() && !isset($blacklist[$property->name])) {
  571. $this->{$property->name} = NULL;
  572. }
  573. }
  574. // Clean FileCache cache.
  575. FileCache::reset();
  576. // Clean up statics, container, and settings.
  577. if (function_exists('drupal_static_reset')) {
  578. drupal_static_reset();
  579. }
  580. \Drupal::unsetContainer();
  581. $this->container = NULL;
  582. new Settings([]);
  583. parent::tearDown();
  584. }
  585. /**
  586. * @after
  587. *
  588. * Additional tear down method to close the connection at the end.
  589. */
  590. public function tearDownCloseDatabaseConnection() {
  591. // Destroy the database connection, which for example removes the memory
  592. // from sqlite in memory.
  593. foreach (Database::getAllConnectionInfo() as $key => $targets) {
  594. Database::removeConnection($key);
  595. }
  596. }
  597. /**
  598. * Installs default configuration for a given list of modules.
  599. *
  600. * @param string|string[] $modules
  601. * A list of modules for which to install default configuration.
  602. *
  603. * @throws \LogicException
  604. * If any module in $modules is not enabled.
  605. */
  606. protected function installConfig($modules) {
  607. foreach ((array) $modules as $module) {
  608. if (!$this->container->get('module_handler')->moduleExists($module)) {
  609. throw new \LogicException("$module module is not enabled.");
  610. }
  611. $this->container->get('config.installer')->installDefaultConfig('module', $module);
  612. }
  613. }
  614. /**
  615. * Installs database tables from a module schema definition.
  616. *
  617. * @param string $module
  618. * The name of the module that defines the table's schema.
  619. * @param string|array $tables
  620. * The name or an array of the names of the tables to install.
  621. *
  622. * @throws \LogicException
  623. * If $module is not enabled or the table schema cannot be found.
  624. */
  625. protected function installSchema($module, $tables) {
  626. // drupal_get_module_schema() is technically able to install a schema
  627. // of a non-enabled module, but its ability to load the module's .install
  628. // file depends on many other factors. To prevent differences in test
  629. // behavior and non-reproducible test failures, we only allow the schema of
  630. // explicitly loaded/enabled modules to be installed.
  631. if (!$this->container->get('module_handler')->moduleExists($module)) {
  632. throw new \LogicException("$module module is not enabled.");
  633. }
  634. $tables = (array) $tables;
  635. foreach ($tables as $table) {
  636. $schema = drupal_get_module_schema($module, $table);
  637. if (empty($schema)) {
  638. // BC layer to avoid some contrib tests to fail.
  639. // @todo Remove the BC layer before 8.1.x release.
  640. // @see https://www.drupal.org/node/2670360
  641. // @see https://www.drupal.org/node/2670454
  642. if ($module == 'system') {
  643. continue;
  644. }
  645. throw new \LogicException("$module module does not define a schema for table '$table'.");
  646. }
  647. $this->container->get('database')->schema()->createTable($table, $schema);
  648. }
  649. }
  650. /**
  651. * Installs the storage schema for a specific entity type.
  652. *
  653. * @param string $entity_type_id
  654. * The ID of the entity type.
  655. */
  656. protected function installEntitySchema($entity_type_id) {
  657. /** @var \Drupal\Core\Entity\EntityManagerInterface $entity_manager */
  658. $entity_manager = $this->container->get('entity.manager');
  659. $entity_type = $entity_manager->getDefinition($entity_type_id);
  660. $entity_manager->onEntityTypeCreate($entity_type);
  661. // For test runs, the most common storage backend is a SQL database. For
  662. // this case, ensure the tables got created.
  663. $storage = $entity_manager->getStorage($entity_type_id);
  664. if ($storage instanceof SqlEntityStorageInterface) {
  665. $tables = $storage->getTableMapping()->getTableNames();
  666. $db_schema = $this->container->get('database')->schema();
  667. $all_tables_exist = TRUE;
  668. foreach ($tables as $table) {
  669. if (!$db_schema->tableExists($table)) {
  670. $this->fail(SafeMarkup::format('Installed entity type table for the %entity_type entity type: %table', [
  671. '%entity_type' => $entity_type_id,
  672. '%table' => $table,
  673. ]));
  674. $all_tables_exist = FALSE;
  675. }
  676. }
  677. if ($all_tables_exist) {
  678. $this->pass(SafeMarkup::format('Installed entity type tables for the %entity_type entity type: %tables', [
  679. '%entity_type' => $entity_type_id,
  680. '%tables' => '{' . implode('}, {', $tables) . '}',
  681. ]));
  682. }
  683. }
  684. }
  685. /**
  686. * Enables modules for this test.
  687. *
  688. * To install test modules outside of the testing environment, add
  689. * @code
  690. * $settings['extension_discovery_scan_tests'] = TRUE;
  691. * @endcode
  692. * to your settings.php.
  693. *
  694. * @param string[] $modules
  695. * A list of modules to enable. Dependencies are not resolved; i.e.,
  696. * multiple modules have to be specified individually. The modules are only
  697. * added to the active module list and loaded; i.e., their database schema
  698. * is not installed. hook_install() is not invoked. A custom module weight
  699. * is not applied.
  700. *
  701. * @throws \LogicException
  702. * If any module in $modules is already enabled.
  703. * @throws \RuntimeException
  704. * If a module is not enabled after enabling it.
  705. */
  706. protected function enableModules(array $modules) {
  707. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  708. if ($trace[1]['function'] === 'setUp') {
  709. trigger_error('KernelTestBase::enableModules() should not be called from setUp(). Use the $modules property instead.', E_USER_DEPRECATED);
  710. }
  711. unset($trace);
  712. // Perform an ExtensionDiscovery scan as this function may receive a
  713. // profile that is not the current profile, and we don't yet have a cached
  714. // way to receive inactive profile information.
  715. // @todo Remove as part of https://www.drupal.org/node/2186491
  716. $listing = new ExtensionDiscovery(\Drupal::root());
  717. $module_list = $listing->scan('module');
  718. // In ModuleHandlerTest we pass in a profile as if it were a module.
  719. $module_list += $listing->scan('profile');
  720. // Set the list of modules in the extension handler.
  721. $module_handler = $this->container->get('module_handler');
  722. // Write directly to active storage to avoid early instantiation of
  723. // the event dispatcher which can prevent modules from registering events.
  724. $active_storage = $this->container->get('config.storage');
  725. $extension_config = $active_storage->read('core.extension');
  726. foreach ($modules as $module) {
  727. if ($module_handler->moduleExists($module)) {
  728. throw new \LogicException("$module module is already enabled.");
  729. }
  730. $module_handler->addModule($module, $module_list[$module]->getPath());
  731. // Maintain the list of enabled modules in configuration.
  732. $extension_config['module'][$module] = 0;
  733. }
  734. $active_storage->write('core.extension', $extension_config);
  735. // Update the kernel to make their services available.
  736. $extensions = $module_handler->getModuleList();
  737. $this->container->get('kernel')->updateModules($extensions, $extensions);
  738. // Ensure isLoaded() is TRUE in order to make
  739. // \Drupal\Core\Theme\ThemeManagerInterface::render() work.
  740. // Note that the kernel has rebuilt the container; this $module_handler is
  741. // no longer the $module_handler instance from above.
  742. $module_handler = $this->container->get('module_handler');
  743. $module_handler->reload();
  744. foreach ($modules as $module) {
  745. if (!$module_handler->moduleExists($module)) {
  746. throw new \RuntimeException("$module module is not enabled after enabling it.");
  747. }
  748. }
  749. }
  750. /**
  751. * Disables modules for this test.
  752. *
  753. * @param string[] $modules
  754. * A list of modules to disable. Dependencies are not resolved; i.e.,
  755. * multiple modules have to be specified with dependent modules first.
  756. * Code of previously enabled modules is still loaded. The modules are only
  757. * removed from the active module list.
  758. *
  759. * @throws \LogicException
  760. * If any module in $modules is already disabled.
  761. * @throws \RuntimeException
  762. * If a module is not disabled after disabling it.
  763. */
  764. protected function disableModules(array $modules) {
  765. // Unset the list of modules in the extension handler.
  766. $module_handler = $this->container->get('module_handler');
  767. $module_filenames = $module_handler->getModuleList();
  768. $extension_config = $this->config('core.extension');
  769. foreach ($modules as $module) {
  770. if (!$module_handler->moduleExists($module)) {
  771. throw new \LogicException("$module module cannot be disabled because it is not enabled.");
  772. }
  773. unset($module_filenames[$module]);
  774. $extension_config->clear('module.' . $module);
  775. }
  776. $extension_config->save();
  777. $module_handler->setModuleList($module_filenames);
  778. $module_handler->resetImplementations();
  779. // Update the kernel to remove their services.
  780. $this->container->get('kernel')->updateModules($module_filenames, $module_filenames);
  781. // Ensure isLoaded() is TRUE in order to make
  782. // \Drupal\Core\Theme\ThemeManagerInterface::render() work.
  783. // Note that the kernel has rebuilt the container; this $module_handler is
  784. // no longer the $module_handler instance from above.
  785. $module_handler = $this->container->get('module_handler');
  786. $module_handler->reload();
  787. foreach ($modules as $module) {
  788. if ($module_handler->moduleExists($module)) {
  789. throw new \RuntimeException("$module module is not disabled after disabling it.");
  790. }
  791. }
  792. }
  793. /**
  794. * Renders a render array.
  795. *
  796. * @param array $elements
  797. * The elements to render.
  798. *
  799. * @return string
  800. * The rendered string output (typically HTML).
  801. */
  802. protected function render(array &$elements) {
  803. // \Drupal\Core\Render\BareHtmlPageRenderer::renderBarePage calls out to
  804. // system_page_attachments() directly.
  805. if (!\Drupal::moduleHandler()->moduleExists('system')) {
  806. throw new \Exception(__METHOD__ . ' requires system module to be installed.');
  807. }
  808. // Use the bare HTML page renderer to render our links.
  809. $renderer = $this->container->get('bare_html_page_renderer');
  810. $response = $renderer->renderBarePage($elements, '', 'maintenance_page');
  811. // Glean the content from the response object.
  812. $content = $response->getContent();
  813. $this->setRawContent($content);
  814. $this->verbose('<pre style="white-space: pre-wrap">' . Html::escape($content));
  815. return $content;
  816. }
  817. /**
  818. * Sets an in-memory Settings variable.
  819. *
  820. * @param string $name
  821. * The name of the setting to set.
  822. * @param bool|string|int|array|null $value
  823. * The value to set. Note that array values are replaced entirely; use
  824. * \Drupal\Core\Site\Settings::get() to perform custom merges.
  825. */
  826. protected function setSetting($name, $value) {
  827. $settings = Settings::getInstance() ? Settings::getAll() : [];
  828. $settings[$name] = $value;
  829. new Settings($settings);
  830. }
  831. /**
  832. * Stops test execution.
  833. */
  834. protected function stop() {
  835. $this->getTestResultObject()->stop();
  836. }
  837. /**
  838. * Dumps the current state of the virtual filesystem to STDOUT.
  839. */
  840. protected function vfsDump() {
  841. vfsStream::inspect(new vfsStreamPrintVisitor());
  842. }
  843. /**
  844. * Returns the modules to enable for this test.
  845. *
  846. * @param string $class
  847. * The fully-qualified class name of this test.
  848. *
  849. * @return array
  850. */
  851. private static function getModulesToEnable($class) {
  852. $modules = [];
  853. while ($class) {
  854. if (property_exists($class, 'modules')) {
  855. // Only add the modules, if the $modules property was not inherited.
  856. $rp = new \ReflectionProperty($class, 'modules');
  857. if ($rp->class == $class) {
  858. $modules[$class] = $class::$modules;
  859. }
  860. }
  861. $class = get_parent_class($class);
  862. }
  863. // Modules have been collected in reverse class hierarchy order; modules
  864. // defined by base classes should be sorted first. Then, merge the results
  865. // together.
  866. $modules = array_reverse($modules);
  867. return call_user_func_array('array_merge_recursive', $modules);
  868. }
  869. /**
  870. * {@inheritdoc}
  871. */
  872. protected function prepareTemplate(\Text_Template $template) {
  873. $bootstrap_globals = '';
  874. // Fix missing bootstrap.php when $preserveGlobalState is FALSE.
  875. // @see https://github.com/sebastianbergmann/phpunit/pull/797
  876. $bootstrap_globals .= '$__PHPUNIT_BOOTSTRAP = ' . var_export($GLOBALS['__PHPUNIT_BOOTSTRAP'], TRUE) . ";\n";
  877. // Avoid repetitive test namespace discoveries to improve performance.
  878. // @see /core/tests/bootstrap.php
  879. $bootstrap_globals .= '$namespaces = ' . var_export($GLOBALS['namespaces'], TRUE) . ";\n";
  880. $template->setVar([
  881. 'constants' => '',
  882. 'included_files' => '',
  883. 'globals' => $bootstrap_globals,
  884. ]);
  885. }
  886. /**
  887. * Returns whether the current test method is running in a separate process.
  888. *
  889. * Note that KernelTestBase will run in a separate process by default.
  890. *
  891. * @return bool
  892. *
  893. * @see \Drupal\KernelTests\KernelTestBase::$runTestInSeparateProcess
  894. * @see https://github.com/sebastianbergmann/phpunit/pull/1350
  895. *
  896. * @deprecated in Drupal 8.4.x, for removal before the Drupal 9.0.0 release.
  897. * KernelTestBase tests are always run in isolated processes.
  898. */
  899. protected function isTestInIsolation() {
  900. @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);
  901. return function_exists('__phpunit_run_isolated_test');
  902. }
  903. /**
  904. * BC: Automatically resolve former KernelTestBase class properties.
  905. *
  906. * Test authors should follow the provided instructions and adjust their tests
  907. * accordingly.
  908. *
  909. * @deprecated in Drupal 8.0.x, will be removed before Drupal 8.2.0.
  910. */
  911. public function __get($name) {
  912. if (in_array($name, [
  913. 'public_files_directory',
  914. 'private_files_directory',
  915. 'temp_files_directory',
  916. 'translation_files_directory',
  917. ])) {
  918. // @comment it in again.
  919. trigger_error(sprintf("KernelTestBase::\$%s no longer exists. Use the regular API method to retrieve it instead (e.g., Settings).", $name), E_USER_DEPRECATED);
  920. switch ($name) {
  921. case 'public_files_directory':
  922. return Settings::get('file_public_path', \Drupal::service('site.path') . '/files');
  923. case 'private_files_directory':
  924. return Settings::get('file_private_path');
  925. case 'temp_files_directory':
  926. return file_directory_temp();
  927. case 'translation_files_directory':
  928. return Settings::get('file_public_path', \Drupal::service('site.path') . '/translations');
  929. }
  930. }
  931. if ($name === 'configDirectories') {
  932. trigger_error(sprintf("KernelTestBase::\$%s no longer exists. Use config_get_config_directory() directly instead.", $name), E_USER_DEPRECATED);
  933. return [
  934. CONFIG_SYNC_DIRECTORY => config_get_config_directory(CONFIG_SYNC_DIRECTORY),
  935. ];
  936. }
  937. $denied = [
  938. // @see \Drupal\simpletest\TestBase
  939. 'testId',
  940. 'timeLimit',
  941. 'results',
  942. 'assertions',
  943. 'skipClasses',
  944. 'verbose',
  945. 'verboseId',
  946. 'verboseClassName',
  947. 'verboseDirectory',
  948. 'verboseDirectoryUrl',
  949. 'dieOnFail',
  950. 'kernel',
  951. // @see \Drupal\simpletest\TestBase::prepareEnvironment()
  952. 'generatedTestFiles',
  953. // Properties from the old KernelTestBase class that has been removed.
  954. 'keyValueFactory',
  955. ];
  956. if (in_array($name, $denied) || strpos($name, 'original') === 0) {
  957. throw new \RuntimeException(sprintf('TestBase::$%s property no longer exists', $name));
  958. }
  959. }
  960. /**
  961. * Prevents serializing any properties.
  962. *
  963. * Kernel tests are run in a separate process. To do this PHPUnit creates a
  964. * script to run the test. If it fails, the test result object will contain a
  965. * stack trace which includes the test object. It will attempt to serialize
  966. * it. Returning an empty array prevents it from serializing anything it
  967. * should not.
  968. *
  969. * @return array
  970. * An empty array.
  971. *
  972. * @see vendor/phpunit/phpunit/src/Util/PHP/Template/TestCaseMethod.tpl.dist
  973. */
  974. public function __sleep() {
  975. return [];
  976. }
  977. /**
  978. * {@inheritdoc}
  979. */
  980. public static function assertEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE) {
  981. // Cast objects implementing MarkupInterface to string instead of
  982. // relying on PHP casting them to string depending on what they are being
  983. // comparing with.
  984. $expected = static::castSafeStrings($expected);
  985. $actual = static::castSafeStrings($actual);
  986. parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase);
  987. }
  988. }