test_html.py 17 KB

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