test_html.py 15 KB

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