HtmlEscapedTextTest.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace Drupal\Tests\Component\Render;
  3. use Drupal\Component\Render\HtmlEscapedText;
  4. use Drupal\Component\Render\MarkupInterface;
  5. use PHPUnit\Framework\TestCase;
  6. /**
  7. * Tests the HtmlEscapedText class.
  8. *
  9. * @coversDefaultClass \Drupal\Component\Render\HtmlEscapedText
  10. * @group utility
  11. */
  12. class HtmlEscapedTextTest extends TestCase {
  13. /**
  14. * @covers ::__toString
  15. * @covers ::jsonSerialize
  16. *
  17. * @dataProvider providerToString
  18. */
  19. public function testToString($text, $expected, $message) {
  20. $escapeable_string = new HtmlEscapedText($text);
  21. $this->assertEquals($expected, (string) $escapeable_string, $message);
  22. $this->assertEquals($expected, $escapeable_string->jsonSerialize());
  23. }
  24. /**
  25. * Data provider for testToString().
  26. *
  27. * @see testToString()
  28. */
  29. public function providerToString() {
  30. // Checks that invalid multi-byte sequences are escaped.
  31. $tests[] = ["Foo\xC0barbaz", 'Foo�barbaz', 'Escapes invalid sequence "Foo\xC0barbaz"'];
  32. $tests[] = ["\xc2\"", '�&quot;', 'Escapes invalid sequence "\xc2\""'];
  33. $tests[] = ["Fooÿñ", "Fooÿñ", 'Does not escape valid sequence "Fooÿñ"'];
  34. // Checks that special characters are escaped.
  35. $script_tag = $this->prophesize(MarkupInterface::class);
  36. $script_tag->__toString()->willReturn('<script>');
  37. $script_tag = $script_tag->reveal();
  38. $tests[] = [$script_tag, '&lt;script&gt;', 'Escapes &lt;script&gt; even inside an object that implements MarkupInterface.'];
  39. $tests[] = ["<script>", '&lt;script&gt;', 'Escapes &lt;script&gt;'];
  40. $tests[] = ['<>&"\'', '&lt;&gt;&amp;&quot;&#039;', 'Escapes reserved HTML characters.'];
  41. $specialchars = $this->prophesize(MarkupInterface::class);
  42. $specialchars->__toString()->willReturn('<>&"\'');
  43. $specialchars = $specialchars->reveal();
  44. $tests[] = [$specialchars, '&lt;&gt;&amp;&quot;&#039;', 'Escapes reserved HTML characters even inside an object that implements MarkupInterface.'];
  45. return $tests;
  46. }
  47. /**
  48. * @covers ::count
  49. */
  50. public function testCount() {
  51. $string = 'Can I please have a <em>kitten</em>';
  52. $escapeable_string = new HtmlEscapedText($string);
  53. $this->assertEquals(strlen($string), $escapeable_string->count());
  54. }
  55. }