Pull merge.
[yaffs-website] / web / core / modules / system / tests / src / Kernel / Extension / ModuleHandlerTest.php
1 <?php
2
3 namespace Drupal\Tests\system\Kernel\Extension;
4
5 use Drupal\Core\Extension\MissingDependencyException;
6 use Drupal\Core\Extension\ModuleUninstallValidatorException;
7 use Drupal\entity_test\Entity\EntityTest;
8 use Drupal\KernelTests\KernelTestBase;
9
10 /**
11  * Tests ModuleHandler functionality.
12  *
13  * @group Extension
14  */
15 class ModuleHandlerTest extends KernelTestBase {
16
17   /**
18    * {@inheritdoc}
19    */
20   public static $modules = ['system'];
21
22   /**
23    * {@inheritdoc}
24    */
25   protected function setUp() {
26     parent::setUp();
27
28     // @todo ModuleInstaller calls system_rebuild_module_data which is part of
29     //   system.module, see https://www.drupal.org/node/2208429.
30     include_once $this->root . '/core/modules/system/system.module';
31
32     // Set up the state values so we know where to find the files when running
33     // drupal_get_filename().
34     // @todo Remove as part of https://www.drupal.org/node/2186491
35     system_rebuild_module_data();
36   }
37
38   /**
39    * The basic functionality of retrieving enabled modules.
40    */
41   public function testModuleList() {
42     $module_list = ['system'];
43
44     $this->assertModuleList($module_list, 'Initial');
45
46     // Try to install a new module.
47     $this->moduleInstaller()->install(['ban']);
48     $module_list[] = 'ban';
49     sort($module_list);
50     $this->assertModuleList($module_list, 'After adding a module');
51
52     // Try to mess with the module weights.
53     module_set_weight('ban', 20);
54
55     // Move ban to the end of the array.
56     unset($module_list[array_search('ban', $module_list)]);
57     $module_list[] = 'ban';
58     $this->assertModuleList($module_list, 'After changing weights');
59
60     // Test the fixed list feature.
61     $fixed_list = [
62       'system' => 'core/modules/system/system.module',
63       'menu' => 'core/modules/menu/menu.module',
64     ];
65     $this->moduleHandler()->setModuleList($fixed_list);
66     $new_module_list = array_combine(array_keys($fixed_list), array_keys($fixed_list));
67     $this->assertModuleList($new_module_list, t('When using a fixed list'));
68   }
69
70   /**
71    * Assert that the extension handler returns the expected values.
72    *
73    * @param array $expected_values
74    *   The expected values, sorted by weight and module name.
75    * @param $condition
76    */
77   protected function assertModuleList(array $expected_values, $condition) {
78     $expected_values = array_values(array_unique($expected_values));
79     $enabled_modules = array_keys($this->container->get('module_handler')->getModuleList());
80     $this->assertEqual($expected_values, $enabled_modules, format_string('@condition: extension handler returns correct results', ['@condition' => $condition]));
81   }
82
83   /**
84    * Tests dependency resolution.
85    *
86    * Intentionally using fake dependencies added via hook_system_info_alter()
87    * for modules that normally do not have any dependencies.
88    *
89    * To simplify things further, all of the manipulated modules are either
90    * purely UI-facing or live at the "bottom" of all dependency chains.
91    *
92    * @see module_test_system_info_alter()
93    * @see https://www.drupal.org/files/issues/dep.gv__0.png
94    */
95   public function testDependencyResolution() {
96     $this->enableModules(['module_test']);
97     $this->assertTrue($this->moduleHandler()->moduleExists('module_test'), 'Test module is enabled.');
98
99     // Ensure that modules are not enabled.
100     $this->assertFalse($this->moduleHandler()->moduleExists('color'), 'Color module is disabled.');
101     $this->assertFalse($this->moduleHandler()->moduleExists('config'), 'Config module is disabled.');
102     $this->assertFalse($this->moduleHandler()->moduleExists('help'), 'Help module is disabled.');
103
104     // Create a missing fake dependency.
105     // Color will depend on Config, which depends on a non-existing module Foo.
106     // Nothing should be installed.
107     \Drupal::state()->set('module_test.dependency', 'missing dependency');
108     \Drupal::service('extension.list.module')->reset();
109
110     try {
111       $result = $this->moduleInstaller()->install(['color']);
112       $this->fail(t('ModuleInstaller::install() throws an exception if dependencies are missing.'));
113     }
114     catch (MissingDependencyException $e) {
115       $this->pass(t('ModuleInstaller::install() throws an exception if dependencies are missing.'));
116     }
117
118     $this->assertFalse($this->moduleHandler()->moduleExists('color'), 'ModuleInstaller::install() aborts if dependencies are missing.');
119
120     // Fix the missing dependency.
121     // Color module depends on Config. Config depends on Help module.
122     \Drupal::state()->set('module_test.dependency', 'dependency');
123     \Drupal::service('extension.list.module')->reset();
124
125     $result = $this->moduleInstaller()->install(['color']);
126     $this->assertTrue($result, 'ModuleInstaller::install() returns the correct value.');
127
128     // Verify that the fake dependency chain was installed.
129     $this->assertTrue($this->moduleHandler()->moduleExists('config') && $this->moduleHandler()->moduleExists('help'), 'Dependency chain was installed.');
130
131     // Verify that the original module was installed.
132     $this->assertTrue($this->moduleHandler()->moduleExists('color'), 'Module installation with dependencies succeeded.');
133
134     // Verify that the modules were enabled in the correct order.
135     $module_order = \Drupal::state()->get('module_test.install_order') ?: [];
136     $this->assertEqual($module_order, ['help', 'config', 'color']);
137
138     // Uninstall all three modules explicitly, but in the incorrect order,
139     // and make sure that ModuleInstaller::uninstall() uninstalled them in the
140     // correct sequence.
141     $result = $this->moduleInstaller()->uninstall(['config', 'help', 'color']);
142     $this->assertTrue($result, 'ModuleInstaller::uninstall() returned TRUE.');
143
144     foreach (['color', 'config', 'help'] as $module) {
145       $this->assertEqual(drupal_get_installed_schema_version($module), SCHEMA_UNINSTALLED, "$module module was uninstalled.");
146     }
147     $uninstalled_modules = \Drupal::state()->get('module_test.uninstall_order') ?: [];
148     $this->assertEqual($uninstalled_modules, ['color', 'config', 'help'], 'Modules were uninstalled in the correct order.');
149
150     // Enable Color module again, which should enable both the Config module and
151     // Help module. But, this time do it with Config module declaring a
152     // dependency on a specific version of Help module in its info file. Make
153     // sure that Drupal\Core\Extension\ModuleInstaller::install() still works.
154     \Drupal::state()->set('module_test.dependency', 'version dependency');
155     \Drupal::service('extension.list.module')->reset();
156
157     $result = $this->moduleInstaller()->install(['color']);
158     $this->assertTrue($result, 'ModuleInstaller::install() returns the correct value.');
159
160     // Verify that the fake dependency chain was installed.
161     $this->assertTrue($this->moduleHandler()->moduleExists('config') && $this->moduleHandler()->moduleExists('help'), 'Dependency chain was installed.');
162
163     // Verify that the original module was installed.
164     $this->assertTrue($this->moduleHandler()->moduleExists('color'), 'Module installation with version dependencies succeeded.');
165
166     // Finally, verify that the modules were enabled in the correct order.
167     $enable_order = \Drupal::state()->get('module_test.install_order') ?: [];
168     $this->assertIdentical($enable_order, ['help', 'config', 'color']);
169   }
170
171   /**
172    * Tests uninstalling a module that is a "dependency" of a profile.
173    *
174    * Note this test does not trigger the deprecation error because of static
175    * caching in \Drupal\Core\Extension\InfoParser::parse().
176    *
177    * @group legacy
178    */
179   public function testUninstallProfileDependencyBC() {
180     $profile = 'testing_install_profile_dependencies_bc';
181     $dependency = 'dblog';
182     $this->setInstallProfile($profile);
183     // Prime the drupal_get_filename() static cache with the location of the
184     // testing profile as it is not the currently active profile and we don't
185     // yet have any cached way to retrieve its location.
186     // @todo Remove as part of https://www.drupal.org/node/2186491
187     drupal_get_filename('profile', $profile, 'core/profiles/' . $profile . '/' . $profile . '.info.yml');
188     $this->enableModules(['module_test', $profile]);
189
190     $data = \Drupal::service('extension.list.module')->reset()->getList();
191     $this->assertFalse(isset($data[$profile]->requires[$dependency]));
192     $this->assertContains($dependency, $data[$profile]->info['install']);
193
194     $this->moduleInstaller()->install([$dependency]);
195     $this->assertTrue($this->moduleHandler()->moduleExists($dependency));
196
197     // Uninstall the profile module "dependency".
198     $result = $this->moduleInstaller()->uninstall([$dependency]);
199     $this->assertTrue($result, 'ModuleInstaller::uninstall() returns TRUE.');
200     $this->assertFalse($this->moduleHandler()->moduleExists($dependency));
201     $this->assertEqual(drupal_get_installed_schema_version($dependency), SCHEMA_UNINSTALLED, "$dependency module was uninstalled.");
202
203     // Verify that the installation profile itself was not uninstalled.
204     $uninstalled_modules = \Drupal::state()->get('module_test.uninstall_order') ?: [];
205     $this->assertTrue(in_array($dependency, $uninstalled_modules), "$dependency module is in the list of uninstalled modules.");
206     $this->assertFalse(in_array($profile, $uninstalled_modules), 'The installation profile is not in the list of uninstalled modules.');
207   }
208
209   /**
210    * Tests uninstalling a module installed by a profile.
211    */
212   public function testUninstallProfileDependency() {
213     $profile = 'testing_install_profile_dependencies';
214     $dependency = 'dblog';
215     $non_dependency = 'ban';
216     $this->setInstallProfile($profile);
217     // Prime the drupal_get_filename() static cache with the location of the
218     // testing_install_profile_dependencies profile as it is not the currently
219     // active profile and we don't yet have any cached way to retrieve its
220     // location.
221     // @todo Remove as part of https://www.drupal.org/node/2186491
222     drupal_get_filename('profile', $profile, 'core/profiles/' . $profile . '/' . $profile . '.info.yml');
223     $this->enableModules(['module_test', $profile]);
224
225     $data = \Drupal::service('extension.list.module')->reset()->getList();
226     $this->assertArrayHasKey($dependency, $data[$profile]->requires);
227     $this->assertArrayNotHasKey($non_dependency, $data[$profile]->requires);
228
229     $this->moduleInstaller()->install([$dependency, $non_dependency]);
230     $this->assertTrue($this->moduleHandler()->moduleExists($dependency));
231
232     // Uninstall the profile module that is not a dependent.
233     $result = $this->moduleInstaller()->uninstall([$non_dependency]);
234     $this->assertTrue($result, 'ModuleInstaller::uninstall() returns TRUE.');
235     $this->assertFalse($this->moduleHandler()->moduleExists($non_dependency));
236     $this->assertEquals(drupal_get_installed_schema_version($non_dependency), SCHEMA_UNINSTALLED, "$non_dependency module was uninstalled.");
237
238     // Verify that the installation profile itself was not uninstalled.
239     $uninstalled_modules = \Drupal::state()->get('module_test.uninstall_order') ?: [];
240     $this->assertContains($non_dependency, $uninstalled_modules, "$non_dependency module is in the list of uninstalled modules.");
241     $this->assertNotContains($profile, $uninstalled_modules, 'The installation profile is not in the list of uninstalled modules.');
242
243     // Try uninstalling the required module.
244     $this->setExpectedException(ModuleUninstallValidatorException::class, 'The following reasons prevent the modules from being uninstalled: The Testing install profile dependencies module is required');
245     $this->moduleInstaller()->uninstall([$dependency]);
246   }
247
248   /**
249    * Tests that a profile can supply only real dependencies
250    */
251   public function testProfileAllDependencies() {
252     $profile = 'testing_install_profile_all_dependencies';
253     $dependencies = ['dblog', 'ban'];
254
255     $this->setInstallProfile($profile);
256     // Prime the drupal_get_filename() static cache with the location of the
257     // testing_install_profile_dependencies profile as it is not the currently
258     // active profile and we don't yet have any cached way to retrieve its
259     // location.
260     // @todo Remove as part of https://www.drupal.org/node/2186491
261     drupal_get_filename('profile', $profile, 'core/profiles/' . $profile . '/' . $profile . '.info.yml');
262     $this->enableModules(['module_test', $profile]);
263
264     $data = \Drupal::service('extension.list.module')->reset()->getList();
265     foreach ($dependencies as $dependency) {
266       $this->assertArrayHasKey($dependency, $data[$profile]->requires);
267     }
268
269     $this->moduleInstaller()->install($dependencies);
270     foreach ($dependencies as $dependency) {
271       $this->assertTrue($this->moduleHandler()->moduleExists($dependency));
272     }
273
274     // Try uninstalling the dependencies.
275     $this->setExpectedException(ModuleUninstallValidatorException::class, 'The following reasons prevent the modules from being uninstalled: The Testing install profile all dependencies module is required');
276     $this->moduleInstaller()->uninstall($dependencies);
277   }
278
279   /**
280    * Tests uninstalling a module that has content.
281    */
282   public function testUninstallContentDependency() {
283     $this->enableModules(['module_test', 'entity_test', 'text', 'user', 'help']);
284     $this->assertTrue($this->moduleHandler()->moduleExists('entity_test'), 'Test module is enabled.');
285     $this->assertTrue($this->moduleHandler()->moduleExists('module_test'), 'Test module is enabled.');
286
287     $this->installSchema('user', 'users_data');
288     $entity_types = \Drupal::entityManager()->getDefinitions();
289     foreach ($entity_types as $entity_type) {
290       if ('entity_test' == $entity_type->getProvider()) {
291         $this->installEntitySchema($entity_type->id());
292       }
293     }
294
295     // Create a fake dependency.
296     // entity_test will depend on help. This way help can not be uninstalled
297     // when there is test content preventing entity_test from being uninstalled.
298     \Drupal::state()->set('module_test.dependency', 'dependency');
299     \Drupal::service('extension.list.module')->reset();
300
301     // Create an entity so that the modules can not be disabled.
302     $entity = EntityTest::create(['name' => $this->randomString()]);
303     $entity->save();
304
305     // Uninstalling entity_test is not possible when there is content.
306     try {
307       $message = 'ModuleInstaller::uninstall() throws ModuleUninstallValidatorException upon uninstalling a module which does not pass validation.';
308       $this->moduleInstaller()->uninstall(['entity_test']);
309       $this->fail($message);
310     }
311     catch (ModuleUninstallValidatorException $e) {
312       $this->pass(get_class($e) . ': ' . $e->getMessage());
313     }
314
315     // Uninstalling help needs entity_test to be un-installable.
316     try {
317       $message = 'ModuleInstaller::uninstall() throws ModuleUninstallValidatorException upon uninstalling a module which does not pass validation.';
318       $this->moduleInstaller()->uninstall(['help']);
319       $this->fail($message);
320     }
321     catch (ModuleUninstallValidatorException $e) {
322       $this->pass(get_class($e) . ': ' . $e->getMessage());
323     }
324
325     // Deleting the entity.
326     $entity->delete();
327
328     $result = $this->moduleInstaller()->uninstall(['help']);
329     $this->assertTrue($result, 'ModuleInstaller::uninstall() returns TRUE.');
330     $this->assertEqual(drupal_get_installed_schema_version('entity_test'), SCHEMA_UNINSTALLED, "entity_test module was uninstalled.");
331   }
332
333   /**
334    * Tests whether the correct module metadata is returned.
335    */
336   public function testModuleMetaData() {
337     // Generate the list of available modules.
338     $modules = system_rebuild_module_data();
339     // Check that the mtime field exists for the system module.
340     $this->assertTrue(!empty($modules['system']->info['mtime']), 'The system.info.yml file modification time field is present.');
341     // Use 0 if mtime isn't present, to avoid an array index notice.
342     $test_mtime = !empty($modules['system']->info['mtime']) ? $modules['system']->info['mtime'] : 0;
343     // Ensure the mtime field contains a number that is greater than zero.
344     $this->assertTrue(is_numeric($test_mtime) && ($test_mtime > 0), 'The system.info.yml file modification time field contains a timestamp.');
345   }
346
347   /**
348    * Tests whether module-provided stream wrappers are registered properly.
349    */
350   public function testModuleStreamWrappers() {
351     // file_test.module provides (among others) a 'dummy' stream wrapper.
352     // Verify that it is not registered yet to prevent false positives.
353     $stream_wrappers = \Drupal::service('stream_wrapper_manager')->getWrappers();
354     $this->assertFalse(isset($stream_wrappers['dummy']));
355     $this->moduleInstaller()->install(['file_test']);
356     // Verify that the stream wrapper is available even without calling
357     // \Drupal::service('stream_wrapper_manager')->getWrappers() again.
358     // If the stream wrapper is not available file_exists() will raise a notice.
359     file_exists('dummy://');
360     $stream_wrappers = \Drupal::service('stream_wrapper_manager')->getWrappers();
361     $this->assertTrue(isset($stream_wrappers['dummy']));
362   }
363
364   /**
365    * Tests whether the correct theme metadata is returned.
366    */
367   public function testThemeMetaData() {
368     // Generate the list of available themes.
369     $themes = \Drupal::service('theme_handler')->rebuildThemeData();
370     // Check that the mtime field exists for the bartik theme.
371     $this->assertTrue(!empty($themes['bartik']->info['mtime']), 'The bartik.info.yml file modification time field is present.');
372     // Use 0 if mtime isn't present, to avoid an array index notice.
373     $test_mtime = !empty($themes['bartik']->info['mtime']) ? $themes['bartik']->info['mtime'] : 0;
374     // Ensure the mtime field contains a number that is greater than zero.
375     $this->assertTrue(is_numeric($test_mtime) && ($test_mtime > 0), 'The bartik.info.yml file modification time field contains a timestamp.');
376   }
377
378   /**
379    * Returns the ModuleHandler.
380    *
381    * @return \Drupal\Core\Extension\ModuleHandlerInterface
382    */
383   protected function moduleHandler() {
384     return $this->container->get('module_handler');
385   }
386
387   /**
388    * Returns the ModuleInstaller.
389    *
390    * @return \Drupal\Core\Extension\ModuleInstallerInterface
391    */
392   protected function moduleInstaller() {
393     return $this->container->get('module_installer');
394   }
395
396 }