test_html.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from datetime import datetime
  4. import os
  5. from unittest import TestCase
  6. import warnings
  7. from django.utils import html, safestring
  8. from django.utils._os import upath
  9. from django.utils.encoding import force_text
  10. class TestUtilsHtml(TestCase):
  11. def check_output(self, function, value, output=None):
  12. """
  13. Check that function(value) equals output. If output is None,
  14. check that function(value) equals value.
  15. """
  16. if output is None:
  17. output = value
  18. self.assertEqual(function(value), output)
  19. def test_escape(self):
  20. f = html.escape
  21. items = (
  22. ('&', '&'),
  23. ('<', '&lt;'),
  24. ('>', '&gt;'),
  25. ('"', '&quot;'),
  26. ("'", '&#39;'),
  27. )
  28. # Substitution patterns for testing the above items.
  29. patterns = ("%s", "asdf%sfdsa", "%s1", "1%sb")
  30. for value, output in items:
  31. for pattern in patterns:
  32. self.check_output(f, pattern % value, pattern % output)
  33. # Check repeated values.
  34. self.check_output(f, value * 2, output * 2)
  35. # Verify it doesn't double replace &.
  36. self.check_output(f, '<&', '&lt;&amp;')
  37. def test_format_html(self):
  38. self.assertEqual(
  39. html.format_html("{} {} {third} {fourth}",
  40. "< Dangerous >",
  41. html.mark_safe("<b>safe</b>"),
  42. third="< dangerous again",
  43. fourth=html.mark_safe("<i>safe again</i>")
  44. ),
  45. "&lt; Dangerous &gt; <b>safe</b> &lt; dangerous again <i>safe again</i>"
  46. )
  47. def test_linebreaks(self):
  48. f = html.linebreaks
  49. items = (
  50. ("para1\n\npara2\r\rpara3", "<p>para1</p>\n\n<p>para2</p>\n\n<p>para3</p>"),
  51. ("para1\nsub1\rsub2\n\npara2", "<p>para1<br />sub1<br />sub2</p>\n\n<p>para2</p>"),
  52. ("para1\r\n\r\npara2\rsub1\r\rpara4", "<p>para1</p>\n\n<p>para2<br />sub1</p>\n\n<p>para4</p>"),
  53. ("para1\tmore\n\npara2", "<p>para1\tmore</p>\n\n<p>para2</p>"),
  54. )
  55. for value, output in items:
  56. self.check_output(f, value, output)
  57. def test_strip_tags(self):
  58. f = html.strip_tags
  59. items = (
  60. ('<p>See: &#39;&eacute; is an apostrophe followed by e acute</p>',
  61. 'See: &#39;&eacute; is an apostrophe followed by e acute'),
  62. ('<adf>a', 'a'),
  63. ('</adf>a', 'a'),
  64. ('<asdf><asdf>e', 'e'),
  65. ('hi, <f x', 'hi, <f x'),
  66. ('234<235, right?', '234<235, right?'),
  67. ('a4<a5 right?', 'a4<a5 right?'),
  68. ('b7>b2!', 'b7>b2!'),
  69. ('</fe', '</fe'),
  70. ('<x>b<y>', 'b'),
  71. ('a<p onclick="alert(\'<test>\')">b</p>c', 'abc'),
  72. ('a<p a >b</p>c', 'abc'),
  73. ('d<a:b c:d>e</p>f', 'def'),
  74. ('<strong>foo</strong><a href="http://example.com">bar</a>', 'foobar'),
  75. )
  76. for value, output in items:
  77. self.check_output(f, value, output)
  78. # Some convoluted syntax for which parsing may differ between python versions
  79. output = html.strip_tags('<sc<!-- -->ript>test<<!-- -->/script>')
  80. self.assertNotIn('<script>', output)
  81. self.assertIn('test', output)
  82. output = html.strip_tags('<script>alert()</script>&h')
  83. self.assertNotIn('<script>', output)
  84. self.assertIn('alert()', output)
  85. # Test with more lengthy content (also catching performance regressions)
  86. for filename in ('strip_tags1.html', 'strip_tags2.txt'):
  87. path = os.path.join(os.path.dirname(upath(__file__)), 'files', filename)
  88. with open(path, 'r') as fp:
  89. content = force_text(fp.read())
  90. start = datetime.now()
  91. stripped = html.strip_tags(content)
  92. elapsed = datetime.now() - start
  93. self.assertEqual(elapsed.seconds, 0)
  94. self.assertIn("Please try again.", stripped)
  95. self.assertNotIn('<', stripped)
  96. def test_strip_spaces_between_tags(self):
  97. f = html.strip_spaces_between_tags
  98. # Strings that should come out untouched.
  99. items = (' <adf>', '<adf> ', ' </adf> ', ' <f> x</f>')
  100. for value in items:
  101. self.check_output(f, value)
  102. # Strings that have spaces to strip.
  103. items = (
  104. ('<d> </d>', '<d></d>'),
  105. ('<p>hello </p>\n<p> world</p>', '<p>hello </p><p> world</p>'),
  106. ('\n<p>\t</p>\n<p> </p>\n', '\n<p></p><p></p>\n'),
  107. )
  108. for value, output in items:
  109. self.check_output(f, value, output)
  110. def test_strip_entities(self):
  111. f = html.strip_entities
  112. # Strings that should come out untouched.
  113. values = ("&", "&a", "&a", "a&#a")
  114. for value in values:
  115. with warnings.catch_warnings(record=True):
  116. warnings.simplefilter("always")
  117. self.check_output(f, value)
  118. # Valid entities that should be stripped from the patterns.
  119. entities = ("&#1;", "&#12;", "&a;", "&fdasdfasdfasdf;")
  120. patterns = (
  121. ("asdf %(entity)s ", "asdf "),
  122. ("%(entity)s%(entity)s", ""),
  123. ("&%(entity)s%(entity)s", "&"),
  124. ("%(entity)s3", "3"),
  125. )
  126. for entity in entities:
  127. for in_pattern, output in patterns:
  128. with warnings.catch_warnings(record=True):
  129. warnings.simplefilter("always")
  130. self.check_output(f, in_pattern % {'entity': entity}, output)
  131. def test_escapejs(self):
  132. f = html.escapejs
  133. items = (
  134. ('"double quotes" and \'single quotes\'', '\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027'),
  135. (r'\ : backslashes, too', '\\u005C : backslashes, too'),
  136. ('and lots of whitespace: \r\n\t\v\f\b', 'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008'),
  137. (r'<script>and this</script>', '\\u003Cscript\\u003Eand this\\u003C/script\\u003E'),
  138. ('paragraph separator:\u2029and line separator:\u2028', 'paragraph separator:\\u2029and line separator:\\u2028'),
  139. )
  140. for value, output in items:
  141. self.check_output(f, value, output)
  142. def test_remove_tags(self):
  143. f = html.remove_tags
  144. items = (
  145. ("<b><i>Yes</i></b>", "b i", "Yes"),
  146. ("<a>x</a> <p><b>y</b></p>", "a b", "x <p>y</p>"),
  147. )
  148. for value, tags, output in items:
  149. with warnings.catch_warnings(record=True):
  150. warnings.simplefilter("always")
  151. self.assertEqual(f(value, tags), output)
  152. def test_smart_urlquote(self):
  153. quote = html.smart_urlquote
  154. # Ensure that IDNs are properly quoted
  155. self.assertEqual(quote('http://öäü.com/'), 'http://xn--4ca9at.com/')
  156. self.assertEqual(quote('http://öäü.com/öäü/'), 'http://xn--4ca9at.com/%C3%B6%C3%A4%C3%BC/')
  157. # Ensure that everything unsafe is quoted, !*'();:@&=+$,/?#[]~ is considered safe as per RFC
  158. self.assertEqual(quote('http://example.com/path/öäü/'), 'http://example.com/path/%C3%B6%C3%A4%C3%BC/')
  159. self.assertEqual(quote('http://example.com/%C3%B6/ä/'), 'http://example.com/%C3%B6/%C3%A4/')
  160. self.assertEqual(quote('http://example.com/?x=1&y=2+3&z='), 'http://example.com/?x=1&y=2+3&z=')
  161. self.assertEqual(quote('http://example.com/?x=<>"\''), 'http://example.com/?x=%3C%3E%22%27')
  162. self.assertEqual(quote('http://example.com/?q=http://example.com/?x=1%26q=django'),
  163. 'http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango')
  164. self.assertEqual(quote('http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango'),
  165. 'http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango')
  166. def test_conditional_escape(self):
  167. s = '<h1>interop</h1>'
  168. self.assertEqual(html.conditional_escape(s),
  169. '&lt;h1&gt;interop&lt;/h1&gt;')
  170. self.assertEqual(html.conditional_escape(safestring.mark_safe(s)), s)