test_html.py 13 KB

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