escape_test.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import unittest
  2. import tornado
  3. from tornado.escape import (
  4. utf8,
  5. xhtml_escape,
  6. xhtml_unescape,
  7. url_escape,
  8. url_unescape,
  9. to_unicode,
  10. json_decode,
  11. json_encode,
  12. squeeze,
  13. recursive_unicode,
  14. )
  15. from tornado.util import unicode_type
  16. from typing import List, Tuple, Union, Dict, Any # noqa: F401
  17. linkify_tests = [
  18. # (input, linkify_kwargs, expected_output)
  19. (
  20. "hello http://world.com/!",
  21. {},
  22. 'hello <a href="http://world.com/">http://world.com/</a>!',
  23. ),
  24. (
  25. "hello http://world.com/with?param=true&stuff=yes",
  26. {},
  27. 'hello <a href="http://world.com/with?param=true&amp;stuff=yes">http://world.com/with?param=true&amp;stuff=yes</a>', # noqa: E501
  28. ),
  29. # an opened paren followed by many chars killed Gruber's regex
  30. (
  31. "http://url.com/w(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  32. {},
  33. '<a href="http://url.com/w">http://url.com/w</a>(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', # noqa: E501
  34. ),
  35. # as did too many dots at the end
  36. (
  37. "http://url.com/withmany.......................................",
  38. {},
  39. '<a href="http://url.com/withmany">http://url.com/withmany</a>.......................................', # noqa: E501
  40. ),
  41. (
  42. "http://url.com/withmany((((((((((((((((((((((((((((((((((a)",
  43. {},
  44. '<a href="http://url.com/withmany">http://url.com/withmany</a>((((((((((((((((((((((((((((((((((a)', # noqa: E501
  45. ),
  46. # some examples from http://daringfireball.net/2009/11/liberal_regex_for_matching_urls
  47. # plus a fex extras (such as multiple parentheses).
  48. (
  49. "http://foo.com/blah_blah",
  50. {},
  51. '<a href="http://foo.com/blah_blah">http://foo.com/blah_blah</a>',
  52. ),
  53. (
  54. "http://foo.com/blah_blah/",
  55. {},
  56. '<a href="http://foo.com/blah_blah/">http://foo.com/blah_blah/</a>',
  57. ),
  58. (
  59. "(Something like http://foo.com/blah_blah)",
  60. {},
  61. '(Something like <a href="http://foo.com/blah_blah">http://foo.com/blah_blah</a>)',
  62. ),
  63. (
  64. "http://foo.com/blah_blah_(wikipedia)",
  65. {},
  66. '<a href="http://foo.com/blah_blah_(wikipedia)">http://foo.com/blah_blah_(wikipedia)</a>',
  67. ),
  68. (
  69. "http://foo.com/blah_(blah)_(wikipedia)_blah",
  70. {},
  71. '<a href="http://foo.com/blah_(blah)_(wikipedia)_blah">http://foo.com/blah_(blah)_(wikipedia)_blah</a>', # noqa: E501
  72. ),
  73. (
  74. "(Something like http://foo.com/blah_blah_(wikipedia))",
  75. {},
  76. '(Something like <a href="http://foo.com/blah_blah_(wikipedia)">http://foo.com/blah_blah_(wikipedia)</a>)', # noqa: E501
  77. ),
  78. (
  79. "http://foo.com/blah_blah.",
  80. {},
  81. '<a href="http://foo.com/blah_blah">http://foo.com/blah_blah</a>.',
  82. ),
  83. (
  84. "http://foo.com/blah_blah/.",
  85. {},
  86. '<a href="http://foo.com/blah_blah/">http://foo.com/blah_blah/</a>.',
  87. ),
  88. (
  89. "<http://foo.com/blah_blah>",
  90. {},
  91. '&lt;<a href="http://foo.com/blah_blah">http://foo.com/blah_blah</a>&gt;',
  92. ),
  93. (
  94. "<http://foo.com/blah_blah/>",
  95. {},
  96. '&lt;<a href="http://foo.com/blah_blah/">http://foo.com/blah_blah/</a>&gt;',
  97. ),
  98. (
  99. "http://foo.com/blah_blah,",
  100. {},
  101. '<a href="http://foo.com/blah_blah">http://foo.com/blah_blah</a>,',
  102. ),
  103. (
  104. "http://www.example.com/wpstyle/?p=364.",
  105. {},
  106. '<a href="http://www.example.com/wpstyle/?p=364">http://www.example.com/wpstyle/?p=364</a>.', # noqa: E501
  107. ),
  108. (
  109. "rdar://1234",
  110. {"permitted_protocols": ["http", "rdar"]},
  111. '<a href="rdar://1234">rdar://1234</a>',
  112. ),
  113. (
  114. "rdar:/1234",
  115. {"permitted_protocols": ["rdar"]},
  116. '<a href="rdar:/1234">rdar:/1234</a>',
  117. ),
  118. (
  119. "http://userid:password@example.com:8080",
  120. {},
  121. '<a href="http://userid:password@example.com:8080">http://userid:password@example.com:8080</a>', # noqa: E501
  122. ),
  123. (
  124. "http://userid@example.com",
  125. {},
  126. '<a href="http://userid@example.com">http://userid@example.com</a>',
  127. ),
  128. (
  129. "http://userid@example.com:8080",
  130. {},
  131. '<a href="http://userid@example.com:8080">http://userid@example.com:8080</a>',
  132. ),
  133. (
  134. "http://userid:password@example.com",
  135. {},
  136. '<a href="http://userid:password@example.com">http://userid:password@example.com</a>',
  137. ),
  138. (
  139. "message://%3c330e7f8409726r6a4ba78dkf1fd71420c1bf6ff@mail.gmail.com%3e",
  140. {"permitted_protocols": ["http", "message"]},
  141. '<a href="message://%3c330e7f8409726r6a4ba78dkf1fd71420c1bf6ff@mail.gmail.com%3e">'
  142. "message://%3c330e7f8409726r6a4ba78dkf1fd71420c1bf6ff@mail.gmail.com%3e</a>",
  143. ),
  144. (
  145. "http://\u27a1.ws/\u4a39",
  146. {},
  147. '<a href="http://\u27a1.ws/\u4a39">http://\u27a1.ws/\u4a39</a>',
  148. ),
  149. (
  150. "<tag>http://example.com</tag>",
  151. {},
  152. '&lt;tag&gt;<a href="http://example.com">http://example.com</a>&lt;/tag&gt;',
  153. ),
  154. (
  155. "Just a www.example.com link.",
  156. {},
  157. 'Just a <a href="http://www.example.com">www.example.com</a> link.',
  158. ),
  159. (
  160. "Just a www.example.com link.",
  161. {"require_protocol": True},
  162. "Just a www.example.com link.",
  163. ),
  164. (
  165. "A http://reallylong.com/link/that/exceedsthelenglimit.html",
  166. {"require_protocol": True, "shorten": True},
  167. 'A <a href="http://reallylong.com/link/that/exceedsthelenglimit.html"'
  168. ' title="http://reallylong.com/link/that/exceedsthelenglimit.html">http://reallylong.com/link...</a>', # noqa: E501
  169. ),
  170. (
  171. "A http://reallylongdomainnamethatwillbetoolong.com/hi!",
  172. {"shorten": True},
  173. 'A <a href="http://reallylongdomainnamethatwillbetoolong.com/hi"'
  174. ' title="http://reallylongdomainnamethatwillbetoolong.com/hi">http://reallylongdomainnametha...</a>!', # noqa: E501
  175. ),
  176. (
  177. "A file:///passwords.txt and http://web.com link",
  178. {},
  179. 'A file:///passwords.txt and <a href="http://web.com">http://web.com</a> link',
  180. ),
  181. (
  182. "A file:///passwords.txt and http://web.com link",
  183. {"permitted_protocols": ["file"]},
  184. 'A <a href="file:///passwords.txt">file:///passwords.txt</a> and http://web.com link',
  185. ),
  186. (
  187. "www.external-link.com",
  188. {"extra_params": 'rel="nofollow" class="external"'},
  189. '<a href="http://www.external-link.com" rel="nofollow" class="external">www.external-link.com</a>', # noqa: E501
  190. ),
  191. (
  192. "www.external-link.com and www.internal-link.com/blogs extra",
  193. {
  194. "extra_params": lambda href: (
  195. 'class="internal"'
  196. if href.startswith("http://www.internal-link.com")
  197. else 'rel="nofollow" class="external"'
  198. )
  199. },
  200. '<a href="http://www.external-link.com" rel="nofollow" class="external">www.external-link.com</a>' # noqa: E501
  201. ' and <a href="http://www.internal-link.com/blogs" class="internal">www.internal-link.com/blogs</a> extra', # noqa: E501
  202. ),
  203. (
  204. "www.external-link.com",
  205. {"extra_params": lambda href: ' rel="nofollow" class="external" '},
  206. '<a href="http://www.external-link.com" rel="nofollow" class="external">www.external-link.com</a>', # noqa: E501
  207. ),
  208. ] # type: List[Tuple[Union[str, bytes], Dict[str, Any], str]]
  209. class EscapeTestCase(unittest.TestCase):
  210. def test_linkify(self):
  211. for text, kwargs, html in linkify_tests:
  212. linked = tornado.escape.linkify(text, **kwargs)
  213. self.assertEqual(linked, html)
  214. def test_xhtml_escape(self):
  215. tests = [
  216. ("<foo>", "&lt;foo&gt;"),
  217. ("<foo>", "&lt;foo&gt;"),
  218. (b"<foo>", b"&lt;foo&gt;"),
  219. ("<>&\"'", "&lt;&gt;&amp;&quot;&#x27;"),
  220. ("&amp;", "&amp;amp;"),
  221. ("<\u00e9>", "&lt;\u00e9&gt;"),
  222. (b"<\xc3\xa9>", b"&lt;\xc3\xa9&gt;"),
  223. ] # type: List[Tuple[Union[str, bytes], Union[str, bytes]]]
  224. for unescaped, escaped in tests:
  225. self.assertEqual(utf8(xhtml_escape(unescaped)), utf8(escaped))
  226. self.assertEqual(utf8(unescaped), utf8(xhtml_unescape(escaped)))
  227. def test_xhtml_unescape_numeric(self):
  228. tests = [
  229. ("foo&#32;bar", "foo bar"),
  230. ("foo&#x20;bar", "foo bar"),
  231. ("foo&#X20;bar", "foo bar"),
  232. ("foo&#xabc;bar", "foo\u0abcbar"),
  233. ("foo&#xyz;bar", "foo&#xyz;bar"), # invalid encoding
  234. ("foo&#;bar", "foo&#;bar"), # invalid encoding
  235. ("foo&#x;bar", "foo&#x;bar"), # invalid encoding
  236. ]
  237. for escaped, unescaped in tests:
  238. self.assertEqual(unescaped, xhtml_unescape(escaped))
  239. def test_url_escape_unicode(self):
  240. tests = [
  241. # byte strings are passed through as-is
  242. ("\u00e9".encode(), "%C3%A9"),
  243. ("\u00e9".encode("latin1"), "%E9"),
  244. # unicode strings become utf8
  245. ("\u00e9", "%C3%A9"),
  246. ] # type: List[Tuple[Union[str, bytes], str]]
  247. for unescaped, escaped in tests:
  248. self.assertEqual(url_escape(unescaped), escaped)
  249. def test_url_unescape_unicode(self):
  250. tests = [
  251. ("%C3%A9", "\u00e9", "utf8"),
  252. ("%C3%A9", "\u00c3\u00a9", "latin1"),
  253. ("%C3%A9", utf8("\u00e9"), None),
  254. ]
  255. for escaped, unescaped, encoding in tests:
  256. # input strings to url_unescape should only contain ascii
  257. # characters, but make sure the function accepts both byte
  258. # and unicode strings.
  259. self.assertEqual(url_unescape(to_unicode(escaped), encoding), unescaped)
  260. self.assertEqual(url_unescape(utf8(escaped), encoding), unescaped)
  261. def test_url_escape_quote_plus(self):
  262. unescaped = "+ #%"
  263. plus_escaped = "%2B+%23%25"
  264. escaped = "%2B%20%23%25"
  265. self.assertEqual(url_escape(unescaped), plus_escaped)
  266. self.assertEqual(url_escape(unescaped, plus=False), escaped)
  267. self.assertEqual(url_unescape(plus_escaped), unescaped)
  268. self.assertEqual(url_unescape(escaped, plus=False), unescaped)
  269. self.assertEqual(url_unescape(plus_escaped, encoding=None), utf8(unescaped))
  270. self.assertEqual(
  271. url_unescape(escaped, encoding=None, plus=False), utf8(unescaped)
  272. )
  273. def test_escape_return_types(self):
  274. # On python2 the escape methods should generally return the same
  275. # type as their argument
  276. self.assertEqual(type(xhtml_escape("foo")), str)
  277. self.assertEqual(type(xhtml_escape("foo")), unicode_type)
  278. def test_json_decode(self):
  279. # json_decode accepts both bytes and unicode, but strings it returns
  280. # are always unicode.
  281. self.assertEqual(json_decode(b'"foo"'), "foo")
  282. self.assertEqual(json_decode('"foo"'), "foo")
  283. # Non-ascii bytes are interpreted as utf8
  284. self.assertEqual(json_decode(utf8('"\u00e9"')), "\u00e9")
  285. def test_json_encode(self):
  286. # json deals with strings, not bytes. On python 2 byte strings will
  287. # convert automatically if they are utf8; on python 3 byte strings
  288. # are not allowed.
  289. self.assertEqual(json_decode(json_encode("\u00e9")), "\u00e9")
  290. if bytes is str:
  291. self.assertEqual(json_decode(json_encode(utf8("\u00e9"))), "\u00e9")
  292. self.assertRaises(UnicodeDecodeError, json_encode, b"\xe9")
  293. def test_squeeze(self):
  294. self.assertEqual(
  295. squeeze("sequences of whitespace chars"),
  296. "sequences of whitespace chars",
  297. )
  298. def test_recursive_unicode(self):
  299. tests = {
  300. "dict": {b"foo": b"bar"},
  301. "list": [b"foo", b"bar"],
  302. "tuple": (b"foo", b"bar"),
  303. "bytes": b"foo",
  304. }
  305. self.assertEqual(recursive_unicode(tests["dict"]), {"foo": "bar"})
  306. self.assertEqual(recursive_unicode(tests["list"]), ["foo", "bar"])
  307. self.assertEqual(recursive_unicode(tests["tuple"]), ("foo", "bar"))
  308. self.assertEqual(recursive_unicode(tests["bytes"]), "foo")