f4db81e18e02246d53bf50dd05ec2d415a79b9d7
[yaffs-website] / web / core / modules / system / src / Tests / Module / InstallUninstallTest.php
1 <?php
2
3 namespace Drupal\system\Tests\Module;
4
5 use Drupal\Component\Render\FormattableMarkup;
6 use Drupal\Core\Logger\RfcLogLevel;
7
8 /**
9  * Install/uninstall core module and confirm table creation/deletion.
10  *
11  * @group Module
12  */
13 class InstallUninstallTest extends ModuleTestBase {
14
15   /**
16    * {@inheritdoc}
17    */
18   public static $modules = ['system_test', 'dblog', 'taxonomy', 'update_test_postupdate'];
19
20   /**
21    * Tests that a fixed set of modules can be installed and uninstalled.
22    */
23   public function testInstallUninstall() {
24     // Set a variable so that the hook implementations in system_test.module
25     // will display messages via drupal_set_message().
26     $this->container->get('state')->set('system_test.verbose_module_hooks', TRUE);
27
28     // Install and uninstall module_test to ensure hook_preinstall_module and
29     // hook_preuninstall_module are fired as expected.
30     $this->container->get('module_installer')->install(['module_test']);
31     $this->assertEqual($this->container->get('state')->get('system_test_preinstall_module'), 'module_test');
32     $this->container->get('module_installer')->uninstall(['module_test']);
33     $this->assertEqual($this->container->get('state')->get('system_test_preuninstall_module'), 'module_test');
34     $this->resetAll();
35
36     $all_modules = system_rebuild_module_data();
37
38     // Test help on required modules, but do not test uninstalling.
39     $required_modules = array_filter($all_modules, function ($module) {
40       if (!empty($module->info['required']) || $module->status == TRUE) {
41         if ($module->info['package'] != 'Testing' && empty($module->info['hidden'])) {
42           return TRUE;
43         }
44       }
45       return FALSE;
46     });
47
48     $required_modules['help'] = $all_modules['help'];
49
50     // Test uninstalling without hidden, required, and already enabled modules.
51     $all_modules = array_filter($all_modules, function ($module) {
52       if (!empty($module->info['hidden']) || !empty($module->info['required']) || $module->status == TRUE || $module->info['package'] == 'Testing') {
53         return FALSE;
54       }
55       return TRUE;
56     });
57
58     // Install the Help module, and verify it installed successfully.
59     unset($all_modules['help']);
60     $this->assertModuleNotInstalled('help');
61     $edit = [];
62     $edit["modules[help][enable]"] = TRUE;
63     $this->drupalPostForm('admin/modules', $edit, t('Install'));
64     $this->assertText('has been enabled', 'Modules status has been updated.');
65     $this->assertText(t('hook_modules_installed fired for help'));
66     $this->assertModuleSuccessfullyInstalled('help');
67
68     // Test help for the required modules.
69     foreach ($required_modules as $name => $module) {
70       $this->assertHelp($name, $module->info['name']);
71     }
72
73     // Go through each module in the list and try to install and uninstall
74     // it with its dependencies.
75     while (list($name, $module) = each($all_modules)) {
76       $was_installed_list = \Drupal::moduleHandler()->getModuleList();
77
78       // Start a list of modules that we expect to be installed this time.
79       $modules_to_install = [$name];
80       foreach (array_keys($module->requires) as $dependency) {
81         if (isset($all_modules[$dependency])) {
82           $modules_to_install[] = $dependency;
83         }
84       }
85
86       // Check that each module is not yet enabled and does not have any
87       // database tables yet.
88       foreach ($modules_to_install as $module_to_install) {
89         $this->assertModuleNotInstalled($module_to_install);
90       }
91
92       // Install the module.
93       $edit = [];
94       $package = $module->info['package'];
95       $edit['modules[' . $name . '][enable]'] = TRUE;
96       $this->drupalPostForm('admin/modules', $edit, t('Install'));
97
98       // Handle experimental modules, which require a confirmation screen.
99       if ($package == 'Core (Experimental)') {
100         $this->assertText('Are you sure you wish to enable experimental modules?');
101         if (count($modules_to_install) > 1) {
102           // When there are experimental modules, needed dependencies do not
103           // result in the same page title, but there will be expected text
104           // indicating they need to be enabled.
105           $this->assertText('You must enable');
106         }
107         $this->drupalPostForm(NULL, [], t('Continue'));
108       }
109       // Handle the case where modules were installed along with this one and
110       // where we therefore hit a confirmation screen.
111       elseif (count($modules_to_install) > 1) {
112         // Verify that we are on the correct form and that the expected text
113         // about enabling dependencies appears.
114         $this->assertText('Some required modules must be enabled');
115         $this->assertText('You must enable');
116         $this->drupalPostForm(NULL, [], t('Continue'));
117       }
118
119       // List the module display names to check the confirmation message.
120       $module_names = [];
121       foreach ($modules_to_install as $module_to_install) {
122         $module_names[] = $all_modules[$module_to_install]->info['name'];
123       }
124       $expected_text = \Drupal::translation()->formatPlural(count($module_names), 'Module @name has been enabled.', '@count modules have been enabled: @names.', [
125         '@name' => $module_names[0],
126         '@names' => implode(', ', $module_names),
127       ]);
128       $this->assertText($expected_text, 'Modules status has been updated.');
129
130       // Check that hook_modules_installed() was invoked with the expected list
131       // of modules, that each module's database tables now exist, and that
132       // appropriate messages appear in the logs.
133       foreach ($modules_to_install as $module_to_install) {
134         $this->assertText(t('hook_modules_installed fired for @module', ['@module' => $module_to_install]));
135         $this->assertLogMessage('system', "%module module installed.", ['%module' => $module_to_install], RfcLogLevel::INFO);
136         $this->assertInstallModuleUpdates($module_to_install);
137         $this->assertModuleSuccessfullyInstalled($module_to_install);
138       }
139
140       // Verify the help page.
141       $this->assertHelp($name, $module->info['name']);
142
143       // Uninstall the original module, plus everything else that was installed
144       // with it.
145       if ($name == 'forum') {
146         // Forum has an extra step to be able to uninstall it.
147         $this->preUninstallForum();
148       }
149
150       $now_installed_list = \Drupal::moduleHandler()->getModuleList();
151       $added_modules = array_diff(array_keys($now_installed_list), array_keys($was_installed_list));
152       while ($added_modules) {
153         $initial_count = count($added_modules);
154         foreach ($added_modules as $to_uninstall) {
155           // See if we can currently uninstall this module (if its dependencies
156           // have been uninstalled), and do so if we can.
157           $this->drupalGet('admin/modules/uninstall');
158           $field_name = "uninstall[$to_uninstall]";
159           $has_checkbox = $this->xpath('//input[@type="checkbox" and @name="' . $field_name . '"]');
160           $disabled = $this->xpath('//input[@type="checkbox" and @name="' . $field_name . '" and @disabled="disabled"]');
161
162           if (!empty($has_checkbox) && empty($disabled)) {
163             // This one is eligible for being uninstalled.
164             $package = $all_modules[$to_uninstall]->info['package'];
165             $this->assertSuccessfulUninstall($to_uninstall, $package);
166             $added_modules = array_diff($added_modules, [$to_uninstall]);
167           }
168         }
169
170         // If we were not able to find a module to uninstall, fail and exit the
171         // loop.
172         $final_count = count($added_modules);
173         if ($initial_count == $final_count) {
174           $this->fail('Remaining modules could not be uninstalled for ' . $name);
175           break;
176         }
177       }
178     }
179
180     // Uninstall the help module and put it back into the list of modules.
181     $all_modules['help'] = $required_modules['help'];
182     $this->assertSuccessfulUninstall('help', $required_modules['help']->info['package']);
183
184     // Now that all modules have been tested, go back and try to enable them
185     // all again at once. This tests two things:
186     // - That each module can be successfully enabled again after being
187     //   uninstalled.
188     // - That enabling more than one module at the same time does not lead to
189     //   any errors.
190     $edit = [];
191     $experimental = FALSE;
192     foreach ($all_modules as $name => $module) {
193       $edit['modules[' . $name . '][enable]'] = TRUE;
194       // Track whether there is at least one experimental module.
195       if ($module->info['package'] == 'Core (Experimental)') {
196         $experimental = TRUE;
197       }
198     }
199     $this->drupalPostForm('admin/modules', $edit, t('Install'));
200
201     // If there are experimental modules, click the confirm form.
202     if ($experimental) {
203       $this->assertText('Are you sure you wish to enable experimental modules?');
204       $this->drupalPostForm(NULL, [], t('Continue'));
205     }
206     // The string tested here is translatable but we are only using a part of it
207     // so using a translated string is wrong. Doing so would create a new string
208     // to translate.
209     $this->assertText(new FormattableMarkup('@count modules have been enabled: ', ['@count' => count($all_modules)]), 'Modules status has been updated.');
210   }
211
212   /**
213    * Asserts that a module is not yet installed.
214    *
215    * @param string $name
216    *   Name of the module to check.
217    */
218   protected function assertModuleNotInstalled($name) {
219     $this->assertModules([$name], FALSE);
220     $this->assertModuleTablesDoNotExist($name);
221   }
222
223   /**
224    * Asserts that a module was successfully installed.
225    *
226    * @param string $name
227    *   Name of the module to check.
228    */
229   protected function assertModuleSuccessfullyInstalled($name) {
230     $this->assertModules([$name], TRUE);
231     $this->assertModuleTablesExist($name);
232     $this->assertModuleConfig($name);
233   }
234
235   /**
236    * Uninstalls a module and asserts that it was done correctly.
237    *
238    * @param string $module
239    *   The name of the module to uninstall.
240    * @param string $package
241    *   (optional) The package of the module to uninstall. Defaults
242    *   to 'Core'.
243    */
244   protected function assertSuccessfulUninstall($module, $package = 'Core') {
245     $edit = [];
246     $edit['uninstall[' . $module . ']'] = TRUE;
247     $this->drupalPostForm('admin/modules/uninstall', $edit, t('Uninstall'));
248     $this->drupalPostForm(NULL, NULL, t('Uninstall'));
249     $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.');
250     $this->assertModules([$module], FALSE);
251
252     // Check that the appropriate hook was fired and the appropriate log
253     // message appears. (But don't check for the log message if the dblog
254     // module was just uninstalled, since the {watchdog} table won't be there
255     // anymore.)
256     $this->assertText(t('hook_modules_uninstalled fired for @module', ['@module' => $module]));
257     $this->assertLogMessage('system', "%module module uninstalled.", ['%module' => $module], RfcLogLevel::INFO);
258
259     // Check that the module's database tables no longer exist.
260     $this->assertModuleTablesDoNotExist($module);
261     // Check that the module's config files no longer exist.
262     $this->assertNoModuleConfig($module);
263     $this->assertUninstallModuleUpdates($module);
264   }
265
266   /**
267    * Asserts the module post update functions after install.
268    *
269    * @param string $module
270    *   The module that got installed.
271    */
272   protected function assertInstallModuleUpdates($module) {
273     /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */
274     $post_update_registry = \Drupal::service('update.post_update_registry');
275     $all_update_functions = $post_update_registry->getPendingUpdateFunctions();
276     $empty_result = TRUE;
277     foreach ($all_update_functions as $function) {
278       list($function_module, ) = explode('_post_update_', $function);
279       if ($module === $function_module) {
280         $empty_result = FALSE;
281         break;
282       }
283     }
284     $this->assertTrue($empty_result, 'Ensures that no pending post update functions are available.');
285
286     $existing_updates = \Drupal::keyValue('post_update')->get('existing_updates', []);
287     switch ($module) {
288       case 'block':
289         $this->assertFalse(array_diff(['block_post_update_disable_blocks_with_missing_contexts'], $existing_updates));
290         break;
291       case 'update_test_postupdate':
292         $this->assertFalse(array_diff(['update_test_postupdate_post_update_first', 'update_test_postupdate_post_update_second', 'update_test_postupdate_post_update_test1', 'update_test_postupdate_post_update_test0'], $existing_updates));
293         break;
294     }
295   }
296
297   /**
298    * Asserts the module post update functions after uninstall.
299    *
300    * @param string $module
301    *   The module that got installed.
302    */
303   protected function assertUninstallModuleUpdates($module) {
304     /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */
305     $post_update_registry = \Drupal::service('update.post_update_registry');
306     $all_update_functions = $post_update_registry->getPendingUpdateFunctions();
307
308     switch ($module) {
309       case 'block':
310         $this->assertFalse(array_intersect(['block_post_update_disable_blocks_with_missing_contexts'], $all_update_functions), 'Asserts that no pending post update functions are available.');
311
312         $existing_updates = \Drupal::keyValue('post_update')->get('existing_updates', []);
313         $this->assertFalse(array_intersect(['block_post_update_disable_blocks_with_missing_contexts'], $existing_updates), 'Asserts that no post update functions are stored in keyvalue store.');
314         break;
315     }
316   }
317
318   /**
319    * Verifies a module's help.
320    *
321    * Verifies that the module help page from hook_help() exists and can be
322    * displayed, and that it contains the phrase "Foo Bar module", where "Foo
323    * Bar" is the name of the module from the .info.yml file.
324    *
325    * @param string $module
326    *   Machine name of the module to verify.
327    * @param string $name
328    *   Human-readable name of the module to verify.
329    */
330   protected function assertHelp($module, $name) {
331     $this->drupalGet('admin/help/' . $module);
332     $this->assertResponse(200, "Help for $module displayed successfully");
333     $this->assertText($name . ' module', "'$name module' is on the help page for $module");
334     $this->assertLink('online documentation for the ' . $name . ' module', 0, "Correct online documentation link is in the help page for $module");
335   }
336
337   /**
338    * Deletes forum taxonomy terms, so Forum can be uninstalled.
339    */
340   protected function preUninstallForum() {
341     // There only should be a 'General discussion' term in the 'forums'
342     // vocabulary, but just delete any terms there in case the name changes.
343     $query = \Drupal::entityQuery('taxonomy_term');
344     $query->condition('vid', 'forums');
345     $ids = $query->execute();
346     $storage = \Drupal::entityManager()->getStorage('taxonomy_term');
347     $terms = $storage->loadMultiple($ids);
348     $storage->delete($terms);
349   }
350
351 }