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