test_html.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import os
  2. from datetime import datetime
  3. from django.test import SimpleTestCase
  4. from django.utils.functional import lazystr
  5. from django.utils.html import (
  6. conditional_escape, escape, escapejs, format_html, html_safe, json_script,
  7. linebreaks, smart_urlquote, strip_spaces_between_tags, strip_tags, urlize,
  8. )
  9. from django.utils.safestring import mark_safe
  10. class TestUtilsHtml(SimpleTestCase):
  11. def check_output(self, function, value, output=None):
  12. """
  13. function(value) equals output. If output is None, function(value)
  14. equals value.
  15. """
  16. if output is None:
  17. output = value
  18. self.assertEqual(function(value), output)
  19. def test_escape(self):
  20. items = (
  21. ('&', '&'),
  22. ('<', '&lt;'),
  23. ('>', '&gt;'),
  24. ('"', '&quot;'),
  25. ("'", '&#x27;'),
  26. )
  27. # Substitution patterns for testing the above items.
  28. patterns = ("%s", "asdf%sfdsa", "%s1", "1%sb")
  29. for value, output in items:
  30. with self.subTest(value=value, output=output):
  31. for pattern in patterns:
  32. with self.subTest(value=value, output=output, pattern=pattern):
  33. self.check_output(escape, pattern % value, pattern % output)
  34. self.check_output(escape, lazystr(pattern % value), pattern % output)
  35. # Check repeated values.
  36. self.check_output(escape, value * 2, output * 2)
  37. # Verify it doesn't double replace &.
  38. self.check_output(escape, '<&', '&lt;&amp;')
  39. def test_format_html(self):
  40. self.assertEqual(
  41. format_html(
  42. "{} {} {third} {fourth}",
  43. "< Dangerous >",
  44. mark_safe("<b>safe</b>"),
  45. third="< dangerous again",
  46. fourth=mark_safe("<i>safe again</i>"),
  47. ),
  48. "&lt; Dangerous &gt; <b>safe</b> &lt; dangerous again <i>safe again</i>"
  49. )
  50. def test_linebreaks(self):
  51. items = (
  52. ("para1\n\npara2\r\rpara3", "<p>para1</p>\n\n<p>para2</p>\n\n<p>para3</p>"),
  53. ("para1\nsub1\rsub2\n\npara2", "<p>para1<br>sub1<br>sub2</p>\n\n<p>para2</p>"),
  54. ("para1\r\n\r\npara2\rsub1\r\rpara4", "<p>para1</p>\n\n<p>para2<br>sub1</p>\n\n<p>para4</p>"),
  55. ("para1\tmore\n\npara2", "<p>para1\tmore</p>\n\n<p>para2</p>"),
  56. )
  57. for value, output in items:
  58. with self.subTest(value=value, output=output):
  59. self.check_output(linebreaks, value, output)
  60. self.check_output(linebreaks, lazystr(value), output)
  61. def test_strip_tags(self):
  62. items = (
  63. ('<p>See: &#39;&eacute; is an apostrophe followed by e acute</p>',
  64. 'See: &#39;&eacute; is an apostrophe followed by e acute'),
  65. ('<p>See: &#x27;&eacute; is an apostrophe followed by e acute</p>',
  66. 'See: &#x27;&eacute; is an apostrophe followed by e acute'),
  67. ('<adf>a', 'a'),
  68. ('</adf>a', 'a'),
  69. ('<asdf><asdf>e', 'e'),
  70. ('hi, <f x', 'hi, <f x'),
  71. ('234<235, right?', '234<235, right?'),
  72. ('a4<a5 right?', 'a4<a5 right?'),
  73. ('b7>b2!', 'b7>b2!'),
  74. ('</fe', '</fe'),
  75. ('<x>b<y>', 'b'),
  76. ('a<p onclick="alert(\'<test>\')">b</p>c', 'abc'),
  77. ('a<p a >b</p>c', 'abc'),
  78. ('d<a:b c:d>e</p>f', 'def'),
  79. ('<strong>foo</strong><a href="http://example.com">bar</a>', 'foobar'),
  80. # caused infinite loop on Pythons not patched with
  81. # https://bugs.python.org/issue20288
  82. ('&gotcha&#;<>', '&gotcha&#;<>'),
  83. ('<sc<!-- -->ript>test<<!-- -->/script>', 'ript>test'),
  84. ('<script>alert()</script>&h', 'alert()h'),
  85. ('><!' + ('&' * 16000) + 'D', '><!' + ('&' * 16000) + 'D'),
  86. ('X<<<<br>br>br>br>X', 'XX'),
  87. )
  88. for value, output in items:
  89. with self.subTest(value=value, output=output):
  90. self.check_output(strip_tags, value, output)
  91. self.check_output(strip_tags, lazystr(value), output)
  92. def test_strip_tags_files(self):
  93. # Test with more lengthy content (also catching performance regressions)
  94. for filename in ('strip_tags1.html', 'strip_tags2.txt'):
  95. with self.subTest(filename=filename):
  96. path = os.path.join(os.path.dirname(__file__), 'files', filename)
  97. with open(path) as fp:
  98. content = fp.read()
  99. start = datetime.now()
  100. stripped = strip_tags(content)
  101. elapsed = datetime.now() - start
  102. self.assertEqual(elapsed.seconds, 0)
  103. self.assertIn("Please try again.", stripped)
  104. self.assertNotIn('<', stripped)
  105. def test_strip_spaces_between_tags(self):
  106. # Strings that should come out untouched.
  107. items = (' <adf>', '<adf> ', ' </adf> ', ' <f> x</f>')
  108. for value in items:
  109. with self.subTest(value=value):
  110. self.check_output(strip_spaces_between_tags, value)
  111. self.check_output(strip_spaces_between_tags, lazystr(value))
  112. # Strings that have spaces to strip.
  113. items = (
  114. ('<d> </d>', '<d></d>'),
  115. ('<p>hello </p>\n<p> world</p>', '<p>hello </p><p> world</p>'),
  116. ('\n<p>\t</p>\n<p> </p>\n', '\n<p></p><p></p>\n'),
  117. )
  118. for value, output in items:
  119. with self.subTest(value=value, output=output):
  120. self.check_output(strip_spaces_between_tags, value, output)
  121. self.check_output(strip_spaces_between_tags, lazystr(value), output)
  122. def test_escapejs(self):
  123. items = (
  124. ('"double quotes" and \'single quotes\'', '\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027'),
  125. (r'\ : backslashes, too', '\\u005C : backslashes, too'),
  126. (
  127. 'and lots of whitespace: \r\n\t\v\f\b',
  128. 'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008'
  129. ),
  130. (r'<script>and this</script>', '\\u003Cscript\\u003Eand this\\u003C/script\\u003E'),
  131. (
  132. 'paragraph separator:\u2029and line separator:\u2028',
  133. 'paragraph separator:\\u2029and line separator:\\u2028'
  134. ),
  135. ('`', '\\u0060'),
  136. )
  137. for value, output in items:
  138. with self.subTest(value=value, output=output):
  139. self.check_output(escapejs, value, output)
  140. self.check_output(escapejs, lazystr(value), output)
  141. def test_json_script(self):
  142. tests = (
  143. # "<", ">" and "&" are quoted inside JSON strings
  144. (('&<>', '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"</script>')),
  145. # "<", ">" and "&" are quoted inside JSON objects
  146. (
  147. {'a': '<script>test&ing</script>'},
  148. '<script id="test_id" type="application/json">'
  149. '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}</script>'
  150. ),
  151. # Lazy strings are quoted
  152. (lazystr('&<>'), '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"</script>'),
  153. (
  154. {'a': lazystr('<script>test&ing</script>')},
  155. '<script id="test_id" type="application/json">'
  156. '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}</script>'
  157. ),
  158. )
  159. for arg, expected in tests:
  160. with self.subTest(arg=arg):
  161. self.assertEqual(json_script(arg, 'test_id'), expected)
  162. def test_json_script_without_id(self):
  163. self.assertHTMLEqual(
  164. json_script({'key': 'value'}),
  165. '<script type="application/json">{"key": "value"}</script>',
  166. )
  167. def test_smart_urlquote(self):
  168. items = (
  169. ('http://öäü.com/', 'http://xn--4ca9at.com/'),
  170. ('http://öäü.com/öäü/', 'http://xn--4ca9at.com/%C3%B6%C3%A4%C3%BC/'),
  171. # Everything unsafe is quoted, !*'();:@&=+$,/?#[]~ is considered
  172. # safe as per RFC.
  173. ('http://example.com/path/öäü/', 'http://example.com/path/%C3%B6%C3%A4%C3%BC/'),
  174. ('http://example.com/%C3%B6/ä/', 'http://example.com/%C3%B6/%C3%A4/'),
  175. ('http://example.com/?x=1&y=2+3&z=', 'http://example.com/?x=1&y=2+3&z='),
  176. ('http://example.com/?x=<>"\'', 'http://example.com/?x=%3C%3E%22%27'),
  177. ('http://example.com/?q=http://example.com/?x=1%26q=django',
  178. 'http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango'),
  179. ('http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango',
  180. 'http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango'),
  181. ('http://.www.f oo.bar/', 'http://.www.f%20oo.bar/'),
  182. )
  183. # IDNs are properly quoted
  184. for value, output in items:
  185. with self.subTest(value=value, output=output):
  186. self.assertEqual(smart_urlquote(value), output)
  187. def test_conditional_escape(self):
  188. s = '<h1>interop</h1>'
  189. self.assertEqual(conditional_escape(s), '&lt;h1&gt;interop&lt;/h1&gt;')
  190. self.assertEqual(conditional_escape(mark_safe(s)), s)
  191. self.assertEqual(conditional_escape(lazystr(mark_safe(s))), s)
  192. def test_html_safe(self):
  193. @html_safe
  194. class HtmlClass:
  195. def __str__(self):
  196. return "<h1>I'm a html class!</h1>"
  197. html_obj = HtmlClass()
  198. self.assertTrue(hasattr(HtmlClass, '__html__'))
  199. self.assertTrue(hasattr(html_obj, '__html__'))
  200. self.assertEqual(str(html_obj), html_obj.__html__())
  201. def test_html_safe_subclass(self):
  202. class BaseClass:
  203. def __html__(self):
  204. # defines __html__ on its own
  205. return 'some html content'
  206. def __str__(self):
  207. return 'some non html content'
  208. @html_safe
  209. class Subclass(BaseClass):
  210. def __str__(self):
  211. # overrides __str__ and is marked as html_safe
  212. return 'some html safe content'
  213. subclass_obj = Subclass()
  214. self.assertEqual(str(subclass_obj), subclass_obj.__html__())
  215. def test_html_safe_defines_html_error(self):
  216. msg = "can't apply @html_safe to HtmlClass because it defines __html__()."
  217. with self.assertRaisesMessage(ValueError, msg):
  218. @html_safe
  219. class HtmlClass:
  220. def __html__(self):
  221. return "<h1>I'm a html class!</h1>"
  222. def test_html_safe_doesnt_define_str(self):
  223. msg = "can't apply @html_safe to HtmlClass because it doesn't define __str__()."
  224. with self.assertRaisesMessage(ValueError, msg):
  225. @html_safe
  226. class HtmlClass:
  227. pass
  228. def test_urlize(self):
  229. tests = (
  230. (
  231. 'Search for google.com/?q=! and see.',
  232. 'Search for <a href="http://google.com/?q=">google.com/?q=</a>! and see.'
  233. ),
  234. (
  235. 'Search for google.com/?q=1&lt! and see.',
  236. 'Search for <a href="http://google.com/?q=1%3C">google.com/?q=1&lt</a>! and see.'
  237. ),
  238. (
  239. lazystr('Search for google.com/?q=!'),
  240. 'Search for <a href="http://google.com/?q=">google.com/?q=</a>!'
  241. ),
  242. ('foo@example.com', '<a href="mailto:foo@example.com">foo@example.com</a>'),
  243. )
  244. for value, output in tests:
  245. with self.subTest(value=value):
  246. self.assertEqual(urlize(value), output)
  247. def test_urlize_unchanged_inputs(self):
  248. tests = (
  249. ('a' + '@a' * 50000) + 'a', # simple_email_re catastrophic test
  250. ('a' + '.' * 1000000) + 'a', # trailing_punctuation catastrophic test
  251. 'foo@',
  252. '@foo.com',
  253. 'foo@.example.com',
  254. 'foo@localhost',
  255. 'foo@localhost.',
  256. )
  257. for value in tests:
  258. with self.subTest(value=value):
  259. self.assertEqual(urlize(value), value)