22648a63912b7edb45685120e9f9216911311d3b
[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_static_reset('system_rebuild_module_data');
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_static_reset('system_rebuild_module_data');
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_static_reset('system_rebuild_module_data');
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   public function testUninstallProfileDependency() {
175     $profile = 'minimal';
176     $dependency = 'dblog';
177     $this->setSetting('install_profile', $profile);
178     // Prime the drupal_get_filename() static cache with the location of the
179     // minimal profile as it is not the currently active profile and we don't
180     // yet have any cached way to retrieve its location.
181     // @todo Remove as part of https://www.drupal.org/node/2186491
182     drupal_get_filename('profile', $profile, 'core/profiles/' . $profile . '/' . $profile . '.info.yml');
183     $this->enableModules(['module_test', $profile]);
184
185     drupal_static_reset('system_rebuild_module_data');
186     $data = system_rebuild_module_data();
187     $this->assertTrue(isset($data[$profile]->requires[$dependency]));
188
189     $this->moduleInstaller()->install([$dependency]);
190     $this->assertTrue($this->moduleHandler()->moduleExists($dependency));
191
192     // Uninstall the profile module "dependency".
193     $result = $this->moduleInstaller()->uninstall([$dependency]);
194     $this->assertTrue($result, 'ModuleInstaller::uninstall() returns TRUE.');
195     $this->assertFalse($this->moduleHandler()->moduleExists($dependency));
196     $this->assertEqual(drupal_get_installed_schema_version($dependency), SCHEMA_UNINSTALLED, "$dependency module was uninstalled.");
197
198     // Verify that the installation profile itself was not uninstalled.
199     $uninstalled_modules = \Drupal::state()->get('module_test.uninstall_order') ?: [];
200     $this->assertTrue(in_array($dependency, $uninstalled_modules), "$dependency module is in the list of uninstalled modules.");
201     $this->assertFalse(in_array($profile, $uninstalled_modules), 'The installation profile is not in the list of uninstalled modules.');
202   }
203
204   /**
205    * Tests uninstalling a module that has content.
206    */
207   public function testUninstallContentDependency() {
208     $this->enableModules(['module_test', 'entity_test', 'text', 'user', 'help']);
209     $this->assertTrue($this->moduleHandler()->moduleExists('entity_test'), 'Test module is enabled.');
210     $this->assertTrue($this->moduleHandler()->moduleExists('module_test'), 'Test module is enabled.');
211
212     $this->installSchema('user', 'users_data');
213     $entity_types = \Drupal::entityManager()->getDefinitions();
214     foreach ($entity_types as $entity_type) {
215       if ('entity_test' == $entity_type->getProvider()) {
216         $this->installEntitySchema($entity_type->id());
217       }
218     }
219
220     // Create a fake dependency.
221     // entity_test will depend on help. This way help can not be uninstalled
222     // when there is test content preventing entity_test from being uninstalled.
223     \Drupal::state()->set('module_test.dependency', 'dependency');
224     drupal_static_reset('system_rebuild_module_data');
225
226     // Create an entity so that the modules can not be disabled.
227     $entity = EntityTest::create(['name' => $this->randomString()]);
228     $entity->save();
229
230     // Uninstalling entity_test is not possible when there is content.
231     try {
232       $message = 'ModuleInstaller::uninstall() throws ModuleUninstallValidatorException upon uninstalling a module which does not pass validation.';
233       $this->moduleInstaller()->uninstall(['entity_test']);
234       $this->fail($message);
235     }
236     catch (ModuleUninstallValidatorException $e) {
237       $this->pass(get_class($e) . ': ' . $e->getMessage());
238     }
239
240     // Uninstalling help needs entity_test to be un-installable.
241     try {
242       $message = 'ModuleInstaller::uninstall() throws ModuleUninstallValidatorException upon uninstalling a module which does not pass validation.';
243       $this->moduleInstaller()->uninstall(['help']);
244       $this->fail($message);
245     }
246     catch (ModuleUninstallValidatorException $e) {
247       $this->pass(get_class($e) . ': ' . $e->getMessage());
248     }
249
250     // Deleting the entity.
251     $entity->delete();
252
253     $result = $this->moduleInstaller()->uninstall(['help']);
254     $this->assertTrue($result, 'ModuleInstaller::uninstall() returns TRUE.');
255     $this->assertEqual(drupal_get_installed_schema_version('entity_test'), SCHEMA_UNINSTALLED, "entity_test module was uninstalled.");
256   }
257
258   /**
259    * Tests whether the correct module metadata is returned.
260    */
261   public function testModuleMetaData() {
262     // Generate the list of available modules.
263     $modules = system_rebuild_module_data();
264     // Check that the mtime field exists for the system module.
265     $this->assertTrue(!empty($modules['system']->info['mtime']), 'The system.info.yml file modification time field is present.');
266     // Use 0 if mtime isn't present, to avoid an array index notice.
267     $test_mtime = !empty($modules['system']->info['mtime']) ? $modules['system']->info['mtime'] : 0;
268     // Ensure the mtime field contains a number that is greater than zero.
269     $this->assertTrue(is_numeric($test_mtime) && ($test_mtime > 0), 'The system.info.yml file modification time field contains a timestamp.');
270   }
271
272   /**
273    * Tests whether module-provided stream wrappers are registered properly.
274    */
275   public function testModuleStreamWrappers() {
276     // file_test.module provides (among others) a 'dummy' stream wrapper.
277     // Verify that it is not registered yet to prevent false positives.
278     $stream_wrappers = \Drupal::service('stream_wrapper_manager')->getWrappers();
279     $this->assertFalse(isset($stream_wrappers['dummy']));
280     $this->moduleInstaller()->install(['file_test']);
281     // Verify that the stream wrapper is available even without calling
282     // \Drupal::service('stream_wrapper_manager')->getWrappers() again.
283     // If the stream wrapper is not available file_exists() will raise a notice.
284     file_exists('dummy://');
285     $stream_wrappers = \Drupal::service('stream_wrapper_manager')->getWrappers();
286     $this->assertTrue(isset($stream_wrappers['dummy']));
287   }
288
289   /**
290    * Tests whether the correct theme metadata is returned.
291    */
292   public function testThemeMetaData() {
293     // Generate the list of available themes.
294     $themes = \Drupal::service('theme_handler')->rebuildThemeData();
295     // Check that the mtime field exists for the bartik theme.
296     $this->assertTrue(!empty($themes['bartik']->info['mtime']), 'The bartik.info.yml file modification time field is present.');
297     // Use 0 if mtime isn't present, to avoid an array index notice.
298     $test_mtime = !empty($themes['bartik']->info['mtime']) ? $themes['bartik']->info['mtime'] : 0;
299     // Ensure the mtime field contains a number that is greater than zero.
300     $this->assertTrue(is_numeric($test_mtime) && ($test_mtime > 0), 'The bartik.info.yml file modification time field contains a timestamp.');
301   }
302
303   /**
304    * Returns the ModuleHandler.
305    *
306    * @return \Drupal\Core\Extension\ModuleHandlerInterface
307    */
308   protected function moduleHandler() {
309     return $this->container->get('module_handler');
310   }
311
312   /**
313    * Returns the ModuleInstaller.
314    *
315    * @return \Drupal\Core\Extension\ModuleInstallerInterface
316    */
317   protected function moduleInstaller() {
318     return $this->container->get('module_installer');
319   }
320
321 }