Drupal investigation

KernelTestBase.php 41KB

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