clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
/**
* Tests if configuration overrides correctly affect cacheability metadata.
*
* @group config
*/
class CacheabilityMetadataConfigOverrideIntegrationTest extends BrowserTestBase {
use AssertPageCacheContextsAndTagsTrait;
/**
* {@inheritdoc}
*/
protected static $modules = [
'block_test',
'config_override_integration_test',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// @todo If our block does not contain any content then the cache context
// is not bubbling up and the test fails. Remove this line once the cache
// contexts are properly set. See https://www.drupal.org/node/2529980.
\Drupal::state()->set('block_test.content', 'Needs to have some content');
$this->drupalLogin($this->drupalCreateUser());
}
/**
* Tests if config overrides correctly set cacheability metadata.
*/
public function testConfigOverride(): void {
// Check the default (disabled) state of the cache context. The block label
// should not be overridden.
$this->drupalGet('<front>');
$this->assertSession()->pageTextNotContains('Overridden block label');
// Both the cache context and tag should be present.
$this->assertCacheContext('config_override_integration_test');
$this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', 'config_override_integration_test_tag');
// Flip the state of the cache context. The block label should now be
// overridden.
\Drupal::state()->set('config_override_integration_test.enabled', TRUE);
$this->drupalGet('<front>');
$this->assertSession()->pageTextContains('Overridden block label');
// Both the cache context and tag should still be present.
$this->assertCacheContext('config_override_integration_test');
$this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', 'config_override_integration_test_tag');
}
}
@@ -0,0 +1,139 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Core\Config\Entity\ConfigEntityStorage;
use Drupal\Tests\BrowserTestBase;
/**
* Tests configuration entities.
*
* @group config
*/
class ConfigDependencyWebTest extends BrowserTestBase {
/**
* The maximum length for the entity storage used in this test.
*/
const MAX_ID_LENGTH = ConfigEntityStorage::MAX_ID_LENGTH;
/**
* {@inheritdoc}
*/
protected static $modules = ['config_test'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests ConfigDependencyDeleteFormTrait.
*
* @see \Drupal\Core\Config\Entity\ConfigDependencyDeleteFormTrait
*/
public function testConfigDependencyDeleteFormTrait(): void {
$this->drupalLogin($this->drupalCreateUser([
'administer site configuration',
]));
/** @var \Drupal\Core\Config\Entity\ConfigEntityStorage $storage */
$storage = $this->container->get('entity_type.manager')->getStorage('config_test');
// Entity1 will be deleted by the test.
$entity1 = $storage->create(
[
'id' => 'entity1',
'label' => 'Entity One',
]
);
$entity1->save();
// Entity2 has a dependency on Entity1 but it can be fixed because
// \Drupal\config_test\Entity::onDependencyRemoval() will remove the
// dependency before config entities are deleted.
$entity2 = $storage->create(
[
'id' => 'entity2',
'dependencies' => [
'enforced' => [
'config' => [$entity1->getConfigDependencyName()],
],
],
]
);
$entity2->save();
$this->drupalGet($entity2->toUrl('delete-form'));
$this->assertSession()->pageTextNotContains('Configuration updates');
$this->assertSession()->pageTextNotContains('Configuration deletions');
$this->drupalGet($entity1->toUrl('delete-form'));
$this->assertSession()->pageTextNotContains('Configuration updates');
$this->assertSession()->pageTextContains('Configuration deletions');
$this->assertSession()->pageTextContains($entity2->id());
$this->drupalGet($entity1->toUrl('delete-form'));
$this->submitForm([], 'Delete');
$storage->resetCache();
$this->assertEmpty($storage->loadMultiple([$entity1->id(), $entity2->id()]), 'Test entities deleted');
// Set a more complicated test where dependencies will be fixed.
// Entity1 will be deleted by the test.
$entity1 = $storage->create(
[
'id' => 'entity1',
]
);
$entity1->save();
\Drupal::state()->set('config_test.fix_dependencies', [$entity1->getConfigDependencyName()]);
// Entity2 has a dependency on Entity1 but it can be fixed because
// \Drupal\config_test\Entity::onDependencyRemoval() will remove the
// dependency before config entities are deleted.
$entity2 = $storage->create(
[
'id' => 'entity2',
'label' => 'Entity Two',
'dependencies' => [
'enforced' => [
'config' => [$entity1->getConfigDependencyName()],
],
],
]
);
$entity2->save();
// Entity3 will be unchanged because it is dependent on Entity2 which can
// be fixed.
$entity3 = $storage->create(
[
'id' => 'entity3',
'dependencies' => [
'enforced' => [
'config' => [$entity2->getConfigDependencyName()],
],
],
]
);
$entity3->save();
$this->drupalGet($entity1->toUrl('delete-form'));
$this->assertSession()->pageTextContains('Configuration updates');
$this->assertSession()->pageTextNotContains('Configuration deletions');
$this->assertSession()->pageTextNotContains($entity2->id());
$this->assertSession()->pageTextContains($entity2->label());
$this->assertSession()->pageTextNotContains($entity3->id());
$this->drupalGet($entity1->toUrl('delete-form'));
$this->submitForm([], 'Delete');
$storage->resetCache();
$this->assertNull($storage->load('entity1'), 'Test entity 1 deleted');
$entity2 = $storage->load('entity2');
$this->assertNotEmpty($entity2, 'Entity 2 not deleted');
$this->assertEquals([], $entity2->calculateDependencies()->getDependencies()['config'], 'Entity 2 dependencies updated to remove dependency on Entity1.');
$entity3 = $storage->load('entity3');
$this->assertNotEmpty($entity3, 'Entity 3 not deleted');
$this->assertEquals([$entity2->getConfigDependencyName()], $entity3->calculateDependencies()->getDependencies()['config'], 'Entity 3 still depends on Entity 2.');
}
}
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Component\Utility\Html;
use Drupal\Tests\BrowserTestBase;
use Drupal\user\Entity\Role;
/**
* Tests draggable list builder.
*
* @group config
*/
class ConfigDraggableListBuilderTest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['config_test'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests draggable lists.
*/
public function testDraggableList(): void {
$this->drupalLogin($this->drupalCreateUser(['administer permissions']));
// Create more than 50 roles.
for ($i = 0; $i < 51; $i++) {
$role = Role::create([
'id' => 'role_' . $i,
'label' => "Role $i",
]);
$role->save();
}
// Navigate to Roles page
$this->drupalGet('admin/people/roles');
// Test for the page title.
$this->assertSession()->titleEquals('Roles | Drupal');
// Count the number of rows in table.
$rows = $this->xpath('//form[@class="user-admin-roles-form"]/table/tbody/tr');
$this->assertGreaterThan(50, count($rows));
for ($i = 0; $i < 51; $i++) {
$this->assertSession()->pageTextContains("Role $i");
}
$role = Role::load('role_0');
$role_name = 'Role <b>0</b>';
$role->set('label', $role_name)->save();
$this->drupalGet('admin/people/roles');
$this->assertSession()->responseContains('<td>' . Html::escape($role_name));
// Make sure that NULL weights do not break the list builder. Use the
// configuration API so that the value does not get type-casted according to
// the configuration schema.
\Drupal::configFactory()
->getEditable('user.role.role_0')
->set('weight', NULL)
->save(TRUE);
$this->drupalGet('admin/people/roles');
$this->assertSession()->statusCodeEquals(200);
}
}
@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Tests that config overrides do not bleed through in entity forms and lists.
*
* @group config
*/
class ConfigEntityFormOverrideTest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['config_test'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests that overrides do not affect forms or listing screens.
*/
public function testFormsWithOverrides(): void {
$this->drupalLogin($this->drupalCreateUser([
'administer site configuration',
]));
$original_label = 'Default';
$overridden_label = 'Overridden label';
$edited_label = 'Edited label';
$config_test_storage = $this->container->get('entity_type.manager')->getStorage('config_test');
// Set up an override.
$settings['config']['config_test.dynamic.dotted.default']['label'] = (object) [
'value' => $overridden_label,
'required' => TRUE,
];
$this->writeSettings($settings);
// Test that the overridden label is loaded with the entity.
$this->assertEquals($overridden_label, $config_test_storage->load('dotted.default')->label());
// Test that the original label on the listing page is intact.
$this->drupalGet('admin/structure/config_test');
$this->assertSession()->pageTextContains($original_label);
$this->assertSession()->pageTextNotContains($overridden_label);
// Test that the original label on the editing page is intact.
$this->drupalGet('admin/structure/config_test/manage/dotted.default');
$this->assertSession()->fieldValueEquals('label', $original_label);
$this->assertSession()->pageTextNotContains($overridden_label);
// Change to a new label and test that the listing now has the edited label.
$edit = [
'label' => $edited_label,
];
$this->submitForm($edit, 'Save');
$this->drupalGet('admin/structure/config_test');
$this->assertSession()->pageTextNotContains($overridden_label);
$this->assertSession()->pageTextContains($edited_label);
// Test that the editing page now has the edited label.
$this->drupalGet('admin/structure/config_test/manage/dotted.default');
$this->assertSession()->fieldValueEquals('label', $edited_label);
// Test that the overridden label is still loaded with the entity.
$this->assertEquals($overridden_label, $config_test_storage->load('dotted.default')->label());
}
}
@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Tests\BrowserTestBase;
use Drupal\language\Entity\ConfigurableLanguage;
// cspell:ignore antilop
/**
* Tests the listing of configuration entities in a multilingual scenario.
*
* @group config
*/
class ConfigEntityListMultilingualTest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['config_test', 'language', 'block'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Delete the override config_test entity. It is not required by this test.
\Drupal::entityTypeManager()->getStorage('config_test')->load('override')->delete();
ConfigurableLanguage::createFromLangcode('hu')->save();
$this->drupalPlaceBlock('local_actions_block');
}
/**
* Tests the listing UI with different language scenarios.
*/
public function testListUI(): void {
// Log in as an administrative user to access the full menu trail.
$this->drupalLogin($this->drupalCreateUser([
'access administration pages',
'administer site configuration',
]));
// Get the list page.
$this->drupalGet('admin/structure/config_test');
$this->assertSession()->linkByHrefExists('admin/structure/config_test/manage/dotted.default');
// Add a new entity using the action link.
$this->clickLink('Add test configuration');
$edit = [
'label' => 'Antilop',
'id' => 'antilop',
'langcode' => 'hu',
];
$this->submitForm($edit, 'Save');
// Ensure that operations for editing the Hungarian entity appear in English.
$this->assertSession()->linkByHrefExists('admin/structure/config_test/manage/antilop');
// Get the list page in Hungarian and assert Hungarian admin links
// regardless of language of config entities.
$this->drupalGet('hu/admin/structure/config_test');
$this->assertSession()->linkByHrefExists('hu/admin/structure/config_test/manage/dotted.default');
$this->assertSession()->linkByHrefExists('hu/admin/structure/config_test/manage/antilop');
}
}
@@ -0,0 +1,346 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Routing\RedirectDestinationTrait;
use Drupal\config_test\Entity\ConfigTest;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Tests\BrowserTestBase;
/**
* Tests the listing of configuration entities.
*
* @group config
*/
class ConfigEntityListTest extends BrowserTestBase {
use RedirectDestinationTrait;
/**
* {@inheritdoc}
*/
protected static $modules = ['block', 'config_test'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Delete the override config_test entity since it is not required by this
// test.
\Drupal::entityTypeManager()->getStorage('config_test')->load('override')->delete();
$this->drupalPlaceBlock('local_actions_block');
}
/**
* Tests entity list builder methods.
*/
public function testList(): void {
$controller = \Drupal::entityTypeManager()->getListBuilder('config_test');
// Test getStorage() method.
$this->assertInstanceOf(EntityStorageInterface::class, $controller->getStorage());
// Get a list of ConfigTest entities and confirm that it contains the
// ConfigTest entity provided by the config_test module.
// @see config_test.dynamic.dotted.default.yml
$list = $controller->load();
$this->assertCount(1, $list, '1 ConfigTest entity found.');
$entity = $list['dotted.default'];
$this->assertInstanceOf(ConfigTest::class, $entity);
// Test getOperations() method.
$edit_url = $entity->toUrl()->setOption('query', $this->getRedirectDestination()->getAsArray());
$edit_url->setOption('attributes', ['aria-label' => 'Edit ' . $entity->label()]);
$delete_url = $entity->toUrl('delete-form')->setOption('query', $this->getRedirectDestination()->getAsArray());
$delete_url->setOption('attributes', ['aria-label' => 'Delete ' . $entity->label()]);
$expected_operations = [
'edit' => [
'title' => 'Edit',
'weight' => 10,
'url' => $edit_url,
],
'disable' => [
'title' => 'Disable',
'weight' => 40,
'url' => $entity->toUrl('disable')->setOption('query', $this->getRedirectDestination()->getAsArray()),
],
'delete' => [
'title' => 'Delete',
'weight' => 100,
'attributes' => [
'class' => ['use-ajax'],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 880,
]),
],
'url' => $delete_url,
],
];
$actual_operations = $controller->getOperations($entity);
// Sort the operations to normalize link order.
uasort($actual_operations, ['Drupal\Component\Utility\SortArray', 'sortByWeightElement']);
$this->assertEquals($expected_operations, $actual_operations, 'The operations are identical.');
// Test buildHeader() method.
$expected_items = [
'label' => 'Label',
'id' => 'Machine name',
'operations' => 'Operations',
];
$actual_items = $controller->buildHeader();
$this->assertEquals($expected_items, $actual_items, 'Return value from buildHeader matches expected.');
// Test buildRow() method.
$build_operations = $controller->buildOperations($entity);
$expected_items = [
'label' => 'Default',
'id' => 'dotted.default',
'operations' => [
'data' => $build_operations,
],
];
$actual_items = $controller->buildRow($entity);
$this->assertEquals($expected_items, $actual_items, 'Return value from buildRow matches expected.');
// Test sorting.
$storage = $controller->getStorage();
$entity = $storage->create([
'id' => 'alpha',
'label' => 'Alpha',
'weight' => 1,
]);
$entity->save();
$entity = $storage->create([
'id' => 'omega',
'label' => 'Omega',
'weight' => 1,
]);
$entity->save();
$entity = $storage->create([
'id' => 'beta',
'label' => 'Beta',
'weight' => 0,
]);
$entity->save();
$list = $controller->load();
$this->assertSame(['beta', 'dotted.default', 'alpha', 'omega'], array_keys($list));
// Test that config entities that do not support status, do not have
// enable/disable operations.
$controller = $this->container->get('entity_type.manager')
->getListBuilder('config_test_no_status');
$list = $controller->load();
$entity = $list['default'];
// Test getOperations() method.
$edit_url = $entity->toUrl()->setOption('query', $this->getRedirectDestination()->getAsArray());
$edit_url->setOption('attributes', ['aria-label' => 'Edit ' . $entity->label()]);
$delete_url = $entity->toUrl('delete-form')->setOption('query', $this->getRedirectDestination()->getAsArray());
$delete_url->setOption('attributes', ['aria-label' => 'Delete ' . $entity->label()]);
$expected_operations = [
'edit' => [
'title' => 'Edit',
'weight' => 10,
'url' => $edit_url,
],
'delete' => [
'title' => 'Delete',
'weight' => 100,
'attributes' => [
'class' => ['use-ajax'],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 880,
]),
],
'url' => $delete_url,
],
];
$actual_operations = $controller->getOperations($entity);
// Sort the operations to normalize link order.
uasort($actual_operations, ['Drupal\Component\Utility\SortArray', 'sortByWeightElement']);
$this->assertEquals($expected_operations, $actual_operations, 'The operations are identical.');
// Test getOperations when label doesn't exist.
$entity->set('label', '');
$entity->save();
$edit_url = $entity->toUrl()->setOption('query', $this->getRedirectDestination()->getAsArray());
$edit_url->setOption('attributes', ['aria-label' => 'Edit ' . $entity->bundle() . ' ' . $entity->id()]);
$delete_url = $entity->toUrl('delete-form')->setOption('query', $this->getRedirectDestination()->getAsArray());
$delete_url->setOption('attributes', ['aria-label' => 'Delete ' . $entity->bundle() . ' ' . $entity->id()]);
$expected_operations = [
'edit' => [
'title' => 'Edit',
'weight' => 10,
'url' => $edit_url,
],
'delete' => [
'title' => 'Delete',
'weight' => 100,
'attributes' => [
'class' => ['use-ajax'],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 880,
]),
],
'url' => $delete_url,
],
];
$actual_operations = $controller->getOperations($entity);
// Sort the operations to normalize link order.
uasort($actual_operations, ['Drupal\Component\Utility\SortArray', 'sortByWeightElement']);
$this->assertEquals($expected_operations, $actual_operations, 'The operations are identical.');
}
/**
* Tests the listing UI.
*/
public function testListUI(): void {
// Log in as an administrative user to access the full menu trail.
$this->drupalLogin($this->drupalCreateUser([
'access administration pages',
'administer site configuration',
]));
// Get the list callback page.
$this->drupalGet('admin/structure/config_test');
// Test for the page title.
$this->assertSession()->titleEquals('Test configuration | Drupal');
// Test for the table.
$this->assertSession()->elementsCount('xpath', '//div[@class="layout-content"]//table', 1);
// Test the table header.
$this->assertSession()->elementsCount('xpath', '//div[@class="layout-content"]//table/thead/tr/th', 3);
// Test the contents of each th cell.
$this->assertSession()->elementTextEquals('xpath', '//div[@class="layout-content"]//table/thead/tr/th[1]', 'Label');
$this->assertSession()->elementTextEquals('xpath', '//div[@class="layout-content"]//table/thead/tr/th[2]', 'Machine name');
$this->assertSession()->elementTextEquals('xpath', '//div[@class="layout-content"]//table/thead/tr/th[3]', 'Operations');
// Check the number of table row cells.
$this->assertSession()->elementsCount('xpath', '//div[@class="layout-content"]//table/tbody/tr[1]/td', 3);
// Check the contents of each row cell. The first cell contains the label,
// the second contains the machine name, and the third contains the
// operations list.
$this->assertSession()->elementTextEquals('xpath', '//div[@class="layout-content"]//table/tbody/tr[1]/td[1]', 'Default');
$this->assertSession()->elementTextEquals('xpath', '//div[@class="layout-content"]//table/tbody/tr[1]/td[2]', 'dotted.default');
$this->assertSession()->elementExists('xpath', '//div[@class="layout-content"]//table/tbody/tr[1]/td[3]//ul');
// Add a new entity using the operations link.
$this->assertSession()->linkExists('Add test configuration');
$this->clickLink('Add test configuration');
$this->assertSession()->statusCodeEquals(200);
$edit = [
'label' => 'Antelope',
'id' => 'antelope',
'weight' => 1,
];
$this->submitForm($edit, 'Save');
// Ensure that the entity's sort method was called.
$this->assertTrue(\Drupal::state()->get('config_entity_sort'), 'ConfigTest::sort() was called.');
// Confirm that the user is returned to the listing, and verify that the
// text of the label and machine name appears in the list (versus elsewhere
// on the page).
$this->assertSession()->elementExists('xpath', '//td[text() = "Antelope"]');
$this->assertSession()->elementExists('xpath', '//td[text() = "antelope"]');
// Edit the entity using the operations link.
$this->assertSession()->linkByHrefExists('admin/structure/config_test/manage/antelope');
$this->clickLink('Edit', 1);
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->titleEquals('Edit Antelope | Drupal');
$edit = ['label' => 'Albatross', 'id' => 'albatross'];
$this->submitForm($edit, 'Save');
// Confirm that the user is returned to the listing, and verify that the
// text of the label and machine name appears in the list (versus elsewhere
// on the page).
$this->assertSession()->elementExists('xpath', '//td[text() = "Albatross"]');
$this->assertSession()->elementExists('xpath', '//td[text() = "albatross"]');
// Delete the added entity using the operations link.
$this->assertSession()->linkByHrefExists('admin/structure/config_test/manage/albatross/delete');
$this->clickLink('Delete', 1);
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->titleEquals('Are you sure you want to delete the test configuration Albatross? | Drupal');
$this->submitForm([], 'Delete');
// Verify that the text of the label and machine name does not appear in
// the list (though it may appear elsewhere on the page).
$this->assertSession()->elementNotExists('xpath', '//td[text() = "Albatross"]');
$this->assertSession()->elementNotExists('xpath', '//td[text() = "albatross"]');
// Delete the original entity using the operations link.
$this->clickLink('Delete');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->titleEquals('Are you sure you want to delete the test configuration Default? | Drupal');
$this->submitForm([], 'Delete');
// Verify that the text of the label and machine name does not appear in
// the list (though it may appear elsewhere on the page).
$this->assertSession()->elementNotExists('xpath', '//td[text() = "Default"]');
$this->assertSession()->elementNotExists('xpath', '//td[text() = "dotted.default"]');
// Confirm that the empty text is displayed.
$this->assertSession()->pageTextContains('There are no test configuration entities yet.');
}
/**
* Tests paging.
*/
public function testPager(): void {
$this->drupalLogin($this->drupalCreateUser([
'administer site configuration',
]));
$storage = \Drupal::service('entity_type.manager')->getListBuilder('config_test')->getStorage();
// Create 51 test entities.
for ($i = 1; $i < 52; $i++) {
$storage->create([
'id' => str_pad((string) $i, 2, '0', STR_PAD_LEFT),
'label' => 'Test config entity ' . $i,
'weight' => $i,
'protected_property' => $i,
])->save();
}
// Load the listing page.
$this->drupalGet('admin/structure/config_test');
// Item 51 should not be present.
$this->assertSession()->pageTextContains('Test config entity 50');
$this->assertSession()->responseNotContains('Test config entity 51');
// Browse to the next page, test config entity 51 is on page 2.
$this->clickLink('Page 2');
$this->assertSession()->responseNotContains('Test config entity 50');
$this->assertSession()->responseContains('dotted.default');
$this->assertSession()->pageTextContains('Test config entity 51');
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Tests configuration entity status UI functionality.
*
* @group config
*/
class ConfigEntityStatusUITest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['config_test'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests status operations.
*/
public function testCRUD(): void {
$this->drupalLogin($this->drupalCreateUser([
'administer site configuration',
]));
$id = $this->randomMachineName();
$edit = [
'id' => $id,
'label' => $this->randomMachineName(),
];
$this->drupalGet('admin/structure/config_test/add');
$this->submitForm($edit, 'Save');
$entity = \Drupal::entityTypeManager()->getStorage('config_test')->load($id);
// Disable an entity.
$disable_url = $entity->toUrl('disable');
$this->assertSession()->linkByHrefExists($disable_url->toString());
$this->drupalGet($disable_url);
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->linkByHrefNotExists($disable_url->toString());
// Enable an entity.
$enable_url = $entity->toUrl('enable');
$this->assertSession()->linkByHrefExists($enable_url->toString());
$this->drupalGet($enable_url);
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->linkByHrefNotExists($enable_url->toString());
}
}
@@ -0,0 +1,353 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Component\Uuid\Uuid;
use Drupal\Core\Entity\EntityMalformedException;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Config\Entity\ConfigEntityStorage;
use Drupal\Core\Config\Entity\Exception\ConfigEntityIdLengthException;
use Drupal\Core\Url;
use Drupal\Tests\BrowserTestBase;
/**
* Tests configuration entities.
*
* @group config
*/
class ConfigEntityTest extends BrowserTestBase {
/**
* The maximum length for the entity storage used in this test.
*/
const MAX_ID_LENGTH = ConfigEntityStorage::MAX_ID_LENGTH;
/**
* {@inheritdoc}
*/
protected static $modules = ['config_test'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests CRUD operations.
*/
public function testCRUD(): void {
$default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
// Verify default properties on a newly created empty entity.
$storage = \Drupal::entityTypeManager()->getStorage('config_test');
$empty = $storage->create();
$this->assertNull($empty->label);
$this->assertNull($empty->style);
$this->assertSame($default_langcode, $empty->language()->getId());
// Verify ConfigEntity properties/methods on the newly created empty entity.
$this->assertTrue($empty->isNew());
$this->assertNull($empty->getOriginalId());
$this->assertSame('config_test', $empty->bundle());
$this->assertNull($empty->id());
$this->assertTrue(Uuid::isValid($empty->uuid()));
$this->assertNull($empty->label());
$this->assertNull($empty->get('id'));
$this->assertTrue(Uuid::isValid($empty->get('uuid')));
$this->assertNull($empty->get('label'));
$this->assertNull($empty->get('style'));
$this->assertSame($default_langcode, $empty->language()->getId());
// Verify Entity properties/methods on the newly created empty entity.
$this->assertSame('config_test', $empty->getEntityTypeId());
// The URI can only be checked after saving.
try {
$empty->toUrl();
$this->fail('EntityMalformedException was thrown.');
}
catch (EntityMalformedException $e) {
// Expected exception; just continue testing.
}
// Verify that an empty entity cannot be saved.
try {
$empty->save();
$this->fail('EntityMalformedException was thrown.');
}
catch (EntityMalformedException $e) {
// Expected exception; just continue testing.
}
// Verify that an entity with an empty ID string is considered empty, too.
$empty_id = $storage->create([
'id' => '',
]);
$this->assertTrue($empty_id->isNew());
try {
$empty_id->save();
$this->fail('EntityMalformedException was thrown.');
}
catch (EntityMalformedException $e) {
// Expected exception; just continue testing.
}
// Verify properties on a newly created entity.
$config_test = $storage->create($expected = [
'id' => $this->randomMachineName(),
'label' => $this->randomString(),
'style' => $this->randomMachineName(),
]);
$this->assertNotEquals($empty->uuid(), $config_test->uuid());
$this->assertSame($expected['label'], $config_test->label);
$this->assertSame($expected['style'], $config_test->style);
$this->assertSame($default_langcode, $config_test->language()->getId());
// Verify methods on the newly created entity.
$this->assertTrue($config_test->isNew());
$this->assertSame($expected['id'], $config_test->getOriginalId());
$this->assertSame($expected['id'], $config_test->id());
$this->assertTrue(Uuid::isValid($config_test->uuid()));
$expected['uuid'] = $config_test->uuid();
$this->assertSame($expected['label'], $config_test->label());
// Verify that the entity can be saved.
try {
$status = $config_test->save();
}
catch (EntityMalformedException $e) {
$this->fail('EntityMalformedException was not thrown.');
}
// The entity path can only be checked after saving.
$this->assertSame(Url::fromRoute('entity.config_test.edit_form', ['config_test' => $expected['id']])->toString(), $config_test->toUrl()->toString());
// Verify that the correct status is returned and properties did not change.
$this->assertSame(SAVED_NEW, $status);
$this->assertSame($expected['id'], $config_test->id());
$this->assertSame($expected['uuid'], $config_test->uuid());
$this->assertSame($expected['label'], $config_test->label());
$this->assertFalse($config_test->isNew());
$this->assertSame($expected['id'], $config_test->getOriginalId());
// Save again, and verify correct status and properties again.
$status = $config_test->save();
$this->assertSame(SAVED_UPDATED, $status);
$this->assertSame($expected['id'], $config_test->id());
$this->assertSame($expected['uuid'], $config_test->uuid());
$this->assertSame($expected['label'], $config_test->label());
$this->assertFalse($config_test->isNew());
$this->assertSame($expected['id'], $config_test->getOriginalId());
// Verify that a configuration entity can be saved with an ID of the
// maximum allowed length, but not longer.
// Test with a short ID.
$id_length_config_test = $storage->create([
'id' => $this->randomMachineName(8),
]);
try {
$id_length_config_test->save();
}
catch (ConfigEntityIdLengthException $e) {
$this->fail($e->getMessage());
}
// Test with an ID of the maximum allowed length.
$id_length_config_test = $storage->create([
'id' => $this->randomMachineName(static::MAX_ID_LENGTH),
]);
try {
$id_length_config_test->save();
}
catch (ConfigEntityIdLengthException $e) {
$this->fail($e->getMessage());
}
// Test with an ID exceeding the maximum allowed length.
$id_length_config_test = $storage->create([
'id' => $this->randomMachineName(static::MAX_ID_LENGTH + 1),
]);
try {
$status = $id_length_config_test->save();
$this->fail(new FormattableMarkup("config_test entity with ID length @length exceeding the maximum allowed length of @max saved successfully", [
'@length' => strlen($id_length_config_test->id()),
'@max' => static::MAX_ID_LENGTH,
]));
}
catch (ConfigEntityIdLengthException $e) {
// Expected exception; just continue testing.
}
// Ensure that creating an entity with the same id as an existing one is not
// possible.
$same_id = $storage->create([
'id' => $config_test->id(),
]);
$this->assertTrue($same_id->isNew());
try {
$same_id->save();
$this->fail('Not possible to overwrite an entity.');
}
catch (EntityStorageException $e) {
// Expected exception; just continue testing.
}
// Verify that renaming the ID returns correct status and properties.
$ids = [$expected['id'], 'second_' . $this->randomMachineName(4), 'third_' . $this->randomMachineName(4)];
for ($i = 1; $i < 3; $i++) {
$old_id = $ids[$i - 1];
$new_id = $ids[$i];
// Before renaming, everything should point to the current ID.
$this->assertSame($old_id, $config_test->id());
$this->assertSame($old_id, $config_test->getOriginalId());
// Rename.
$config_test->set('id', $new_id);
$this->assertSame($new_id, $config_test->id());
$status = $config_test->save();
$this->assertSame(SAVED_UPDATED, $status);
$this->assertFalse($config_test->isNew());
// Verify that originalID points to new ID directly after renaming.
$this->assertSame($new_id, $config_test->id());
$this->assertSame($new_id, $config_test->getOriginalId());
}
// Test config entity prepopulation.
\Drupal::state()->set('config_test.prepopulate', TRUE);
$config_test = $storage->create(['foo' => 'bar']);
$this->assertEquals('baz', $config_test->get('foo'), 'Initial value correctly populated');
}
/**
* Tests CRUD operations through the UI.
*/
public function testCrudUi(): void {
$this->drupalLogin($this->drupalCreateUser([
'administer site configuration',
]));
$id = $this->randomMachineName();
$label1 = $this->randomMachineName();
$label2 = $this->randomMachineName();
$label3 = $this->randomMachineName();
$message_insert = "$label1 configuration has been created.";
$message_update = "$label2 configuration has been updated.";
$message_delete = "The test configuration $label2 has been deleted.";
// Create a configuration entity.
$edit = [
'id' => $id,
'label' => $label1,
];
$this->drupalGet('admin/structure/config_test/add');
$this->submitForm($edit, 'Save');
$this->assertSession()->addressEquals('admin/structure/config_test');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextContains($message_insert);
$this->assertSession()->pageTextNotContains($message_update);
$this->assertSession()->linkByHrefExists("admin/structure/config_test/manage/$id");
// Update the configuration entity.
$edit = [
'label' => $label2,
];
$this->drupalGet("admin/structure/config_test/manage/{$id}");
$this->submitForm($edit, 'Save');
$this->assertSession()->addressEquals('admin/structure/config_test');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextNotContains($message_insert);
$this->assertSession()->pageTextContains($message_update);
$this->assertSession()->linkByHrefExists("admin/structure/config_test/manage/$id");
$this->assertSession()->linkByHrefExists("admin/structure/config_test/manage/$id/delete");
// Delete the configuration entity.
$this->drupalGet("admin/structure/config_test/manage/$id");
$this->clickLink('Delete');
$this->assertSession()->addressEquals("admin/structure/config_test/manage/$id/delete");
$this->submitForm([], 'Delete');
$this->assertSession()->addressEquals('admin/structure/config_test');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextNotContains($message_update);
$this->assertSession()->pageTextContains($message_delete);
$this->assertSession()->pageTextNotContains($label1);
$this->assertSession()->linkByHrefNotExists("admin/structure/config_test/manage/$id");
// Re-create a configuration entity.
$edit = [
'id' => $id,
'label' => $label1,
];
$this->drupalGet('admin/structure/config_test/add');
$this->submitForm($edit, 'Save');
$this->assertSession()->addressEquals('admin/structure/config_test');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextContains($label1);
$this->assertSession()->linkByHrefExists("admin/structure/config_test/manage/$id");
// Rename the configuration entity's ID/machine name.
$edit = [
'id' => $this->randomMachineName(),
'label' => $label3,
];
$this->drupalGet("admin/structure/config_test/manage/{$id}");
$this->submitForm($edit, 'Save');
$this->assertSession()->addressEquals('admin/structure/config_test');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextNotContains($label1);
$this->assertSession()->pageTextNotContains($label2);
$this->assertSession()->pageTextContains($label3);
$this->assertSession()->linkByHrefNotExists("admin/structure/config_test/manage/$id");
$id = $edit['id'];
$this->assertSession()->linkByHrefExists("admin/structure/config_test/manage/$id");
// Create a configuration entity with '0' machine name.
$edit = [
'id' => '0',
'label' => '0',
];
$this->drupalGet('admin/structure/config_test/add');
$this->submitForm($edit, 'Save');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextContains('0 configuration has been created.');
$this->assertSession()->linkByHrefExists('admin/structure/config_test/manage/0');
$this->assertSession()->linkByHrefExists('admin/structure/config_test/manage/0/delete');
$this->drupalGet('admin/structure/config_test/manage/0/delete');
$this->submitForm([], 'Delete');
$storage = \Drupal::entityTypeManager()->getStorage('config_test');
$this->assertNull($storage->load(0), 'Test entity deleted');
// Create a configuration entity with a property that uses AJAX to show
// extra form elements. Test this scenario in a non-JS case by using a
// 'js-hidden' submit button.
// @see \Drupal\Tests\config\FunctionalJavascript\ConfigEntityTest::testAjaxOnAddPage()
$this->drupalGet('admin/structure/config_test/add');
$id = $this->randomMachineName();
$edit = [
'id' => $id,
'label' => $this->randomString(),
'size' => 'custom',
];
$this->assertSession()->fieldExists('size');
$this->assertSession()->fieldNotExists('size_value');
$this->submitForm($edit, 'Change size');
$this->assertSession()->fieldExists('size');
$this->assertSession()->fieldExists('size_value');
// Submit the form with the regular 'Save' button and check that the entity
// values are correct.
$edit += ['size_value' => 'medium'];
$this->submitForm($edit, 'Save');
$entity = $storage->load($id);
$this->assertEquals('custom', $entity->get('size'));
$this->assertEquals('medium', $entity->get('size_value'));
}
}
@@ -0,0 +1,336 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Core\Archiver\ArchiveTar;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\BrowserTestBase;
/**
* Tests the user interface for importing/exporting configuration.
*
* Each testX method does a complete rebuild of a Drupal site, so values being
* tested need to be stored in protected properties in order to survive until
* the next rebuild.
*
* @group config
*/
class ConfigExportImportUITest extends BrowserTestBase {
/**
* The contents of the config export tarball, held between test methods.
*
* @var string
*/
protected $tarball;
/**
* Holds the original 'site slogan' before testing.
*
* @var string
*/
protected $originalSlogan;
/**
* Holds a randomly generated new 'site slogan' for testing.
*
* @var string
*/
protected $newSlogan;
/**
* Holds a content type.
*
* @var \Drupal\node\NodeInterface
*/
protected $contentType;
/**
* Holds the randomly-generated name of a field.
*
* @var string
*/
protected $fieldName;
/**
* Holds the field storage entity for $fieldName.
*
* @var \Drupal\field\FieldStorageConfigInterface
*/
protected $fieldStorage;
/**
* {@inheritdoc}
*/
protected static $modules = ['config', 'node', 'field'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Create a content type.
$this->contentType = $this->drupalCreateContentType(['type' => 'test']);
$this->drupalLogin($this->drupalCreateUser([
'export configuration',
'import configuration',
'synchronize configuration',
'access administration pages',
'administer site configuration',
'create test content',
'view the administration theme',
]));
}
/**
* Tests a simple site export import case.
*/
public function testExportImport(): void {
// After installation there is no snapshot and nothing to import.
$this->drupalGet('admin/config/development/configuration');
$this->assertSession()->pageTextNotContains('Warning message');
$this->assertSession()->pageTextContains('There is no staged configuration.');
$this->originalSlogan = $this->config('system.site')->get('slogan');
$this->newSlogan = $this->randomString(16);
$this->assertNotEquals($this->originalSlogan, $this->newSlogan);
$this->config('system.site')
->set('slogan', $this->newSlogan)
->save();
$this->assertEquals($this->newSlogan, $this->config('system.site')->get('slogan'));
// Create a field.
$this->fieldName = $this->randomMachineName();
$this->fieldStorage = FieldStorageConfig::create([
'field_name' => $this->fieldName,
'entity_type' => 'node',
'type' => 'text',
]);
$this->fieldStorage->save();
FieldConfig::create([
'field_storage' => $this->fieldStorage,
'bundle' => $this->contentType->id(),
])->save();
$display_repository = $this->container->get('entity_display.repository');
// Update the displays so that configuration does not change unexpectedly on
// import.
$display_repository->getFormDisplay('node', $this->contentType->id(), 'default')
->setComponent($this->fieldName, [
'type' => 'text_textfield',
])
->save();
$display_repository->getViewDisplay('node', $this->contentType->id(), 'full')
->setComponent($this->fieldName)
->save();
$display_repository->getViewDisplay('node', $this->contentType->id(), 'default')
->setComponent($this->fieldName)
->save();
$display_repository->getViewDisplay('node', $this->contentType->id(), 'teaser')
->removeComponent($this->fieldName)
->save();
$this->drupalGet('node/add/' . $this->contentType->id());
$this->assertSession()->fieldValueEquals("{$this->fieldName}[0][value]", '');
// Export the configuration.
$this->drupalGet('admin/config/development/configuration/full/export');
$this->submitForm([], 'Export');
$this->tarball = $this->getSession()->getPage()->getContent();
$this->config('system.site')
->set('slogan', $this->originalSlogan)
->save();
$this->assertEquals($this->originalSlogan, $this->config('system.site')->get('slogan'));
// Delete the custom field.
$fields = FieldConfig::loadMultiple();
foreach ($fields as $field) {
if ($field->getName() == $this->fieldName) {
$field->delete();
}
}
$field_storages = FieldStorageConfig::loadMultiple();
foreach ($field_storages as $field_storage) {
if ($field_storage->getName() == $this->fieldName) {
$field_storage->delete();
}
}
$this->drupalGet('node/add/' . $this->contentType->id());
$this->assertSession()->fieldNotExists("{$this->fieldName}[0][value]");
// Import the configuration.
$filename = 'temporary://' . $this->randomMachineName();
file_put_contents($filename, $this->tarball);
$this->drupalGet('admin/config/development/configuration/full/import');
$this->submitForm(['files[import_tarball]' => $filename], 'Upload');
// There is no snapshot yet because an import has never run.
$this->assertSession()->pageTextNotContains('Warning message');
$this->assertSession()->pageTextNotContains('There is no staged configuration.');
$this->assertSession()->pageTextContains($this->contentType->label());
$this->submitForm([], 'Import all');
// After importing the snapshot has been updated and there are no warnings.
$this->assertSession()->pageTextNotContains('Warning message');
$this->assertSession()->pageTextContains('The staged configuration is identical to the active configuration.');
$this->assertEquals($this->newSlogan, $this->config('system.site')->get('slogan'));
$this->drupalGet('node/add');
$this->assertSession()->fieldValueEquals("{$this->fieldName}[0][value]", '');
$this->config('system.site')
->set('slogan', $this->originalSlogan)
->save();
$this->drupalGet('admin/config/development/configuration');
$this->assertSession()->pageTextContains('Warning message');
$this->assertSession()->pageTextContains('The following items in your active configuration have changes since the last import that may be lost on the next import.');
// Ensure the item is displayed as part of a list (to avoid false matches
// on the rest of the page) and that the list markup is not escaped.
$this->assertSession()->responseContains('<li>system.site</li>');
// Remove everything from sync. The warning about differences between the
// active and snapshot should no longer exist.
\Drupal::service('config.storage.sync')->deleteAll();
$this->drupalGet('admin/config/development/configuration');
$this->assertSession()->pageTextNotContains('Warning message');
$this->assertSession()->pageTextNotContains('The following items in your active configuration have changes since the last import that may be lost on the next import.');
$this->assertSession()->pageTextContains('There is no staged configuration.');
// Write a file to sync. The warning about differences between the active
// and snapshot should now exist.
/** @var \Drupal\Core\Config\StorageInterface $sync */
$sync = $this->container->get('config.storage.sync');
$data = $this->config('system.site')->get();
$data['slogan'] = 'in the face';
$this->copyConfig($this->container->get('config.storage'), $sync);
$sync->write('system.site', $data);
$this->drupalGet('admin/config/development/configuration');
$this->assertSession()->pageTextContains('Warning message');
$this->assertSession()->pageTextContains('The following items in your active configuration have changes since the last import that may be lost on the next import.');
// Ensure the item is displayed as part of a list (to avoid false matches
// on the rest of the page) and that the list markup is not escaped.
$this->assertSession()->responseContains('<li>system.site</li>');
}
/**
* Tests an export and import of collections.
*/
public function testExportImportCollections(): void {
/** @var \Drupal\Core\Config\StorageInterface $active_storage */
$active_storage = \Drupal::service('config.storage');
$test1_storage = $active_storage->createCollection('collection.test1');
$test1_storage->write('config_test.create', ['foo' => 'bar']);
$test1_storage->write('config_test.update', ['foo' => 'bar']);
$test2_storage = $active_storage->createCollection('collection.test2');
$test2_storage->write('config_test.another_create', ['foo' => 'bar']);
$test2_storage->write('config_test.another_update', ['foo' => 'bar']);
// Export the configuration.
$this->drupalGet('admin/config/development/configuration/full/export');
$this->submitForm([], 'Export');
$this->tarball = $this->getSession()->getPage()->getContent();
$filename = \Drupal::service('file_system')->getTempDirectory() . '/' . $this->randomMachineName();
file_put_contents($filename, $this->tarball);
// Set up the active storage collections to test import.
$test1_storage->delete('config_test.create');
$test1_storage->write('config_test.update', ['foo' => 'baz']);
$test1_storage->write('config_test.delete', ['foo' => 'bar']);
$test2_storage->delete('config_test.another_create');
$test2_storage->write('config_test.another_update', ['foo' => 'baz']);
$test2_storage->write('config_test.another_delete', ['foo' => 'bar']);
// Create a snapshot.
$snapshot_storage = \Drupal::service('config.storage.snapshot');
\Drupal::service('config.manager')->createSnapshot($active_storage, $snapshot_storage);
// Ensure that the snapshot has the expected collection data before import.
$test1_snapshot = $snapshot_storage->createCollection('collection.test1');
$data = $test1_snapshot->read('config_test.delete');
$this->assertEquals(['foo' => 'bar'], $data, 'The config_test.delete in collection.test1 exists in the snapshot storage.');
$data = $test1_snapshot->read('config_test.update');
$this->assertEquals(['foo' => 'baz'], $data, 'The config_test.update in collection.test1 exists in the snapshot storage.');
$this->assertFalse($test1_snapshot->read('config_test.create'), 'The config_test.create in collection.test1 does not exist in the snapshot storage.');
$test2_snapshot = $snapshot_storage->createCollection('collection.test2');
$data = $test2_snapshot->read('config_test.another_delete');
$this->assertEquals(['foo' => 'bar'], $data, 'The config_test.another_delete in collection.test2 exists in the snapshot storage.');
$data = $test2_snapshot->read('config_test.another_update');
$this->assertEquals(['foo' => 'baz'], $data, 'The config_test.another_update in collection.test2 exists in the snapshot storage.');
$this->assertFalse($test2_snapshot->read('config_test.another_create'), 'The config_test.another_create in collection.test2 does not exist in the snapshot storage.');
// Create the tar that contains the expected content for the collections.
$tar = new ArchiveTar($filename, 'gz');
$content_list = $tar->listContent();
// Convert the list of files into something easy to search.
$files = [];
foreach ($content_list as $file) {
$files[] = $file['filename'];
}
$this->assertContains('collection/test1/config_test.create.yml', $files, 'Config export contains collection/test1/config_test.create.yml.');
$this->assertContains('collection/test2/config_test.another_create.yml', $files, 'Config export contains collection/test2/config_test.another_create.yml.');
$this->assertContains('collection/test1/config_test.update.yml', $files, 'Config export contains collection/test1/config_test.update.yml.');
$this->assertContains('collection/test2/config_test.another_update.yml', $files, 'Config export contains collection/test2/config_test.another_update.yml.');
$this->assertNotContains('collection/test1/config_test.delete.yml', $files, 'Config export does not contain collection/test1/config_test.delete.yml.');
$this->assertNotContains('collection/test2/config_test.another_delete.yml', $files, 'Config export does not contain collection/test2/config_test.another_delete.yml.');
$this->drupalGet('admin/config/development/configuration/full/import');
$this->submitForm(['files[import_tarball]' => $filename], 'Upload');
// Verify that there are configuration differences to import.
$this->drupalGet('admin/config/development/configuration');
$this->assertSession()->pageTextNotContains('There is no staged configuration.');
$this->assertSession()->pageTextContains('collection.test1 configuration collection');
$this->assertSession()->pageTextContains('collection.test2 configuration collection');
$this->assertSession()->pageTextContains('config_test.create');
$this->assertSession()->linkByHrefExists('admin/config/development/configuration/sync/diff_collection/collection.test1/config_test.create');
$this->assertSession()->pageTextContains('config_test.update');
$this->assertSession()->linkByHrefExists('admin/config/development/configuration/sync/diff_collection/collection.test1/config_test.update');
$this->assertSession()->pageTextContains('config_test.delete');
$this->assertSession()->linkByHrefExists('admin/config/development/configuration/sync/diff_collection/collection.test1/config_test.delete');
$this->assertSession()->pageTextContains('config_test.another_create');
$this->assertSession()->linkByHrefExists('admin/config/development/configuration/sync/diff_collection/collection.test2/config_test.another_create');
$this->assertSession()->pageTextContains('config_test.another_update');
$this->assertSession()->linkByHrefExists('admin/config/development/configuration/sync/diff_collection/collection.test2/config_test.another_update');
$this->assertSession()->pageTextContains('config_test.another_delete');
$this->assertSession()->linkByHrefExists('admin/config/development/configuration/sync/diff_collection/collection.test2/config_test.another_delete');
$this->submitForm([], 'Import all');
$this->assertSession()->pageTextContains('The staged configuration is identical to the active configuration.');
// Test data in collections.
$data = $test1_storage->read('config_test.create');
$this->assertEquals(['foo' => 'bar'], $data, 'The config_test.create in collection.test1 has been created.');
$data = $test1_storage->read('config_test.update');
$this->assertEquals(['foo' => 'bar'], $data, 'The config_test.update in collection.test1 has been updated.');
$this->assertFalse($test1_storage->read('config_test.delete'), 'The config_test.delete in collection.test1 has been deleted.');
$data = $test2_storage->read('config_test.another_create');
$this->assertEquals(['foo' => 'bar'], $data, 'The config_test.another_create in collection.test2 has been created.');
$data = $test2_storage->read('config_test.another_update');
$this->assertEquals(['foo' => 'bar'], $data, 'The config_test.another_update in collection.test2 has been updated.');
$this->assertFalse($test2_storage->read('config_test.another_delete'), 'The config_test.another_delete in collection.test2 has been deleted.');
// Ensure that the snapshot has been updated with the collection data.
$snapshot_storage = \Drupal::service('config.storage.snapshot');
$test1_snapshot = $snapshot_storage->createCollection('collection.test1');
$data = $test1_snapshot->read('config_test.create');
$this->assertEquals(['foo' => 'bar'], $data, 'The config_test.create in collection.test1 has been created in the snapshot storage.');
$data = $test1_snapshot->read('config_test.update');
$this->assertEquals(['foo' => 'bar'], $data, 'The config_test.update in collection.test1 has been updated in the snapshot storage.');
$this->assertFalse($test1_snapshot->read('config_test.delete'), 'The config_test.delete in collection.test1 does not exist in the snapshot storage.');
$test2_snapshot = $snapshot_storage->createCollection('collection.test2');
$data = $test2_snapshot->read('config_test.another_create');
$this->assertEquals(['foo' => 'bar'], $data, 'The config_test.another_create in collection.test2 has been created in the snapshot storage.');
$data = $test2_snapshot->read('config_test.another_update');
$this->assertEquals(['foo' => 'bar'], $data, 'The config_test.another_update in collection.test2 has been updated in the snapshot storage.');
$this->assertFalse($test2_snapshot->read('config_test.another_delete'), 'The config_test.another_delete in collection.test2 does not exist in the snapshot storage.');
}
}
@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Core\Archiver\Tar;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Tests\BrowserTestBase;
/**
* Tests the user interface for exporting configuration.
*
* @group config
*/
class ConfigExportUITest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['config', 'config_test'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Set up an override.
$settings['config']['system.maintenance']['message'] = (object) [
'value' => 'Foo',
'required' => TRUE,
];
$this->writeSettings($settings);
$this->drupalLogin($this->drupalCreateUser(['export configuration']));
}
/**
* Tests export of configuration.
*/
public function testExport(): void {
// Verify the export page with export submit button is available.
$this->drupalGet('admin/config/development/configuration/full/export');
$this->assertSession()->buttonExists('Export');
// Submit the export form and verify response. This will create a file in
// temporary directory with the default name config.tar.gz.
$this->drupalGet('admin/config/development/configuration/full/export');
$this->submitForm([], 'Export');
$this->assertSession()->statusCodeEquals(200);
// Test if header contains file name with hostname and timestamp.
$request = \Drupal::request();
$hostname = str_replace('.', '-', $request->getHttpHost());
$this->assertSession()->responseHeaderMatches('content-disposition', '/attachment; filename="config-' . preg_quote($hostname) . '-\d{4}-\d{2}-\d{2}-\d{2}-\d{2}\.tar\.gz"/');
// Extract the archive and verify it's not empty.
$file_system = \Drupal::service('file_system');
assert($file_system instanceof FileSystemInterface);
$temp_directory = $file_system->getTempDirectory();
$file_path = $temp_directory . '/config.tar.gz';
$archiver = new Tar($file_path);
$archive_contents = $archiver->listContents();
$this->assertNotEmpty($archive_contents, 'Downloaded archive file is not empty.');
// Prepare the list of config files from active storage, see
// \Drupal\config\Controller\ConfigController::downloadExport().
$storage_active = $this->container->get('config.storage');
$config_files = [];
foreach ($storage_active->listAll() as $config_name) {
$config_files[] = $config_name . '.yml';
}
// Assert that the downloaded archive file contents are the same as the test
// site active store.
$this->assertSame($config_files, $archive_contents);
// Ensure the test configuration override is in effect but was not exported.
$this->assertSame('Foo', \Drupal::config('system.maintenance')->get('message'));
$archiver->extract($temp_directory, ['system.maintenance.yml']);
$file_contents = file_get_contents($temp_directory . '/' . 'system.maintenance.yml');
$exported = Yaml::decode($file_contents);
$this->assertNotSame('Foo', $exported['message']);
// Check the single export form doesn't have "form-required" elements.
$this->drupalGet('admin/config/development/configuration/single/export');
$this->assertSession()->responseNotContains('js-form-required form-required');
// Ensure the temporary file is not available to users without the
// permission.
$this->drupalLogout();
$this->drupalGet('system/temporary', ['query' => ['file' => 'config.tar.gz']]);
$this->assertSession()->statusCodeEquals(403);
}
}
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Tests config overrides do not appear on forms that extend ConfigFormBase.
*
* @group config
* @see \Drupal\Core\Form\ConfigFormBase
*/
class ConfigFormOverrideTest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests that overrides do not affect forms.
*/
public function testFormsWithOverrides(): void {
$this->drupalLogin($this->drupalCreateUser([
'access administration pages',
'administer site configuration',
]));
$overridden_name = 'Site name global conf override';
// Set up an override.
$settings['config']['system.site']['name'] = (object) [
'value' => $overridden_name,
'required' => TRUE,
];
$this->writeSettings($settings);
// Test that everything on the form is the same, but that the override
// worked for the actual site name.
$this->drupalGet('admin/config/system/site-information');
$this->assertSession()->titleEquals('Basic site settings | ' . $overridden_name);
$this->assertSession()->fieldValueEquals("site_name", 'Drupal');
// Submit the form and ensure the site name is not changed.
$edit = [
'site_name' => 'Custom site name',
];
$this->drupalGet('admin/config/system/site-information');
$this->submitForm($edit, 'Save configuration');
$this->assertSession()->titleEquals('Basic site settings | ' . $overridden_name);
$this->assertSession()->fieldValueEquals("site_name", $edit['site_name']);
}
}
@@ -0,0 +1,180 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Core\Config\StorageComparer;
use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\Core\Extension\ExtensionLifecycle;
use Drupal\Tests\SchemaCheckTestTrait;
use Drupal\Tests\system\Functional\Module\ModuleTestBase;
/**
* Tests the largest configuration import possible with all available modules.
*
* Note that the use of SchemaCheckTestTrait means that the schema conformance
* of all default configuration is also tested.
*
* @group config
* @group #slow
*/
class ConfigImportAllTest extends ModuleTestBase {
use SchemaCheckTestTrait;
/**
* A user with the 'synchronize configuration' permission.
*
* @var \Drupal\user\UserInterface
*/
protected $webUser;
/**
* {@inheritdoc}
*/
protected static $modules = ['config'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected $profile = 'testing';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->webUser = $this->drupalCreateUser(['synchronize configuration']);
$this->drupalLogin($this->webUser);
}
/**
* Tests that a fixed set of modules can be installed and uninstalled.
*/
public function testInstallUninstall(): void {
// Get a list of modules to install.
$all_modules = $this->container->get('extension.list.module')->getList();
$all_modules = array_filter($all_modules, function ($module) {
// Filter out contrib, hidden, testing, experimental, and deprecated
// modules. We also don't need to enable modules that are already enabled.
if ($module->origin !== 'core'
|| !empty($module->info['hidden'])
|| $module->status == TRUE
|| $module->info['package'] == 'Testing'
|| $module->info[ExtensionLifecycle::LIFECYCLE_IDENTIFIER] === ExtensionLifecycle::DEPRECATED) {
return FALSE;
}
return TRUE;
});
// Install every module possible.
\Drupal::service('module_installer')->install(array_keys($all_modules));
$this->assertModules(array_keys($all_modules), TRUE);
foreach ($all_modules as $module => $info) {
$this->assertModuleConfig($module);
$this->assertModuleTablesExist($module);
}
// Export active config to sync.
$this->copyConfig($this->container->get('config.storage'), $this->container->get('config.storage.sync'));
$this->resetAll();
// Delete all entities provided by modules that prevent uninstallation. For
// example, if any content entity exists its provider cannot be uninstalled.
// So deleting all taxonomy terms allows the Taxonomy to be uninstalled.
// Additionally, every field is deleted so modules can be uninstalled. For
// example, if a comment field exists then Comment cannot be uninstalled.
$entity_type_manager = \Drupal::entityTypeManager();
foreach ($entity_type_manager->getDefinitions() as $entity_type) {
if (($entity_type instanceof ContentEntityTypeInterface || in_array($entity_type->id(), ['field_storage_config', 'filter_format'], TRUE))
&& !in_array($entity_type->getProvider(), ['system', 'user'], TRUE)) {
$storage = $entity_type_manager->getStorage($entity_type->id());
$storage->delete($storage->loadMultiple());
}
}
// Purge the field data.
field_purge_batch(1000);
$all_modules = \Drupal::service('extension.list.module')->getList();
$database_module = \Drupal::service('database')->getProvider();
$expected_modules = ['path_alias', 'system', 'user', $database_module];
// Ensure that only core required modules and the install profile can not be uninstalled.
$validation_reasons = \Drupal::service('module_installer')->validateUninstall(array_keys($all_modules));
$validation_modules = array_keys($validation_reasons);
$this->assertEqualsCanonicalizing($expected_modules, $validation_modules);
$modules_to_uninstall = array_filter($all_modules, function ($module) {
// Filter profiles, and required and not enabled modules.
if (!empty($module->info['required']) || $module->status == FALSE || $module->getType() === 'profile') {
return FALSE;
}
return TRUE;
});
// Can not uninstall config and use admin/config/development/configuration!
unset($modules_to_uninstall['config']);
// Can not uninstall the database module.
unset($modules_to_uninstall[$database_module]);
$this->assertTrue(isset($modules_to_uninstall['comment']), 'The comment module will be disabled');
$this->assertTrue(isset($modules_to_uninstall['file']), 'The File module will be disabled');
$this->assertTrue(isset($modules_to_uninstall['editor']), 'The Editor module will be disabled');
// Uninstall all modules that can be uninstalled.
\Drupal::service('module_installer')->uninstall(array_keys($modules_to_uninstall));
$this->assertModules(array_keys($modules_to_uninstall), FALSE);
foreach ($modules_to_uninstall as $module => $info) {
$this->assertNoModuleConfig($module);
$this->assertModuleTablesDoNotExist($module);
}
// Import the configuration thereby re-installing all the modules.
$this->drupalGet('admin/config/development/configuration');
$this->submitForm([], 'Import all');
// Modules have been installed that have services.
$this->rebuildContainer();
// Check that there are no errors.
$this->assertSame([], $this->configImporter()->getErrors());
// Check that all modules that were uninstalled are now reinstalled.
$this->assertModules(array_keys($modules_to_uninstall), TRUE);
foreach ($modules_to_uninstall as $module => $info) {
$this->assertModuleConfig($module);
$this->assertModuleTablesExist($module);
}
// Ensure that we have no configuration changes to import.
$storage_comparer = new StorageComparer(
$this->container->get('config.storage.sync'),
$this->container->get('config.storage')
);
$this->assertSame($storage_comparer->getEmptyChangelist(), $storage_comparer->createChangelist()->getChangelist());
// Now we have all configuration imported, test all of them for schema
// conformance. Ensures all imported default configuration is valid when
// all modules are enabled.
$names = $this->container->get('config.storage')->listAll();
/** @var \Drupal\Core\Config\TypedConfigManagerInterface $typed_config */
$typed_config = $this->container->get('config.typed');
foreach ($names as $name) {
$config = $this->config($name);
$this->assertConfigSchema($typed_config, $name, $config->get());
}
}
}
@@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Tests the importing/exporting configuration based on the install profile.
*
* @group config
*/
class ConfigImportInstallProfileTest extends BrowserTestBase {
/**
* The profile to install as a basis for testing.
*
* @var string
*/
protected $profile = 'testing_config_import';
/**
* {@inheritdoc}
*/
protected static $modules = ['config'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* A user with the 'synchronize configuration' permission.
*
* @var \Drupal\user\UserInterface
*/
protected $webUser;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->webUser = $this->drupalCreateUser(['synchronize configuration']);
$this->drupalLogin($this->webUser);
$this->copyConfig($this->container->get('config.storage'), $this->container->get('config.storage.sync'));
}
/**
* Tests config importer can uninstall install profiles.
*
* Install profiles can be uninstalled when none of the modules or themes
* they contain are installed.
*
* @see \Drupal\Core\EventSubscriber\ConfigImportSubscriber
*/
public function testInstallProfileValidation(): void {
$sync = $this->container->get('config.storage.sync');
$this->copyConfig($this->container->get('config.storage'), $sync);
$core = $sync->read('core.extension');
// Ensure install profiles can not be uninstalled.
unset($core['module']['testing_config_import']);
$sync->write('core.extension', $core);
$this->drupalGet('admin/config/development/configuration');
$this->submitForm([], 'Import all');
$this->assertSession()->pageTextContains('The configuration cannot be imported because it failed validation for the following reasons:');
$this->assertSession()->pageTextContains("The install profile 'Testing config import' is providing the following module(s): testing_config_import_module");
// Uninstall dependencies of testing_config_import.
unset($core['module']['syslog']);
unset($core['module']['testing_config_import_module']);
unset($core['theme']['stark']);
$core['module']['testing_config_import'] = 0;
$core['theme']['test_theme_theme'] = 0;
$sync->write('core.extension', $core);
$sync->deleteAll('syslog.');
$theme = $sync->read('system.theme');
$theme['default'] = 'test_theme_theme';
$sync->write('system.theme', $theme);
$this->drupalGet('admin/config/development/configuration');
$this->submitForm([], 'Import all');
$this->assertSession()->pageTextContains('The configuration was imported successfully.');
$this->rebuildContainer();
$this->assertFalse(\Drupal::moduleHandler()->moduleExists('syslog'), 'The syslog module has been uninstalled.');
$this->assertFalse(\Drupal::moduleHandler()->moduleExists('testing_config_import_module'), 'The testing_config_import_module module has been uninstalled.');
$this->assertFalse(\Drupal::service('theme_handler')->themeExists('stark'), 'The stark theme has been uninstalled.');
$this->assertTrue(\Drupal::service('theme_handler')->themeExists('test_theme_theme'), 'The test_theme_theme theme has been installed.');
// Uninstall testing_config_import profile without removing the profile key.
unset($core['module']['testing_config_import']);
$sync->write('core.extension', $core);
$this->drupalGet('admin/config/development/configuration');
$this->submitForm([], 'Import all');
$this->assertSession()->pageTextContains('The configuration cannot be imported because it failed validation for the following reasons:');
$this->assertSession()->pageTextContains('The install profile testing_config_import is not in the list of installed modules.');
// Uninstall testing_config_import profile properly.
unset($core['profile']);
$sync->write('core.extension', $core);
$this->drupalGet('admin/config/development/configuration');
$this->submitForm([], 'Import all');
$this->assertSession()->pageTextContains('The configuration was imported successfully.');
$this->rebuildContainer();
$this->assertFalse(\Drupal::moduleHandler()->moduleExists('testing_config_import'), 'The testing_config_import profile has been uninstalled.');
}
}
@@ -0,0 +1,551 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Core\Config\InstallStorage;
use Drupal\Core\Serialization\Yaml;
use Drupal\Tests\BrowserTestBase;
/**
* Tests the user interface for importing configuration.
*
* @group config
* @group #slow
*/
class ConfigImportUITest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'config',
'config_test',
'config_import_test',
'text',
'options',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* A user with the 'synchronize configuration' permission.
*
* @var \Drupal\user\UserInterface
*/
protected $webUser;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->webUser = $this->drupalCreateUser(['synchronize configuration']);
$this->drupalLogin($this->webUser);
$this->copyConfig($this->container->get('config.storage'), $this->container->get('config.storage.sync'));
}
/**
* Tests importing configuration.
*/
public function testImport(): void {
$name = 'system.site';
$dynamic_name = 'config_test.dynamic.new';
/** @var \Drupal\Core\Config\StorageInterface $sync */
$sync = $this->container->get('config.storage.sync');
$this->drupalGet('admin/config/development/configuration');
$this->assertSession()->pageTextContains('The staged configuration is identical to the active configuration.');
$this->assertSession()->buttonNotExists('Import all');
// Create updated configuration object.
$new_site_name = 'Config import test ' . $this->randomString();
$this->prepareSiteNameUpdate($new_site_name);
$this->assertTrue($sync->exists($name), $name . ' found.');
// Create new config entity.
$original_dynamic_data = [
'uuid' => '30df59bd-7b03-4cf7-bb35-d42fc49f0651',
'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
'status' => TRUE,
'dependencies' => [],
'id' => 'new',
'label' => 'New',
'weight' => 0,
'style' => '',
'size' => '',
'size_value' => '',
'protected_property' => '',
];
$sync->write($dynamic_name, $original_dynamic_data);
$this->assertTrue($sync->exists($dynamic_name), $dynamic_name . ' found.');
// Enable the Automated Cron and Ban modules during import. The Ban
// module is used because it creates a table during the install.
// The Automated Cron module is used because it creates a single simple
// configuration file during the install.
$core_extension = $this->config('core.extension')->get();
$core_extension['module']['automated_cron'] = 0;
$core_extension['module']['ban'] = 0;
$core_extension['module'] = module_config_sort($core_extension['module']);
$core_extension['theme']['olivero'] = 0;
$sync->write('core.extension', $core_extension);
// Olivero ships with configuration.
$sync->write('olivero.settings', Yaml::decode(file_get_contents('core/themes/olivero/config/install/olivero.settings.yml')));
// Use the install storage so that we can read configuration from modules
// and themes that are not installed.
$install_storage = new InstallStorage();
// Set the Olivero theme as default.
$system_theme = $this->config('system.theme')->get();
$system_theme['default'] = 'olivero';
$sync->write('system.theme', $system_theme);
// Read the automated_cron config from module default config folder.
$settings = $install_storage->read('automated_cron.settings');
$settings['interval'] = 10000;
$sync->write('automated_cron.settings', $settings);
// Uninstall the Options and Text modules to ensure that dependencies are
// handled correctly. Options depends on Text so Text should be installed
// first. Since they were enabled during the test setup the core.extension
// file in sync will already contain them.
\Drupal::service('module_installer')->uninstall(['text', 'options']);
// Set the state system to record installations and uninstallations.
\Drupal::state()->set('ConfigImportUITest.core.extension.modules_installed', []);
\Drupal::state()->set('ConfigImportUITest.core.extension.modules_uninstalled', []);
// Verify that both appear as ready to import.
$this->drupalGet('admin/config/development/configuration');
$this->assertSession()->responseContains('<td>' . $name);
$this->assertSession()->responseContains('<td>' . $dynamic_name);
$this->assertSession()->responseContains('<td>core.extension');
$this->assertSession()->responseContains('<td>system.theme');
$this->assertSession()->responseContains('<td>automated_cron.settings');
$this->assertSession()->buttonExists('Import all');
// Import and verify that both do not appear anymore.
$this->submitForm([], 'Import all');
$this->assertSession()->responseNotContains('<td>' . $name);
$this->assertSession()->responseNotContains('<td>' . $dynamic_name);
$this->assertSession()->responseNotContains('<td>core.extension');
$this->assertSession()->responseNotContains('<td>system.theme');
$this->assertSession()->responseNotContains('<td>automated_cron.settings');
$this->assertSession()->buttonNotExists('Import all');
// Verify that there are no further changes to import.
$this->assertSession()->pageTextContains('The staged configuration is identical to the active configuration.');
$this->rebuildContainer();
// Verify site name has changed.
$this->assertSame($new_site_name, $this->config('system.site')->get('name'));
// Verify that new config entity exists.
$this->assertSame($original_dynamic_data, $this->config($dynamic_name)->get());
// Verify the cache got cleared.
$this->assertTrue(isset($GLOBALS['hook_cache_flush']));
$this->rebuildContainer();
$this->assertTrue(\Drupal::moduleHandler()->moduleExists('ban'), 'Ban module installed during import.');
$this->assertTrue(\Drupal::database()->schema()->tableExists('ban_ip'), 'The database table ban_ip exists.');
$this->assertTrue(\Drupal::moduleHandler()->moduleExists('automated_cron'), 'Automated Cron module installed during import.');
$this->assertTrue(\Drupal::moduleHandler()->moduleExists('options'), 'Options module installed during import.');
$this->assertTrue(\Drupal::moduleHandler()->moduleExists('text'), 'Text module installed during import.');
$this->assertTrue(\Drupal::service('theme_handler')->themeExists('olivero'), 'Olivero theme installed during import.');
// Ensure installations and uninstallation occur as expected.
$installed = \Drupal::state()->get('ConfigImportUITest.core.extension.modules_installed', []);
$uninstalled = \Drupal::state()->get('ConfigImportUITest.core.extension.modules_uninstalled', []);
$expected = ['automated_cron', 'ban', 'text', 'options'];
$this->assertSame($expected, $installed, 'Automated Cron, Ban, Text and Options modules installed in the correct order.');
$this->assertEmpty($uninstalled, 'No modules uninstalled during import');
// Verify that the automated_cron configuration object was only written
// once during the import process and only with the value set in the staged
// configuration. This verifies that the module's default configuration is
// used during configuration import and, additionally, that after installing
// a module, that configuration is not synced twice.
$interval_values = \Drupal::state()->get('ConfigImportUITest.automated_cron.settings.interval', []);
$this->assertSame([10000], $interval_values);
$core_extension = $this->config('core.extension')->get();
unset($core_extension['module']['automated_cron']);
unset($core_extension['module']['ban']);
unset($core_extension['module']['options']);
unset($core_extension['module']['text']);
unset($core_extension['theme']['olivero']);
$sync->write('core.extension', $core_extension);
$sync->delete('automated_cron.settings');
$sync->delete('text.settings');
$sync->delete('olivero.settings');
$system_theme = $this->config('system.theme')->get();
$system_theme = [
'_core' => $system_theme['_core'],
'admin' => 'stark',
'default' => 'stark',
];
$sync->write('system.theme', $system_theme);
// Set the state system to record installations and uninstallations.
\Drupal::state()->set('ConfigImportUITest.core.extension.modules_installed', []);
\Drupal::state()->set('ConfigImportUITest.core.extension.modules_uninstalled', []);
// Verify that both appear as ready to import.
$this->drupalGet('admin/config/development/configuration');
$this->assertSession()->responseContains('<td>core.extension');
$this->assertSession()->responseContains('<td>system.theme');
$this->assertSession()->responseContains('<td>automated_cron.settings');
// Import and verify that both do not appear anymore.
$this->submitForm([], 'Import all');
$this->assertSession()->responseNotContains('<td>core.extension');
$this->assertSession()->responseNotContains('<td>system.theme');
$this->assertSession()->responseNotContains('<td>automated_cron.settings');
$this->rebuildContainer();
$this->assertFalse(\Drupal::moduleHandler()->moduleExists('ban'), 'Ban module uninstalled during import.');
$this->assertFalse(\Drupal::database()->schema()->tableExists('ban_ip'), 'The database table ban_ip does not exist.');
$this->assertFalse(\Drupal::moduleHandler()->moduleExists('automated_cron'), 'Automated cron module uninstalled during import.');
$this->assertFalse(\Drupal::moduleHandler()->moduleExists('options'), 'Options module uninstalled during import.');
$this->assertFalse(\Drupal::moduleHandler()->moduleExists('text'), 'Text module uninstalled during import.');
// Ensure installations and uninstallation occur as expected.
$installed = \Drupal::state()->get('ConfigImportUITest.core.extension.modules_installed', []);
$uninstalled = \Drupal::state()->get('ConfigImportUITest.core.extension.modules_uninstalled', []);
$expected = ['options', 'text', 'ban', 'automated_cron'];
$this->assertSame($expected, $uninstalled, 'Options, Text, Ban and Automated Cron modules uninstalled in the correct order.');
$this->assertEmpty($installed, 'No modules installed during import');
$theme_info = \Drupal::service('theme_handler')->listInfo();
$this->assertFalse(isset($theme_info['olivero']), 'Olivero theme uninstalled during import.');
// Verify that the automated_cron.settings configuration object was only
// deleted once during the import process.
$delete_called = \Drupal::state()->get('ConfigImportUITest.automated_cron.settings.delete', 0);
$this->assertSame(1, $delete_called, "The automated_cron.settings configuration was deleted once during configuration import.");
}
/**
* Tests concurrent importing of configuration.
*/
public function testImportLock(): void {
// Create updated configuration object.
$new_site_name = 'Config import test ' . $this->randomString();
$this->prepareSiteNameUpdate($new_site_name);
// Verify that there are configuration differences to import.
$this->drupalGet('admin/config/development/configuration');
$this->assertSession()->pageTextNotContains('The staged configuration is identical to the active configuration.');
// Acquire a fake-lock on the import mechanism.
$config_importer = $this->configImporter();
$this->container->get('lock.persistent')->acquire($config_importer::LOCK_NAME);
// Attempt to import configuration and verify that an error message appears.
$this->submitForm([], 'Import all');
$this->assertSession()->pageTextContains('Another request may be synchronizing configuration already.');
// Release the lock, just to keep testing sane.
$this->container->get('lock.persistent')->release($config_importer::LOCK_NAME);
// Verify site name has not changed.
$this->assertNotEquals($this->config('system.site')->get('name'), $new_site_name);
}
/**
* Tests verification of site UUID before importing configuration.
*/
public function testImportSiteUuidValidation(): void {
$sync = \Drupal::service('config.storage.sync');
// Create updated configuration object.
$config_data = $this->config('system.site')->get();
// Generate a new site UUID.
$config_data['uuid'] = \Drupal::service('uuid')->generate();
$sync->write('system.site', $config_data);
// Verify that there are configuration differences to import.
$this->drupalGet('admin/config/development/configuration');
$this->assertSession()->pageTextContains('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.');
$this->assertSession()->buttonNotExists('Import all');
}
/**
* Tests the screen that shows differences between active and sync.
*/
public function testImportDiff(): void {
$sync = $this->container->get('config.storage.sync');
$config_name = 'config_test.system';
$change_key = 'foo';
$remove_key = '404';
$add_key = 'biff';
$add_data = '<em>bangPow</em>';
$change_data = '<p><em>foobar</em></p>';
$original_data = [
'foo' => '<p>foobar</p>',
'baz' => '<strong>no change</strong>',
'404' => '<em>herp</em>',
];
// Update active storage to have html in config data.
$this->config($config_name)->setData($original_data)->save();
// Change a configuration value in sync.
$sync_data = $original_data;
$sync_data[$change_key] = $change_data;
$sync_data[$add_key] = $add_data;
unset($sync_data[$remove_key]);
$sync->write($config_name, $sync_data);
// Load the diff UI and verify that the diff reflects the change.
$this->drupalGet('admin/config/development/configuration/sync/diff/' . $config_name);
$this->assertSession()->responseNotContains('&amp;nbsp;');
$this->assertSession()->titleEquals("View changes of $config_name | Drupal");
// The following assertions do not use
// $this->assertSession()->assertEscaped() because
// \Drupal\Component\Diff\DiffFormatter adds markup that signifies what has
// changed.
// Changed values are escaped.
$this->assertSession()->pageTextContains("foo: '<p><em>foobar</em></p>'");
$this->assertSession()->pageTextContains("foo: '<p>foobar</p>'");
// The no change values are escaped.
$this->assertSession()->pageTextContains("baz: '<strong>no change</strong>'");
// Added value is escaped.
$this->assertSession()->pageTextContains("biff: '<em>bangPow</em>'");
// Deleted value is escaped.
$this->assertSession()->pageTextContains("404: '<em>herp</em>'");
// Verify diff colors are displayed.
$this->assertSession()->elementsCount('xpath', '//table[contains(@class, "diff")]', 1);
// Reset data back to original, and remove a key
$sync_data = $original_data;
unset($sync_data[$remove_key]);
$sync->write($config_name, $sync_data);
// Load the diff UI and verify that the diff reflects a removed key.
$this->drupalGet('admin/config/development/configuration/sync/diff/' . $config_name);
// The no change values are escaped.
$this->assertSession()->pageTextContains("foo: '<p>foobar</p>'");
$this->assertSession()->pageTextContains("baz: '<strong>no change</strong>'");
// Removed key is escaped.
$this->assertSession()->pageTextContains("404: '<em>herp</em>'");
// Reset data back to original and add a key
$sync_data = $original_data;
$sync_data[$add_key] = $add_data;
$sync->write($config_name, $sync_data);
// Load the diff UI and verify that the diff reflects an added key.
$this->drupalGet('admin/config/development/configuration/sync/diff/' . $config_name);
// The no change values are escaped.
$this->assertSession()->pageTextContains("baz: '<strong>no change</strong>'");
$this->assertSession()->pageTextContains("404: '<em>herp</em>'");
// Added key is escaped.
$this->assertSession()->pageTextContains("biff: '<em>bangPow</em>'");
}
/**
* Tests that multiple validation errors are listed on the page.
*/
public function testImportValidation(): void {
// Set state value so that
// \Drupal\config_import_test\EventSubscriber::onConfigImportValidate() logs
// validation errors.
\Drupal::state()->set('config_import_test.config_import_validate_fail', TRUE);
// Ensure there is something to import.
$new_site_name = 'Config import test ' . $this->randomString();
$this->prepareSiteNameUpdate($new_site_name);
$this->drupalGet('admin/config/development/configuration');
$this->assertSession()->pageTextNotContains('The staged configuration is identical to the active configuration.');
$this->submitForm([], 'Import all');
// Verify that the validation messages appear.
$this->assertSession()->pageTextContains('The configuration cannot be imported because it failed validation for the following reasons:');
$this->assertSession()->pageTextContains('Config import validate error 1.');
$this->assertSession()->pageTextContains('Config import validate error 2.');
// Verify site name has not changed.
$this->assertNotEquals($this->config('system.site')->get('name'), $new_site_name);
}
public function testConfigUninstallConfigException(): void {
$sync = $this->container->get('config.storage.sync');
$core_extension = $this->config('core.extension')->get();
unset($core_extension['module']['config']);
$sync->write('core.extension', $core_extension);
$this->drupalGet('admin/config/development/configuration');
$this->assertSession()->pageTextContains('core.extension');
// Import and verify that both do not appear anymore.
$this->submitForm([], 'Import all');
$this->assertSession()->pageTextContains('Can not uninstall the Configuration module as part of a configuration synchronization through the user interface.');
}
public function prepareSiteNameUpdate($new_site_name) {
$sync = $this->container->get('config.storage.sync');
// Create updated configuration object.
$config_data = $this->config('system.site')->get();
$config_data['name'] = $new_site_name;
$sync->write('system.site', $config_data);
}
/**
* Tests an import that results in an error.
*/
public function testImportErrorLog(): void {
$name_primary = 'config_test.dynamic.primary';
$name_secondary = 'config_test.dynamic.secondary';
$sync = $this->container->get('config.storage.sync');
$uuid = $this->container->get('uuid');
$values_primary = [
'uuid' => $uuid->generate(),
'langcode' => 'en',
'status' => TRUE,
'dependencies' => [],
'id' => 'primary',
'label' => 'Primary',
'weight' => 0,
'style' => NULL,
'size' => NULL,
'size_value' => NULL,
'protected_property' => NULL,
];
$sync->write($name_primary, $values_primary);
$values_secondary = [
'uuid' => $uuid->generate(),
'langcode' => 'en',
'status' => TRUE,
// Add a dependency on primary, to ensure that is synced first.
'dependencies' => [
'config' => [$name_primary],
],
'id' => 'secondary',
'label' => 'Secondary Sync',
'weight' => 0,
'style' => NULL,
'size' => NULL,
'size_value' => NULL,
'protected_property' => NULL,
];
$sync->write($name_secondary, $values_secondary);
// Verify that there are configuration differences to import.
$this->drupalGet('admin/config/development/configuration');
$this->assertSession()->pageTextNotContains('The staged configuration is identical to the active configuration.');
// Attempt to import configuration and verify that an error message appears.
$this->submitForm([], 'Import all');
$this->assertSession()->pageTextContains('Deleted and replaced configuration entity "' . $name_secondary . '"');
$this->assertSession()->pageTextContains('The configuration was imported with errors.');
$this->assertSession()->pageTextNotContains('The configuration was imported successfully.');
$this->assertSession()->pageTextContains('The staged configuration is identical to the active configuration.');
}
/**
* Tests the config importer cannot delete bundles with existing entities.
*
* @see \Drupal\Core\Entity\Event\BundleConfigImportValidate
*/
public function testEntityBundleDelete(): void {
\Drupal::service('module_installer')->install(['node']);
$this->copyConfig($this->container->get('config.storage'), $this->container->get('config.storage.sync'));
$node_type = $this->drupalCreateContentType();
$node = $this->drupalCreateNode(['type' => $node_type->id()]);
$this->drupalGet('admin/config/development/configuration');
// The node type, body field and entity displays will be scheduled for
// removal.
$this->assertSession()->pageTextContains('node.type.' . $node_type->id());
$this->assertSession()->pageTextContains('field.field.node.' . $node_type->id() . '.body');
$this->assertSession()->pageTextContains('core.entity_view_display.node.' . $node_type->id() . '.teaser');
$this->assertSession()->pageTextContains('core.entity_view_display.node.' . $node_type->id() . '.default');
$this->assertSession()->pageTextContains('core.entity_form_display.node.' . $node_type->id() . '.default');
// Attempt to import configuration and verify that an error message appears
// and the node type, body field and entity displays are still scheduled for
// removal.
$this->submitForm([], 'Import all');
$validation_message = "Entities exist of type {$node->getEntityType()->getLabel()} and {$node->getEntityType()->getBundleLabel()} {$node_type->label()}. These entities need to be deleted before importing.";
$this->assertSession()->pageTextContains($validation_message);
$this->assertSession()->pageTextContains('node.type.' . $node_type->id());
$this->assertSession()->pageTextContains('field.field.node.' . $node_type->id() . '.body');
$this->assertSession()->pageTextContains('core.entity_view_display.node.' . $node_type->id() . '.teaser');
$this->assertSession()->pageTextContains('core.entity_view_display.node.' . $node_type->id() . '.default');
$this->assertSession()->pageTextContains('core.entity_form_display.node.' . $node_type->id() . '.default');
// Delete the node and try to import again.
$node->delete();
$this->submitForm([], 'Import all');
$this->assertSession()->pageTextNotContains($validation_message);
$this->assertSession()->pageTextContains('The staged configuration is identical to the active configuration.');
$this->assertSession()->pageTextNotContains('node.type.' . $node_type->id());
$this->assertSession()->pageTextNotContains('field.field.node.' . $node_type->id() . '.body');
$this->assertSession()->pageTextNotContains('core.entity_view_display.node.' . $node_type->id() . '.teaser');
$this->assertSession()->pageTextNotContains('core.entity_view_display.node.' . $node_type->id() . '.default');
$this->assertSession()->pageTextNotContains('core.entity_form_display.node.' . $node_type->id() . '.default');
}
/**
* Tests config importer cannot uninstall extensions which are depended on.
*
* @see \Drupal\Core\EventSubscriber\ConfigImportSubscriber
*/
public function testExtensionValidation(): void {
\Drupal::service('module_installer')->install(['node']);
\Drupal::service('theme_installer')->install(['test_subtheme']);
$this->rebuildContainer();
$sync = $this->container->get('config.storage.sync');
$this->copyConfig($this->container->get('config.storage'), $sync);
$core = $sync->read('core.extension');
// Node depends on text.
unset($core['module']['text']);
$module_data = $this->container->get('extension.list.module')->getList();
$this->assertTrue(isset($module_data['node']->requires['text']), 'The Node module depends on the Text module.');
unset($core['theme']['test_basetheme']);
$theme_data = \Drupal::service('extension.list.theme')->reset()->getList();
$this->assertTrue(isset($theme_data['test_subtheme']->requires['test_basetheme']), 'The Test Subtheme theme depends on the Test Basetheme theme.');
// This module does not exist.
$core['module']['does_not_exist'] = 0;
// This theme does not exist.
$core['theme']['does_not_exist'] = 0;
$sync->write('core.extension', $core);
$this->drupalGet('admin/config/development/configuration');
$this->submitForm([], 'Import all');
$this->assertSession()->pageTextContains('The configuration cannot be imported because it failed validation for the following reasons:');
$this->assertSession()->pageTextContains('Unable to uninstall the Text module since the Node module is installed.');
$this->assertSession()->pageTextContains('Unable to uninstall the Theme test base theme theme since the Theme test subtheme theme is installed.');
$this->assertSession()->pageTextContains('Unable to install the does_not_exist module since it does not exist.');
$this->assertSession()->pageTextContains('Unable to install the does_not_exist theme since it does not exist.');
}
/**
* Tests that errors set in the batch and on the ConfigImporter are merged.
*/
public function testBatchErrors(): void {
$new_site_name = 'Config import test ' . $this->randomString();
$this->prepareSiteNameUpdate($new_site_name);
\Drupal::state()->set('config_import_steps_alter.error', TRUE);
$this->drupalGet('admin/config/development/configuration');
$this->submitForm([], 'Import all');
$this->assertSession()->responseContains('_config_import_test_config_import_steps_alter batch error');
$this->assertSession()->responseContains('_config_import_test_config_import_steps_alter ConfigImporter error');
$this->assertSession()->responseContains('The configuration was imported with errors.');
}
}
@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Core\Site\Settings;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\TestFileCreationTrait;
/**
* Tests importing configuration from an uploaded file.
*
* @group config
*/
class ConfigImportUploadTest extends BrowserTestBase {
use TestFileCreationTrait;
/**
* A user with the 'import configuration' permission.
*
* @var \Drupal\user\UserInterface
*/
protected $webUser;
/**
* {@inheritdoc}
*/
protected static $modules = ['config'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->webUser = $this->drupalCreateUser(['import configuration']);
$this->drupalLogin($this->webUser);
}
/**
* Tests importing configuration.
*/
public function testImport(): void {
// Verify access to the config upload form.
$this->drupalGet('admin/config/development/configuration/full/import');
$this->assertSession()->statusCodeEquals(200);
// Attempt to upload a non-tar file.
$text_file = $this->getTestFiles('text')[0];
$edit = ['files[import_tarball]' => \Drupal::service('file_system')->realpath($text_file->uri)];
$this->drupalGet('admin/config/development/configuration/full/import');
$this->submitForm($edit, 'Upload');
$this->assertSession()->pageTextContains('Could not extract the contents of the tar file');
// Make the sync directory read-only.
$directory = Settings::get('config_sync_directory');
\Drupal::service('file_system')->chmod($directory, 0555);
$this->drupalGet('admin/config/development/configuration/full/import');
$this->assertSession()->pageTextContains("The directory $directory is not writable.");
// Ensure submit button for \Drupal\config\Form\ConfigImportForm is
// disabled.
$submit_is_disabled = $this->cssSelect('form.config-import-form input[type="submit"]:disabled');
$this->assertCount(1, $submit_is_disabled, 'The submit button is disabled.');
}
}
@@ -0,0 +1,153 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Component\Utility\Crypt;
use Drupal\Component\Uuid\Uuid;
use Drupal\Core\Config\InstallStorage;
use Drupal\entity_test\Entity\EntityTestBundle;
use Drupal\system\Entity\Action;
use Drupal\Tests\BrowserTestBase;
use Drupal\Core\Config\FileStorage;
use Drupal\user\Entity\Role;
/**
* Tests that configuration objects are correct after various operations.
*
* The installation and removal of configuration objects in install, disable
* and uninstall functionality is tested.
*
* @group config
*/
class ConfigInstallProfileOverrideTest extends BrowserTestBase {
/**
* The profile to install as a basis for testing.
*
* @var string
*/
protected $profile = 'testing_config_overrides';
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests install profile config changes.
*/
public function testInstallProfileConfigOverwrite(): void {
$config_name = 'system.cron';
// The expected configuration from the system module.
$expected_original_data = [
'threshold' => [
'requirements_warning' => 172800,
'requirements_error' => 1209600,
],
'logging' => TRUE,
];
// The expected active configuration altered by the install profile.
$expected_profile_data = [
'threshold' => [
'requirements_warning' => 259200,
'requirements_error' => 1209600,
],
'logging' => TRUE,
];
$expected_profile_data = ['_core' => ['default_config_hash' => Crypt::hashBase64(serialize($expected_profile_data))]] + $expected_profile_data;
// Verify that the original data matches. We have to read the module config
// file directly, because the install profile default system.cron.yml
// configuration file was used to create the active configuration.
$config_dir = $this->getModulePath('system') . '/' . InstallStorage::CONFIG_INSTALL_DIRECTORY;
$this->assertDirectoryExists($config_dir);
$source_storage = new FileStorage($config_dir);
$data = $source_storage->read($config_name);
$this->assertSame($expected_original_data, $data);
// Verify that active configuration matches the expected data, which was
// created from the testing install profile's system.cron.yml file.
$config = $this->config($config_name);
$this->assertSame($expected_profile_data, $config->get());
$config = $this->config('system.site');
// Verify the system.site config has a valid UUID.
$this->assertTrue(Uuid::isValid($config->get('uuid')));
// Verify the profile overrides have been used.
$this->assertEquals(91, $config->get('weight_select_max'));
// Ensure the site configure form is used.
$this->assertEquals('Drupal', $config->get('name'));
$this->assertEquals('[email protected]', $config->get('mail'));
// Ensure that the configuration entity has the expected dependencies and
// overrides.
$action = Action::load('user_block_user_action');
$this->assertEquals('Overridden block the selected user(s)', $action->label());
$action = Action::load('user_cancel_user_action');
$this->assertEquals('Cancel the selected user account(s)', $action->label(), 'Default configuration that is not overridden is not affected.');
// Ensure that optional configuration can be overridden.
$config_test = \Drupal::entityTypeManager()->getStorage('entity_test_bundle')->load('install_test');
$this->assertEquals('Optional configuration can be overridden.', $config_test->label());
$config_test = \Drupal::entityTypeManager()->getStorage('entity_test_bundle')->load('install_test2');
$this->assertEquals('Optional configuration that is not overridden.', $config_test->label());
// Ensure the optional configuration is installed. Note that the overridden
// EntityTestBundle config with ID testing_config_overrides has a
// dependency on EntityTestBundle with ID testing_config_overrides_module,
// so it has to exist.
$this->assertInstanceOf(EntityTestBundle::class, \Drupal::entityTypeManager()->getStorage('entity_test_bundle')->load('testing_config_overrides_module'));
// Ensure that optional configuration from a profile is created if
// dependencies are met.
$this->assertEquals('Config override test', \Drupal::entityTypeManager()->getStorage('entity_test_bundle')->load('testing_config_overrides')->label());
// Ensure that optional configuration from a profile is not created if
// dependencies are not met. Cannot use the entity system since the entity
// type does not exist.
$optional_dir = $this->getModulePath('testing_config_overrides') . '/' . InstallStorage::CONFIG_OPTIONAL_DIRECTORY;
$optional_storage = new FileStorage($optional_dir);
foreach (['config_test.dynamic.dotted.default', 'config_test.dynamic.override', 'config_test.dynamic.override_unmet'] as $id) {
$this->assertTrue(\Drupal::config($id)->isNew(), "The config_test entity $id contained in the profile's optional directory does not exist.");
// Make that we don't get false positives from the assertion above.
$this->assertTrue($optional_storage->exists($id), "The config_test entity $id does exist in the profile's optional directory.");
}
// Install the config_test module and ensure that the override from the
// install profile is used. Optional configuration can override
// configuration in a modules config/install directory.
$this->container->get('module_installer')->install(['config_test']);
$this->rebuildContainer();
$config_test_storage = \Drupal::entityTypeManager()->getStorage('config_test');
$this->assertEquals('Default install profile override', $config_test_storage->load('dotted.default')->label(), 'The config_test entity is overridden by the profile optional configuration.');
// Test that override of optional configuration does work.
$this->assertEquals('Override', $config_test_storage->load('override')->label(), 'The optional config_test entity is overridden by the profile optional configuration.');
// Test that override of optional configuration which introduces an unmet
// dependency does not get created.
$this->assertNull($config_test_storage->load('override_unmet'), 'The optional config_test entity with unmet dependencies is not created.');
$this->assertNull($config_test_storage->load('completely_new'), 'The completely new optional config_test entity with unmet dependencies is not created.');
// Installing dblog creates the optional configuration.
$this->container->get('module_installer')->install(['dblog']);
$this->rebuildContainer();
$this->assertEquals('Override', $config_test_storage->load('override_unmet')->label(), 'The optional config_test entity is overridden by the profile optional configuration and is installed when its dependencies are met.');
$config_test_new = $config_test_storage->load('completely_new');
$this->assertEquals('Completely new optional configuration', $config_test_new->label(), 'The optional config_test entity is provided by the profile optional configuration and is installed when its dependencies are met.');
$config_test_new->delete();
// Install another module that provides optional configuration and ensure
// that deleted profile configuration is not re-created.
$this->container->get('module_installer')->install(['config_other_module_config_test']);
$this->rebuildContainer();
$config_test_storage = \Drupal::entityTypeManager()->getStorage('config_test');
$this->assertNull($config_test_storage->load('completely_new'));
// Ensure the authenticated role has the access entity_test_bundle permission.
$role = Role::load(Role::AUTHENTICATED_ID);
$this->assertTrue($role->hasPermission('administer entity_test_bundle content'), 'The Authenticated role has the "administer entity_test_bundle content" permission.');
$this->assertEquals(['module' => ['entity_test']], $role->getDependencies());
}
}
@@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\FunctionalTests\Installer\InstallerTestBase;
use Drupal\Core\Config\InstallStorage;
use Drupal\Core\Serialization\Yaml;
use Drupal\Tests\RequirementsPageTrait;
/**
* Tests install profile config overrides can not add unmet dependencies.
*
* @group Config
*/
class ConfigInstallProfileUnmetDependenciesTest extends InstallerTestBase {
use RequirementsPageTrait;
/**
* The installation profile to install.
*
* @var string
*/
protected $profile = 'testing_config_overrides';
/**
* Contains the expected exception if it is thrown.
*
* @var \Drupal\Core\Config\UnmetDependenciesException
*/
protected $expectedException = FALSE;
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function prepareEnvironment() {
parent::prepareEnvironment();
$this->copyTestingOverrides();
}
/**
* {@inheritdoc}
*/
public function setUpSettings() {
// During set up an UnmetDependenciesException should be thrown, which will
// be re-thrown by TestHttpClientMiddleware as a standard Exception.
try {
parent::setUpSettings();
}
catch (\Exception $exception) {
$this->expectedException = $exception;
}
}
/**
* {@inheritdoc}
*/
public function setUpSite() {
// This step can no longer be reached.
}
/**
* Copy the testing_config_overrides install profile.
*
* So we can change the configuration to include a dependency that can not be
* met. File API functions are not available yet.
*/
protected function copyTestingOverrides() {
$dest = $this->siteDirectory . '/profiles/testing_config_overrides';
mkdir($dest, 0777, TRUE);
$source = DRUPAL_ROOT . '/core/profiles/testing_config_overrides';
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $item) {
if ($item->isDir()) {
mkdir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
}
else {
copy((string) $item, $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
}
}
// Add a dependency that can not be met.
$config_file = $dest . DIRECTORY_SEPARATOR . InstallStorage::CONFIG_INSTALL_DIRECTORY . DIRECTORY_SEPARATOR . 'system.action.user_block_user_action.yml';
$action = Yaml::decode(file_get_contents($config_file));
$action['dependencies']['module'][] = 'does_not_exist';
file_put_contents($config_file, Yaml::encode($action));
}
/**
* Confirms that the installation succeeded.
*/
public function testInstalled(): void {
if ($this->expectedException) {
$this->assertStringContainsString('Configuration objects provided by <em class="placeholder">testing_config_overrides</em> have unmet dependencies: <em class="placeholder">system.action.user_block_user_action (does_not_exist)</em>', $this->expectedException->getMessage());
$this->assertStringContainsString('Drupal\Core\Config\UnmetDependenciesException', $this->expectedException->getMessage());
}
else {
$this->fail('Expected Drupal\Core\Config\UnmetDependenciesException exception not thrown');
}
}
}
@@ -0,0 +1,247 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\config_test\Entity\ConfigTest;
use Drupal\Core\Config\PreExistingConfigException;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\File\Exception\FileException;
use Drupal\Core\Site\Settings;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\Tests\BrowserTestBase;
// cspell:ignore suis
/**
* Tests configuration objects before and after module install and uninstall.
*
* The installation and removal of configuration objects in install, disable
* and uninstall functionality is tested.
*
* @group config
* @group #slow
*/
class ConfigInstallWebTest extends BrowserTestBase {
/**
* The admin user used in this test.
*/
protected $adminUser;
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->adminUser = $this->drupalCreateUser([
'administer modules',
'administer themes',
'administer site configuration',
]);
// Ensure the global variable being asserted by this test does not exist;
// a previous test executed in this request/process might have set it.
unset($GLOBALS['hook_config_test']);
}
/**
* Tests module re-installation.
*/
public function testIntegrationModuleReinstallation(): void {
$default_config = 'config_integration_test.settings';
$default_configuration_entity = 'config_test.dynamic.config_integration_test';
// Install the config_test module we're integrating with.
\Drupal::service('module_installer')->install(['config_test']);
// Verify the configuration does not exist prior to installation.
$config_static = $this->config($default_config);
$this->assertTrue($config_static->isNew());
$config_entity = $this->config($default_configuration_entity);
$this->assertTrue($config_entity->isNew());
// Install the integration module.
\Drupal::service('module_installer')->install(['config_integration_test']);
$this->resetAll();
// Verify that default module config exists.
\Drupal::configFactory()->reset($default_config);
\Drupal::configFactory()->reset($default_configuration_entity);
$config_static = $this->config($default_config);
$this->assertFalse($config_static->isNew());
$this->assertSame('default setting', $config_static->get('foo'));
$config_entity = $this->config($default_configuration_entity);
$this->assertFalse($config_entity->isNew());
$this->assertSame('Default integration config label', $config_entity->get('label'));
// Customize both configuration objects.
$config_static->set('foo', 'customized setting')->save();
$config_entity->set('label', 'Customized integration config label')->save();
// @todo FIXME: Setting config keys WITHOUT SAVING retains the changed config
// object in memory. Every new call to $this->config() MUST revert in-memory changes
// that haven't been saved!
// In other words: This test passes even without this reset, but it shouldn't.
$this->container->get('config.factory')->reset();
// Disable and uninstall the integration module.
$this->container->get('module_installer')->uninstall(['config_integration_test']);
// Verify the integration module's config was uninstalled.
$config_static = $this->config($default_config);
$this->assertTrue($config_static->isNew());
// Verify the integration config still exists.
$config_entity = $this->config($default_configuration_entity);
$this->assertFalse($config_entity->isNew());
$this->assertSame('Customized integration config label', $config_entity->get('label'));
// Reinstall the integration module.
try {
\Drupal::service('module_installer')->install(['config_integration_test']);
$this->fail('Expected PreExistingConfigException not thrown.');
}
catch (PreExistingConfigException $e) {
$this->assertEquals('config_integration_test', $e->getExtension());
$this->assertEquals([StorageInterface::DEFAULT_COLLECTION => ['config_test.dynamic.config_integration_test']], $e->getConfigObjects());
$this->assertEquals('Configuration objects (config_test.dynamic.config_integration_test) provided by config_integration_test already exist in active configuration', $e->getMessage());
}
// Delete the configuration entity so that the install will work.
$config_entity->delete();
\Drupal::service('module_installer')->install(['config_integration_test']);
// Verify the integration module's config was re-installed.
\Drupal::configFactory()->reset($default_config);
\Drupal::configFactory()->reset($default_configuration_entity);
$config_static = $this->config($default_config);
$this->assertFalse($config_static->isNew());
$this->assertSame('default setting', $config_static->get('foo'));
// Verify the integration config is using the default.
$config_entity = \Drupal::config($default_configuration_entity);
$this->assertFalse($config_entity->isNew());
$this->assertSame('Default integration config label', $config_entity->get('label'));
}
/**
* Tests pre-existing configuration detection.
*/
public function testPreExistingConfigInstall(): void {
$this->drupalLogin($this->adminUser);
// Try to install config_install_fail_test and config_test. Doing this
// will install the config_test module first because it is a dependency of
// config_install_fail_test.
// @see \Drupal\system\Form\ModulesListForm::submitForm()
$this->drupalGet('admin/modules');
$this->submitForm([
'modules[config_test][enable]' => TRUE,
'modules[config_install_fail_test][enable]' => TRUE,
], 'Install');
$this->assertSession()->responseContains('Unable to install Configuration install fail test, <em class="placeholder">config_test.dynamic.dotted.default</em> already exists in active configuration.');
// Uninstall the config_test module to test the confirm form.
$this->drupalGet('admin/modules/uninstall');
$this->submitForm(['uninstall[config_test]' => TRUE], 'Uninstall');
$this->submitForm([], 'Uninstall');
// Try to install config_install_fail_test without selecting config_test.
// The user is shown a confirm form because the config_test module is a
// dependency.
// @see \Drupal\system\Form\ModulesListConfirmForm::submitForm()
$this->drupalGet('admin/modules');
$this->submitForm(['modules[config_install_fail_test][enable]' => TRUE], 'Install');
$this->submitForm([], 'Continue');
$this->assertSession()->responseContains('Unable to install Configuration install fail test, <em class="placeholder">config_test.dynamic.dotted.default</em> already exists in active configuration.');
// Test that collection configuration clashes during a module install are
// reported correctly.
\Drupal::service('module_installer')->install(['language']);
$this->rebuildContainer();
ConfigurableLanguage::createFromLangcode('fr')->save();
\Drupal::languageManager()
->getLanguageConfigOverride('fr', 'config_test.dynamic.dotted.default')
->set('label', 'Je suis Charlie')
->save();
$this->drupalGet('admin/modules');
$this->submitForm(['modules[config_install_fail_test][enable]' => TRUE], 'Install');
$this->assertSession()->responseContains('Unable to install Configuration install fail test, <em class="placeholder">config_test.dynamic.dotted.default, language/fr/config_test.dynamic.dotted.default</em> already exist in active configuration.');
// Test installing a theme through the UI that has existing configuration.
// This relies on the fact the config_test has been installed and created
// the config_test.dynamic.dotted.default configuration and the translation
// override created still exists.
$this->drupalGet('admin/appearance');
$url = $this->xpath("//a[contains(@href,'config_clash_test_theme') and contains(@href,'/install?')]/@href")[0];
$this->drupalGet($this->getAbsoluteUrl($url->getText()));
$this->assertSession()->responseContains('Unable to install config_clash_test_theme, <em class="placeholder">config_test.dynamic.dotted.default, language/fr/config_test.dynamic.dotted.default</em> already exist in active configuration.');
// Test installing a theme through the API that has existing configuration.
try {
\Drupal::service('theme_installer')->install(['config_clash_test_theme']);
$this->fail('Expected PreExistingConfigException not thrown.');
}
catch (PreExistingConfigException $e) {
$this->assertEquals('config_clash_test_theme', $e->getExtension());
$this->assertEquals([StorageInterface::DEFAULT_COLLECTION => ['config_test.dynamic.dotted.default'], 'language.fr' => ['config_test.dynamic.dotted.default']], $e->getConfigObjects());
$this->assertEquals('Configuration objects (config_test.dynamic.dotted.default, language/fr/config_test.dynamic.dotted.default) provided by config_clash_test_theme already exist in active configuration', $e->getMessage());
}
}
/**
* Tests unmet dependencies detection.
*/
public function testUnmetDependenciesInstall(): void {
$this->drupalLogin($this->adminUser);
// We need to install separately since config_install_dependency_test does
// not depend on config_test and order is important.
$this->drupalGet('admin/modules');
$this->submitForm(['modules[config_test][enable]' => TRUE], 'Install');
$this->drupalGet('admin/modules');
$this->submitForm(['modules[config_install_dependency_test][enable]' => TRUE], 'Install');
$this->assertSession()->responseContains('Unable to install <em class="placeholder">Config install dependency test</em> due to unmet dependencies: <em class="placeholder">config_test.dynamic.other_module_test_with_dependency (config_other_module_config_test, config_test.dynamic.dotted.english)</em>');
$this->drupalGet('admin/modules');
$this->submitForm(['modules[config_test_language][enable]' => TRUE], 'Install');
$this->drupalGet('admin/modules');
$this->submitForm(['modules[config_install_dependency_test][enable]' => TRUE], 'Install');
$this->assertSession()->responseContains('Unable to install <em class="placeholder">Config install dependency test</em> due to unmet dependencies: <em class="placeholder">config_test.dynamic.other_module_test_with_dependency (config_other_module_config_test)</em>');
$this->drupalGet('admin/modules');
$this->submitForm(['modules[config_other_module_config_test][enable]' => TRUE], 'Install');
$this->drupalGet('admin/modules');
$this->submitForm(['modules[config_install_dependency_test][enable]' => TRUE], 'Install');
$this->rebuildContainer();
$this->assertInstanceOf(ConfigTest::class, \Drupal::entityTypeManager()->getStorage('config_test')->load('other_module_test_with_dependency'));
}
/**
* Tests config_requirements().
*/
public function testConfigModuleRequirements(): void {
$this->drupalLogin($this->adminUser);
$this->drupalGet('admin/modules');
$this->submitForm(['modules[config][enable]' => TRUE], 'Install');
$directory = Settings::get('config_sync_directory');
try {
\Drupal::service('file_system')->deleteRecursive($directory);
}
catch (FileException $e) {
// Ignore failed deletes.
}
$this->drupalGet('/admin/reports/status');
$this->assertSession()->pageTextContains("The directory $directory does not exist.");
}
}
@@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Core\Language\LanguageInterface;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\Tests\BrowserTestBase;
/**
* Tests language overrides applied through the website.
*
* @group config
*/
class ConfigLanguageOverrideWebTest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'block',
'language',
'system',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
}
/**
* Tests translating the site name.
*/
public function testSiteNameTranslation(): void {
$adminUser = $this->drupalCreateUser([
'administer site configuration',
'administer languages',
]);
$this->drupalLogin($adminUser);
// Add a custom language.
$langcode = 'xx';
$name = $this->randomMachineName(16);
$edit = [
'predefined_langcode' => 'custom',
'langcode' => $langcode,
'label' => $name,
'direction' => LanguageInterface::DIRECTION_LTR,
];
$this->drupalGet('admin/config/regional/language/add');
$this->submitForm($edit, 'Add custom language');
\Drupal::languageManager()
->getLanguageConfigOverride($langcode, 'system.site')
->set('name', 'XX site name')
->save();
// Place branding block with site name into header region.
$this->drupalPlaceBlock('system_branding_block', ['region' => 'header']);
$this->drupalLogout();
// The home page in English should not have the override.
$this->drupalGet('');
$this->assertSession()->pageTextNotContains('XX site name');
// During path resolution the system.site configuration object is used to
// determine the front page. This occurs before language negotiation causing
// the configuration factory to cache an object without the correct
// overrides. We are testing that the configuration factory is
// re-initialized after language negotiation. Ensure that it applies when
// we access the XX front page.
// @see \Drupal\Core\PathProcessor::processInbound()
$this->drupalGet('xx');
$this->assertSession()->pageTextContains('XX site name');
// Set the xx language to be the default language and delete the English
// language so the site is no longer multilingual and confirm configuration
// overrides still work.
$language_manager = \Drupal::languageManager()->reset();
$this->assertTrue($language_manager->isMultilingual(), 'The test site is multilingual.');
$this->config('system.site')->set('default_langcode', 'xx')->save();
ConfigurableLanguage::load('en')->delete();
$this->assertFalse($language_manager->isMultilingual(), 'The test site is monolingual.');
$this->drupalGet('xx');
$this->assertSession()->pageTextContains('XX site name');
}
}
@@ -0,0 +1,276 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Core\Serialization\Yaml;
use Drupal\Tests\BrowserTestBase;
/**
* Tests the user interface for importing/exporting a single configuration.
*
* @group config
*/
class ConfigSingleImportExportTest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'block',
'config',
'config_test',
// Adding language module makes it possible to involve non-default
// (language.xx) collections in import/export operations.
'language',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->drupalPlaceBlock('page_title_block');
}
/**
* Tests importing a single configuration file.
*/
public function testImport(): void {
$storage = \Drupal::entityTypeManager()->getStorage('config_test');
$uuid = \Drupal::service('uuid');
$this->drupalLogin($this->drupalCreateUser(['import configuration']));
// Attempt an import with invalid YAML.
$edit = [
'config_type' => 'action',
'import' => '{{{',
];
$this->drupalGet('admin/config/development/configuration/single/import');
$this->submitForm($edit, 'Import');
// Assert the static portion of the error since different parsers could give different text in their error.
$this->assertSession()->pageTextContains('The import failed with the following message: ');
$import = <<<EOD
label: First
weight: 0
style: ''
status: '1'
EOD;
$edit = [
'config_type' => 'config_test',
'import' => $import,
];
// Attempt an import with a missing ID.
$this->drupalGet('admin/config/development/configuration/single/import');
$this->submitForm($edit, 'Import');
$this->assertSession()->pageTextContains('Missing ID key "id" for this Test configuration import.');
// Perform an import with no specified UUID and a unique ID.
$this->assertNull($storage->load('first'));
$edit['import'] = "id: first\n" . $edit['import'];
$this->drupalGet('admin/config/development/configuration/single/import');
$this->submitForm($edit, 'Import');
$this->assertSession()->pageTextContains('Are you sure you want to create a new first test configuration?');
$this->submitForm([], 'Confirm');
$entity = $storage->load('first');
$this->assertSame('First', $entity->label());
$this->assertSame('first', $entity->id());
$this->assertTrue($entity->status());
$this->assertSession()->pageTextContains('The configuration was imported successfully.');
// Attempt an import with an existing ID but missing UUID.
$this->drupalGet('admin/config/development/configuration/single/import');
$this->submitForm($edit, 'Import');
$this->assertSession()->pageTextContains('An entity with this machine name already exists but the import did not specify a UUID.');
// Attempt an import with a mismatched UUID and existing ID.
$edit['import'] .= "\nuuid: " . $uuid->generate();
$this->drupalGet('admin/config/development/configuration/single/import');
$this->submitForm($edit, 'Import');
$this->assertSession()->pageTextContains('An entity with this machine name already exists but the UUID does not match.');
// Attempt an import with a custom ID.
$edit['custom_entity_id'] = 'custom_id';
$this->drupalGet('admin/config/development/configuration/single/import');
$this->submitForm($edit, 'Import');
$this->assertSession()->pageTextContains('Are you sure you want to create a new custom_id test configuration?');
$this->submitForm([], 'Confirm');
$this->assertSession()->pageTextContains('The configuration was imported successfully.');
// Perform an import with a unique ID and UUID.
$import = <<<EOD
id: second
label: Second
weight: 0
style: ''
status: '0'
EOD;
$edit = [
'config_type' => 'config_test',
'import' => $import,
];
$second_uuid = $uuid->generate();
$edit['import'] .= "\nuuid: " . $second_uuid;
$this->drupalGet('admin/config/development/configuration/single/import');
$this->submitForm($edit, 'Import');
$this->assertSession()->pageTextContains('Are you sure you want to create a new second test configuration?');
$this->submitForm([], 'Confirm');
$entity = $storage->load('second');
$this->assertSession()->pageTextContains('The configuration was imported successfully.');
$this->assertSame('Second', $entity->label());
$this->assertSame('second', $entity->id());
$this->assertFalse($entity->status());
$this->assertSame($second_uuid, $entity->uuid());
// Perform an update.
$import = <<<EOD
id: second
uuid: $second_uuid
label: 'Second updated'
weight: 0
style: ''
status: '0'
EOD;
$edit = [
'config_type' => 'config_test',
'import' => $import,
];
$this->drupalGet('admin/config/development/configuration/single/import');
$this->submitForm($edit, 'Import');
$this->assertSession()->pageTextContains('Are you sure you want to update the second test configuration?');
$this->submitForm([], 'Confirm');
$entity = $storage->load('second');
$this->assertSession()->pageTextContains('The configuration was imported successfully.');
$this->assertSame('Second updated', $entity->label());
// Try to perform an update which adds missing dependencies.
$import = <<<EOD
id: second
uuid: $second_uuid
label: 'Second updated'
weight: 0
style: ''
status: '0'
dependencies:
module:
- does_not_exist
EOD;
$edit = [
'config_type' => 'config_test',
'import' => $import,
];
$this->drupalGet('admin/config/development/configuration/single/import');
$this->submitForm($edit, 'Import');
$this->assertSession()->pageTextContains('Configuration config_test.dynamic.second depends on the does_not_exist module that will not be installed after import.');
// Try to preform an update which would create a PHP object if Yaml parsing
// not securely set up.
// Perform an update.
$import = <<<EOD
id: second
uuid: $second_uuid
label: !php/object "O:36:\"Drupal\\\Core\\\Test\\\ObjectSerialization\":0:{}"
weight: 0
style: ''
status: '0'
EOD;
$edit = [
'config_type' => 'config_test',
'import' => $import,
];
$this->drupalGet('admin/config/development/configuration/single/import');
$this->submitForm($edit, 'Import');
// @see \Drupal\Tests\Component\Serialization\YamlSymfonyTest:: testDecodeObjectSupportDisabled()
$this->assertSession()->responseContains('The import failed with the following message:');
$this->assertSession()->responseContains('Object support when parsing a YAML file has been disabled');
}
/**
* Tests importing a simple configuration file.
*/
public function testImportSimpleConfiguration(): void {
$this->drupalLogin($this->drupalCreateUser(['import configuration']));
$config = $this->config('system.site')->set('name', 'Test simple import');
// Place branding block with site name into header region.
$this->drupalPlaceBlock('system_branding_block', ['region' => 'header']);
$edit = [
'config_type' => 'system.simple',
'config_name' => $config->getName(),
'import' => Yaml::encode($config->get()),
];
$this->drupalGet('admin/config/development/configuration/single/import');
$this->submitForm($edit, 'Import');
$this->assertSession()->pageTextContains('Are you sure you want to update the ' . $config->getName() . ' simple configuration?');
$this->submitForm([], 'Confirm');
$this->drupalGet('');
$this->assertSession()->pageTextContains('Test simple import');
// Ensure that ConfigImporter validation is running when importing simple
// configuration.
$config_data = $this->config('core.extension')->get();
// Simulate uninstalling the Config module.
unset($config_data['module']['config']);
$edit = [
'config_type' => 'system.simple',
'config_name' => 'core.extension',
'import' => Yaml::encode($config_data),
];
$this->drupalGet('admin/config/development/configuration/single/import');
$this->submitForm($edit, 'Import');
$this->assertSession()->pageTextContains('Can not uninstall the Configuration module as part of a configuration synchronization through the user interface.');
// Try to import without any values.
$this->drupalGet('admin/config/development/configuration/single/import');
$this->submitForm([], 'Import');
$this->assertSession()->pageTextContains('Configuration type field is required.');
$this->assertSession()->pageTextContains('Paste your configuration here field is required.');
}
/**
* Tests exporting a single configuration file.
*/
public function testExport(): void {
$this->drupalLogin($this->drupalCreateUser(['export configuration']));
// Verify that the simple configuration option is selected when specified
// in the URL.
$this->drupalGet('admin/config/development/configuration/single/export/system.simple');
$option_node = $this->assertSession()->optionExists("config_type", 'Simple configuration');
$this->assertTrue($option_node->isSelected());
// Spot check several known simple configuration files.
$this->assertSession()->optionExists('config_name', 'system.site');
$this->assertSession()->optionExists('config_name', 'user.settings');
$this->drupalGet('admin/config/development/configuration/single/export/system.simple/system.image');
// cspell:disable-next-line
$this->assertSession()->fieldValueEquals('export', "_core:\n default_config_hash: durWHaKeBaq4d9Wpi4RqwADj1OufDepcnJuhVLmKN24\ntoolkit: gd\n");
// Verify that the date format entity type is selected when specified in
// the URL.
$this->drupalGet('admin/config/development/configuration/single/export/date_format');
$option_node = $this->assertSession()->optionExists("config_type", 'Date format');
$this->assertTrue($option_node->isSelected());
// Verify that the fallback date format config entity is selected when
// specified in the URL.
$this->drupalGet('admin/config/development/configuration/single/export/date_format/fallback');
$option_node = $this->assertSession()->optionExists("config_name", 'fallback (Fallback date format)');
$this->assertTrue($option_node->isSelected());
$fallback_date = \Drupal::entityTypeManager()->getStorage('date_format')->load('fallback');
$yaml_text = $this->assertSession()->fieldExists('export')->getValue();
$this->assertEquals(Yaml::decode($yaml_text), $fallback_date->toArray(), 'The fallback date format config entity export code is displayed.');
}
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Tests\system\Functional\Module\GenericModuleTestBase;
/**
* Generic module test for config.
*
* @group config
*/
class GenericTest extends GenericModuleTestBase {}
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Tests language-negotiation overrides are not on language-negotiation form.
*
* @group config
* @see \Drupal\Core\Form\ConfigFormBase
*/
class LanguageNegotiationFormOverrideTest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['language', 'locale', 'locale_test'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests that overrides do not affect language-negotiation form values.
*/
public function testFormWithOverride(): void {
$this->drupalLogin($this->drupalCreateUser([
'access administration pages',
'administer site configuration',
'administer languages',
'view the administration theme',
]));
$overridden_value_en = 'whatever';
$overridden_value_es = 'loquesea';
// Set up an override.
$settings['config']['language.negotiation']['url']['prefixes'] = (object) [
'value' => ['en' => $overridden_value_en, 'es' => $overridden_value_es],
'required' => TRUE,
];
$this->writeSettings($settings);
// Add predefined language.
$edit = [
'predefined_langcode' => 'es',
];
$this->drupalGet('admin/config/regional/language/add');
$this->submitForm($edit, 'Add language');
// Overridden string for language-negotiation should not exist in the form.
$this->drupalGet('admin/config/regional/language/detection/url');
// The language-negotiation form should be found.
$this->assertSession()->pageTextContains('Path prefix configuration');
// The English override should not be found.
$this->assertSession()->fieldValueNotEquals('prefix[en]', $overridden_value_en);
// Now check the Spanish version of the page for the same thing.
$this->drupalGet($overridden_value_es . '/admin/config/regional/language/detection/url');
// The language-negotiation form should be found.
$this->assertSession()->pageTextContains('Path prefix configuration');
// The Spanish override should not be found.
$this->assertSession()->fieldValueNotEquals('prefix[es]', $overridden_value_es);
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Core\Config\Schema\SchemaIncompleteException;
use Drupal\Tests\BrowserTestBase;
/**
* Tests the functionality of ConfigSchemaChecker in BrowserTestBase tests.
*
* @group config
*/
class SchemaConfigListenerWebTest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['config_test'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests \Drupal\Core\Config\Development\ConfigSchemaChecker.
*/
public function testConfigSchemaChecker(): void {
$this->drupalLogin($this->drupalCreateUser(['administer site configuration']));
// Test a non-existing schema.
try {
$this->config('config_schema_test.schemaless')->set('foo', 'bar')->save();
$this->fail('Expected SchemaIncompleteException thrown');
}
catch (SchemaIncompleteException $e) {
$this->assertEquals('No schema for config_schema_test.schemaless', $e->getMessage());
}
// Test a valid schema.
$config = $this->config('config_test.types')->set('int', 10);
try {
$config->save();
}
catch (SchemaIncompleteException $e) {
$this->fail('Unexpected SchemaIncompleteException thrown');
}
// Test an invalid schema.
$config = $this->config('config_test.types')
->set('foo', 'bar')
->set('array', 1);
try {
$config->save();
$this->fail('Expected SchemaIncompleteException thrown');
}
catch (SchemaIncompleteException $e) {
$this->assertEquals("Schema errors for config_test.types with the following errors: config_test.types:array variable type is integer but applied schema class is Drupal\Core\Config\Schema\Sequence, config_test.types:foo missing schema, 0 [foo] &#039;foo&#039; is not a supported key.", $e->getMessage());
}
// Test that the config event listener is working in the child site.
$this->drupalGet('config_test/schema_listener');
$this->assertSession()->pageTextContains('No schema for config_schema_test.schemaless');
}
}
@@ -0,0 +1,106 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Functional;
use Drupal\Tests\BrowserTestBase;
// cspell:ignore arrr
/**
* Tests the user interface for importing/exporting transformed configuration.
*
* @group config
*/
class TransformedConfigExportImportUITest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'config',
'config_transformer_test',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$permissions = [
'export configuration',
'import configuration',
'synchronize configuration',
];
$this->drupalLogin($this->drupalCreateUser($permissions));
// Start off with the sync storage being the same as the active storage.
$this->copyConfig($this->container->get('config.storage'), $this->container->get('config.storage.sync'));
}
/**
* Tests a simple site export import case.
*/
public function testTransformedExportImport(): void {
// After installation there is no snapshot but a new site name.
$this->drupalGet('admin/config/development/configuration');
$this->assertSession()->pageTextNotContains('Warning message');
$this->assertSession()->pageTextNotContains('There are no configuration changes to import.');
// Tests changes of system.site.
$this->drupalGet('admin/config/development/configuration/sync/diff/system.site');
$this->assertSession()->pageTextContains('name: Drupal');
$this->assertSession()->pageTextContains("name: 'Drupal Arrr'");
// Add a slogan.
$originalSlogan = $this->config('system.site')->get('slogan');
$this->assertEmpty($originalSlogan);
$newSlogan = $this->randomMachineName(16);
$this->assertNotEquals($originalSlogan, $newSlogan);
$this->config('system.site')
->set('slogan', $newSlogan)
->save();
$this->assertEquals($newSlogan, $this->config('system.site')->get('slogan'));
// Tests changes of system.site.
$this->drupalGet('admin/config/development/configuration/sync/diff/system.site');
$this->assertSession()->pageTextContains("slogan: ''");
$this->assertSession()->pageTextContains("slogan: $newSlogan");
// Export the configuration.
$this->drupalGet('admin/config/development/configuration/full/export');
$this->submitForm([], 'Export');
$tarball = $this->getSession()->getPage()->getContent();
// Import the configuration from the tarball.
$filename = 'temporary://' . $this->randomMachineName();
file_put_contents($filename, $tarball);
$this->drupalGet('admin/config/development/configuration/full/import');
$this->submitForm(['files[import_tarball]' => $filename], 'Upload');
// Assert the new name and slogan.
$this->drupalGet('admin/config/development/configuration/sync/diff/system.site');
$this->assertSession()->pageTextContains("name: 'Drupal Arrr'");
$this->assertSession()->pageTextContains("slogan: '$originalSlogan Arrr'");
$this->assertEquals('Drupal', $this->config('system.site')->get('name'));
$this->assertEquals($newSlogan, $this->config('system.site')->get('slogan'));
// Sync the configuration.
$this->drupalGet('admin/config/development/configuration');
$this->submitForm([], 'Import all');
$this->assertEquals('Drupal Arrr', $this->config('system.site')->get('name'));
$this->assertEquals($originalSlogan . " Arrr", $this->config('system.site')->get('slogan'));
// Assert that the event was dispatched again on the new config.
$this->drupalGet('admin/config/development/configuration/sync/diff/system.site');
$this->assertSession()->pageTextContains("name: 'Drupal Arrr Arrr'");
}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\FunctionalJavascript;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
/**
* Tests the Config operations through the UI.
*
* @group config
*/
class ConfigEntityTest extends WebDriverTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['config_test'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests ajax operations through the UI on 'Add' page.
*/
public function testAjaxOnAddPage(): void {
$this->drupalLogin($this->drupalCreateUser([
'administer site configuration',
]));
$page = $this->getSession()->getPage();
$assert_session = $this->assertSession();
$this->drupalGet('admin/structure/config_test/add');
// Test that 'size value' field is not show initially, and it is show after
// selecting value in the 'size' field.
$this->assertNull($page->findField('size_value'));
$page->findField('size')->setValue('custom');
$this->assertNotNull($assert_session->waitForField('size_value'));
}
}
@@ -0,0 +1,122 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\FunctionalJavascript;
use Drupal\block_content\Entity\BlockContent;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
/**
* Tests the config export form.
*
* @group config
*/
class ConfigExportTest extends WebDriverTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['config', 'system', 'block', 'block_content'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* @var string
* A prefix string used in naming the test blocks.
*/
protected string $blockNamePrefix = 'aaaaaa_config_export_test_block';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->drupalLogin($this->drupalCreateUser([
'administer blocks',
'access block library',
'administer block types',
'administer block content',
]));
// Create test blocks, so we know what the titles will be to check their order.
foreach ([1, 2, 3, 4] as $num) {
$block_name = $this->blockNamePrefix . $num;
$new_block = $this->createBlockContent($block_name);
$this->drupalPlaceBlock('block_content:' . $new_block->uuid(), [
'id' => $block_name,
'label' => $this->randomMachineName(),
'theme' => $this->defaultTheme,
'region' => 'sidebar_first',
]);
}
}
/**
* Creates test blocks.
*
* @param $title
* Title of the block.
*
* @return \Drupal\block_content\Entity\BlockContent
*
* @throws \Drupal\Core\Entity\EntityStorageException
*/
protected function createBlockContent($title) {
$block_content = BlockContent::create([
'info' => $title,
'type' => 'basic',
]);
$block_content->save();
return $block_content;
}
/**
* Tests Ajax form functionality on the config export page.
*/
public function testAjaxOnExportPage(): void {
$this->drupalLogin($this->drupalCreateUser([
'export configuration',
'administer blocks',
]));
$page = $this->getSession()->getPage();
// Check that the export is empty on load.
$this->drupalGet('admin/config/development/configuration/single/export');
$this->assertTrue($this->assertSession()->optionExists('edit-config-name', '- Select -')->isSelected());
$this->assertSession()->fieldValueEquals('export', '');
// Check that the export is filled when selecting a config name.
$page->selectFieldOption('config_name', 'system.site');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->fieldValueNotEquals('export', '');
// Check that the export is empty when selecting "- Select -" option in
// the config name.
$page->selectFieldOption('config_name', '- Select -');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->fieldValueEquals('export', '');
// Check that the export is emptied again when selecting a config type.
$page->selectFieldOption('config_type', 'Action');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->fieldValueEquals('export', '');
// Check that the 'Configuration name' list is sorted alphabetically by ID,
// which always begins with our prefix, and not the label, which is randomized.
$page->selectFieldOption('config_type', 'Block');
$this->assertSession()->assertWaitOnAjaxRequest();
$options = $page->findField('config_name')->findAll('css', 'option');
foreach ([1, 2, 3, 4] as $num) {
$block_name = $this->blockNamePrefix . $num;
$this->assertStringStartsWith($block_name, $options[$num]->getText());
$this->assertEquals($block_name, $options[$num]->getValue());
}
}
}
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\FunctionalJavascript;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
/**
* Tests the user interface for importing configuration.
*
* @group config
*/
class ConfigImportUIAjaxTest extends WebDriverTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'config',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests an updated configuration object can be viewed more than once.
*/
public function testImport(): void {
$name = 'system.site';
$assert_session = $this->assertSession();
$page = $this->getSession()->getPage();
$user = $this->drupalCreateUser(['synchronize configuration']);
$this->drupalLogin($user);
$this->copyConfig($this->container->get('config.storage'), $this->container->get('config.storage.sync'));
// Create updated configuration object.
$new_site_name = 'Config import test ' . $this->randomString();
$sync = $this->container->get('config.storage.sync');
// Create updated configuration object.
$config_data = $this->config('system.site')->get();
$config_data['name'] = $new_site_name;
$sync->write('system.site', $config_data);
$this->assertTrue($sync->exists($name), $name . ' found.');
// Verify that system.site appears as ready to import.
$this->drupalGet('admin/config/development/configuration');
$this->assertSession()->responseContains('<td>' . $name);
$this->assertSession()->buttonExists('Import all');
// Click the dropbutton to show the differences in a modal and close it.
$page->find('css', '.dropbutton-action')->click();
$assert_session->waitForElementVisible('css', '.ui-dialog');
$assert_session->assertVisibleInViewport('css', '.ui-dialog .ui-dialog-content');
$page->pressButton('Close');
$assert_session->assertNoElementAfterWait('css', '.ui-dialog');
// Do this again to make sure no JavaScript errors occur on revisits.
$page->find('css', '.dropbutton-action')->click();
$assert_session->waitForElementVisible('css', '.ui-dialog');
$assert_session->assertVisibleInViewport('css', '.ui-dialog .ui-dialog-content');
$page->pressButton('Close');
$assert_session->assertNoElementAfterWait('css', '.ui-dialog');
}
}
@@ -0,0 +1,158 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Kernel;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\KernelTests\KernelTestBase;
/**
* Tests default configuration provided by a module that does not own it.
*
* @group config
*/
class ConfigOtherModuleTest extends KernelTestBase {
/**
* Tests enabling the provider of the default configuration first.
*/
public function testInstallOtherModuleFirst(): void {
$this->installModule('config_other_module_config_test');
// Check that the config entity doesn't exist before the config_test module
// is enabled. We cannot use the entity system because the config_test
// entity type does not exist.
$config = $this->config('config_test.dynamic.other_module_test');
$this->assertTrue($config->isNew(), 'Default configuration for other modules is not installed if that module is not enabled.');
// Install the module that provides the entity type. This installs the
// default configuration.
$this->installModule('config_test');
$this->assertNotEmpty($this->getStorage()->load('other_module_test'), 'Default configuration has been installed.');
// Uninstall the module that provides the entity type. This will remove the
// default configuration.
$this->uninstallModule('config_test');
$config = $this->config('config_test.dynamic.other_module_test');
$this->assertTrue($config->isNew(), 'Default configuration for other modules is removed when the config entity provider is disabled.');
// Install the module that provides the entity type again. This installs the
// default configuration.
$this->installModule('config_test');
/** @var \Drupal\Core\Config\Entity\ConfigEntityInterface $other_module_config_entity */
$other_module_config_entity = $this->getStorage()->load('other_module_test');
$this->assertNotEmpty($other_module_config_entity, "Default configuration has been recreated.");
// Update the default configuration to test that the changes are preserved
// if the module that provides the default configuration is uninstalled.
$other_module_config_entity->set('style', "The piano ain't got no wrong notes.");
$other_module_config_entity->save();
// Uninstall the module that provides the default configuration.
$this->uninstallModule('config_other_module_config_test');
$this->assertNotEmpty($this->getStorage()->load('other_module_test'), 'Default configuration for other modules is not removed when the module that provides it is uninstalled.');
// Default configuration provided by config_test should still exist.
$this->assertNotEmpty($this->getStorage()->load('dotted.default'), 'The configuration is not deleted.');
// Re-enable module to test that pre-existing optional configuration does
// not throw an error.
$this->installModule('config_other_module_config_test');
$this->assertTrue(\Drupal::moduleHandler()->moduleExists('config_other_module_config_test'), 'The config_other_module_config_test module is installed.');
// Ensure that optional configuration with unmet dependencies is only
// installed once all the dependencies are met.
$this->assertNull($this->getStorage()->load('other_module_test_unmet'), 'The optional configuration config_test.dynamic.other_module_test_unmet whose dependencies are not met is not created.');
$this->assertNull($this->getStorage()->load('other_module_test_optional_entity_unmet'), 'The optional configuration config_test.dynamic.other_module_test_optional_entity_unmet whose dependencies are not met is not created.');
$this->installModule('config_test_language');
$this->assertNull($this->getStorage()->load('other_module_test_optional_entity_unmet'), 'The optional configuration config_test.dynamic.other_module_test_optional_entity_unmet whose dependencies are met is not created.');
$this->installModule('config_install_dependency_test');
$this->assertNotEmpty($this->getStorage()->load('other_module_test_unmet'), 'The optional configuration config_test.dynamic.other_module_test_unmet whose dependencies are met is now created.');
// The following configuration entity's dependencies are now met. It is
// indirectly dependent on the config_install_dependency_test module because
// it has a dependency on the config_test.dynamic.dependency_for_unmet2
// configuration provided by that module and, therefore, should be created.
$this->assertNotEmpty($this->getStorage()->load('other_module_test_optional_entity_unmet2'), 'The optional configuration config_test.dynamic.other_module_test_optional_entity_unmet2 whose dependencies are met is now created.');
// The following configuration entity's dependencies are now met even though
// it has no direct dependency on the module. It is indirectly dependent on
// the config_install_dependency_test module because it has a dependency on
// the config_test.dynamic.other_module_test_unmet configuration that is
// dependent on the config_install_dependency_test module and, therefore,
// should be created.
$entity = $this->getStorage()->load('other_module_test_optional_entity_unmet');
$this->assertNotEmpty($entity, 'The optional configuration config_test.dynamic.other_module_test_optional_entity_unmet whose dependencies are met is created.');
$entity->delete();
// Install another module to ensure the configuration just deleted is not
// recreated.
$this->installModule('config');
$this->assertNull($this->getStorage()->load('other_module_test_optional_entity_unmet'), 'The optional configuration config_test.dynamic.other_module_test_optional_entity_unmet whose dependencies are met is not installed when an unrelated module is installed.');
// Ensure that enforced dependencies do not overwrite base ones.
$this->installModule('config_install_dependency_enforced_combo_test');
$this->assertTrue(\Drupal::moduleHandler()->moduleExists('config_install_dependency_enforced_combo_test'), 'The config_install_dependency_enforced_combo_test module is installed.');
$this->assertNull($this->getStorage()->load('config_test.dynamic.enforced_and_base_dependencies'), 'The optional configuration config_test.dynamic.enforced_and_base_dependencies whose enforced dependencies are met but base module dependencies are not met is not created.');
}
/**
* Tests enabling the provider of the config entity type first.
*/
public function testInstallConfigEntityModuleFirst(): void {
$this->installModule('config_test');
$this->assertNull($this->getStorage()->load('other_module_test'), 'Default configuration provided by config_other_module_config_test does not exist.');
$this->installModule('config_other_module_config_test');
$this->assertNotEmpty($this->getStorage()->load('other_module_test'), 'Default configuration provided by config_other_module_config_test has been installed.');
}
/**
* Tests uninstalling Node module removes views which are dependent on it.
*/
public function testUninstall(): void {
$this->installModule('views');
$this->assertNull($this->getStorage('view')->load('frontpage'), 'After installing Views, frontpage view which is dependant on the Node and Views modules does not exist.');
$this->installModule('node');
$this->assertNotNull($this->getStorage('view')->load('frontpage'), 'After installing Node, frontpage view which is dependant on the Node and Views modules exists.');
$this->uninstallModule('node');
$this->assertNull($this->getStorage('view')->load('frontpage'), 'After uninstalling Node, frontpage view which is dependant on the Node and Views modules does not exist.');
}
/**
* Installs a module.
*
* @param string $module
* The module name.
*/
protected function installModule(string $module): void {
$this->container->get('module_installer')->install([$module]);
$this->container = \Drupal::getContainer();
}
/**
* Uninstalls a module.
*
* @param string $module
* The module name.
*/
protected function uninstallModule(string $module): void {
$this->container->get('module_installer')->uninstall([$module]);
$this->container = \Drupal::getContainer();
}
/**
* Gets the provided entity type's storage.
*
* @param string $entity_type_id
* (optional) The entity type ID to get a storage for. Defaults to
* 'config_test'.
*
* @return \Drupal\Core\Entity\EntityStorageInterface
* The entity type's storage.
*/
protected function getStorage(string $entity_type_id = 'config_test'): EntityStorageInterface {
return \Drupal::entityTypeManager()->getStorage($entity_type_id);
}
}
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Kernel;
use Drupal\Core\Config\ConfigImporter;
use Drupal\Core\Config\StorageComparer;
use Drupal\KernelTests\KernelTestBase;
/**
* Tests importing configuration from files into active configuration.
*
* @group config
*/
class ConfigUninstallViaCliImportTest extends KernelTestBase {
/**
* Config Importer object used for testing.
*
* @var \Drupal\Core\Config\ConfigImporter
*/
protected $configImporter;
/**
* {@inheritdoc}
*/
protected static $modules = ['system', 'config'];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
if (PHP_SAPI !== 'cli') {
$this->markTestSkipped('This test has to be run from the CLI');
}
$this->installConfig(['system']);
$this->copyConfig($this->container->get('config.storage'), $this->container->get('config.storage.sync'));
// Set up the ConfigImporter object for testing.
$storage_comparer = new StorageComparer(
$this->container->get('config.storage.sync'),
$this->container->get('config.storage')
);
$this->configImporter = new ConfigImporter(
$storage_comparer->createChangelist(),
$this->container->get('event_dispatcher'),
$this->container->get('config.manager'),
$this->container->get('lock'),
$this->container->get('config.typed'),
$this->container->get('module_handler'),
$this->container->get('module_installer'),
$this->container->get('theme_handler'),
$this->container->get('string_translation'),
$this->container->get('extension.list.module'),
$this->container->get('extension.list.theme')
);
}
/**
* Tests that the config module can be uninstalled via CLI config import.
*
* @see \Drupal\config\ConfigSubscriber
*/
public function testConfigUninstallViaCli(): void {
$this->assertTrue($this->container->get('module_handler')->moduleExists('config'));
$sync = $this->container->get('config.storage.sync');
$extensions = $sync->read('core.extension');
unset($extensions['module']['config']);
$sync->write('core.extension', $extensions);
$this->configImporter->reset()->import();
$this->assertFalse($this->container->get('module_handler')->moduleExists('config'));
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Traits;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
/**
* Provides test assertions for testing config entity synchronization.
*
* Can be used by test classes that extend \Drupal\Tests\BrowserTestBase or
* \Drupal\KernelTests\KernelTestBase.
*/
trait AssertConfigEntityImportTrait {
/**
* Asserts that a config entity can be imported without changing it.
*
* @param \Drupal\Core\Config\Entity\ConfigEntityInterface $entity
* The config entity to test importing.
*/
public function assertConfigEntityImport(ConfigEntityInterface $entity) {
// Save original config information.
$entity_uuid = $entity->uuid();
$entity_type_id = $entity->getEntityTypeId();
$original_data = $entity->toArray();
// Copy everything to sync.
$this->copyConfig(\Drupal::service('config.storage'), \Drupal::service('config.storage.sync'));
// Delete the configuration from active. Don't worry about side effects of
// deleting config like fields cleaning up field storages. The coming import
// should recreate everything as necessary.
$entity->delete();
$this->configImporter()->reset()->import();
$imported_entity = \Drupal::service('entity.repository')->loadEntityByUuid($entity_type_id, $entity_uuid);
$this->assertSame($original_data, $imported_entity->toArray());
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\config\Unit\Menu;
use Drupal\Tests\Core\Menu\LocalTaskIntegrationTestBase;
/**
* Tests existence of config local tasks.
*
* @group config
*/
class ConfigLocalTasksTest extends LocalTaskIntegrationTestBase {
/**
* {@inheritdoc}
*/
protected function setUp(): void {
$this->directoryList = ['config' => 'core/modules/config'];
parent::setUp();
}
/**
* Tests config local tasks existence.
*
* @dataProvider getConfigAdminRoutes
*/
public function testConfigAdminLocalTasks($route, $expected): void {
$this->assertLocalTasks($route, $expected);
}
/**
* Provides a list of routes to test.
*/
public static function getConfigAdminRoutes() {
return [
['config.sync', [['config.sync', 'config.import', 'config.export']]],
['config.import_full', [['config.sync', 'config.import', 'config.export'], ['config.import_full', 'config.import_single']]],
['config.import_single', [['config.sync', 'config.import', 'config.export'], ['config.import_full', 'config.import_single']]],
['config.export_full', [['config.sync', 'config.import', 'config.export'], ['config.export_full', 'config.export_single']]],
['config.export_single', [['config.sync', 'config.import', 'config.export'], ['config.export_full', 'config.export_single']]],
];
}
}