3 namespace Drupal\KernelTests\Core\Plugin\Discovery;
5 use Drupal\Core\StringTranslation\TranslatableMarkup;
6 use Drupal\KernelTests\KernelTestBase;
9 * Base class for plugin discovery tests.
11 abstract class DiscoveryTestBase extends KernelTestBase {
14 * The discovery component to test.
16 * @var \Drupal\Component\Plugin\Discovery\DiscoveryInterface
21 * The plugin definitions the discovery component is expected to discover.
25 protected $expectedDefinitions;
28 * An empty discovery component.
30 * This will be tested to ensure that the case where no plugin information is
31 * found, is handled correctly.
33 * @var \Drupal\Component\Plugin\Discovery\DiscoveryInterface
35 protected $emptyDiscovery;
38 * Tests getDefinitions() and getDefinition().
40 public function testDiscoveryInterface() {
41 // Ensure that getDefinitions() returns the expected definitions.
42 // For the arrays to be identical (instead of only equal), they must be
43 // sorted equally, which seems unnecessary here.
44 // The discovered definitions may contain circular references; use a custom
45 // assertion message to prevent var_export() from getting called.
46 $this->assertEqual($this->discovery->getDefinitions(), $this->expectedDefinitions, 'Expected definitions found.');
48 // Ensure that getDefinition() returns the expected definition.
49 foreach ($this->expectedDefinitions as $id => $definition) {
50 $this->assertDefinitionIdentical($this->discovery->getDefinition($id), $definition);
53 // Ensure that an empty array is returned if no plugin definitions are found.
54 $this->assertIdentical($this->emptyDiscovery->getDefinitions(), [], 'array() returned if no plugin definitions are found.');
56 // Ensure that NULL is returned as the definition of a non-existing plugin.
57 $this->assertIdentical($this->emptyDiscovery->getDefinition('non_existing', FALSE), NULL, 'NULL returned as the definition of a non-existing plugin.');
61 * Asserts a definition against an expected definition.
63 * Converts any instances of \Drupal\Core\Annotation\Translation to a string.
65 * @param array $definition
66 * The definition to test.
67 * @param array $expected_definition
68 * The expected definition to test against.
71 * TRUE if the assertion succeeded, FALSE otherwise.
73 protected function assertDefinitionIdentical(array $definition, array $expected_definition) {
74 $func = function (&$item) {
75 if ($item instanceof TranslatableMarkup) {
76 $item = (string) $item;
79 array_walk_recursive($definition, $func);
80 array_walk_recursive($expected_definition, $func);
81 return $this->assertIdentical($definition, $expected_definition);