3 namespace Drupal\Tests\Core\Common;
5 use Drupal\Core\Template\Attribute;
6 use Drupal\Tests\UnitTestCase;
9 * Tests the Drupal\Core\Template\Attribute functionality.
13 class AttributesTest extends UnitTestCase {
16 * Provides data for the Attribute test.
20 public function providerTestAttributeData() {
22 // Verify that special characters are HTML encoded.
23 [['&"\'<>' => 'value'], ' &"'<>="value"', 'HTML encode attribute names.'],
24 [['title' => '&"\'<>'], ' title="&"'<>"', 'HTML encode attribute values.'],
25 // Verify multi-value attributes are concatenated with spaces.
26 [['class' => ['first', 'last']], ' class="first last"', 'Concatenate multi-value attributes.'],
27 // Verify boolean attribute values are rendered correctly.
28 [['disabled' => TRUE], ' disabled', 'Boolean attribute is rendered.'],
29 [['disabled' => FALSE], '', 'Boolean attribute is not rendered.'],
30 // Verify empty attribute values are rendered.
31 [['alt' => ''], ' alt=""', 'Empty attribute value #1.'],
32 [['alt' => NULL], '', 'Null attribute value #2.'],
33 // Verify multiple attributes are rendered.
37 'class' => ['first', 'last'],
40 ' id="id-test" class="first last" alt="Alternate"',
41 'Multiple attributes.',
43 // Verify empty attributes array is rendered.
44 [[], '', 'Empty attributes array.'],
49 * Tests casting an Attribute object to a string.
51 * @see \Drupal\Core\Template\Attribute::__toString()
53 * @dataProvider providerTestAttributeData
55 public function testDrupalAttributes($attributes, $expected, $message) {
56 $this->assertSame($expected, (string) new Attribute($attributes), $message);
60 * Test attribute iteration
62 public function testAttributeIteration() {
63 $attribute = new Attribute(['key1' => 'value1']);
64 foreach ($attribute as $value) {
65 $this->assertSame((string) $value, 'value1', 'Iterate over attribute.');
70 * Test AttributeValueBase copy.
72 public function testAttributeValueBaseCopy() {
73 $original_attributes = new Attribute([
75 'class' => ['who', 'is', 'on'],
78 $attributes['selected'] = $original_attributes['checked'];
79 $attributes['id'] = $original_attributes['id'];
80 $attributes = new Attribute($attributes);
81 $this->assertSame(' checked class="who is on" id="first"', (string) $original_attributes, 'Original boolean value used with original name.');
82 $this->assertSame(' selected id="first"', (string) $attributes, 'Original boolean value used with new name.');