715976d1622e8dc60b38a09fe0fcb515954a4c68
[yaffs-website] / web / core / modules / config / tests / src / Functional / ConfigImportUITest.php
1 <?php
2
3 namespace Drupal\Tests\config\Functional;
4
5 use Drupal\Component\Utility\Html;
6 use Drupal\Component\Render\FormattableMarkup;
7 use Drupal\Core\Config\InstallStorage;
8 use Drupal\Tests\BrowserTestBase;
9
10 /**
11  * Tests the user interface for importing configuration.
12  *
13  * @group config
14  */
15 class ConfigImportUITest extends BrowserTestBase {
16
17   /**
18    * Modules to install.
19    *
20    * @var array
21    */
22   public static $modules = ['config', 'config_test', 'config_import_test', 'text', 'options'];
23
24   /**
25    * A user with the 'synchronize configuration' permission.
26    *
27    * @var \Drupal\user\UserInterface
28    */
29   protected $webUser;
30
31   protected function setUp() {
32     parent::setUp();
33
34     $this->webUser = $this->drupalCreateUser(['synchronize configuration']);
35     $this->drupalLogin($this->webUser);
36     $this->copyConfig($this->container->get('config.storage'), $this->container->get('config.storage.sync'));
37   }
38
39   /**
40    * Tests importing configuration.
41    */
42   public function testImport() {
43     $name = 'system.site';
44     $dynamic_name = 'config_test.dynamic.new';
45     /** @var \Drupal\Core\Config\StorageInterface $sync */
46     $sync = $this->container->get('config.storage.sync');
47
48     $this->drupalGet('admin/config/development/configuration');
49     $this->assertText('There are no configuration changes to import.');
50     $this->assertNoFieldById('edit-submit', t('Import all'));
51
52     // Create updated configuration object.
53     $new_site_name = 'Config import test ' . $this->randomString();
54     $this->prepareSiteNameUpdate($new_site_name);
55     $this->assertIdentical($sync->exists($name), TRUE, $name . ' found.');
56
57     // Create new config entity.
58     $original_dynamic_data = [
59       'uuid' => '30df59bd-7b03-4cf7-bb35-d42fc49f0651',
60       'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
61       'status' => TRUE,
62       'dependencies' => [],
63       'id' => 'new',
64       'label' => 'New',
65       'weight' => 0,
66       'style' => '',
67       'size' => '',
68       'size_value' => '',
69       'protected_property' => '',
70     ];
71     $sync->write($dynamic_name, $original_dynamic_data);
72     $this->assertIdentical($sync->exists($dynamic_name), TRUE, $dynamic_name . ' found.');
73
74     // Enable the Action and Ban modules during import. The Ban
75     // module is used because it creates a table during the install. The Action
76     // module is used because it creates a single simple configuration file
77     // during the install.
78     $core_extension = $this->config('core.extension')->get();
79     $core_extension['module']['action'] = 0;
80     $core_extension['module']['ban'] = 0;
81     $core_extension['module'] = module_config_sort($core_extension['module']);
82     // Bartik is a subtheme of classy so classy must be enabled.
83     $core_extension['theme']['classy'] = 0;
84     $core_extension['theme']['bartik'] = 0;
85     $sync->write('core.extension', $core_extension);
86
87     // Use the install storage so that we can read configuration from modules
88     // and themes that are not installed.
89     $install_storage = new InstallStorage();
90
91     // Set the Bartik theme as default.
92     $system_theme = $this->config('system.theme')->get();
93     $system_theme['default'] = 'bartik';
94     $sync->write('system.theme', $system_theme);
95
96     // Read the action config from module default config folder.
97     $action_settings = $install_storage->read('action.settings');
98     $action_settings['recursion_limit'] = 50;
99     $sync->write('action.settings', $action_settings);
100
101     // Uninstall the Options and Text modules to ensure that dependencies are
102     // handled correctly. Options depends on Text so Text should be installed
103     // first. Since they were enabled during the test setup the core.extension
104     // file in sync will already contain them.
105     \Drupal::service('module_installer')->uninstall(['text', 'options']);
106
107     // Set the state system to record installations and uninstallations.
108     \Drupal::state()->set('ConfigImportUITest.core.extension.modules_installed', []);
109     \Drupal::state()->set('ConfigImportUITest.core.extension.modules_uninstalled', []);
110
111     // Verify that both appear as ready to import.
112     $this->drupalGet('admin/config/development/configuration');
113     $this->assertRaw('<td>' . $name);
114     $this->assertRaw('<td>' . $dynamic_name);
115     $this->assertRaw('<td>core.extension');
116     $this->assertRaw('<td>system.theme');
117     $this->assertRaw('<td>action.settings');
118     $this->assertFieldById('edit-submit', t('Import all'));
119
120     // Import and verify that both do not appear anymore.
121     $this->drupalPostForm(NULL, [], t('Import all'));
122     $this->assertNoRaw('<td>' . $name);
123     $this->assertNoRaw('<td>' . $dynamic_name);
124     $this->assertNoRaw('<td>core.extension');
125     $this->assertNoRaw('<td>system.theme');
126     $this->assertNoRaw('<td>action.settings');
127
128     $this->assertNoFieldById('edit-submit', t('Import all'));
129
130     // Verify that there are no further changes to import.
131     $this->assertText(t('There are no configuration changes to import.'));
132
133     $this->rebuildContainer();
134     // Verify site name has changed.
135     $this->assertIdentical($new_site_name, $this->config('system.site')->get('name'));
136
137     // Verify that new config entity exists.
138     $this->assertIdentical($original_dynamic_data, $this->config($dynamic_name)->get());
139
140     // Verify the cache got cleared.
141     $this->assertTrue(isset($GLOBALS['hook_cache_flush']));
142
143     $this->rebuildContainer();
144     $this->assertTrue(\Drupal::moduleHandler()->moduleExists('ban'), 'Ban module installed during import.');
145     $this->assertTrue(\Drupal::database()->schema()->tableExists('ban_ip'), 'The database table ban_ip exists.');
146     $this->assertTrue(\Drupal::moduleHandler()->moduleExists('action'), 'Action module installed during import.');
147     $this->assertTrue(\Drupal::moduleHandler()->moduleExists('options'), 'Options module installed during import.');
148     $this->assertTrue(\Drupal::moduleHandler()->moduleExists('text'), 'Text module installed during import.');
149
150     $theme_info = \Drupal::service('theme_handler')->listInfo();
151     $this->assertTrue($theme_info['bartik']->status, 'Bartik theme installed during import.');
152
153     // Ensure installations and uninstallation occur as expected.
154     $installed = \Drupal::state()->get('ConfigImportUITest.core.extension.modules_installed', []);
155     $uninstalled = \Drupal::state()->get('ConfigImportUITest.core.extension.modules_uninstalled', []);
156     $expected = ['action', 'ban', 'text', 'options'];
157     $this->assertIdentical($expected, $installed, 'Action, Ban, Text and Options modules installed in the correct order.');
158     $this->assertTrue(empty($uninstalled), 'No modules uninstalled during import');
159
160     // Verify that the action.settings configuration object was only written
161     // once during the import process and only with the value set in the staged
162     // configuration. This verifies that the module's default configuration is
163     // used during configuration import and, additionally, that after installing
164     // a module, that configuration is not synced twice.
165     $recursion_limit_values = \Drupal::state()->get('ConfigImportUITest.action.settings.recursion_limit', []);
166     $this->assertIdentical($recursion_limit_values, [50]);
167
168     $core_extension = $this->config('core.extension')->get();
169     unset($core_extension['module']['action']);
170     unset($core_extension['module']['ban']);
171     unset($core_extension['module']['options']);
172     unset($core_extension['module']['text']);
173     unset($core_extension['theme']['bartik']);
174     $sync->write('core.extension', $core_extension);
175     $sync->delete('action.settings');
176     $sync->delete('text.settings');
177
178     $system_theme = $this->config('system.theme')->get();
179     $system_theme['default'] = 'stark';
180     $system_theme['admin'] = 'stark';
181     $sync->write('system.theme', $system_theme);
182
183     // Set the state system to record installations and uninstallations.
184     \Drupal::state()->set('ConfigImportUITest.core.extension.modules_installed', []);
185     \Drupal::state()->set('ConfigImportUITest.core.extension.modules_uninstalled', []);
186
187     // Verify that both appear as ready to import.
188     $this->drupalGet('admin/config/development/configuration');
189     $this->assertRaw('<td>core.extension');
190     $this->assertRaw('<td>system.theme');
191     $this->assertRaw('<td>action.settings');
192
193     // Import and verify that both do not appear anymore.
194     $this->drupalPostForm(NULL, [], t('Import all'));
195     $this->assertNoRaw('<td>core.extension');
196     $this->assertNoRaw('<td>system.theme');
197     $this->assertNoRaw('<td>action.settings');
198
199     $this->rebuildContainer();
200     $this->assertFalse(\Drupal::moduleHandler()->moduleExists('ban'), 'Ban module uninstalled during import.');
201     $this->assertFalse(\Drupal::database()->schema()->tableExists('ban_ip'), 'The database table ban_ip does not exist.');
202     $this->assertFalse(\Drupal::moduleHandler()->moduleExists('action'), 'Action module uninstalled during import.');
203     $this->assertFalse(\Drupal::moduleHandler()->moduleExists('options'), 'Options module uninstalled during import.');
204     $this->assertFalse(\Drupal::moduleHandler()->moduleExists('text'), 'Text module uninstalled during import.');
205
206     // Ensure installations and uninstallation occur as expected.
207     $installed = \Drupal::state()->get('ConfigImportUITest.core.extension.modules_installed', []);
208     $uninstalled = \Drupal::state()->get('ConfigImportUITest.core.extension.modules_uninstalled', []);
209     $expected = ['options', 'text', 'ban', 'action'];
210     $this->assertIdentical($expected, $uninstalled, 'Options, Text, Ban and Action modules uninstalled in the correct order.');
211     $this->assertTrue(empty($installed), 'No modules installed during import');
212
213     $theme_info = \Drupal::service('theme_handler')->listInfo();
214     $this->assertFalse(isset($theme_info['bartik']), 'Bartik theme uninstalled during import.');
215
216     // Verify that the action.settings configuration object was only deleted
217     // once during the import process.
218     $delete_called = \Drupal::state()->get('ConfigImportUITest.action.settings.delete', 0);
219     $this->assertIdentical($delete_called, 1, "The action.settings configuration was deleted once during configuration import.");
220   }
221
222   /**
223    * Tests concurrent importing of configuration.
224    */
225   public function testImportLock() {
226     // Create updated configuration object.
227     $new_site_name = 'Config import test ' . $this->randomString();
228     $this->prepareSiteNameUpdate($new_site_name);
229
230     // Verify that there are configuration differences to import.
231     $this->drupalGet('admin/config/development/configuration');
232     $this->assertNoText(t('There are no configuration changes to import.'));
233
234     // Acquire a fake-lock on the import mechanism.
235     $config_importer = $this->configImporter();
236     $this->container->get('lock.persistent')->acquire($config_importer::LOCK_NAME);
237
238     // Attempt to import configuration and verify that an error message appears.
239     $this->drupalPostForm(NULL, [], t('Import all'));
240     $this->assertText(t('Another request may be synchronizing configuration already.'));
241
242     // Release the lock, just to keep testing sane.
243     $this->container->get('lock.persistent')->release($config_importer::LOCK_NAME);
244
245     // Verify site name has not changed.
246     $this->assertNotEqual($new_site_name, $this->config('system.site')->get('name'));
247   }
248
249   /**
250    * Tests verification of site UUID before importing configuration.
251    */
252   public function testImportSiteUuidValidation() {
253     $sync = \Drupal::service('config.storage.sync');
254     // Create updated configuration object.
255     $config_data = $this->config('system.site')->get();
256     // Generate a new site UUID.
257     $config_data['uuid'] = \Drupal::service('uuid')->generate();
258     $sync->write('system.site', $config_data);
259
260     // Verify that there are configuration differences to import.
261     $this->drupalGet('admin/config/development/configuration');
262     $this->assertText(t('The staged configuration cannot be imported, because it originates from a different site than this site. You can only synchronize configuration between cloned instances of this site.'));
263     $this->assertNoFieldById('edit-submit', t('Import all'));
264   }
265
266   /**
267    * Tests the screen that shows differences between active and sync.
268    */
269   public function testImportDiff() {
270     $sync = $this->container->get('config.storage.sync');
271     $config_name = 'config_test.system';
272     $change_key = 'foo';
273     $remove_key = '404';
274     $add_key = 'biff';
275     $add_data = '<em>bangpow</em>';
276     $change_data = '<p><em>foobar</em></p>';
277     $original_data = [
278       'foo' => '<p>foobar</p>',
279       'baz' => '<strong>no change</strong>',
280       '404' => '<em>herp</em>',
281     ];
282     // Update active storage to have html in config data.
283     $this->config($config_name)->setData($original_data)->save();
284
285     // Change a configuration value in sync.
286     $sync_data = $original_data;
287     $sync_data[$change_key] = $change_data;
288     $sync_data[$add_key] = $add_data;
289     unset($sync_data[$remove_key]);
290     $sync->write($config_name, $sync_data);
291
292     // Load the diff UI and verify that the diff reflects the change.
293     $this->drupalGet('admin/config/development/configuration/sync/diff/' . $config_name);
294     $this->assertNoRaw('&amp;nbsp;');
295     $this->assertTitle(format_string('View changes of @config_name | Drupal', ['@config_name' => $config_name]));
296
297     // The following assertions do not use $this::assertEscaped() because
298     // \Drupal\Component\Diff\DiffFormatter adds markup that signifies what has
299     // changed.
300
301     // Changed values are escaped.
302     $this->assertText(Html::escape("foo: '<p><em>foobar</em></p>'"));
303     $this->assertText(Html::escape("foo: '<p>foobar</p>'"));
304     // The no change values are escaped.
305     $this->assertText(Html::escape("baz: '<strong>no change</strong>'"));
306     // Added value is escaped.
307     $this->assertText(Html::escape("biff: '<em>bangpow</em>'"));
308     // Deleted value is escaped.
309     $this->assertText(Html::escape("404: '<em>herp</em>'"));
310
311     // Verify diff colors are displayed.
312     $result = $this->xpath('//table[contains(@class, :class)]', [':class' => 'diff']);
313     $this->assertEqual(count($result), 1, "Diff UI is displaying colors.");
314
315     // Reset data back to original, and remove a key
316     $sync_data = $original_data;
317     unset($sync_data[$remove_key]);
318     $sync->write($config_name, $sync_data);
319
320     // Load the diff UI and verify that the diff reflects a removed key.
321     $this->drupalGet('admin/config/development/configuration/sync/diff/' . $config_name);
322     // The no change values are escaped.
323     $this->assertText(Html::escape("foo: '<p>foobar</p>'"));
324     $this->assertText(Html::escape("baz: '<strong>no change</strong>'"));
325     // Removed key is escaped.
326     $this->assertText(Html::escape("404: '<em>herp</em>'"));
327
328     // Reset data back to original and add a key
329     $sync_data = $original_data;
330     $sync_data[$add_key] = $add_data;
331     $sync->write($config_name, $sync_data);
332
333     // Load the diff UI and verify that the diff reflects an added key.
334     $this->drupalGet('admin/config/development/configuration/sync/diff/' . $config_name);
335     // The no change values are escaped.
336     $this->assertText(Html::escape("baz: '<strong>no change</strong>'"));
337     $this->assertText(Html::escape("404: '<em>herp</em>'"));
338     // Added key is escaped.
339     $this->assertText(Html::escape("biff: '<em>bangpow</em>'"));
340   }
341
342   /**
343    * Tests that multiple validation errors are listed on the page.
344    */
345   public function testImportValidation() {
346     // Set state value so that
347     // \Drupal\config_import_test\EventSubscriber::onConfigImportValidate() logs
348     // validation errors.
349     \Drupal::state()->set('config_import_test.config_import_validate_fail', TRUE);
350     // Ensure there is something to import.
351     $new_site_name = 'Config import test ' . $this->randomString();
352     $this->prepareSiteNameUpdate($new_site_name);
353
354     $this->drupalGet('admin/config/development/configuration');
355     $this->assertNoText(t('There are no configuration changes to import.'));
356     $this->drupalPostForm(NULL, [], t('Import all'));
357
358     // Verify that the validation messages appear.
359     $this->assertText('The configuration cannot be imported because it failed validation for the following reasons:');
360     $this->assertText('Config import validate error 1.');
361     $this->assertText('Config import validate error 2.');
362
363     // Verify site name has not changed.
364     $this->assertNotEqual($new_site_name, $this->config('system.site')->get('name'));
365   }
366
367   public function testConfigUninstallConfigException() {
368     $sync = $this->container->get('config.storage.sync');
369
370     $core_extension = $this->config('core.extension')->get();
371     unset($core_extension['module']['config']);
372     $sync->write('core.extension', $core_extension);
373
374     $this->drupalGet('admin/config/development/configuration');
375     $this->assertText('core.extension');
376
377     // Import and verify that both do not appear anymore.
378     $this->drupalPostForm(NULL, [], t('Import all'));
379     $this->assertText('Can not uninstall the Configuration module as part of a configuration synchronization through the user interface.');
380   }
381
382   public function prepareSiteNameUpdate($new_site_name) {
383     $sync = $this->container->get('config.storage.sync');
384     // Create updated configuration object.
385     $config_data = $this->config('system.site')->get();
386     $config_data['name'] = $new_site_name;
387     $sync->write('system.site', $config_data);
388   }
389
390   /**
391    * Tests an import that results in an error.
392    */
393   public function testImportErrorLog() {
394     $name_primary = 'config_test.dynamic.primary';
395     $name_secondary = 'config_test.dynamic.secondary';
396     $sync = $this->container->get('config.storage.sync');
397     $uuid = $this->container->get('uuid');
398
399     $values_primary = [
400       'uuid' => $uuid->generate(),
401       'langcode' => 'en',
402       'status' => TRUE,
403       'dependencies' => [],
404       'id' => 'primary',
405       'label' => 'Primary',
406       'weight' => 0,
407       'style' => NULL,
408       'size' => NULL,
409       'size_value' => NULL,
410       'protected_property' => NULL,
411     ];
412     $sync->write($name_primary, $values_primary);
413     $values_secondary = [
414       'uuid' => $uuid->generate(),
415       'langcode' => 'en',
416       'status' => TRUE,
417       // Add a dependency on primary, to ensure that is synced first.
418       'dependencies' => [
419         'config' => [$name_primary],
420       ],
421       'id' => 'secondary',
422       'label' => 'Secondary Sync',
423       'weight' => 0,
424       'style' => NULL,
425       'size' => NULL,
426       'size_value' => NULL,
427       'protected_property' => NULL,
428     ];
429     $sync->write($name_secondary, $values_secondary);
430     // Verify that there are configuration differences to import.
431     $this->drupalGet('admin/config/development/configuration');
432     $this->assertNoText(t('There are no configuration changes to import.'));
433
434     // Attempt to import configuration and verify that an error message appears.
435     $this->drupalPostForm(NULL, [], t('Import all'));
436     $this->assertText(new FormattableMarkup('Deleted and replaced configuration entity "@name"', ['@name' => $name_secondary]));
437     $this->assertText(t('The configuration was imported with errors.'));
438     $this->assertNoText(t('The configuration was imported successfully.'));
439     $this->assertText(t('There are no configuration changes to import.'));
440   }
441
442   /**
443    * Tests the config importer cannot delete bundles with existing entities.
444    *
445    * @see \Drupal\Core\Entity\Event\BundleConfigImportValidate
446    */
447   public function testEntityBundleDelete() {
448     \Drupal::service('module_installer')->install(['node']);
449     $this->copyConfig($this->container->get('config.storage'), $this->container->get('config.storage.sync'));
450
451     $node_type = $this->drupalCreateContentType();
452     $node = $this->drupalCreateNode(['type' => $node_type->id()]);
453     $this->drupalGet('admin/config/development/configuration');
454     // The node type, body field and entity displays will be scheduled for
455     // removal.
456     $this->assertText(format_string('node.type.@type', ['@type' => $node_type->id()]));
457     $this->assertText(format_string('field.field.node.@type.body', ['@type' => $node_type->id()]));
458     $this->assertText(format_string('core.entity_view_display.node.@type.teaser', ['@type' => $node_type->id()]));
459     $this->assertText(format_string('core.entity_view_display.node.@type.default', ['@type' => $node_type->id()]));
460     $this->assertText(format_string('core.entity_form_display.node.@type.default', ['@type' => $node_type->id()]));
461
462     // Attempt to import configuration and verify that an error message appears
463     // and the node type, body field and entity displays are still scheduled for
464     // removal.
465     $this->drupalPostForm(NULL, [], t('Import all'));
466     $validation_message = t('Entities exist of type %entity_type and %bundle_label %bundle. These entities need to be deleted before importing.', ['%entity_type' => $node->getEntityType()->getLabel(), '%bundle_label' => $node->getEntityType()->getBundleLabel(), '%bundle' => $node_type->label()]);
467     $this->assertRaw($validation_message);
468     $this->assertText(format_string('node.type.@type', ['@type' => $node_type->id()]));
469     $this->assertText(format_string('field.field.node.@type.body', ['@type' => $node_type->id()]));
470     $this->assertText(format_string('core.entity_view_display.node.@type.teaser', ['@type' => $node_type->id()]));
471     $this->assertText(format_string('core.entity_view_display.node.@type.default', ['@type' => $node_type->id()]));
472     $this->assertText(format_string('core.entity_form_display.node.@type.default', ['@type' => $node_type->id()]));
473
474     // Delete the node and try to import again.
475     $node->delete();
476     $this->drupalPostForm(NULL, [], t('Import all'));
477     $this->assertNoRaw($validation_message);
478     $this->assertText(t('There are no configuration changes to import.'));
479     $this->assertNoText(format_string('node.type.@type', ['@type' => $node_type->id()]));
480     $this->assertNoText(format_string('field.field.node.@type.body', ['@type' => $node_type->id()]));
481     $this->assertNoText(format_string('core.entity_view_display.node.@type.teaser', ['@type' => $node_type->id()]));
482     $this->assertNoText(format_string('core.entity_view_display.node.@type.default', ['@type' => $node_type->id()]));
483     $this->assertNoText(format_string('core.entity_form_display.node.@type.default', ['@type' => $node_type->id()]));
484   }
485
486   /**
487    * Tests config importer cannot uninstall extensions which are depended on.
488    *
489    * @see \Drupal\Core\EventSubscriber\ConfigImportSubscriber
490    */
491   public function testExtensionValidation() {
492     \Drupal::service('module_installer')->install(['node']);
493     \Drupal::service('theme_handler')->install(['bartik']);
494     $this->rebuildContainer();
495
496     $sync = $this->container->get('config.storage.sync');
497     $this->copyConfig($this->container->get('config.storage'), $sync);
498     $core = $sync->read('core.extension');
499     // Node depends on text.
500     unset($core['module']['text']);
501     $module_data = system_rebuild_module_data();
502     $this->assertTrue(isset($module_data['node']->requires['text']), 'The Node module depends on the Text module.');
503     // Bartik depends on classy.
504     unset($core['theme']['classy']);
505     $theme_data = \Drupal::service('theme_handler')->rebuildThemeData();
506     $this->assertTrue(isset($theme_data['bartik']->requires['classy']), 'The Bartik theme depends on the Classy theme.');
507     // This module does not exist.
508     $core['module']['does_not_exist'] = 0;
509     // This theme does not exist.
510     $core['theme']['does_not_exist'] = 0;
511     $sync->write('core.extension', $core);
512
513     $this->drupalPostForm('admin/config/development/configuration', [], t('Import all'));
514     $this->assertText('The configuration cannot be imported because it failed validation for the following reasons:');
515     $this->assertText('Unable to uninstall the Text module since the Node module is installed.');
516     $this->assertText('Unable to uninstall the Classy theme since the Bartik theme is installed.');
517     $this->assertText('Unable to install the does_not_exist module since it does not exist.');
518     $this->assertText('Unable to install the does_not_exist theme since it does not exist.');
519   }
520
521   /**
522    * Tests that errors set in the batch and on the ConfigImporter are merged.
523    */
524   public function testBatchErrors() {
525     $new_site_name = 'Config import test ' . $this->randomString();
526     $this->prepareSiteNameUpdate($new_site_name);
527     \Drupal::state()->set('config_import_steps_alter.error', TRUE);
528     $this->drupalPostForm('admin/config/development/configuration', [], t('Import all'));
529     $this->assertSession()->responseContains('_config_import_test_config_import_steps_alter batch error');
530     $this->assertSession()->responseContains('_config_import_test_config_import_steps_alter ConfigImporter error');
531     $this->assertSession()->responseContains('The configuration was imported with errors.');
532   }
533
534 }