test_html.py 13 KB

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