Further Drupal 8.6.4 changes. Some core files were not committed before a commit...
[yaffs-website] / web / core / modules / simpletest / src / Tests / KernelTestBaseTest.php
1 <?php
2
3 namespace Drupal\simpletest\Tests;
4
5 use Drupal\Core\Database\Database;
6 use Drupal\field\Entity\FieldConfig;
7 use Drupal\simpletest\KernelTestBase;
8 use Drupal\field\Entity\FieldStorageConfig;
9 use Drupal\Core\Entity\Entity\EntityViewDisplay;
10
11 /**
12  * Tests KernelTestBase functionality.
13  *
14  * @group simpletest
15  */
16 class KernelTestBaseTest extends KernelTestBase {
17
18   /**
19    * Modules to enable.
20    *
21    * @var array
22    */
23   public static $modules = ['entity_test'];
24
25   /**
26    * {@inheritdoc}
27    */
28   protected function setUp() {
29     $php = <<<'EOS'
30 <?php
31 # Make sure that the $test_class variable is defined when this file is included.
32 if ($test_class) {
33 }
34
35 # Define a function to be able to check that this file was loaded with
36 # function_exists().
37 if (!function_exists('simpletest_test_stub_settings_function')) {
38   function simpletest_test_stub_settings_function() {}
39 }
40 EOS;
41
42     $settings_testing_file = $this->siteDirectory . '/settings.testing.php';
43     file_put_contents($settings_testing_file, $php);
44
45     $original_container = $this->originalContainer;
46     parent::setUp();
47     $this->assertNotIdentical(\Drupal::getContainer(), $original_container, 'KernelTestBase test creates a new container.');
48   }
49
50   /**
51    * Tests expected behavior of setUp().
52    */
53   public function testSetUp() {
54     $modules = ['entity_test'];
55     $table = 'entity_test';
56
57     // Verify that specified $modules have been loaded.
58     $this->assertTrue(function_exists('entity_test_entity_bundle_info'), 'entity_test.module was loaded.');
59     // Verify that there is a fixed module list.
60     $this->assertIdentical(array_keys(\Drupal::moduleHandler()->getModuleList()), $modules);
61     $this->assertIdentical(\Drupal::moduleHandler()->getImplementations('entity_bundle_info'), ['entity_test']);
62     $this->assertIdentical(\Drupal::moduleHandler()->getImplementations('entity_type_alter'), ['entity_test']);
63
64     // Verify that no modules have been installed.
65     $this->assertFalse(Database::getConnection()->schema()->tableExists($table), "'$table' database table not found.");
66
67     // Verify that the settings.testing.php got taken into account.
68     $this->assertTrue(function_exists('simpletest_test_stub_settings_function'));
69
70     // Ensure that the database tasks have been run during set up. Neither MySQL
71     // nor SQLite make changes that are testable.
72     $database = $this->container->get('database');
73     if ($database->driver() == 'pgsql') {
74       $this->assertEqual('on', $database->query("SHOW standard_conforming_strings")->fetchField());
75       $this->assertEqual('escape', $database->query("SHOW bytea_output")->fetchField());
76     }
77   }
78
79   /**
80    * Tests expected load behavior of enableModules().
81    */
82   public function testEnableModulesLoad() {
83     $module = 'field_test';
84
85     // Verify that the module does not exist yet.
86     $this->assertFalse(\Drupal::moduleHandler()->moduleExists($module), "$module module not found.");
87     $list = array_keys(\Drupal::moduleHandler()->getModuleList());
88     $this->assertFalse(in_array($module, $list), "$module module not found in the extension handler's module list.");
89     $list = \Drupal::moduleHandler()->getImplementations('entity_display_build_alter');
90     $this->assertFalse(in_array($module, $list), "{$module}_entity_display_build_alter() in \Drupal::moduleHandler()->getImplementations() not found.");
91
92     // Enable the module.
93     $this->enableModules([$module]);
94
95     // Verify that the module exists.
96     $this->assertTrue(\Drupal::moduleHandler()->moduleExists($module), "$module module found.");
97     $list = array_keys(\Drupal::moduleHandler()->getModuleList());
98     $this->assertTrue(in_array($module, $list), "$module module found in the extension handler's module list.");
99     $list = \Drupal::moduleHandler()->getImplementations('query_efq_table_prefixing_test_alter');
100     $this->assertTrue(in_array($module, $list), "{$module}_query_efq_table_prefixing_test_alter() in \Drupal::moduleHandler()->getImplementations() found.");
101   }
102
103   /**
104    * Tests expected installation behavior of enableModules().
105    */
106   public function testEnableModulesInstall() {
107     $module = 'module_test';
108     $table = 'module_test';
109
110     // Verify that the module does not exist yet.
111     $this->assertFalse(\Drupal::moduleHandler()->moduleExists($module), "$module module not found.");
112     $list = array_keys(\Drupal::moduleHandler()->getModuleList());
113     $this->assertFalse(in_array($module, $list), "$module module not found in the extension handler's module list.");
114     $list = \Drupal::moduleHandler()->getImplementations('hook_info');
115     $this->assertFalse(in_array($module, $list), "{$module}_hook_info() in \Drupal::moduleHandler()->getImplementations() not found.");
116
117     $this->assertFalse(Database::getConnection()->schema()->tableExists($table), "'$table' database table not found.");
118
119     // Install the module.
120     \Drupal::service('module_installer')->install([$module]);
121
122     // Verify that the enabled module exists.
123     $this->assertTrue(\Drupal::moduleHandler()->moduleExists($module), "$module module found.");
124     $list = array_keys(\Drupal::moduleHandler()->getModuleList());
125     $this->assertTrue(in_array($module, $list), "$module module found in the extension handler's module list.");
126     $list = \Drupal::moduleHandler()->getImplementations('hook_info');
127     $this->assertTrue(in_array($module, $list), "{$module}_hook_info() in \Drupal::moduleHandler()->getImplementations() found.");
128
129     $this->assertTrue(Database::getConnection()->schema()->tableExists($table), "'$table' database table found.");
130     $schema = drupal_get_module_schema($module, $table);
131     $this->assertTrue($schema, "'$table' table schema found.");
132   }
133
134   /**
135    * Tests installing modules with DependencyInjection services.
136    */
137   public function testEnableModulesInstallContainer() {
138     // Install Node module.
139     $this->enableModules(['user', 'field', 'node']);
140
141     $this->installEntitySchema('node', ['node', 'node_field_data']);
142     // Perform an entity query against node.
143     $query = \Drupal::entityQuery('node');
144     // Disable node access checks, since User module is not enabled.
145     $query->accessCheck(FALSE);
146     $query->condition('nid', 1);
147     $query->execute();
148     $this->pass('Entity field query was executed.');
149   }
150
151   /**
152    * Tests expected behavior of installSchema().
153    */
154   public function testInstallSchema() {
155     $module = 'entity_test';
156     $table = 'entity_test_example';
157     // Verify that we can install a table from the module schema.
158     $this->installSchema($module, $table);
159     $this->assertTrue(Database::getConnection()->schema()->tableExists($table), "'$table' database table found.");
160
161     // Verify that the schema is known to Schema API.
162     $schema = drupal_get_module_schema($module, $table);
163     $this->assertTrue($schema, "'$table' table schema found.");
164
165     // Verify that a unknown table from an enabled module throws an error.
166     $table = 'unknown_entity_test_table';
167     try {
168       $this->installSchema($module, $table);
169       $this->fail('Exception for non-retrievable schema found.');
170     }
171     catch (\Exception $e) {
172       $this->pass('Exception for non-retrievable schema found.');
173     }
174     $this->assertFalse(Database::getConnection()->schema()->tableExists($table), "'$table' database table not found.");
175     $schema = drupal_get_module_schema($module, $table);
176     $this->assertFalse($schema, "'$table' table schema not found.");
177
178     // Verify that a table from a unknown module cannot be installed.
179     $module = 'database_test';
180     $table = 'test';
181     try {
182       $this->installSchema($module, $table);
183       $this->fail('Exception for non-retrievable schema found.');
184     }
185     catch (\Exception $e) {
186       $this->pass('Exception for non-retrievable schema found.');
187     }
188     $this->assertFalse(Database::getConnection()->schema()->tableExists($table), "'$table' database table not found.");
189     $schema = drupal_get_module_schema($module, $table);
190     $this->assertTrue($schema, "'$table' table schema found.");
191
192     // Verify that the same table can be installed after enabling the module.
193     $this->enableModules([$module]);
194     $this->installSchema($module, $table);
195     $this->assertTrue(Database::getConnection()->schema()->tableExists($table), "'$table' database table found.");
196     $schema = drupal_get_module_schema($module, $table);
197     $this->assertTrue($schema, "'$table' table schema found.");
198   }
199
200   /**
201    * Tests expected behavior of installEntitySchema().
202    */
203   public function testInstallEntitySchema() {
204     $entity = 'entity_test';
205     // The entity_test Entity has a field that depends on the User module.
206     $this->enableModules(['user']);
207     // Verity that the entity schema is created properly.
208     $this->installEntitySchema($entity);
209     $this->assertTrue(Database::getConnection()->schema()->tableExists($entity), "'$entity' database table found.");
210   }
211
212   /**
213    * Tests expected behavior of installConfig().
214    */
215   public function testInstallConfig() {
216     // The user module has configuration that depends on system.
217     $this->enableModules(['system']);
218     $module = 'user';
219
220     // Verify that default config can only be installed for enabled modules.
221     try {
222       $this->installConfig([$module]);
223       $this->fail('Exception for non-enabled module found.');
224     }
225     catch (\Exception $e) {
226       $this->pass('Exception for non-enabled module found.');
227     }
228     $this->assertFalse($this->container->get('config.storage')->exists('user.settings'));
229
230     // Verify that default config can be installed.
231     $this->enableModules(['user']);
232     $this->installConfig(['user']);
233     $this->assertTrue($this->container->get('config.storage')->exists('user.settings'));
234     $this->assertTrue($this->config('user.settings')->get('register'));
235   }
236
237   /**
238    * Tests that the module list is retained after enabling/installing/disabling.
239    */
240   public function testEnableModulesFixedList() {
241     // Install system module.
242     $this->container->get('module_installer')->install(['system', 'menu_link_content']);
243     $entity_manager = \Drupal::entityManager();
244
245     // entity_test is loaded via $modules; its entity type should exist.
246     $this->assertEqual($this->container->get('module_handler')->moduleExists('entity_test'), TRUE);
247     $this->assertTrue(TRUE == $entity_manager->getDefinition('entity_test'));
248
249     // Load some additional modules; entity_test should still exist.
250     $this->enableModules(['field', 'text', 'entity_test']);
251     $this->assertEqual($this->container->get('module_handler')->moduleExists('entity_test'), TRUE);
252     $this->assertTrue(TRUE == $entity_manager->getDefinition('entity_test'));
253
254     // Install some other modules; entity_test should still exist.
255     $this->container->get('module_installer')->install(['user', 'field', 'field_test'], FALSE);
256     $this->assertEqual($this->container->get('module_handler')->moduleExists('entity_test'), TRUE);
257     $this->assertTrue(TRUE == $entity_manager->getDefinition('entity_test'));
258
259     // Uninstall one of those modules; entity_test should still exist.
260     $this->container->get('module_installer')->uninstall(['field_test']);
261     $this->assertEqual($this->container->get('module_handler')->moduleExists('entity_test'), TRUE);
262     $this->assertTrue(TRUE == $entity_manager->getDefinition('entity_test'));
263
264     // Set the weight of a module; entity_test should still exist.
265     module_set_weight('field', -1);
266     $this->assertEqual($this->container->get('module_handler')->moduleExists('entity_test'), TRUE);
267     $this->assertTrue(TRUE == $entity_manager->getDefinition('entity_test'));
268
269     // Reactivate the previously uninstalled module.
270     $this->enableModules(['field_test']);
271
272     // Create a field.
273     $display = EntityViewDisplay::create([
274       'targetEntityType' => 'entity_test',
275       'bundle' => 'entity_test',
276       'mode' => 'default',
277     ]);
278     $field_storage = FieldStorageConfig::create([
279       'field_name' => 'test_field',
280       'entity_type' => 'entity_test',
281       'type' => 'test_field',
282     ]);
283     $field_storage->save();
284     FieldConfig::create([
285       'field_storage' => $field_storage,
286       'bundle' => 'entity_test',
287     ])->save();
288   }
289
290   /**
291    * Tests that ThemeManager works right after loading a module.
292    */
293   public function testEnableModulesTheme() {
294     /** @var \Drupal\Core\Render\RendererInterface $renderer */
295     $renderer = $this->container->get('renderer');
296     $original_element = $element = [
297       '#type' => 'container',
298       '#markup' => 'Foo',
299       '#attributes' => [],
300     ];
301     $this->enableModules(['system']);
302     // \Drupal\Core\Theme\ThemeManager::render() throws an exception if modules
303     // are not loaded yet.
304     $this->assertTrue($renderer->renderRoot($element));
305
306     $element = $original_element;
307     $this->disableModules(['entity_test']);
308     $this->assertTrue($renderer->renderRoot($element));
309   }
310
311   /**
312    * Tests that there is no theme by default.
313    */
314   public function testNoThemeByDefault() {
315     $themes = $this->config('core.extension')->get('theme');
316     $this->assertEqual($themes, []);
317
318     $extensions = $this->container->get('config.storage')->read('core.extension');
319     $this->assertEqual($extensions['theme'], []);
320
321     $active_theme = $this->container->get('theme.manager')->getActiveTheme();
322     $this->assertEqual($active_theme->getName(), 'core');
323   }
324
325   /**
326    * Tests that \Drupal::installProfile() returns NULL.
327    *
328    * As the currently active installation profile is used when installing
329    * configuration, for example, this is essential to ensure test isolation.
330    */
331   public function testDrupalGetProfile() {
332     $this->assertNull(\Drupal::installProfile());
333   }
334
335   /**
336    * {@inheritdoc}
337    */
338   public function run(array $methods = []) {
339     parent::run($methods);
340
341     // Check that all tables of the test instance have been deleted. At this
342     // point the original database connection is restored so we need to prefix
343     // the tables.
344     $connection = Database::getConnection();
345     if ($connection->databaseType() != 'sqlite') {
346       $tables = $connection->schema()->findTables($this->databasePrefix . '%');
347       $this->assertTrue(empty($tables), 'All test tables have been removed.');
348     }
349     else {
350       // We don't have the test instance connection anymore so we have to
351       // re-attach its database and then use the same query as
352       // \Drupal\Core\Database\Driver\sqlite\Schema::findTables().
353       // @see \Drupal\Core\Database\Driver\sqlite\Connection::__construct()
354       $info = Database::getConnectionInfo();
355       $connection->query('ATTACH DATABASE :database AS :prefix', [
356         ':database' => $info['default']['database'] . '-' . $this->databasePrefix,
357         ':prefix' => $this->databasePrefix,
358       ]);
359
360       $result = $connection->query("SELECT name FROM " . $this->databasePrefix . ".sqlite_master WHERE type = :type AND name LIKE :table_name AND name NOT LIKE :pattern", [
361         ':type' => 'table',
362         ':table_name' => '%',
363         ':pattern' => 'sqlite_%',
364       ])->fetchAllKeyed(0, 0);
365
366       $this->assertTrue(empty($result), 'All test tables have been removed.');
367     }
368   }
369
370 }