3 namespace Drupal\Core\Test;
5 use Drupal\Component\FileCache\FileCacheFactory;
6 use Drupal\Component\Utility\SafeMarkup;
7 use Drupal\Core\Cache\Cache;
8 use Drupal\Core\Config\Development\ConfigSchemaChecker;
9 use Drupal\Core\DrupalKernel;
10 use Drupal\Core\Extension\MissingDependencyException;
11 use Drupal\Core\Serialization\Yaml;
12 use Drupal\Core\Session\UserSession;
13 use Drupal\Core\Site\Settings;
14 use Symfony\Component\DependencyInjection\ContainerInterface;
15 use Symfony\Component\HttpFoundation\Request;
16 use Symfony\Component\Yaml\Yaml as SymfonyYaml;
19 * Defines a trait for shared functional test setup functionality.
21 trait FunctionalTestSetupTrait {
24 * The "#1" admin user.
26 * @var \Drupal\Core\Session\AccountInterface
31 * The class loader to use for installation and initialization of setup.
33 * @var \Symfony\Component\Classloader\Classloader
35 protected $classLoader;
38 * The config directories used in this test.
40 protected $configDirectories = [];
43 * Prepares site settings and services before installation.
45 protected function prepareSettings() {
46 // Prepare installer settings that are not install_drupal() parameters.
47 // Copy and prepare an actual settings.php, so as to resemble a regular
49 // Not using File API; a potential error must trigger a PHP warning.
50 $directory = DRUPAL_ROOT . '/' . $this->siteDirectory;
51 copy(DRUPAL_ROOT . '/sites/default/default.settings.php', $directory . '/settings.php');
53 // The public file system path is created during installation. Additionally,
55 // - The temporary directory is set and created by install_base_system().
56 // - The private file directory is created post install by
57 // FunctionalTestSetupTrait::initConfig().
58 // @see system_requirements()
59 // @see TestBase::prepareEnvironment()
60 // @see install_base_system()
61 // @see \Drupal\Core\Test\FunctionalTestSetupTrait::initConfig()
62 $settings['settings']['file_public_path'] = (object) [
63 'value' => $this->publicFilesDirectory,
66 $settings['settings']['file_private_path'] = (object) [
67 'value' => $this->privateFilesDirectory,
70 // Save the original site directory path, so that extensions in the
71 // site-specific directory can still be discovered in the test site
73 // @see \Drupal\Core\Extension\ExtensionDiscovery::scan()
74 $settings['settings']['test_parent_site'] = (object) [
75 'value' => $this->originalSite,
78 // Add the parent profile's search path to the child site's search paths.
79 // @see \Drupal\Core\Extension\ExtensionDiscovery::getProfileDirectories()
80 $settings['conf']['simpletest.settings']['parent_profile'] = (object) [
81 'value' => $this->originalProfile,
84 $this->writeSettings($settings);
85 // Allow for test-specific overrides.
86 $settings_testing_file = DRUPAL_ROOT . '/' . $this->originalSite . '/settings.testing.php';
87 if (file_exists($settings_testing_file)) {
88 // Copy the testing-specific settings.php overrides in place.
89 copy($settings_testing_file, $directory . '/settings.testing.php');
90 // Add the name of the testing class to settings.php and include the
91 // testing specific overrides.
92 file_put_contents($directory . '/settings.php', "\n\$test_class = '" . get_class($this) . "';\n" . 'include DRUPAL_ROOT . \'/\' . $site_path . \'/settings.testing.php\';' . "\n", FILE_APPEND);
94 $settings_services_file = DRUPAL_ROOT . '/' . $this->originalSite . '/testing.services.yml';
95 if (!file_exists($settings_services_file)) {
96 // Otherwise, use the default services as a starting point for overrides.
97 $settings_services_file = DRUPAL_ROOT . '/sites/default/default.services.yml';
99 // Copy the testing-specific service overrides in place.
100 copy($settings_services_file, $directory . '/services.yml');
101 if ($this->strictConfigSchema) {
102 // Add a listener to validate configuration schema on save.
103 $yaml = new SymfonyYaml();
104 $content = file_get_contents($directory . '/services.yml');
105 $services = $yaml->parse($content);
106 $services['services']['simpletest.config_schema_checker'] = [
107 'class' => ConfigSchemaChecker::class,
108 'arguments' => ['@config.typed', $this->getConfigSchemaExclusions()],
109 'tags' => [['name' => 'event_subscriber']],
111 file_put_contents($directory . '/services.yml', $yaml->dump($services));
113 // Since Drupal is bootstrapped already, install_begin_request() will not
114 // bootstrap again. Hence, we have to reload the newly written custom
115 // settings.php manually.
116 Settings::initialize(DRUPAL_ROOT, $this->siteDirectory, $this->classLoader);
120 * Rewrites the settings.php file of the test site.
122 * @param array $settings
123 * An array of settings to write out, in the format expected by
124 * drupal_rewrite_settings().
126 * @see drupal_rewrite_settings()
128 protected function writeSettings(array $settings) {
129 include_once DRUPAL_ROOT . '/core/includes/install.inc';
130 $filename = $this->siteDirectory . '/settings.php';
131 // system_requirements() removes write permissions from settings.php
132 // whenever it is invoked.
133 // Not using File API; a potential error must trigger a PHP warning.
134 chmod($filename, 0666);
135 drupal_rewrite_settings($settings, $filename);
139 * Changes parameters in the services.yml file.
141 * @param string $name
142 * The name of the parameter.
143 * @param string $value
144 * The value of the parameter.
146 protected function setContainerParameter($name, $value) {
147 $filename = $this->siteDirectory . '/services.yml';
148 chmod($filename, 0666);
150 $services = Yaml::decode(file_get_contents($filename));
151 $services['parameters'][$name] = $value;
152 file_put_contents($filename, Yaml::encode($services));
154 // Ensure that the cache is deleted for the yaml file loader.
155 $file_cache = FileCacheFactory::get('container_yaml_loader');
156 $file_cache->delete($filename);
160 * Rebuilds \Drupal::getContainer().
162 * Use this to update the test process's kernel with a new service container.
163 * For example, when the list of enabled modules is changed via the internal
164 * browser the test process's kernel has a service container with an out of
167 * @see TestBase::prepareEnvironment()
168 * @see TestBase::restoreEnvironment()
170 * @todo Fix https://www.drupal.org/node/2021959 so that module enable/disable
171 * changes are immediately reflected in \Drupal::getContainer(). Until then,
172 * tests can invoke this workaround when requiring services from newly
173 * enabled modules to be immediately available in the same request.
175 protected function rebuildContainer() {
176 // Rebuild the kernel and bring it back to a fully bootstrapped state.
177 $this->container = $this->kernel->rebuildContainer();
179 // Make sure the url generator has a request object, otherwise calls to
180 // $this->drupalGet() will fail.
181 $this->prepareRequestForGenerator();
185 * Resets all data structures after having enabled new modules.
187 * This method is called by FunctionalTestSetupTrait::rebuildAll() after
188 * enabling the requested modules. It must be called again when additional
189 * modules are enabled later.
191 * @see \Drupal\Core\Test\FunctionalTestSetupTrait::rebuildAll()
192 * @see \Drupal\Tests\BrowserTestBase::installDrupal()
193 * @see \Drupal\simpletest\WebTestBase::setUp()
195 protected function resetAll() {
196 // Clear all database and static caches and rebuild data structures.
197 drupal_flush_all_caches();
198 $this->container = \Drupal::getContainer();
200 // Reset static variables and reload permissions.
201 $this->refreshVariables();
205 * Refreshes in-memory configuration and state information.
207 * Useful after a page request is made that changes configuration or state in
208 * a different thread.
210 * In other words calling a settings page with $this->drupalPostForm() with a
211 * changed value would update configuration to reflect that change, but in the
212 * thread that made the call (thread running the test) the changed values
213 * would not be picked up.
215 * This method clears the cache and loads a fresh copy.
217 protected function refreshVariables() {
218 // Clear the tag cache.
219 \Drupal::service('cache_tags.invalidator')->resetChecksums();
220 foreach (Cache::getBins() as $backend) {
221 if (is_callable([$backend, 'reset'])) {
226 $this->container->get('config.factory')->reset();
227 $this->container->get('state')->resetCache();
231 * Creates a mock request and sets it on the generator.
233 * This is used to manipulate how the generator generates paths during tests.
234 * It also ensures that calls to $this->drupalGet() will work when running
235 * from run-tests.sh because the url generator no longer looks at the global
236 * variables that are set there but relies on getting this information from a
239 * @param bool $clean_urls
240 * Whether to mock the request using clean urls.
241 * @param array $override_server_vars
242 * An array of server variables to override.
244 * @return \Symfony\Component\HttpFoundation\Request
245 * The mocked request object.
247 protected function prepareRequestForGenerator($clean_urls = TRUE, $override_server_vars = []) {
248 $request = Request::createFromGlobals();
249 $server = $request->server->all();
250 if (basename($server['SCRIPT_FILENAME']) != basename($server['SCRIPT_NAME'])) {
251 // We need this for when the test is executed by run-tests.sh.
252 // @todo Remove this once run-tests.sh has been converted to use a Request
255 $server['SCRIPT_FILENAME'] = $cwd . '/' . basename($server['SCRIPT_NAME']);
256 $base_path = rtrim($server['REQUEST_URI'], '/');
259 $base_path = $request->getBasePath();
262 $request_path = $base_path ? $base_path . '/user' : 'user';
265 $request_path = $base_path ? $base_path . '/index.php/user' : '/index.php/user';
267 $server = array_merge($server, $override_server_vars);
269 $request = Request::create($request_path, 'GET', [], [], [], $server);
270 // Ensure the request time is REQUEST_TIME to ensure that API calls
271 // in the test use the right timestamp.
272 $request->server->set('REQUEST_TIME', REQUEST_TIME);
273 $this->container->get('request_stack')->push($request);
275 // The request context is normally set by the router_listener from within
276 // its KernelEvents::REQUEST listener. In the simpletest parent site this
277 // event is not fired, therefore it is necessary to updated the request
278 // context manually here.
279 $this->container->get('router.request_context')->fromRequest($request);
285 * Execute the non-interactive installer.
287 * @see install_drupal()
289 protected function doInstall() {
290 require_once DRUPAL_ROOT . '/core/includes/install.core.inc';
291 install_drupal($this->classLoader, $this->installParameters());
295 * Initialize settings created during install.
297 protected function initSettings() {
298 Settings::initialize(DRUPAL_ROOT, $this->siteDirectory, $this->classLoader);
299 foreach ($GLOBALS['config_directories'] as $type => $path) {
300 $this->configDirectories[$type] = $path;
303 // After writing settings.php, the installer removes write permissions
304 // from the site directory. To allow drupal_generate_test_ua() to write
305 // a file containing the private key for drupal_valid_test_ua(), the site
306 // directory has to be writable.
307 // TestBase::restoreEnvironment() will delete the entire site directory.
308 // Not using File API; a potential error must trigger a PHP warning.
309 chmod(DRUPAL_ROOT . '/' . $this->siteDirectory, 0777);
311 // During tests, cacheable responses should get the debugging cacheability
312 // headers by default.
313 $this->setContainerParameter('http.response.debug_cacheability_headers', TRUE);
317 * Initialize various configurations post-installation.
319 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
322 protected function initConfig(ContainerInterface $container) {
323 $config = $container->get('config.factory');
325 // Manually create the private directory.
326 file_prepare_directory($this->privateFilesDirectory, FILE_CREATE_DIRECTORY);
328 // Manually configure the test mail collector implementation to prevent
329 // tests from sending out emails and collect them in state instead.
330 // While this should be enforced via settings.php prior to installation,
331 // some tests expect to be able to test mail system implementations.
332 $config->getEditable('system.mail')
333 ->set('interface.default', 'test_mail_collector')
336 // By default, verbosely display all errors and disable all production
337 // environment optimizations for all tests to avoid needless overhead and
338 // ensure a sane default experience for test authors.
339 // @see https://www.drupal.org/node/2259167
340 $config->getEditable('system.logging')
341 ->set('error_level', 'verbose')
343 $config->getEditable('system.performance')
344 ->set('css.preprocess', FALSE)
345 ->set('js.preprocess', FALSE)
348 // Set an explicit time zone to not rely on the system one, which may vary
349 // from setup to setup. The Australia/Sydney time zone is chosen so all
350 // tests are run using an edge case scenario (UTC10 and DST). This choice
351 // is made to prevent time zone related regressions and reduce the
352 // fragility of the testing system in general.
353 $config->getEditable('system.date')
354 ->set('timezone.default', 'Australia/Sydney')
359 * Initializes user 1 for the site to be installed.
361 protected function initUserSession() {
362 $password = $this->randomMachineName();
363 // Define information about the user 1 account.
364 $this->rootUser = new UserSession([
367 'mail' => 'admin@example.com',
368 'pass_raw' => $password,
369 'passRaw' => $password,
370 'timezone' => date_default_timezone_get(),
373 // The child site derives its session name from the database prefix when
374 // running web tests.
375 $this->generateSessionName($this->databasePrefix);
379 * Initializes the kernel after installation.
381 * @param \Symfony\Component\HttpFoundation\Request $request
384 * @return \Symfony\Component\DependencyInjection\ContainerInterface
387 protected function initKernel(Request $request) {
388 $this->kernel = DrupalKernel::createFromRequest($request, $this->classLoader, 'prod', TRUE);
389 $this->kernel->prepareLegacyRequest($request);
390 // Force the container to be built from scratch instead of loaded from the
391 // disk. This forces us to not accidentally load the parent site.
392 return $this->kernel->rebuildContainer();
396 * Install modules defined by `static::$modules`.
398 * To install test modules outside of the testing environment, add
400 * $settings['extension_discovery_scan_tests'] = TRUE;
402 * to your settings.php.
404 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
407 protected function installModulesFromClassProperty(ContainerInterface $container) {
408 $class = get_class($this);
411 if (property_exists($class, 'modules')) {
412 $modules = array_merge($modules, $class::$modules);
414 $class = get_parent_class($class);
417 $modules = array_unique($modules);
419 $success = $container->get('module_installer')->install($modules, TRUE);
420 $this->assertTrue($success, SafeMarkup::format('Enabled modules: %modules', ['%modules' => implode(', ', $modules)]));
422 catch (MissingDependencyException $e) {
423 // The exception message has all the details.
424 $this->fail($e->getMessage());
427 $this->rebuildContainer();
432 * Resets and rebuilds the environment after setup.
434 protected function rebuildAll() {
435 // Reset/rebuild all data structures after enabling the modules, primarily
436 // to synchronize all data structures and caches between the test runner and
438 // @see \Drupal\Core\DrupalKernel::bootCode()
439 // @todo Test-specific setUp() methods may set up further fixtures; find a
440 // way to execute this after setUp() is done, or to eliminate it entirely.
442 $this->kernel->prepareLegacyRequest(\Drupal::request());
444 // Explicitly call register() again on the container registered in \Drupal.
445 // @todo This should already be called through
446 // DrupalKernel::prepareLegacyRequest() -> DrupalKernel::boot() but that
447 // appears to be calling a different container.
448 $this->container->get('stream_wrapper_manager')->register();