first commit

This commit is contained in:
2018-04-23 21:08:22 +02:00
commit c68c1dd9b0
12994 changed files with 1500824 additions and 0 deletions
@@ -0,0 +1,7 @@
langcode: en
status: true
dependencies: { }
id: short
label: 'Default short date'
locked: false
pattern: 'm/d/Y - H:i'
@@ -0,0 +1,3 @@
threshold:
requirements_warning: 172800
requirements_error: 1209600
@@ -0,0 +1,3 @@
bundle: test
excluded:
- system.theme
@@ -0,0 +1,13 @@
name: feature
type: module
# core: 8.x
package: Test
# Force this to install after features.
dependencies:
- features
# Information added by Drupal.org packaging script on 2017-03-07
version: '8.x-3.5'
core: '8.x'
project: 'features'
datestamp: 1488908587
@@ -0,0 +1,7 @@
langcode: en
status: true
dependencies: { }
id: long
label: 'Default long date'
locked: false
pattern: 'l, F j, Y - H:i'
@@ -0,0 +1,3 @@
bundle: test_mybundle
excluded:
- system.theme
@@ -0,0 +1,13 @@
name: Test Core
type: module
# core: 8.x
package: Test
# Ensure features is enabled first
dependencies:
- features
# Information added by Drupal.org packaging script on 2017-03-07
version: '8.x-3.5'
core: '8.x'
project: 'features'
datestamp: 1488908587
@@ -0,0 +1,82 @@
<?php
namespace Drupal\Tests\features\Kernel\Entity;
use Drupal\features\Entity\FeaturesBundle;
use Drupal\features\FeaturesBundleInterface;
use Drupal\KernelTests\KernelTestBase;
/**
* @coversDefaultClass \Drupal\features\Entity\FeaturesBundle
* @group features
*/
class FeaturesBundleIntegrationTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['features'];
public function testCrud() {
$bundle = FeaturesBundle::create([
'machine_name' => 'test',
'name' => 'Test',
]);
$bundle->save();
/** @var \Drupal\features\Entity\FeaturesBundle $bundle */
$bundle = FeaturesBundle::load('test');
$this->assertEquals('Test', $bundle->getName());
}
/**
* @covers ::isDefault
*/
public function testIsDefaultWithDefaultBundle() {
$bundle = FeaturesBundle::create([
'machine_name' => FeaturesBundleInterface::DEFAULT_BUNDLE,
]);
$this->assertTrue($bundle->isDefault());
}
/**
* @covers ::isDefault
*/
public function testIsDefaultWithNonDefaultBundle() {
$bundle = FeaturesBundle::create([
'machine_name' => 'other',
]);
$this->assertFalse($bundle->isDefault());
}
/**
* @covers ::getFullName
*/
public function testGetFullName() {
}
/**
* @covers ::getShortName
*/
public function testGetShortName() {
}
/**
* @covers ::getProfileName
* @covers ::setProfileName
*/
public function testGetProfile() {
$bundle = FeaturesBundle::create([
'machine_name' => 'other',
'profile_name' => 'example',
'is_profile' => TRUE,
]);
$this->assertEquals('example', $bundle->getProfileName());
$bundle->setProfileName('example2');
$this->assertEquals('example2', $bundle->getProfileName());
}
}
@@ -0,0 +1,834 @@
<?php
namespace Drupal\Tests\features\Kernel;
use Drupal\KernelTests\KernelTestBase;
use Drupal\features\ConfigurationItem;
use Drupal\features\FeaturesManagerInterface;
use Drupal\Core\Config\InstallStorage;
/**
* @group features
*/
class FeaturesAssignTest extends KernelTestBase {
const PACKAGE_NAME = 'my_test_package';
// Installed test feature package
const TEST_INSTALLED_PACKAGE = 'test_mybundle_core';
// Uninstalled test feature package
const TEST_UNINSTALLED_PACKAGE = 'test_feature';
/**
* {@inheritdoc}
*/
public static $modules = ['features', 'node', 'system', 'user', self::TEST_INSTALLED_PACKAGE];
/**
* @var \Drupal\features\FeaturesManager
*/
protected $featuresManager;
/**
* @var \Drupal\features\FeaturesAssigner
*/
protected $assigner;
/**
* @var \Drupal\features\FeaturesBundleInterface
*/
protected $bundle;
/**
* @todo Remove the disabled strict config schema checking.
*/
protected $strictConfigSchema = FALSE;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig('features');
$this->installConfig('system');
$this->featuresManager = \Drupal::service('features.manager');
$this->assigner = \Drupal::service('features_assigner');
$this->bundle = $this->assigner->getBundle();
// Turn off all assignment plugins.
$this->bundle->setEnabledAssignments([]);
// Start with an empty configuration collection.
$this->featuresManager->setConfigCollection([]);
}
/**
* @covers Drupal\features\Plugin\FeaturesAssignment\FeaturesAssignmentAlter
*/
public function testAssignAlter() {
$method_id = 'alter';
// Enable the method.
$this->enableAssignmentMethod($method_id);
// Add some configuration.
$this->addConfigurationItem('example.settings', [
'_core' => ['something'],
'uuid' => 'something',
],
[
'type' => FeaturesManagerInterface::SYSTEM_SIMPLE_CONFIG,
]);
$this->addConfigurationItem('node.type.article', [
'_core' => ['something'],
'uuid' => 'something',
'permissions' => [
'first',
'second',
],
],
[
'type' => 'node_type',
]);
$this->addConfigurationItem('user.role.test', [
'_core' => ['something'],
'uuid' => 'something',
'permissions' => [
'first',
'second',
],
],
[
'type' => 'user_role',
]);
// Set all settings to FALSE.
$settings = [
'core' => FALSE,
'uuid' => FALSE,
'user_permissions' => FALSE,
];
$this->bundle->setAssignmentSettings($method_id, $settings);
$this->assigner->applyAssignmentMethod($method_id);
$config = $this->featuresManager->getConfigCollection();
$this->assertNotEmpty($config['example.settings'], 'Expected config not created.');
$this->assertNotEmpty($config['node.type.article'], 'Expected config not created.');
$this->assertNotEmpty($config['user.role.test'], 'Expected config not created.');
$example_settings_data = $config['example.settings']->getData();
$this->assertEquals($example_settings_data['_core'], ['something'], 'Expected _core value missing.');
$this->assertEquals($example_settings_data['uuid'], 'something', 'Expected uuid value missing.');
$node_type_data = $config['node.type.article']->getData();
$this->assertEquals($node_type_data['_core'], ['something'], 'Expected _core value missing.');
$this->assertEquals($node_type_data['uuid'], 'something', 'Expected uuid value missing.');
$this->assertEquals($node_type_data['permissions'], [
'first',
'second',
], 'Expected permissions value missing.');
$user_role_data = $config['user.role.test']->getData();
$this->assertEquals($user_role_data['_core'], ['something'], 'Expected _core value missing.');
$this->assertEquals($user_role_data['uuid'], 'something', 'Expected uuid value missing.');
$this->assertEquals($user_role_data['permissions'], [
'first',
'second',
], 'Expected permissions value missing.');
// Set all settings to TRUE.
$settings = [
'core' => TRUE,
'uuid' => TRUE,
'user_permissions' => TRUE,
];
$this->bundle->setAssignmentSettings($method_id, $settings);
$this->assigner->applyAssignmentMethod($method_id);
$config = $this->featuresManager->getConfigCollection();
$this->assertNotEmpty($config['example.settings'], 'Expected config not created.');
$this->assertNotEmpty($config['node.type.article'], 'Expected config not created.');
$this->assertNotEmpty($config['user.role.test'], 'Expected config not created.');
$example_settings_data = $config['example.settings']->getData();
$this->assertFalse(isset($example_settings_data['_core']), 'Unexpected _core value present.');
// uuid should be retained for simple configuration.
$this->assertEquals($example_settings_data['uuid'], 'something', 'Expected uuid value missing.');
$node_type_data = $config['node.type.article']->getData();
$this->assertFalse(isset($node_type_data['_core']), 'Unexpected _core value present.');
$this->assertFalse(isset($node_type_data['uuid']), 'Unexpected uuid value present.');
// permissions should be stripped only for user_role configuration.
$this->assertEquals($node_type_data['permissions'], [
'first',
'second',
], 'Expected permissions value missing.');
$user_role_data = $config['user.role.test']->getData();
$this->assertFalse(isset($user_role_data['_core']), 'Unexpected _core value present.');
$this->assertFalse(isset($user_role_data['uuid']), 'Unexpected uuid value present.');
$this->assertFalse(isset($user_role_data['permissions']), 'Unexpected permissions value present.');
}
/**
* @covers Drupal\features\Plugin\FeaturesAssignment\FeaturesAssignmentBaseType
*/
public function testAssignBase() {
$method_id = 'base';
// Enable the method.
$this->enableAssignmentMethod($method_id);
// Test the default options for the base assignment method.
// Test node type assignments.
// Declare the node_type entity 'article'.
$this->addConfigurationItem('node.type.article', [], [
'shortName' => 'article',
'label' => 'Article',
'type' => 'node_type',
'dependents' => ['field.field.node.article.body'],
]);
// Add a piece of dependent configuration.
$this->addConfigurationItem('field.field.node.article.body', [], [
'shortName' => 'node.article.body',
'label' => 'Body',
'type' => 'field_config',
'dependents' => [],
]);
$this->assigner->applyAssignmentMethod($method_id);
$packages = $this->featuresManager->getPackages();
$expected_package_names = ['article', 'user'];
$this->assertEquals($expected_package_names, array_keys($packages), 'Expected packages not created.');
// Dependents like field.field.node.article.body should not be assigned.
$expected_config_items = [
'node.type.article',
];
$this->assertEquals($expected_config_items, $packages['article']->getConfig(), 'Expected configuration items not present in article package.');
}
/**
* @covers Drupal\features\Plugin\FeaturesAssignment\FeaturesAssignmentCoreType
*/
public function testAssignCore() {
$method_id = 'core';
// Enable the method.
$this->enableAssignmentMethod($method_id);
// Test the default options for the core assignment method.
// Add a piece of configuration of a core type.
$this->addConfigurationItem('field.storage.node.body', [], [
'shortName' => 'node.body',
'label' => 'node.body',
'type' => 'field_storage_config',
'dependents' => ['field.field.node.article.body'],
]);
// Add a piece of configuration of a non-core type.
$this->addConfigurationItem('field.field.node.article.body', [], [
'shortName' => 'node.article.body',
'label' => 'Body',
'type' => 'field_config',
'dependents' => [],
]);
$this->assigner->applyAssignmentMethod($method_id);
$packages = $this->featuresManager->getPackages();
$expected_package_names = ['core'];
$this->assertEquals($expected_package_names, array_keys($packages), 'Expected packages not created.');
$this->assertTrue(in_array('field.storage.node.body', $packages['core']->getConfig(), 'Expected configuration item not present in core package.'));
$this->assertFalse(in_array('field.field.node.article.body', $packages['core']->getConfig(), 'Unexpected configuration item present in core package.'));
}
/**
* @covers Drupal\features\Plugin\FeaturesAssignment\FeaturesAssignmentDependency
*/
public function testAssignDependency() {
$method_id = 'dependency';
// Enable the method.
$this->enableAssignmentMethod($method_id);
// Test the default options for the base assignment method.
// Test node type assignments.
// Declare the node_type entity 'article'.
$this->addConfigurationItem('node.type.article', [], [
'shortName' => 'article',
'label' => 'Article',
'type' => 'node_type',
'dependents' => ['field.field.node.article.body'],
]);
// Add a piece of dependent configuration.
$this->addConfigurationItem('field.field.node.article.body', [], [
'shortName' => 'node.article.body',
'label' => 'Body',
'type' => 'field_config',
'dependents' => [],
]);
$this->featuresManager->initPackage(self::PACKAGE_NAME, 'My test package');
$this->featuresManager->assignConfigPackage(self::PACKAGE_NAME, ['node.type.article']);
$this->assigner->applyAssignmentMethod($method_id);
$packages = $this->featuresManager->getPackages();
$expected_package_names = [self::PACKAGE_NAME];
$this->assertEquals($expected_package_names, array_keys($packages), 'Expected packages not created.');
$expected_config_items = [
'node.type.article',
'field.field.node.article.body',
];
$this->assertEquals($expected_config_items, $packages[self::PACKAGE_NAME]->getConfig(), 'Expected configuration items not present in article package.');
}
/**
* @covers Drupal\features\Plugin\FeaturesAssignment\FeaturesAssignmentExclude
*/
public function testAssignExclude() {
$method_id = 'exclude';
// Enable the method.
$this->enableAssignmentMethod($method_id);
// Also enable Packages and Core plugins.
$this->enableAssignmentMethod('packages', FALSE);
$this->enableAssignmentMethod('core', FALSE);
// Apply the bundle
$this->bundle = $this->assigner->loadBundle('test_mybundle');
$this->assigner->applyAssignmentMethod('packages');
$packages = $this->featuresManager->getPackages();
$this->assertNotEmpty($packages[self::TEST_INSTALLED_PACKAGE], 'Expected package not created.');
// 1. When Required is set to True, config should stay with the module
// First, test with "Required" set to True.
$packages[self::TEST_INSTALLED_PACKAGE]->setRequired(true);
$this->featuresManager->setPackages($packages);
$this->assigner->applyAssignmentMethod('exclude');
$this->assigner->applyAssignmentMethod('core');
$this->assigner->applyAssignmentMethod('existing');
$packages = $this->featuresManager->getPackages();
$expected_config_items = [
'core.date_format.long',
];
$this->assertEquals($expected_config_items, $packages[self::TEST_INSTALLED_PACKAGE]->getConfig(), 'Expected configuration items not present in existing test_core package.');
// 2. When Required is set to False, config still stays with module
// Because the module is installed.
$this->reset();
$this->bundle = $this->assigner->loadBundle('test_mybundle');
$this->assigner->applyAssignmentMethod('packages');
$packages = $this->featuresManager->getPackages();
$this->assertNotEmpty($packages[self::TEST_INSTALLED_PACKAGE], 'Expected test_mybundle_core package not created.');
// Set "Required" set to False
$packages[self::TEST_INSTALLED_PACKAGE]->setRequired(false);
$this->featuresManager->setPackages($packages);
$this->assigner->applyAssignmentMethod('exclude');
$this->assigner->applyAssignmentMethod('core');
$this->assigner->applyAssignmentMethod('existing');
$packages = $this->featuresManager->getPackages();
$this->assertFalse(array_key_exists('core', $packages), 'Core package should not be created.');
$expected_config_items = [
'core.date_format.long',
];
$this->assertEquals($expected_config_items, $packages[self::TEST_INSTALLED_PACKAGE]->getConfig(), 'Expected configuration items not present in existing test_core package.');
// 3. When Required is set to False and module is NOT installed,
// Config stays with module if it doesn't match the current namespace
$this->reset();
// Load a bundle different from TEST_UNINSTALLED_PACKAGE
$this->bundle = $this->assigner->loadBundle('test_mybundle');
$this->assigner->applyAssignmentMethod('packages');
$packages = $this->featuresManager->getPackages();
$this->assertNotEmpty($packages[self::TEST_UNINSTALLED_PACKAGE], 'Expected test_feature package not created.');
$this->assertNotEmpty($packages[self::TEST_INSTALLED_PACKAGE], 'Expected test_mybundle_core package not created.');
// Mark package as uninstalled, set "Required" set to False
$packages[self::TEST_UNINSTALLED_PACKAGE]->setRequired(false);
$this->featuresManager->setPackages($packages);
$this->assigner->applyAssignmentMethod('exclude');
$this->assigner->applyAssignmentMethod('core');
$this->assigner->applyAssignmentMethod('existing');
$packages = $this->featuresManager->getPackages();
$this->assertFalse(array_key_exists('core', $packages), 'Core package should not be created.');
$expected_config_items = [
'core.date_format.short',
'system.cron',
];
$this->assertEquals($expected_config_items, $packages[self::TEST_UNINSTALLED_PACKAGE]->getConfig(), 'Expected configuration items not present in existing test_feature package.');
// 4. When Required is set to False and module is NOT installed,
// Config is reassigned within modules that match the namespace.
$this->reset();
// Load the bundle used in TEST_UNINSTALLED_PACKAGE
$this->bundle = $this->assigner->loadBundle('test');
if (empty($this->bundle) || $this->bundle->isDefault()) {
// Since we uninstalled the test_feature, we probably need to create
// an empty "test" bundle
$this->bundle = $this->assigner->createBundleFromDefault('test');
}
$this->assigner->applyAssignmentMethod('packages');
$packages = $this->featuresManager->getPackages();
$this->assertNotEmpty($packages[self::TEST_UNINSTALLED_PACKAGE], 'Expected test_feature package not created.');
// Set "Required" set to False
$packages[self::TEST_UNINSTALLED_PACKAGE]->setRequired(false);
$this->featuresManager->setPackages($packages);
$this->assigner->applyAssignmentMethod('exclude');
$this->assigner->applyAssignmentMethod('core');
$this->assigner->applyAssignmentMethod('existing');
$packages = $this->featuresManager->getPackages();
$this->assertNotEmpty($packages['core'], 'Expected Core package not created.');
// Ensure "core" package is not confused with "test_core" module
// Since we are in a bundle
$this->assertEmpty($packages['core']->getExtension(), 'Autogenerated core package should not have an extension');
// Core config should be reassigned from TEST_UNINSTALLED_PACKAGE into Core
$expected_config_items = [
'system.cron',
];
$this->assertEquals($expected_config_items, $packages[self::TEST_UNINSTALLED_PACKAGE]->getConfig(), 'Expected configuration items not present in existing test_feature package.');
$expected_config_items = [
'core.date_format.short',
];
$this->assertEquals($expected_config_items, $packages['core']->getConfig(), 'Expected configuration items not present in core package.');
}
/**
* @covers Drupal\features\Plugin\FeaturesAssignment\FeaturesAssignmentExclude
*/
public function testAssignExisting() {
$method_id = 'existing';
// Enable the method.
$this->enableAssignmentMethod($method_id);
// Also enable Packages plugin.
$this->enableAssignmentMethod('packages', FALSE);
// First create the existing packages.
$this->assigner->applyAssignmentMethod('packages');
// Now move config into those existing packages.
$this->assigner->applyAssignmentMethod($method_id);
$packages = $this->featuresManager->getPackages();
$this->assertNotEmpty($packages[self::TEST_INSTALLED_PACKAGE], 'Expected package not created.');
$this->assertNotEmpty($packages[self::TEST_UNINSTALLED_PACKAGE], 'Expected package not created.');
// Turn off any "required" option in package to let config get reassigned
$package = $packages[self::TEST_INSTALLED_PACKAGE];
$package->setRequired(true);
$expected_config_items = [
'core.date_format.long',
];
$this->assertEquals($expected_config_items, $packages[self::TEST_INSTALLED_PACKAGE]->getConfig(), 'Expected configuration items not present in existing package.');
$expected_config_items = [
'core.date_format.short',
'system.cron',
];
$this->assertEquals($expected_config_items, $packages[self::TEST_UNINSTALLED_PACKAGE]->getConfig(), 'Expected configuration items not present in existing package.');
}
/**
* @covers Drupal\features\Plugin\FeaturesAssignment\FeaturesAssignmentForwardDependency
*/
public function testAssignForwardDependency() {
$method_id = 'forward_dependency';
// Enable the method.
$this->enableAssignmentMethod($method_id);
// Add some configuration.
// Two parent items.
$this->addConfigurationItem('parent1', [], [
'type' => 'node_type',
'dependents' => ['grandparent'],
]);
$this->addConfigurationItem('parent2', [], [
'type' => 'node_type',
'dependents' => [],
]);
// Something that belongs to just one parent.
$this->addConfigurationItem('child1', [], [
'type' => 'node_type',
'dependents' => ['parent1'],
]);
// Something that belongs to both parents.
$this->addConfigurationItem('child2', [], [
'type' => 'node_type',
'dependents' => ['parent1', 'parent2'],
]);
// Something that indirectly belongs to parent1.
$this->addConfigurationItem('grandchild', [], [
'type' => 'node_type',
'dependents' => ['child1'],
]);
// A dependent, not a dependency.
$this->addConfigurationItem('grandparent', [], [
'type' => 'node_type',
'dependents' => [],
]);
// Something completely unrelated.
$this->addConfigurationItem('stranger', [], [
'type' => 'node_type',
'dependents' => [],
]);
$this->featuresManager->initPackage(self::PACKAGE_NAME, 'My test package');
$this->featuresManager->assignConfigPackage(self::PACKAGE_NAME, ['parent1']);
$other_package_name = 'other_package';
$this->featuresManager->initPackage($other_package_name, 'Other package');
$this->featuresManager->assignConfigPackage($other_package_name, ['parent2']);
$this->assigner->applyAssignmentMethod($method_id);
$packages = $this->featuresManager->getPackages();
$expected_package_names = [self::PACKAGE_NAME, $other_package_name];
sort($expected_package_names);
$actual_package_names = array_keys($packages);
sort($actual_package_names);
$this->assertEquals($expected_package_names, $actual_package_names, 'Expected packages not created.');
$expected_config_items = [
'parent1',
'child1',
'grandchild',
];
sort($expected_config_items);
$actual_config_items = $packages[self::PACKAGE_NAME]->getConfig();
sort($actual_config_items);
$this->assertEquals($expected_config_items, $actual_config_items, 'Expected configuration items not present in article package.');
}
/**
* @covers Drupal\features\Plugin\FeaturesAssignment\FeaturesAssignmentNamespace
*/
public function testAssignNamespace() {
$method_id = 'namespace';
// Enable the method.
$this->enableAssignmentMethod($method_id);
// Apply the bundle
$this->bundle = $this->assigner->loadBundle('test_mybundle');
$package_data = [
'article' => [
// Items that should be assigned to 'article'.
'article',
'article-after',
'before.article',
'something_article',
'something-article',
'something.article',
'article_something',
'article-something',
'article.something',
'something_article_something',
'something-article-something',
'something.article.something',
'something.article_something',
],
'article_after' => [
// Items that should be assigned to 'article_after'.
'article_after',
'something_article_after',
'something-article_after',
'something.article_after',
'article_after_something',
'article_after-something',
'article_after.something',
'something_article_after_something',
'something-article_after-something',
'something.article_after.something',
'something.article_after_something',
],
'before_article' => [
// Items that should be assigned to 'before_article'.
'before_article',
'something_before_article',
'something-before_article',
'something.before_article',
'before_article_something',
'before_article-something',
'before_article.something',
'something_before_article_something',
'something-before_article-something',
'something.before_article.something',
'something.before_article_something',
],
// Emulate an existing feature, which has a machine name prefixed by
// the bundle name.
'test_mybundle_page' => [
// Items that should be assigned to 'test_mybundle_page'.
// Items should match the short name, 'page'.
'page',
'page-after',
'before.page',
'something_page',
'something-page',
'something.page',
'page_something',
'page-something',
'page.something',
'something_page_something',
'something-page-something',
'something.page.something',
'something.page_something',
],
];
foreach ($package_data as $machine_name => $config_short_names) {
$this->featuresManager->initPackage($machine_name, 'My test package ' . $machine_name);
foreach ($config_short_names as $short_name) {
$this->addConfigurationItem('node.type.' . $short_name, [], [
'type' => 'node_type',
'shortName' => $short_name,
]);
}
}
// Add some config that should not be matched.
$config_short_names = [
'example',
'example_something',
'article~',
'myarticle',
];
foreach ($config_short_names as $short_name) {
$this->addConfigurationItem('node.type.' . $short_name, [], [
'type' => 'node_type',
'shortName' => $short_name,
]);
}
$this->assigner->applyAssignmentMethod($method_id);
$packages = $this->featuresManager->getPackages();
foreach ($package_data as $machine_name => $config_short_names) {
$this->assertNotEmpty($packages[$machine_name], 'Expected package ' . $machine_name . ' not created.');
array_walk($config_short_names, function(&$value) {
$value = 'node.type.' . $value;
});
sort($config_short_names);
$package_config = $packages[$machine_name]->getConfig();
sort($package_config);
$this->assertEquals($config_short_names, $package_config, 'Expected configuration items not present in ' . $machine_name . ' package.');
}
}
/**
* @covers Drupal\features\Plugin\FeaturesAssignment\FeaturesAssignmentOptionalType
*/
public function testAssignOptionalType() {
$method_id = 'optional';
// Enable the method.
$this->enableAssignmentMethod($method_id);
$settings = [
'types' => [
'config' => ['image_style'],
],
];
$this->bundle->setAssignmentSettings($method_id, $settings);
// Add some configuration.
$this->addConfigurationItem('node.type.article', [], [
'type' => 'node_type',
]);
$this->addConfigurationItem('image.style.test', [], [
'type' => 'image_style',
]);
$this->featuresManager->initPackage(self::PACKAGE_NAME, 'My test package');
$this->assigner->applyAssignmentMethod($method_id);
$packages = $this->featuresManager->getPackages();
$this->assertNotEmpty($packages[self::PACKAGE_NAME], 'Expected package not created.');
$config = $this->featuresManager->getConfigCollection();
$this->assertNotEmpty($config['node.type.article'], 'Expected config not created.');
$this->assertNotEmpty($config['image.style.test'], 'Expected config not created.');
$this->assertNull($config['node.type.article']->getSubdirectory(), 'Expected package subdirectory not set to default.');
$this->assertEquals($config['image.style.test']->getSubdirectory(), InstallStorage::CONFIG_OPTIONAL_DIRECTORY, 'Expected package subdirectory not set to optional.');
}
/**
* @covers Drupal\features\Plugin\FeaturesAssignment\FeaturesAssignmentPackages
*/
public function testAssignPackages() {
$method_id = 'packages';
// Enable the method.
$this->enableAssignmentMethod($method_id);
$this->assigner->applyAssignmentMethod($method_id);
$packages = $this->featuresManager->getPackages();
$this->assertNotEmpty($packages[self::TEST_INSTALLED_PACKAGE], 'Expected package not created.');
}
/**
* @covers Drupal\features\Plugin\FeaturesAssignment\FeaturesAssignmentProfile
*/
public function testAssignProfile() {
$method_id = 'profile';
// Enable the method.
$this->enableAssignmentMethod($method_id);
// Add some configuration.
$this->addConfigurationItem('shortcut.myshortcut', [], [
'type' => 'shortcut_set',
]);
$this->addConfigurationItem('node.type.article', [], [
'type' => 'node_type',
]);
$this->addConfigurationItem('image.style.test', [], [
'type' => 'image_style',
]);
$this->addConfigurationItem('system.cron', [], [
'type' => 'simple',
]);
$this->bundle = $this->assigner->createBundleFromDefault('myprofile');
$this->bundle->setProfileName('myprofile');
$this->bundle->setIsProfile(TRUE);
$this->assigner->applyAssignmentMethod($method_id);
$packages = $this->featuresManager->getPackages();
$this->assertNotEmpty($packages['myprofile'], 'Expected package not created.');
$expected_config_items = [
'shortcut.myshortcut',
'system.cron',
'system.theme',
];
$this->assertEquals($expected_config_items, $packages['myprofile']->getConfig(), 'Expected configuration items not present in package.');
}
/**
* @covers Drupal\features\Plugin\FeaturesAssignment\FeaturesAssignmentSiteType
*/
public function testAssignSiteType() {
$method_id = 'site';
// Enable the method.
$this->enableAssignmentMethod($method_id);
// Test the default options for the site assignment method.
// Add a piece of configuration of a site type.
$this->addConfigurationItem('filter.format.plain_text', [], [
'shortName' => 'plain_text',
'label' => 'Plain text',
'type' => 'filter_format',
]);
// Add a piece of configuration of a non-site type.
$this->addConfigurationItem('field.field.node.article.body', [], [
'shortName' => 'node.article.body',
'label' => 'Body',
'type' => 'field_config',
'dependents' => [],
]);
$this->assigner->applyAssignmentMethod($method_id);
$packages = $this->featuresManager->getPackages();
$expected_package_names = ['site'];
$this->assertEquals($expected_package_names, array_keys($packages), 'Expected packages not created.');
$this->assertTrue(in_array('filter.format.plain_text', $packages['site']->getConfig(), 'Expected configuration item not present in site package.'));
$this->assertFalse(in_array('field.field.node.article.body', $packages['site']->getConfig(), 'Unexpected configuration item present in site package.'));
}
/**
* Enables a specified assignment method.
*
* @param string $method_id
* The ID of an assignment method.
* @param bool $exclusive
* (optional) Whether to set the method as the only enabled method.
* Defaults to TRUE.
*/
protected function enableAssignmentMethod($method_id, $exclusive = TRUE) {
if ($exclusive) {
$this->bundle->setEnabledAssignments([$method_id]);
}
else {
$enabled = array_keys($this->bundle->getEnabledAssignments());
$enabled[] = $method_id;
$this->bundle->setEnabledAssignments($enabled);
}
}
/**
* Adds a configuration item.
*
* @param string $name
* The config name.
* @param array $data
* The config data.
* @param array $properties
* (optional) Additional properties set on the object.
*/
protected function addConfigurationItem($name, array $data = [], array $properties = []) {
$config_collection = $this->featuresManager->getConfigCollection();
$config_collection[$name] = new ConfigurationItem($name, $data, $properties);
$this->featuresManager->setConfigCollection($config_collection);
}
/**
* Reset the config to reapply assignment plugins
*/
protected function reset() {
$this->assigner->reset();
// Start with an empty configuration collection.
$this->featuresManager->setConfigCollection([]);
}
}
@@ -0,0 +1,58 @@
<?php
namespace Drupal\Tests\features\Kernel;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\features\FeaturesBundleInterface;
use Drupal\KernelTests\KernelTestBase;
/**
* @group features
*/
class FeaturesAssignerTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['system', 'config'];
protected $strictConfigSchema = FALSE;
/**
* Test bundle auto-creation during config import.
*
* We check the case where the import also causes features to be installed,
* so at the time auto-creation happens there's not yet a default bundle.
*/
public function testBundleAutoCreationImport() {
// Install the feature.
$installer = $this->container->get('module_installer');
// Have to do these separately so features_modules_installed() doesn't
// just exit.
$installer->install(['features']);
$installer->install(['test_feature']);
// Save config.
$this->copyConfig(
$this->container->get('config.storage'),
$this->container->get('config.storage.sync')
);
// Uninstall modules.
$installer->uninstall(['features', 'test_feature']);
// Restore the config from after install..
$this->configImporter()->import();
// Find the auto-created bundle.
$bundle_storage = $this->container->get('entity_type.manager')
->getStorage('features_bundle');
$bundle = $bundle_storage->load('test');
$this->assertNotNull($bundle, "Features bundle doesn't exist");
$this->assertContains(
'Auto-generated bundle',
$bundle->getDescription(),
"Features bundle not auto-created");
}
}
@@ -0,0 +1,210 @@
<?php
namespace Drupal\Tests\features\Kernel;
use Drupal\features\Entity\FeaturesBundle;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Component\Serialization\Yaml;
use Drupal\Core\Archiver\ArchiveTar;
use org\bovigo\vfs\vfsStream;
/**
* @group features
*/
class FeaturesGenerateTest extends KernelTestBase {
const PACKAGE_NAME = 'my_test_package';
const BUNDLE_NAME = 'giraffe';
/**
* {@inheritdoc}
*/
public static $modules = ['features', 'system'];
/**
* @var \Drupal\features\FeaturesManagerInterface
*/
protected $featuresManager;
/**
* @var \Drupal\features\FeaturesGeneratorInterface
*/
protected $generator;
protected $strictConfigSchema = FALSE;
/**
* @var \Drupal\features\FeaturesAssignerInterface
*/
protected $assigner;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig('features');
$this->installConfig('system');
$this->featuresManager = \Drupal::service('features.manager');
$this->generator = \Drupal::service('features_generator');
$this->assigner = \Drupal::service('features_assigner');
$this->featuresManager->initPackage(self::PACKAGE_NAME, 'My test package');
$package = $this->featuresManager->getPackage(self::PACKAGE_NAME);
$package->appendConfig('system.site');
$this->featuresManager->setPackage($package);
}
/**
* @covers \Drupal\features\Plugin\FeaturesGeneration\FeaturesGenerationArchive
*/
public function testExportArchive() {
$filename = file_directory_temp() . '/' . self::PACKAGE_NAME . '.tar.gz';
if (file_exists($filename)) {
unlink($filename);
}
$this->assertFalse(file_exists($filename), 'Archive file already exists.');
$this->generator->generatePackages('archive', $this->assigner->getBundle(), [self::PACKAGE_NAME]);
$this->assertTrue(file_exists($filename), 'Archive file was not generated.');
$archive = new ArchiveTar($filename);
$files = $archive->listContent();
$this->assertEquals(3, count($files));
$this->assertEquals(self::PACKAGE_NAME . '/' . self::PACKAGE_NAME . '.info.yml', $files[0]['filename']);
$this->assertEquals(self::PACKAGE_NAME . '/' . self::PACKAGE_NAME . '.features.yml', $files[1]['filename']);
$this->assertEquals(self::PACKAGE_NAME . '/config/install/system.site.yml', $files[2]['filename']);
$expected_info = [
"name" => "My test package",
"type" => "module",
"core" => "8.x",
];
$info = Yaml::decode($archive->extractInString(self::PACKAGE_NAME . '/' . self::PACKAGE_NAME . '.info.yml'));
$this->assertEquals($expected_info, $info, 'Incorrect info file generated');
}
public function testGeneratorWithBundle() {
$filename = file_directory_temp() . '/' . self::BUNDLE_NAME . '_' . self::PACKAGE_NAME . '.tar.gz';
if (file_exists($filename)) {
unlink($filename);
}
$this->assertFalse(file_exists($filename), 'Archive file already exists.');
$bundle = FeaturesBundle::create([
'machine_name' => self::BUNDLE_NAME
]);
$this->generator->generatePackages('archive', $bundle, [self::PACKAGE_NAME]);
$package = $this->featuresManager->getPackage(self::PACKAGE_NAME);
$this->assertNull($package);
$package = $this->featuresManager->getPackage( self::BUNDLE_NAME . '_' . self::PACKAGE_NAME);
$this->assertEquals(self::BUNDLE_NAME . '_' . self::PACKAGE_NAME, $package->getMachineName());
$this->assertEquals(self::BUNDLE_NAME, $package->getBundle());
$this->assertTrue(file_exists($filename), 'Archive file was not generated.');
}
/**
* @covers \Drupal\features\Plugin\FeaturesGeneration\FeaturesGenerationWrite
*/
public function testExportWrite() {
// Set a fake drupal root, so the testbot can also write into it.
vfsStream::setup('drupal');
\Drupal::getContainer()->set('app.root', 'vfs://drupal');
$this->featuresManager->setRoot('vfs://drupal');
$package = $this->featuresManager->getPackage(self::PACKAGE_NAME);
// Find out where package will be exported
list($full_name, $path) = $this->featuresManager->getExportInfo($package, $this->assigner->getBundle());
$path = 'vfs://drupal/' . $path . '/' . $full_name;
if (file_exists($path)) {
file_unmanaged_delete_recursive($path);
}
$this->assertFalse(file_exists($path), 'Package directory already exists.');
$this->generator->generatePackages('write', $this->assigner->getBundle(), [self::PACKAGE_NAME]);
$info_file_uri = $path . '/' . self::PACKAGE_NAME . '.info.yml';
$this->assertTrue(file_exists($path), 'Package directory was not generated.');
$this->assertTrue(file_exists($info_file_uri), 'Package info.yml not generated.');
$this->assertTrue(file_exists($path . '/config/install'), 'Package config/install not generated.');
$this->assertTrue(file_exists($path . '/config/install/system.site.yml'), 'Config.yml not exported.');
$expected_info = [
"name" => "My test package",
"type" => "module",
"core" => "8.x",
];
$info = Yaml::decode(file_get_contents($info_file_uri));
$this->assertEquals($expected_info, $info, 'Incorrect info file generated');
// Now, add stuff to the feature and re-export to ensure it is preserved
// Add a dependency to the package itself to see that it gets exported.
$package->setDependencies(['user']);
$this->featuresManager->setPackage($package);
// Add dependency and custom key to the info file to simulate manual edit.
$info['dependencies'] = ['node'];
$info['mykey'] = "test value";
$info_contents = Yaml::encode($info);
file_put_contents($info_file_uri, $info_contents);
// Add an extra file that should be retained.
$css_file = $path . '/' . self::PACKAGE_NAME . '.css';
$file_contents = "This is a dummy file";
file_put_contents($css_file, $file_contents);
// Add a config file that should be removed since it's not part of the
// feature.
$config_file = $path . '/config/install/node.type.mytype.yml';
file_put_contents($config_file, $file_contents);
$this->generator->generatePackages('write', $this->assigner->getBundle(), [self::PACKAGE_NAME]);
$this->assertTrue(file_exists($info_file_uri), 'Package info.yml not generated.');
$expected_info = [
"name" => "My test package",
"type" => "module",
"core" => "8.x",
"dependencies" => ["node", "user"],
"mykey" => "test value",
];
$info = Yaml::decode(file_get_contents($info_file_uri));
$this->assertEquals($expected_info, $info, 'Incorrect info file generated');
$this->assertTrue(file_exists($css_file), 'Extra file was not retained.');
$this->assertFalse(file_exists($config_file), 'Config directory was not cleaned.');
$this->assertEquals($file_contents, file_get_contents($css_file), 'Extra file contents not retained');
// Next, test that generating an Archive picks up the extra files.
$filename = file_directory_temp() . '/' . self::PACKAGE_NAME . '.tar.gz';
if (file_exists($filename)) {
unlink($filename);
}
$this->assertFalse(file_exists($filename), 'Archive file already exists.');
$this->generator->generatePackages('archive', $this->assigner->getBundle(), [self::PACKAGE_NAME]);
$this->assertTrue(file_exists($filename), 'Archive file was not generated.');
$archive = new ArchiveTar($filename);
$files = $archive->listContent();
$this->assertEquals(4, count($files));
$this->assertEquals(self::PACKAGE_NAME . '/' . self::PACKAGE_NAME . '.info.yml', $files[0]['filename']);
$this->assertEquals(self::PACKAGE_NAME . '/' . self::PACKAGE_NAME . '.features.yml', $files[1]['filename']);
$this->assertEquals(self::PACKAGE_NAME . '/config/install/system.site.yml', $files[2]['filename']);
$this->assertEquals(self::PACKAGE_NAME . '/' . self::PACKAGE_NAME . '.css', $files[3]['filename']);
$expected_info = [
"name" => "My test package",
"type" => "module",
"core" => "8.x",
"dependencies" => ["node", "user"],
"mykey" => "test value",
];
$info = Yaml::decode($archive->extractInString(self::PACKAGE_NAME . '/' . self::PACKAGE_NAME . '.info.yml'));
$this->assertEquals($expected_info, $info, 'Incorrect info file generated');
$this->assertEquals($file_contents, $archive->extractInString(self::PACKAGE_NAME . '/' . self::PACKAGE_NAME . '.css'), 'Extra file contents not retained');
}
}
@@ -0,0 +1,103 @@
<?php
namespace Drupal\Tests\features\Kernel;
use Drupal\KernelTests\KernelTestBase;
use Drupal\features\ConfigurationItem;
use Drupal\features\Package;
/**
* @group features
*/
class FeaturesManagerKernelTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['system', 'config', 'features'];
protected $strictConfigSchema = FALSE;
/**
* @var \Drupal\features\FeaturesManagerInterface
*/
protected $featuresManager;
/**
* @var \Drupal\Core\Config\ConfigFactory
*/
protected $configFactory;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig('features');
$this->installConfig('system');
$this->featuresManager = $this->container->get('features.manager');
$this->configFactory = $this->container->get('config.factory');
}
/**
* @covers \Drupal\features\FeaturesManager::createConfiguration
*/
public function testCreateConfiguration() {
$config_name = 'system_simple.testcreate';
$config = [
'string_value' => 'example',
'array_value' => [
'item1' => 'value1',
'item2' => 'value2',
],
];
$this->featuresManager->createConfiguration([$config_name => $config]);
$config_item = $this->configFactory->get($config_name);
$this->assertEquals($config['string_value'], $config_item->get('string_value'), 'Test config string saved');
$this->assertEquals($config['array_value'], $config_item->get('array_value'), 'Test config array saved');
}
/**
* @covers \Drupal\features\FeaturesManager::import
*/
public function testImport() {
$packages = [
'package' => new Package('package', [
'configOrig' => ['system_simple.example' => 'system_simple.example'],
'dependencies' => [],
'bundle' => '',
]),
'package2' => new Package('package2', [
'configOrig' => ['system_simple.example2' => 'system_simple.example2'],
'dependencies' => [],
'bundle' => '',
]),
'package3' => new Package('package3', [
'configOrig' => ['system_simple.example3' => 'system_simple.example3'],
'dependencies' => [],
'bundle' => '',
]),
];
$this->featuresManager->setPackages($packages);
// Create all three configuration items.
$config_item = new ConfigurationItem('system_simple.example', ['value' => 'example'], ['package' => 'package']);
$config_item2 = new ConfigurationItem('system_simple.example2', ['value' => 'example2'], ['package' => 'package2']);
$config_item3 = new ConfigurationItem('system_simple.example3', ['value' => 'example3'], ['package' => 'package3']);
// Only save example and example3 as currently active config (so example2 will be new).
$this->featuresManager->setConfigCollection(['system_simple.example' => $config_item, 'system_simple.example3' => $config_item3]);
// Only import example and example2, so example3 is unchanged.
$result = $this->featuresManager->import(['package', 'package2']);
$this->assertEquals(['system_simple.example'], array_keys($result['package']['updated']), 'Expected config updated');
$this->assertEquals(['system_simple.example2'], array_keys($result['package2']['new']), 'Expected config created');
// Test if config was actually saved to the Factory.
// Cannot test for example2 because we didn't save the original config data
// and Package2 isn't a real module so config can't be loaded from module.
$example = $this->configFactory->get('system_simple.example')->get('value');
$this->assertEquals('example', $example, 'Example config saved');
}
}
@@ -0,0 +1,21 @@
<?php
namespace Drupal\Tests\features\Unit;
use Drupal\features\ConfigurationItem;
use Drupal\features\FeaturesManagerInterface;
/**
* @coversDefaultClass \Drupal\features\ConfigurationItem
* @group features
*/
class ConfigurationItemTest extends \PHPUnit_Framework_TestCase {
/**
* @covers ::fromConfigStringToConfigType
*/
public function testFromConfigStringToConfigType() {
$this->assertEquals('system.simple', ConfigurationItem::fromConfigStringToConfigType(FeaturesManagerInterface::SYSTEM_SIMPLE_CONFIG));
$this->assertEquals('node', ConfigurationItem::fromConfigStringToConfigType('node'));
}
}
@@ -0,0 +1,206 @@
<?php
namespace Drupal\Tests\features\Unit;
use Drupal\features\Entity\FeaturesBundle;
use Drupal\Tests\UnitTestCase;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Site\Settings;
/**
* @coversDefaultClass Drupal\features\Entity\FeaturesBundle
* @group features
*/
class FeaturesBundleTest extends UnitTestCase {
public function setUp() {
parent::setUp();
// Mock an assigner.
$manager = new DummyPluginManager();
// Mock the container.
$container = $this->prophesize('\Symfony\Component\DependencyInjection\ContainerInterface');
$container->get('plugin.manager.features_assignment_method')
->willReturn($manager);
\Drupal::setContainer($container->reveal());
}
/**
* @covers ::getEnabledAssignments
* @covers ::getAssignmentWeights
* @covers ::getAssignmentSettings
* @covers ::setAssignmentSettings
* @covers ::setAssignmentWeights
* @covers ::setEnabledAssignments
*/
public function testAssignmentSetting() {
// Create an entity.
$settings = [
'foo' => [
'enabled' => TRUE,
'weight' => 0,
'my_setting' => 42,
],
'bar' => [
'enabled' => FALSE,
'weight' => 1,
'another_setting' => 'value',
],
];
$bundle = new FeaturesBundle([
'assignments' => $settings,
], 'features_bundle');
// Get assignments and attributes.
$this->assertArrayEquals(
$bundle->getEnabledAssignments(),
['foo' => 'foo'],
'Can get enabled assignments'
);
$this->assertArrayEquals(
$bundle->getAssignmentWeights(),
['foo' => 0, 'bar' => 1],
'Can get assignment weights'
);
$this->assertArrayEquals(
$bundle->getAssignmentSettings('foo'),
$settings['foo'],
'Can get assignment settings'
);
$this->assertArrayEquals(
$bundle->getAssignmentSettings(),
$settings,
'Can get all assignment settings'
);
// Change settings.
$settings['foo']['my_setting'] = 97;
$bundle->setAssignmentSettings('foo', $settings['foo']);
$this->assertArrayEquals(
$bundle->getAssignmentSettings('foo'),
$settings['foo'],
'Can change assignment settings'
);
// Change weights.
$settings['foo']['weight'] = 1;
$settings['bar']['weight'] = 0;
$bundle->setAssignmentWeights(['foo' => 1, 'bar' => 0]);
$this->assertArrayEquals(
$bundle->getAssignmentWeights(),
['foo' => 1, 'bar' => 0],
'Can change assignment weights'
);
$this->assertArrayEquals(
$bundle->getAssignmentSettings(),
$settings,
'Weight changes are reflected in settings'
);
// Enable existing assignment.
$settings['bar']['enabled'] = TRUE;
$bundle->setEnabledAssignments(['foo', 'bar']);
$this->assertArrayEquals(
$bundle->getEnabledAssignments(),
['foo' => 'foo', 'bar' => 'bar'],
'Can enable assignment'
);
$this->assertArrayEquals(
$bundle->getAssignmentSettings(),
$settings,
'Enabled assignment status is reflected in settings'
);
// Disable existing assignments.
$settings['foo']['enabled'] = FALSE;
$settings['bar']['enabled'] = FALSE;
$bundle->setEnabledAssignments([]);
$this->assertArrayEquals(
$bundle->getEnabledAssignments(),
[],
'Can disable assignments'
);
$this->assertArrayEquals(
$bundle->getAssignmentSettings(),
$settings,
'Disabled assignment status is reflected in settings'
);
// Enable a new assignment.
$settings['foo']['enabled'] = TRUE;
$settings['iggy'] = ['enabled' => TRUE, 'weight' => 0, 'new_setting' => 3];
$bundle->setEnabledAssignments(['foo', 'iggy']);
$this->assertArrayEquals(
$bundle->getEnabledAssignments(),
['foo' => 'foo', 'iggy' => 'iggy'],
'Can enable new assignment'
);
$bundle->setAssignmentSettings('iggy', $settings['iggy']);
$this->assertArrayEquals(
$bundle->getAssignmentSettings(),
$settings,
'New enabled assignment status is reflected in settings'
);
}
/**
* @covers ::getFullName
* @covers ::getShortName
* @covers ::SetIsProfile
* @covers ::isProfile
* @covers ::getProfileName
* @covers ::isProfilePackage
* @covers ::inBundle
*/
public function testFullname() {
$bundle = new FeaturesBundle([
'machine_name' => 'mybundle',
'profile_name' => 'mybundle'
], 'mybundle');
$this->assertFalse($bundle->isProfile());
// Settings:get('profile_name') isn't defined in test, so this returns NULL.
$this->assertNull($bundle->getProfileName());
$this->assertFalse($bundle->isProfilePackage('mybundle'));
$this->assertEquals('mybundle_test', $bundle->getFullName('test'));
$this->assertEquals('mybundle_test', $bundle->getFullName('mybundle_test'));
$this->assertEquals('mybundle_mybundle', $bundle->getFullName('mybundle'));
$this->assertEquals('test', $bundle->getShortName('test'));
$this->assertEquals('test', $bundle->getShortName('mybundle_test'));
$this->assertEquals('mybundle', $bundle->getShortName('mybundle_mybundle'));
$this->assertEquals('mybundle', $bundle->getShortName('mybundle'));
$this->assertFalse($bundle->inBundle('test'));
$this->assertTrue($bundle->inBundle('mybundle_test'));
$this->assertFalse($bundle->inBundle('mybundle'));
// Now test it as a profile bundle.
$bundle->setIsProfile(TRUE);
$this->assertTrue($bundle->isProfile());
$this->assertTrue($bundle->isProfilePackage('mybundle'));
$this->assertFalse($bundle->isProfilePackage('standard'));
$this->assertEquals('mybundle', $bundle->getProfileName());
$this->assertEquals('mybundle', $bundle->getFullName('mybundle'));
$this->assertFalse($bundle->inBundle('test'));
$this->assertTrue($bundle->inBundle('mybundle_test'));
$this->assertTrue($bundle->inBundle('mybundle'));
}
}
/**
* A dummy plugin manager, to help testing.
*/
class DummyPluginManager {
public function getDefinition($method_id) {
$definition = [
'enabled' => TRUE,
'weight' => 0,
'default_settings' => [
'my_setting' => 42,
],
];
return $definition;
}
}
@@ -0,0 +1,798 @@
<?php
namespace Drupal\Tests\features\Unit;
use Drupal\Component\Serialization\Yaml;
use Drupal\config_update\ConfigDiffInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\ConfigManagerInterface;
use Drupal\Core\Config\InstallStorage;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Extension\Extension;
use Drupal\Core\Extension\InfoParser;
use Drupal\Core\Extension\InfoParserInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\config_update\ConfigRevertInterface;
use Drupal\features\Entity\FeaturesBundle;
use Drupal\features\FeaturesAssignerInterface;
use Drupal\features\FeaturesBundleInterface;
use Drupal\features\ConfigurationItem;
use Drupal\features\FeaturesExtensionStoragesInterface;
use Drupal\features\FeaturesManager;
use Drupal\features\FeaturesManagerInterface;
use Drupal\features\Package;
use Drupal\Tests\UnitTestCase;
use org\bovigo\vfs\vfsStream;
use Prophecy\Argument;
/**
* @coversDefaultClass Drupal\features\FeaturesManager
* @group features
*/
class FeaturesManagerTest extends UnitTestCase {
/**
* @var string
* The name of the install profile.
*/
const PROFILE_NAME = 'my_profile';
/**
* @var \Drupal\features\FeaturesManagerInterface
*/
protected $featuresManager;
/**
* @var \Drupal\Core\Entity\EntityTypeManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $entityTypeManager;
/**
* @var \Drupal\Core\Config\StorageInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $configStorage;
/**
* @var \Drupal\Core\Config\ConfigFactoryInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $configFactory;
/**
* @var \Drupal\Core\Config\ConfigManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $configManager;
/**
* @var \Drupal\Core\Extension\ModuleHandlerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $moduleHandler;
/**
* @var \Drupal\Core\Extension\ModuleHandlerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $configReverter;
/**
* {@inheritdoc}
*/
public function setUp() {
parent::setUp();
$container = new ContainerBuilder();
$container->set('string_translation', $this->getStringTranslationStub());
$container->set('app.root', $this->root);
// Since in Drupal 8.3 the "\Drupal::installProfile()" was introduced
// then we have to spoof a value for the "install_profile" parameter
// because it will be used by "ExtensionInstallStorage" class, which
// extends the "FeaturesInstallStorage".
// @see \Drupal\features\FeaturesConfigInstaller::__construct()
$container->setParameter('install_profile', '');
\Drupal::setContainer($container);
$entity_type = $this->getMock('\Drupal\Core\Config\Entity\ConfigEntityTypeInterface');
$entity_type->expects($this->any())
->method('getConfigPrefix')
->willReturn('custom');
$entity_type->expects($this->any())
->method('getProvider')
->willReturn('my_module');
$this->entityTypeManager = $this->getMock('\Drupal\Core\Entity\EntityTypeManagerInterface');
$this->entityTypeManager->expects($this->any())
->method('getDefinition')
->willReturn($entity_type);
$this->configFactory = $this->getMock(ConfigFactoryInterface::class);
$this->configStorage = $this->getMock(StorageInterface::class);
$this->configManager = $this->getMock(ConfigManagerInterface::class);
$this->moduleHandler = $this->getMock(ModuleHandlerInterface::class);
// getModuleList should return an array of extension objects.
// but we just need ::getConfigDependency isset($module_list[$provider]).
$this->moduleHandler->expects($this->any())
->method('getModuleList')
->willReturn(['my_module' => true]);
$this->configReverter = $this->getMock(ConfigRevertInterface::class);
$this->configReverter->expects($this->any())
->method('import')
->willReturn(true);
$this->configReverter->expects($this->any())
->method('revert')
->willReturn(true);
$this->featuresManager = new FeaturesManager($this->root, $this->entityTypeManager, $this->configFactory, $this->configStorage, $this->configManager, $this->moduleHandler, $this->configReverter);
}
/**
* @covers ::getActiveStorage
*/
public function testGetActiveStorage() {
$this->assertInstanceOf('\Drupal\Core\Config\StorageInterface', $this->featuresManager->getActiveStorage());
}
/**
* @covers ::getExtensionStorages
*/
public function testGetExtensionStorages() {
$this->assertInstanceOf('\Drupal\features\FeaturesExtensionStoragesInterface', $this->featuresManager->getExtensionStorages());
}
/**
* @covers ::getFullName
* @dataProvider providerTestGetFullName
*/
public function testGetFullName($type, $name, $expected) {
$this->assertEquals($this->featuresManager->getFullName($type, $name), $expected);
}
/**
* Data provider for ::testGetFullName().
*/
public function providerTestGetFullName() {
return [
[NULL, 'name', 'name'],
[FeaturesManagerInterface::SYSTEM_SIMPLE_CONFIG, 'name', 'name'],
['custom', 'name', 'custom.name'],
];
}
/**
* @covers ::getPackage
* @covers ::getPackages
* @covers ::reset
* @covers ::setPackages
*/
public function testPackages() {
$packages = ['foo' => 'bar'];
$this->featuresManager->setPackages($packages);
$this->assertEquals($packages, $this->featuresManager->getPackages());
$this->assertEquals('bar', $this->featuresManager->getPackage('foo'));
$this->featuresManager->reset();
$this->assertArrayEquals([], $this->featuresManager->getPackages());
$this->assertNull($this->featuresManager->getPackage('foo'));
}
/**
* @covers ::setConfigCollection
* @covers ::getConfigCollection
*/
public function testConfigCollection() {
$config = ['config' => new ConfigurationItem('', [])];
$this->featuresManager->setConfigCollection($config);
$this->assertArrayEquals($config, $this->featuresManager->getConfigCollection());
}
/**
* @covers ::setPackage
* @covers ::getPackage
*/
public function testSetPackage() {
$package = new Package('foo');
$this->featuresManager->setPackage($package);
$this->assertEquals($package, $this->featuresManager->getPackage('foo'));
}
protected function getAssignInterPackageDependenciesConfigCollection() {
$config_collection = [];
$config_collection['example.config'] = (new ConfigurationItem('example.config', [
'dependencies' => [
'config' => [
'example.config2',
'example.config3',
'example.config4',
],
],
]))->setPackage('package');
$config_collection['example.config2'] = (new ConfigurationItem('example.config2', [
'dependencies' => [],
]))
->setPackage('package2')
->setProvider('my_feature');
$config_collection['example.config3'] = (new ConfigurationItem('example.config3', [
'dependencies' => [],
]))
->setProvider('my_other_feature');
$config_collection['example.config4'] = (new ConfigurationItem('example.config3', [
'dependencies' => [],
]))
->setProvider(static::PROFILE_NAME);
return $config_collection;
}
/**
* @covers ::assignInterPackageDependencies
*/
public function testAssignInterPackageDependenciesWithoutBundle() {
$assigner = $this->prophesize(FeaturesAssignerInterface::class);
$bundle = $this->prophesize(FeaturesBundleInterface::class);
// Provide a bundle without any prefix.
$bundle->getFullName('package')->willReturn('package');
$bundle->getFullName('package2')->willReturn('package2');
$bundle->isDefault()->willReturn(TRUE);
$assigner->getBundle('')->willReturn($bundle->reveal());
// Use the wrapper because we need ::drupalGetProfile().
$features_manager = new TestFeaturesManager($this->root, $this->entityTypeManager, $this->configFactory, $this->configStorage, $this->configManager, $this->moduleHandler, $this->configReverter);
$features_manager->setAssigner($assigner->reveal());
$features_manager->setConfigCollection($this->getAssignInterPackageDependenciesConfigCollection());
$packages = [
'package' => new Package('package', [
'config' => ['example.config', 'example.config3'],
'dependencies' => [],
'bundle' => '',
]),
'package2' => new Package('package2', [
'config' => ['example.config2'],
'dependencies' => [],
'bundle' => '',
]),
];
$features_manager->setPackages($packages);
// Dependencies require the full package names.
$package_names = array_keys($packages);
$features_manager->setPackageBundleNames($bundle->reveal(), $package_names);
$packages = $features_manager->getPackages();
$features_manager->assignInterPackageDependencies($bundle->reveal(), $packages);
// example.config3 has a providing_feature but no assigned package.
// my_package2 provides configuration required by configuration in
// my_package.
// Because package assignments take precedence over providing_feature ones,
// package2 should have been assigned rather than my_feature.
$this->assertEquals(['my_other_feature', 'package2'], $packages['package']->getDependencies());
$this->assertEquals([], $packages['package2']->getDependencies());
}
/**
* @covers ::assignInterPackageDependencies
*/
public function testAssignInterPackageDependenciesWithBundle() {
$assigner = $this->prophesize(FeaturesAssignerInterface::class);
$bundle = $this->prophesize(FeaturesBundleInterface::class);
// Provide a bundle without any prefix.
$bundle->getFullName('package')->willReturn('giraffe_package');
$bundle->getFullName('package2')->willReturn('giraffe_package2');
$bundle->getFullName('giraffe_package')->willReturn('giraffe_package');
$bundle->getFullName('giraffe_package2')->willReturn('giraffe_package2');
$bundle->isDefault()->willReturn(FALSE);
$bundle->getMachineName()->willReturn('giraffe');
$assigner->getBundle('giraffe')->willReturn($bundle->reveal());
// Use the wrapper because we need ::drupalGetProfile().
$features_manager = new TestFeaturesManager($this->root, $this->entityTypeManager, $this->configFactory, $this->configStorage, $this->configManager, $this->moduleHandler, $this->configReverter);
$features_manager->setAssigner($assigner->reveal());
$features_manager->setConfigCollection($this->getAssignInterPackageDependenciesConfigCollection());
$packages = [
'package' => new Package('package', [
'config' => ['example.config'],
'dependencies' => [],
'bundle' => 'giraffe',
]),
'package2' => new Package('package2', [
'config' => ['example.config2'],
'dependencies' => [],
'bundle' => 'giraffe',
]),
];
$features_manager->setPackages($packages);
// Dependencies require the full package names.
$package_names = array_keys($packages);
$features_manager->setPackageBundleNames($bundle->reveal(), $package_names);
$packages = $features_manager->getPackages();
$features_manager->assignInterPackageDependencies($bundle->reveal(), $packages);
// example.config3 has a providing_feature but no assigned package.
// my_package2 provides configuration required by configuration in
// my_package.
// Because package assignments take precedence over providing_feature ones,
// package2 should have been assigned rather than my_feature.
$expected = ['giraffe_package2', 'my_other_feature'];
$this->assertEquals($expected, $packages['giraffe_package']->getDependencies());
}
/**
* @covers ::assignInterPackageDependencies
* @expectedException \Exception
* @expectedExceptionMessage The packages have not yet been prefixed with a bundle name
*/
public function testAssignInterPackageDependenciesPrematureCall() {
$bundle = $this->prophesize(FeaturesBundleInterface::class);
$packages = [
'package' => new Package('package', [
'config' => ['example.config', 'example.config3'],
'dependencies' => [],
'bundle' => 'giraffe',
]),
];
$this->featuresManager->assignInterPackageDependencies($bundle->reveal(), $packages);
}
/**
* @covers ::reset
*/
public function testReset() {
$packages = [
'package' => [
'machine_name' => 'package',
'config' => ['example.config', 'example.config3'],
'dependencies' => [],
'bundle' => 'giraffe',
],
'package2' => [
'machine_name' => 'package2',
'config' => ['example.config2'],
'dependencies' => [],
'bundle' => 'giraffe',
],
];
$this->featuresManager->setPackages($packages);
$config_item = new ConfigurationItem('example', [], ['package' => 'package']);
$config_item2 = new ConfigurationItem('example2', [], ['package' => 'package2']);
$this->featuresManager->setConfigCollection([$config_item, $config_item2]);
$this->featuresManager->reset();
$this->assertEmpty($this->featuresManager->getPackages());
$config_collection = $this->featuresManager->getConfigCollection();
$this->assertEquals('', $config_collection[0]->getPackage());
$this->assertEquals('', $config_collection[1]->getPackage());
}
/**
* @covers ::detectMissing
*/
public function testDetectMissing() {
$package = new Package('test-package', [
'configOrig' => ['test_config', 'test_config_non_existing'],
]);
$config_collection = [];
$config_collection['test_config'] = new ConfigurationItem('test_config', []);
$this->featuresManager->setConfigCollection($config_collection);
$this->assertEquals(['test_config_non_existing'], $this->featuresManager->detectMissing($package));
}
/**
* @covers ::detectOverrides
*/
public function testDetectOverrides() {
$config_diff = $this->prophesize(ConfigDiffInterface::class);
$config_diff->same(Argument::cetera())->will(function($args) {
return $args[0] == $args[1];
});
\Drupal::getContainer()->set('config_update.config_diff', $config_diff->reveal());
$package = new Package('test-package', [
'config' => ['test_config', 'test_overridden'],
]);
$config_storage = $this->prophesize(StorageInterface::class);
$config_storage->read('test_config')->willReturn([
'key' => 'value',
]);
$config_storage->read('test_overridden')->willReturn([
'key2' => 'value2',
]);
$extension_storage = $this->prophesize(FeaturesExtensionStoragesInterface::class);
$extension_storage->read('test_config')->willReturn([
'key' => 'value',
]);
$extension_storage->read('test_overridden')->willReturn([
'key2' => 'value0',
]);
$features_manager = new TestFeaturesManager($this->root, $this->entityTypeManager, $this->configFactory, $config_storage->reveal(), $this->configManager, $this->moduleHandler, $this->configReverter);
$features_manager->setExtensionStorages($extension_storage->reveal());
$this->assertEquals(['test_overridden'], $features_manager->detectOverrides($package));
}
/**
* @covers ::assignConfigPackage
*/
public function testAssignConfigPackageWithNonProviderExcludedConfig() {
$assigner = $this->prophesize(FeaturesAssignerInterface::class);
$bundle = $this->prophesize(FeaturesBundleInterface::class);
$bundle->isProfilePackage('test_package')->willReturn(FALSE);
$assigner->getBundle(NULL)->willReturn($bundle->reveal());
$this->featuresManager->setAssigner($assigner->reveal());
$config_collection = [
'test_config' => new ConfigurationItem('test_config', []),
'test_config2' => new ConfigurationItem('test_config2', [
'dependencies' => [
'module' => ['example'],
]
], [
'subdirectory' => InstallStorage::CONFIG_INSTALL_DIRECTORY,
]),
];
$this->featuresManager->setConfigCollection($config_collection);
$package = new Package('test_package');
$this->featuresManager->setPackage($package);
$this->featuresManager->assignConfigPackage('test_package', ['test_config', 'test_config2']);
$this->assertEquals(['test_config', 'test_config2'], $this->featuresManager->getPackage('test_package')->getConfig());
$this->assertEquals(['example', 'my_module'], $this->featuresManager->getPackage('test_package')->getDependencies());
}
/**
* @covers ::assignConfigPackage
*/
public function testAssignConfigPackageWithProviderExcludedConfig() {
$config_collection = [
'test_config' => new ConfigurationItem('test_config', []),
'test_config2' => new ConfigurationItem('test_config2', [], ['providerExcluded' => TRUE]),
];
$this->featuresManager->setConfigCollection($config_collection);
$feature_assigner = $this->prophesize(FeaturesAssignerInterface::class);
$feature_assigner->getBundle(NULL)->willReturn(new FeaturesBundle(['machine_name' => 'default'], 'features_bundle'));
$this->featuresManager->setAssigner($feature_assigner->reveal());
$package = new Package('test_package');
$original_package = clone $package;
$this->featuresManager->setPackage($package);
$this->featuresManager->assignConfigPackage('test_package', ['test_config', 'test_config2']);
$this->assertEquals(['test_config'], $this->featuresManager->getPackage('test_package')->getConfig(), 'just assign new packages');
$this->featuresManager->setPackage($original_package);
$this->featuresManager->assignConfigPackage('test_package', ['test_config', 'test_config2'], TRUE);
$this->assertEquals(['test_config', 'test_config2'], $this->featuresManager->getPackage('test_package')->getConfig(), 'just assign new packages');
}
/**
* @covers ::initPackageFromExtension
* @covers ::getPackageObject
*/
public function testInitPackageFromNonInstalledExtension() {
$extension = new Extension($this->root, 'module', 'modules/test_module/test_module.info.yml');
$info_parser = $this->prophesize(InfoParserInterface::class);
$info_parser->parse($this->root . '/modules/test_module/test_module.info.yml')->willReturn([
'name' => 'Test module',
'description' => 'test description',
'type' => 'module',
]);
\Drupal::getContainer()->set('info_parser', $info_parser->reveal());
$bundle = $this->prophesize(FeaturesBundle::class);
$bundle->getFullName('test_module')->willReturn('test_module');
$bundle->isDefault()->willReturn(TRUE);
$assigner = $this->prophesize(FeaturesAssignerInterface::class);
$assigner->findBundle(Argument::cetera())->willReturn($bundle->reveal());
$this->featuresManager->setAssigner($assigner->reveal());
$result = $this->featuresManager->initPackageFromExtension($extension);
$this->assertInstanceOf(Package::class, $result);
// Ensure that that calling the function twice works.
$result = $this->featuresManager->initPackageFromExtension($extension);
$this->assertInstanceOf(Package::class, $result);
$this->assertEquals('test_module', $result->getMachineName());
$this->assertEquals('Test module', $result->getName());
$this->assertEquals('test description', $result->getDescription());
$this->assertEquals('module', $result->getType());
$this->assertEquals(FeaturesManagerInterface::STATUS_UNINSTALLED, $result->getStatus());
}
/**
* @covers ::initPackageFromExtension
* @covers ::getPackageObject
*/
public function testInitPackageFromInstalledExtension() {
$extension = new Extension($this->root, 'module', 'modules/test_module/test_module.info.yml');
$info_parser = $this->prophesize(InfoParserInterface::class);
$info_parser->parse($this->root . '/modules/test_module/test_module.info.yml')->willReturn([
'name' => 'Test module',
'description' => 'test description',
'type' => 'module',
]);
\Drupal::getContainer()->set('info_parser', $info_parser->reveal());
$bundle = $this->prophesize(FeaturesBundle::class);
$bundle->getFullName('test_module')->willReturn('test_module');
$bundle->isDefault()->willReturn(TRUE);
$assigner = $this->prophesize(FeaturesAssignerInterface::class);
$assigner->findBundle(Argument::cetera())->willReturn($bundle->reveal());
$this->featuresManager->setAssigner($assigner->reveal());
$this->moduleHandler->expects($this->any())
->method('moduleExists')
->with('test_module')
->willReturn(TRUE);
$result = $this->featuresManager->initPackageFromExtension($extension);
$this->assertEquals(FeaturesManagerInterface::STATUS_INSTALLED, $result->getStatus());
}
public function testDetectNewWithNoConfig() {
$package = new Package('test_feature');
$this->assertEmpty($this->featuresManager->detectNew($package));
}
public function testDetectNewWithNoNewConfig() {
$package = new Package('test_feature', ['config' => ['test_config']]);
$extension_storage = $this->prophesize(FeaturesExtensionStoragesInterface::class);
$extension_storage->read('test_config')->willReturn([
'key' => 'value',
]);
$features_manager = new TestFeaturesManager($this->root, $this->entityTypeManager, $this->configFactory, $this->configStorage, $this->configManager, $this->moduleHandler, $this->configReverter);
$features_manager->setExtensionStorages($extension_storage->reveal());
$this->assertEmpty($features_manager->detectNew($package));
}
public function testDetectNewWithNewConfig() {
$package = new Package('test_feature', ['config' => ['test_config']]);
$extension_storage = $this->prophesize(FeaturesExtensionStoragesInterface::class);
$extension_storage->read('test_config')->willReturn(FALSE);
$features_manager = new TestFeaturesManager($this->root, $this->entityTypeManager, $this->configFactory, $this->configStorage, $this->configManager, $this->moduleHandler, $this->configReverter);
$features_manager->setExtensionStorages($extension_storage->reveal());
$this->assertEquals(['test_config'], $features_manager->detectNew($package));
}
/**
* @todo This could have of course much more test coverage.
*
* @covers ::mergeInfoArray
*
* @dataProvider providerTestMergeInfoArray
*/
public function testMergeInfoArray($expected, $info1, $info2, $keys = []) {
$this->assertSame($expected, $this->featuresManager->mergeInfoArray($info1, $info2, $keys));
}
public function providerTestMergeInfoArray() {
$data = [];
$data['empty-info'] = [[], [], []];
$data['override-info'] = [
['name' => 'New name', 'core' => '8.x'],
['name' => 'Old name', 'core' => '8.x'],
['name' => 'New name']
];
$data['dependency-merging'] = [
['dependencies' => ['a', 'b', 'c', 'd', 'e']],
['dependencies' => ['b', 'd', 'c']],
['dependencies' => ['a', 'b', 'e']],
[],
];
return $data;
}
/**
* @covers ::initPackage
**/
public function testInitPackageWithNewPackage() {
$bundle = new FeaturesBundle(['machine_name' => 'test'], 'features_bundle');
$features_manager = new TestFeaturesManager($this->root, $this->entityTypeManager, $this->configFactory, $this->configStorage, $this->configManager, $this->moduleHandler, $this->configReverter);
$features_manager->setAllModules([]);
$package = $features_manager->initPackage('test_feature', 'test name', 'test description', 'module', $bundle);
$this->assertInstanceOf(Package::class, $package);
$this->assertEquals('test_feature', $package->getMachineName());
$this->assertEquals('test name', $package->getName());
$this->assertEquals('test description', $package->getDescription());
$this->assertEquals('module', $package->getType());
$this->assertEquals(['bundle' => 'test'], $package->getFeaturesInfo());
$this->assertEquals('test', $package->getBundle());
$this->assertEquals(FALSE, $package->getRequired());
$this->assertEquals([], $package->getExcluded());
}
/**
* @covers ::getFeaturesInfo
* @covers ::getFeaturesModules
**/
public function testInitPackageWithExistingPackage() {
$bundle = new FeaturesBundle(['machine_name' => 'test'], 'features_bundle');
$features_manager = new TestFeaturesManager('vfs://drupal', $this->entityTypeManager, $this->configFactory, $this->configStorage, $this->configManager, $this->moduleHandler, $this->configReverter);
vfsStream::setup('drupal');
\Drupal::getContainer()->set('app.root', 'vfs://drupal');
vfsStream::create([
'modules' => [
'test_feature' => [
'test_feature.info.yml' => <<<EOT
name: Test feature 2
type: module
core: 8.x
description: test description 2
EOT
,
'test_feature.features.yml' => <<<EOT
bundle: test
excluded:
- system.theme
required: true
EOT
,
],
],
]);
$extension = new Extension('vfs://drupal', 'module', 'modules/test_feature/test_feature.info.yml');
$features_manager->setAllModules(['test_feature' => $extension]);
$this->moduleHandler->expects($this->any())
->method('exists')
->with('test_feature')
->willReturn(TRUE);
$info_parser = new InfoParser();
\Drupal::getContainer()->set('info_parser', $info_parser);
$package = $features_manager->initPackage('test_feature', 'test name', 'test description', 'module', $bundle);
$this->assertEquals([
'bundle' => 'test',
'excluded' => [
0 => 'system.theme',
],
'required' => TRUE,
], $features_manager->getFeaturesInfo($extension));
$this->assertEquals(['test_feature' => $extension], $features_manager->getFeaturesModules($bundle));
$this->assertInstanceOf(Package::class, $package);
$this->assertEquals([
'bundle' => 'test',
'excluded' => [
0 => 'system.theme',
],
'required' => TRUE,
], $package->getFeaturesInfo());
$this->assertEquals('test', $package->getBundle());
$this->assertEquals(TRUE, $package->getRequired());
$this->assertEquals(['system.theme'], $package->getExcluded());
}
/**
* @covers ::prepareFiles
*/
public function testPrepareFiles() {
$packages = [];
$packages['test_feature'] = new Package('test_feature', [
'config' => ['test_config'],
'name' => 'Test feature',
]);
$config_collection = [];
$config_collection['test_config'] = new ConfigurationItem('test_config', ['foo' => 'bar']);
$this->featuresManager->setConfigCollection($config_collection);
$this->featuresManager->prepareFiles($packages);
$files = $packages['test_feature']->getFiles();
$this->assertCount(3, $files);
$this->assertEquals('test_feature.info.yml', $files['info']['filename']);
$this->assertEquals(Yaml::encode([
'name' => 'Test feature',
'type' => 'module',
'core' => '8.x',
]), $files['info']['string']);
$this->assertEquals(Yaml::encode(TRUE), $files['features']['string']);
$this->assertEquals('test_config.yml', $files['test_config']['filename']);
$this->assertEquals(Yaml::encode([
'foo' => 'bar'
]), $files['test_config']['string']);
$this->assertEquals('test_feature.features.yml', $files['features']['filename']);
$this->assertEquals(Yaml::encode(TRUE), $files['features']['string']);
}
/**
* @covers ::getExportInfo
*/
public function testGetExportInfoWithoutBundle() {
$config_factory = $this->getConfigFactoryStub([
'features.settings' => [
'export' => [
'folder' => 'custom',
],
],
]);
$this->featuresManager = new FeaturesManager($this->root, $this->entityTypeManager, $config_factory, $this->configStorage, $this->configManager, $this->moduleHandler, $this->configReverter);
$package = new Package('test_feature');
$result = $this->featuresManager->getExportInfo($package);
$this->assertEquals(['test_feature', 'modules/custom'], $result);
}
/**
* @covers ::getExportInfo
*/
public function testGetExportInfoWithBundle() {
$config_factory = $this->getConfigFactoryStub([
'features.settings' => [
'export' => [
'folder' => 'custom',
],
],
]);
$this->featuresManager = new FeaturesManager($this->root, $this->entityTypeManager, $config_factory, $this->configStorage, $this->configManager, $this->moduleHandler, $this->configReverter);
$package = new Package('test_feature');
$bundle = new FeaturesBundle(['machine_name' => 'test_bundle'], 'features_bundle');
$result = $this->featuresManager->getExportInfo($package, $bundle);
$this->assertEquals(['test_bundle_test_feature', 'modules/custom'], $result);
}
}
class TestFeaturesManager extends FeaturesManager {
protected $allModules;
/**
* @param \Drupal\features\FeaturesExtensionStoragesInterface $extensionStorages
*/
public function setExtensionStorages($extensionStorages) {
$this->extensionStorages = $extensionStorages;
}
/**
* {@inheritdoc}
*/
public function getAllModules() {
if (isset($this->allModules)) {
return $this->allModules;
}
return parent::getAllModules();
}
/**
* @param mixed $all_modules
*/
public function setAllModules($all_modules) {
$this->allModules = $all_modules;
return $this;
}
protected function drupalGetProfile() {
return FeaturesManagerTest::PROFILE_NAME;
}
}
@@ -0,0 +1,53 @@
<?php
namespace Drupal\Tests\features\Unit;
use Drupal\features\Package;
/**
* @coversDefaultClass \Drupal\features\Package
* @group features
*/
class PackageTest extends \PHPUnit_Framework_TestCase {
/**
* @covers ::setFeaturesInfo
*/
public function testSetFeaturesInfo() {
$package = new Package('test_feature', []);
$this->assertEquals([], $package->getFeaturesInfo());
$package->setFeaturesInfo(['bundle' => 'test_bundle']);
$this->assertEquals(['bundle' => 'test_bundle'], $package->getFeaturesInfo());
$this->assertEquals('test_bundle', $package->getBundle());
}
public function testGetConfig() {
$package = new Package('test_feature', ['config' => ['test_config_a', 'test_config_b']]);
$this->assertEquals(['test_config_a', 'test_config_b'], $package->getConfig());
return $package;
}
/**
* @depends testGetConfig
* @covers ::appendConfig
*/
public function testAppendConfig(Package $package) {
$package->appendConfig('test_config_a');
$package->appendConfig('test_config_c');
$this->assertEquals(['test_config_a', 'test_config_b', 'test_config_c'], array_values($package->getConfig()));
return $package;
}
/**
* @depends testAppendConfig
* @covers ::removeConfig
*/
public function testRemoveConfig(Package $package) {
$package->removeConfig('test_config_a');
$this->assertEquals(['test_config_b', 'test_config_c'], array_values($package->getConfig()));
}
}