class IconPackManagerKernelTest

@coversDefaultClass \Drupal\Core\Theme\Icon\Plugin\IconPackManager

Tests values are from test module icon_test. Any change of the definition will impact the tests.

@group icon

Hierarchy

Expanded class hierarchy of IconPackManagerKernelTest

See also

core/modules/system/tests/modules/icon_test/icon_test.icons.yml

File

core/tests/Drupal/KernelTests/Core/Theme/Icon/IconPackManagerKernelTest.php, line 23

Namespace

Drupal\KernelTests\Core\Theme\Icon
View source
class IconPackManagerKernelTest extends KernelTestBase {
    
    /**
     * Icon from icon_test module.
     */
    private const TEST_ICON_FULL_ID = 'test_minimal:foo';
    private const EXPECTED_TOTAL_TEST_ICONS = 30;
    
    /**
     * {@inheritdoc}
     */
    protected static $modules = [
        'system',
        'icon_test',
    ];
    
    /**
     * The IconPackManager instance.
     *
     * @var \Drupal\Core\Theme\Icon\Plugin\IconPackManagerInterface
     */
    private IconPackManagerInterface $pluginManagerIconPack;
    
    /**
     * The App root instance.
     *
     * @var string
     */
    private string $appRoot;
    
    /**
     * {@inheritdoc}
     */
    protected function setUp() : void {
        parent::setUp();
        $module_handler = $this->container
            ->get('module_handler');
        $theme_handler = $this->container
            ->get('theme_handler');
        $cache_backend = $this->container
            ->get('cache.default');
        $icon_extractor_plugin_manager = $this->container
            ->get('plugin.manager.icon_extractor');
        $icon_collector = $this->container
            ->get('Drupal\\Core\\Theme\\Icon\\IconCollector');
        $this->appRoot = $this->container
            ->getParameter('app.root');
        $this->pluginManagerIconPack = new IconPackManager($module_handler, $theme_handler, $cache_backend, $icon_extractor_plugin_manager, $icon_collector, $this->appRoot);
    }
    
    /**
     * Test the IconPackManager::_construct method.
     */
    public function testConstructor() : void {
        $this->assertInstanceOf(IconPackManager::class, $this->pluginManagerIconPack);
    }
    
    /**
     * Test the IconPackManager::getIcons method.
     */
    public function testGetIcons() : void {
        $icons = $this->pluginManagerIconPack
            ->getIcons();
        $this->assertCount(self::EXPECTED_TOTAL_TEST_ICONS, $icons);
        foreach ($icons as $icon) {
            $this->assertArrayHasKey('source', $icon);
            $this->assertArrayHasKey('group', $icon);
        }
        $icons = $this->pluginManagerIconPack
            ->getIcons([
            'test_minimal',
        ]);
        $this->assertCount(1, $icons);
        foreach ($icons as $icon) {
            $this->assertArrayHasKey('source', $icon);
            $this->assertArrayHasKey('group', $icon);
        }
        $icons = $this->pluginManagerIconPack
            ->getIcons([
            'do_not_exist',
        ]);
        $this->assertEmpty($icons);
    }
    
    /**
     * Test the IconPackManager::getIcon method.
     */
    public function testGetIcon() : void {
        $icon = $this->pluginManagerIconPack
            ->getIcon(self::TEST_ICON_FULL_ID);
        $this->assertInstanceOf(IconDefinitionInterface::class, $icon);
        $icon = $this->pluginManagerIconPack
            ->getIcon('test_minimal:_do_not_exist_');
        $this->assertNull($icon);
    }
    
    /**
     * Test the IconPackManager::listIconPackOptions method.
     */
    public function testListIconPackOptions() : void {
        $actual = $this->pluginManagerIconPack
            ->listIconPackOptions();
        $expected = [
            'test_minimal' => 'test_minimal (1)',
            'test_path' => 'Test path (10)',
            'test_svg' => 'Test svg (12)',
            'test_svg_sprite' => 'Test sprite (3)',
            'test_no_settings' => 'test_no_settings (1)',
            'test_settings' => 'Test settings (1)',
            'test_url_path' => 'Test url path (2)',
        ];
        $this->assertEquals($expected, $actual);
        $actual = $this->pluginManagerIconPack
            ->listIconPackOptions(TRUE);
        $expected = [
            'test_minimal' => 'test_minimal (1)',
            'test_path' => 'Test path - Local png files available for test with all metadata. (10)',
            'test_svg' => 'Test svg (12)',
            'test_svg_sprite' => 'Test sprite (3)',
            'test_no_settings' => 'test_no_settings (1)',
            'test_settings' => 'Test settings (1)',
            'test_url_path' => 'Test url path (2)',
        ];
        $this->assertEquals($expected, $actual);
    }
    
    /**
     * Test the IconPackManager::getExtractorFormDefault method.
     */
    public function testGetExtractorFormDefaults() : void {
        $actual = $this->pluginManagerIconPack
            ->getExtractorFormDefaults('test_settings');
        // @see core/modules/system/tests/modules/icon_test/icon_test.icons.yml
        $expected = [
            'width' => 32,
            'height' => 33,
            'title' => 'Default title',
            'alt' => 'Default alt',
            'select' => 400,
            'boolean' => TRUE,
            'decimal' => 66.66,
            'number' => 30,
        ];
        $this->assertSame($expected, $actual);
        $actual = $this->pluginManagerIconPack
            ->getExtractorFormDefaults('test_no_settings');
        $this->assertSame([], $actual);
    }
    
    /**
     * Test the IconPackManager::getExtractorPluginForms method.
     */
    public function testGetExtractorPluginForms() : void {
        $form_state = $this->getMockBuilder('Drupal\\Core\\Form\\FormState')
            ->disableOriginalConstructor()
            ->getMock();
        $form = [];
        $this->pluginManagerIconPack
            ->getExtractorPluginForms($form, $form_state);
        // @see core/modules/system/tests/modules/icon_test/icon_test.icons.yml
        $this->assertCount(4, array_keys($form));
        $expected = [
            'test_path',
            'test_svg',
            'test_svg_sprite',
            'test_settings',
        ];
        $this->assertSame($expected, array_keys($form));
        $expected = [
            '#type',
            '#title',
            'width',
            'height',
            'title',
        ];
        $this->assertSame($expected, array_keys($form['test_path']));
        $expected = [
            '#type',
            '#title',
            'width',
            'height',
        ];
        $this->assertSame($expected, array_keys($form['test_svg_sprite']));
        $expected = [
            '#type',
            '#title',
            'width',
            'height',
            'title',
            'alt',
            'select',
            'select_string',
            'boolean',
            'decimal',
            'number',
        ];
        $this->assertSame($expected, array_keys($form['test_settings']));
        // No form if no settings.
        $this->assertArrayNotHasKey('test_no_settings', $form);
    }
    
    /**
     * Test the IconPackManager::getExtractorPluginForms method.
     */
    public function testGetExtractorPluginFormsWithAllowed() : void {
        $form_state = $this->getMockBuilder('Drupal\\Core\\Form\\FormState')
            ->disableOriginalConstructor()
            ->getMock();
        $form = [];
        $allowed_icon_pack['test_svg'] = '';
        $this->pluginManagerIconPack
            ->getExtractorPluginForms($form, $form_state, [], $allowed_icon_pack);
        $this->assertArrayHasKey('test_svg', $form);
        $this->assertArrayNotHasKey('test_minimal', $form);
        $this->assertArrayNotHasKey('test_svg_sprite', $form);
        $this->assertArrayNotHasKey('test_no_icons', $form);
    }
    
    /**
     * Test the IconPackManager::getExtractorPluginForms method with default.
     */
    public function testGetExtractorPluginFormsWithDefault() : void {
        $form = [
            '#parents' => [],
            'test_settings' => [
                '#parents' => [
                    'test_settings',
                ],
                '#array_parents' => [
                    'test_settings',
                ],
            ],
        ];
        $form_state = $this->getMockBuilder('Drupal\\Core\\Form\\FormState')
            ->disableOriginalConstructor()
            ->onlyMethods([
            'setValue',
            'getValue',
        ])
            ->getMock();
        $this->pluginManagerIconPack
            ->getExtractorPluginForms($form, $form_state);
        // Without default, values are from definition.
        $expected = [
            'width' => 32,
            'height' => 33,
            'title' => 'Default title',
            'alt' => 'Default alt',
            'select' => 400,
            'boolean' => TRUE,
            'decimal' => 66.66,
            'number' => 30,
        ];
        foreach ($expected as $key => $value) {
            $this->assertSame($value, $form['test_settings'][$key]['#default_value']);
        }
        // Test definition without value.
        $this->assertArrayNotHasKey('#default_value', $form['test_svg']['size']);
        $default_settings = [
            'test_settings' => [
                'width' => 100,
                'height' => 110,
                'title' => 'Test',
            ],
        ];
        // Test the set/get of default values as 'saved_values'.
        $form_state->expects($this->once())
            ->method('setValue')
            ->with('saved_values', $default_settings['test_settings']);
        $form_state->expects($this->once())
            ->method('getValue')
            ->with('saved_values')
            ->willReturn($default_settings['test_settings']);
        $this->pluginManagerIconPack
            ->getExtractorPluginForms($form, $form_state, $default_settings, [
            'test_settings' => '',
        ]);
        $this->assertSame($default_settings['test_settings']['width'], $form['test_settings']['width']['#default_value']);
        $this->assertSame($default_settings['test_settings']['height'], $form['test_settings']['height']['#default_value']);
        $this->assertSame($default_settings['test_settings']['title'], $form['test_settings']['title']['#default_value']);
    }
    
    /**
     * Test the IconPackManager::processDefinition method.
     */
    public function testProcessDefinition() : void {
        $relative_path = 'core/modules/system/tests/modules/icon_test';
        $definition = [
            'id' => 'foo',
            'label' => 'Foo',
            'provider' => 'icon_test',
            'extractor' => 'test',
        ];
        $this->pluginManagerIconPack
            ->processDefinition($definition, 'foo');
        $this->assertSame('foo', $definition['id']);
        $this->assertSame('Foo', $definition['label']);
        $this->assertEquals($relative_path, $definition['relative_path']);
        $absolute_path = sprintf('%s/%s', $this->appRoot, $relative_path);
        $this->assertEquals($absolute_path, $definition['absolute_path']);
        $this->assertArrayHasKey('icons', $definition);
        $this->assertEmpty($definition['icons']);
        $definition = [
            'id' => 'foo',
            'provider' => 'icon_test',
            'extractor' => 'test_finder',
            'template' => '{{ icon_id }}',
            'config' => [
                'sources' => [
                    'icons/flat/*.svg',
                ],
            ],
        ];
        $this->pluginManagerIconPack
            ->processDefinition($definition, 'foo');
        $this->assertArrayHasKey('icons', $definition);
        $this->assertNotEmpty($definition['icons']);
        $this->assertCount(5, $definition['icons']);
        foreach ($definition['icons'] as $icon) {
            $this->assertInstanceOf(IconDefinitionInterface::class, $icon);
        }
    }
    
    /**
     * Test the IconPackManager::processDefinition method with disable pack.
     */
    public function testProcessDefinitionDisabled() : void {
        $definition = [
            'id' => 'foo',
            'enabled' => FALSE,
            'provider' => 'icon_test',
            'extractor' => 'bar',
            'template' => '',
        ];
        $this->pluginManagerIconPack
            ->processDefinition($definition, 'foo');
        $this->assertSame('foo', $definition['id']);
        $this->assertArrayNotHasKey('relative_path', $definition);
        $this->assertArrayNotHasKey('absolute_path', $definition);
        $this->assertArrayNotHasKey('icons', $definition);
    }
    
    /**
     * Test the IconPackManager::processDefinition method with exception.
     */
    public function testProcessDefinitionExceptionName() : void {
        $definition = [
            'provider' => 'foo',
        ];
        $this->expectException(IconPackConfigErrorException::class);
        $this->expectExceptionMessage('Invalid icon pack id in: foo, name: $ Not valid !* must contain only lowercase letters, numbers, and underscores.');
        $this->pluginManagerIconPack
            ->processDefinition($definition, '$ Not valid !*');
    }
    
    /**
     * Test the IconPackManager::processDefinition method with exception.
     */
    public function testProcessDefinitionExceptionRequired() : void {
        $definition = [
            'id' => 'foo',
            'provider' => 'icon_test',
        ];
        $this->pluginManagerIconPack
            ->setValidator();
        $this->expectException(IconPackConfigErrorException::class);
        $this->expectExceptionMessage('icon_test:foo Error in definition `foo`:[extractor] The property extractor is required, [template] The property template is required');
        $this->pluginManagerIconPack
            ->processDefinition($definition, 'foo');
    }

}

Members

Title Sort descending Deprecated Modifiers Object type Summary Overriden Title Overrides
AssertContentTrait::$content protected property The current raw content.
AssertContentTrait::$drupalSettings protected property The drupalSettings value from the current raw $content.
AssertContentTrait::$elements protected property The XML structure parsed from the current raw $content. 1
AssertContentTrait::$plainTextContent protected property The plain-text content of raw $content (text nodes).
AssertContentTrait::assertEscaped protected function Passes if the raw text IS found escaped on the loaded page, fail otherwise.
AssertContentTrait::assertField protected function Asserts that a field exists with the given name or ID.
AssertContentTrait::assertFieldById Deprecated protected function Asserts that a field exists with the given ID and value.
AssertContentTrait::assertFieldByName protected function Asserts that a field exists with the given name and value.
AssertContentTrait::assertFieldByXPath protected function Asserts that a field exists in the current page by the given XPath.
AssertContentTrait::assertFieldChecked Deprecated protected function Asserts that a checkbox field in the current page is checked.
AssertContentTrait::assertFieldsByValue protected function Asserts that a field exists in the current page with a given Xpath result.
AssertContentTrait::assertLink protected function Passes if a link with the specified label is found.
AssertContentTrait::assertLinkByHref protected function Passes if a link containing a given href (part) is found.
AssertContentTrait::assertNoDuplicateIds Deprecated protected function Asserts that each HTML ID is used for just a single element.
AssertContentTrait::assertNoEscaped protected function Passes if raw text IS NOT found escaped on loaded page, fail otherwise.
AssertContentTrait::assertNoField Deprecated protected function Asserts that a field does not exist with the given name or ID.
AssertContentTrait::assertNoFieldById Deprecated protected function Asserts that a field does not exist with the given ID and value.
AssertContentTrait::assertNoFieldByName Deprecated protected function Asserts that a field does not exist with the given name and value.
AssertContentTrait::assertNoFieldByXPath Deprecated protected function Asserts that a field does not exist or its value does not match, by XPath.
AssertContentTrait::assertNoFieldChecked Deprecated protected function Asserts that a checkbox field in the current page is not checked.
AssertContentTrait::assertNoLink protected function Passes if a link with the specified label is not found.
AssertContentTrait::assertNoLinkByHref Deprecated protected function Passes if a link containing a given href (part) is not found.
AssertContentTrait::assertNoLinkByHrefInMainRegion Deprecated protected function Passes if a link containing a given href is not found in the main region.
AssertContentTrait::assertNoOption Deprecated protected function Asserts that a select option in the current page does not exist.
AssertContentTrait::assertNoOptionSelected Deprecated protected function Asserts that a select option in the current page is not checked.
AssertContentTrait::assertNoPattern protected function Triggers a pass if the perl regex pattern is not found in raw content.
AssertContentTrait::assertNoRaw protected function Passes if the raw text is NOT found on the loaded page, fail otherwise.
AssertContentTrait::assertNoText protected function Passes if the page (with HTML stripped) does not contains the text.
AssertContentTrait::assertNoTitle protected function Pass if the page title is not the given string.
AssertContentTrait::assertNoUniqueText Deprecated protected function Passes if the text is found MORE THAN ONCE on the text version of the page.
AssertContentTrait::assertOption protected function Asserts that a select option in the current page exists.
AssertContentTrait::assertOptionByText Deprecated protected function Asserts that a select option with the visible text exists.
AssertContentTrait::assertOptionSelected Deprecated protected function Asserts that a select option in the current page is checked.
AssertContentTrait::assertOptionSelectedWithDrupalSelector Deprecated protected function Asserts that a select option in the current page is checked.
AssertContentTrait::assertOptionWithDrupalSelector protected function Asserts that a select option in the current page exists.
AssertContentTrait::assertPattern protected function Triggers a pass if the Perl regex pattern is found in the raw content.
AssertContentTrait::assertRaw protected function Passes if the raw text IS found on the loaded page, fail otherwise.
AssertContentTrait::assertText protected function Passes if the page (with HTML stripped) contains the text.
AssertContentTrait::assertTextHelper protected function Helper for assertText and assertNoText.
AssertContentTrait::assertTextPattern Deprecated protected function Asserts that a Perl regex pattern is found in the plain-text content.
AssertContentTrait::assertThemeOutput protected function Asserts themed output.
AssertContentTrait::assertTitle protected function Pass if the page title is the given string.
AssertContentTrait::assertUniqueText Deprecated protected function Passes if the text is found ONLY ONCE on the text version of the page.
AssertContentTrait::assertUniqueTextHelper Deprecated protected function Helper for assertUniqueText and assertNoUniqueText.
AssertContentTrait::buildXPathQuery protected function Builds an XPath query.
AssertContentTrait::constructFieldXpath protected function Helper: Constructs an XPath for the given set of attributes and value.
AssertContentTrait::cssSelect protected function Searches elements using a CSS selector in the raw content.
AssertContentTrait::getAllOptions protected function Get all option elements, including nested options, in a select.
AssertContentTrait::getDrupalSettings protected function Gets the value of drupalSettings for the currently-loaded page.
AssertContentTrait::getRawContent protected function Gets the current raw content.
AssertContentTrait::getSelectedItem protected function Get the selected value from a select field.
AssertContentTrait::getTextContent protected function Retrieves the plain-text content from the current raw content.
AssertContentTrait::parse protected function Parse content returned from curlExec using DOM and SimpleXML.
AssertContentTrait::removeWhiteSpace protected function Removes all white-space between HTML tags from the raw content.
AssertContentTrait::setDrupalSettings protected function Sets the value of drupalSettings for the currently-loaded page.
AssertContentTrait::setRawContent protected function Sets the raw content (e.g. HTML).
AssertContentTrait::xpath protected function Performs an xpath search on the contents of the internal browser.
ConfigTestTrait::configImporter protected function Returns a ConfigImporter object to import test configuration.
ConfigTestTrait::copyConfig protected function Copies configuration objects from source storage to target storage.
ExpectDeprecationTrait::expectDeprecation public function Adds an expected deprecation.
ExpectDeprecationTrait::getCallableName private static function Returns a callable as a string suitable for inclusion in a message.
ExpectDeprecationTrait::setUpErrorHandler public function Sets up the test error handler.
ExpectDeprecationTrait::tearDownErrorHandler public function Tears down the test error handler.
ExtensionListTestTrait::getModulePath protected function Gets the path for the specified module.
ExtensionListTestTrait::getThemePath protected function Gets the path for the specified theme.
IconPackManagerKernelTest::$appRoot private property The App root instance.
IconPackManagerKernelTest::$modules protected static property Modules to install. Overrides KernelTestBase::$modules
IconPackManagerKernelTest::$pluginManagerIconPack private property The IconPackManager instance.
IconPackManagerKernelTest::EXPECTED_TOTAL_TEST_ICONS private constant
IconPackManagerKernelTest::setUp protected function Overrides KernelTestBase::setUp
IconPackManagerKernelTest::testConstructor public function Test the IconPackManager::_construct method.
IconPackManagerKernelTest::testGetExtractorFormDefaults public function Test the IconPackManager::getExtractorFormDefault method.
IconPackManagerKernelTest::testGetExtractorPluginForms public function Test the IconPackManager::getExtractorPluginForms method.
IconPackManagerKernelTest::testGetExtractorPluginFormsWithAllowed public function Test the IconPackManager::getExtractorPluginForms method.
IconPackManagerKernelTest::testGetExtractorPluginFormsWithDefault public function Test the IconPackManager::getExtractorPluginForms method with default.
IconPackManagerKernelTest::testGetIcon public function Test the IconPackManager::getIcon method.
IconPackManagerKernelTest::testGetIcons public function Test the IconPackManager::getIcons method.
IconPackManagerKernelTest::testListIconPackOptions public function Test the IconPackManager::listIconPackOptions method.
IconPackManagerKernelTest::testProcessDefinition public function Test the IconPackManager::processDefinition method.
IconPackManagerKernelTest::testProcessDefinitionDisabled public function Test the IconPackManager::processDefinition method with disable pack.
IconPackManagerKernelTest::testProcessDefinitionExceptionName public function Test the IconPackManager::processDefinition method with exception.
IconPackManagerKernelTest::testProcessDefinitionExceptionRequired public function Test the IconPackManager::processDefinition method with exception.
IconPackManagerKernelTest::TEST_ICON_FULL_ID private constant Icon from icon_test module.
KernelTestBase::$backupStaticAttributes protected property Back up and restore static class properties that may be changed by tests.
KernelTestBase::$backupStaticAttributesBlacklist protected property Contains a few static class properties for performance.
KernelTestBase::$classLoader protected property
KernelTestBase::$configImporter protected property @todo Move into Config test base class. 6
KernelTestBase::$configSchemaCheckerExclusions protected static property An array of config object names that are excluded from schema checking. 4
KernelTestBase::$container protected property
KernelTestBase::$databasePrefix protected property
KernelTestBase::$keyValue protected property The key_value service that must persist between container rebuilds.
KernelTestBase::$root protected property The app root.
KernelTestBase::$siteDirectory protected property
KernelTestBase::$strictConfigSchema protected property Set to TRUE to strict check all configuration saved. 9
KernelTestBase::$usesSuperUserAccessPolicy protected property Set to TRUE to make user 1 a super user. 2
KernelTestBase::$vfsRoot protected property The virtual filesystem root directory.
KernelTestBase::assertPostConditions protected function 1
KernelTestBase::bootEnvironment protected function Bootstraps a basic test environment.
KernelTestBase::bootKernel protected function Bootstraps a kernel for a test. 1
KernelTestBase::config protected function Configuration accessor for tests. Returns non-overridden configuration.
KernelTestBase::disableModules protected function Disables modules for this test.
KernelTestBase::enableModules protected function Enables modules for this test. 2
KernelTestBase::getConfigSchemaExclusions protected function Gets the config schema exclusions for this test.
KernelTestBase::getDatabaseConnectionInfo protected function Returns the Database connection info to be used for this test. 2
KernelTestBase::getDatabasePrefix public function
KernelTestBase::getExtensionsForModules private function Returns Extension objects for $modules to install.
KernelTestBase::getModulesToEnable private static function Returns the modules to install for this test.
KernelTestBase::initFileCache protected function Initializes the FileCache component.
KernelTestBase::installConfig protected function Installs default configuration for a given list of modules.
KernelTestBase::installEntitySchema protected function Installs the storage schema for a specific entity type.
KernelTestBase::installSchema protected function Installs database tables from a module schema definition.
KernelTestBase::register public function Registers test-specific services. Overrides ServiceProviderInterface::register 29
KernelTestBase::render protected function Renders a render array. 1
KernelTestBase::setInstallProfile protected function Sets the install profile and rebuilds the container to update it.
KernelTestBase::setSetting protected function Sets an in-memory Settings variable.
KernelTestBase::setUpBeforeClass public static function
KernelTestBase::setUpFilesystem protected function Sets up the filesystem, so things like the file directory. 3
KernelTestBase::tearDown protected function 7
KernelTestBase::tearDownCloseDatabaseConnection public function Additional tear down method to close the connection at the end.
KernelTestBase::vfsDump protected function Dumps the current state of the virtual filesystem to STDOUT.
KernelTestBase::__construct public function
KernelTestBase::__sleep public function Prevents serializing any properties.
RandomGeneratorTrait::getRandomGenerator protected function Gets the random generator for the utility methods.
RandomGeneratorTrait::randomMachineName protected function Generates a unique random string containing letters and numbers.
RandomGeneratorTrait::randomObject public function Generates a random PHP object.
RandomGeneratorTrait::randomString public function Generates a pseudo-random string of ASCII characters of codes 32 to 126.
StorageCopyTrait::replaceStorageContents protected static function Copy the configuration from one storage to another and remove stale items.
TestRequirementsTrait::getDrupalRoot protected static function Returns the Drupal root directory.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.