escape_test.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. from __future__ import absolute_import, division, print_function
  2. import tornado.escape
  3. from tornado.escape import (
  4. utf8, xhtml_escape, xhtml_unescape, url_escape, url_unescape,
  5. to_unicode, json_decode, json_encode, squeeze, recursive_unicode,
  6. )
  7. from tornado.util import unicode_type
  8. from tornado.test.util import unittest
  9. linkify_tests = [
  10. # (input, linkify_kwargs, expected_output)
  11. ("hello http://world.com/!", {},
  12. u'hello <a href="http://world.com/">http://world.com/</a>!'),
  13. ("hello http://world.com/with?param=true&stuff=yes", {},
  14. u'hello <a href="http://world.com/with?param=true&amp;stuff=yes">http://world.com/with?param=true&amp;stuff=yes</a>'), # noqa: E501
  15. # an opened paren followed by many chars killed Gruber's regex
  16. ("http://url.com/w(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", {},
  17. u'<a href="http://url.com/w">http://url.com/w</a>(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'), # noqa: E501
  18. # as did too many dots at the end
  19. ("http://url.com/withmany.......................................", {},
  20. u'<a href="http://url.com/withmany">http://url.com/withmany</a>.......................................'), # noqa: E501
  21. ("http://url.com/withmany((((((((((((((((((((((((((((((((((a)", {},
  22. u'<a href="http://url.com/withmany">http://url.com/withmany</a>((((((((((((((((((((((((((((((((((a)'), # noqa: E501
  23. # some examples from http://daringfireball.net/2009/11/liberal_regex_for_matching_urls
  24. # plus a fex extras (such as multiple parentheses).
  25. ("http://foo.com/blah_blah", {},
  26. u'<a href="http://foo.com/blah_blah">http://foo.com/blah_blah</a>'),
  27. ("http://foo.com/blah_blah/", {},
  28. u'<a href="http://foo.com/blah_blah/">http://foo.com/blah_blah/</a>'),
  29. ("(Something like http://foo.com/blah_blah)", {},
  30. u'(Something like <a href="http://foo.com/blah_blah">http://foo.com/blah_blah</a>)'),
  31. ("http://foo.com/blah_blah_(wikipedia)", {},
  32. u'<a href="http://foo.com/blah_blah_(wikipedia)">http://foo.com/blah_blah_(wikipedia)</a>'),
  33. ("http://foo.com/blah_(blah)_(wikipedia)_blah", {},
  34. u'<a href="http://foo.com/blah_(blah)_(wikipedia)_blah">http://foo.com/blah_(blah)_(wikipedia)_blah</a>'), # noqa: E501
  35. ("(Something like http://foo.com/blah_blah_(wikipedia))", {},
  36. u'(Something like <a href="http://foo.com/blah_blah_(wikipedia)">http://foo.com/blah_blah_(wikipedia)</a>)'), # noqa: E501
  37. ("http://foo.com/blah_blah.", {},
  38. u'<a href="http://foo.com/blah_blah">http://foo.com/blah_blah</a>.'),
  39. ("http://foo.com/blah_blah/.", {},
  40. u'<a href="http://foo.com/blah_blah/">http://foo.com/blah_blah/</a>.'),
  41. ("<http://foo.com/blah_blah>", {},
  42. u'&lt;<a href="http://foo.com/blah_blah">http://foo.com/blah_blah</a>&gt;'),
  43. ("<http://foo.com/blah_blah/>", {},
  44. u'&lt;<a href="http://foo.com/blah_blah/">http://foo.com/blah_blah/</a>&gt;'),
  45. ("http://foo.com/blah_blah,", {},
  46. u'<a href="http://foo.com/blah_blah">http://foo.com/blah_blah</a>,'),
  47. ("http://www.example.com/wpstyle/?p=364.", {},
  48. u'<a href="http://www.example.com/wpstyle/?p=364">http://www.example.com/wpstyle/?p=364</a>.'),
  49. ("rdar://1234",
  50. {"permitted_protocols": ["http", "rdar"]},
  51. u'<a href="rdar://1234">rdar://1234</a>'),
  52. ("rdar:/1234",
  53. {"permitted_protocols": ["rdar"]},
  54. u'<a href="rdar:/1234">rdar:/1234</a>'),
  55. ("http://userid:password@example.com:8080", {},
  56. u'<a href="http://userid:password@example.com:8080">http://userid:password@example.com:8080</a>'), # noqa: E501
  57. ("http://userid@example.com", {},
  58. u'<a href="http://userid@example.com">http://userid@example.com</a>'),
  59. ("http://userid@example.com:8080", {},
  60. u'<a href="http://userid@example.com:8080">http://userid@example.com:8080</a>'),
  61. ("http://userid:password@example.com", {},
  62. u'<a href="http://userid:password@example.com">http://userid:password@example.com</a>'),
  63. ("message://%3c330e7f8409726r6a4ba78dkf1fd71420c1bf6ff@mail.gmail.com%3e",
  64. {"permitted_protocols": ["http", "message"]},
  65. u'<a href="message://%3c330e7f8409726r6a4ba78dkf1fd71420c1bf6ff@mail.gmail.com%3e">'
  66. u'message://%3c330e7f8409726r6a4ba78dkf1fd71420c1bf6ff@mail.gmail.com%3e</a>'),
  67. (u"http://\u27a1.ws/\u4a39", {},
  68. u'<a href="http://\u27a1.ws/\u4a39">http://\u27a1.ws/\u4a39</a>'),
  69. ("<tag>http://example.com</tag>", {},
  70. u'&lt;tag&gt;<a href="http://example.com">http://example.com</a>&lt;/tag&gt;'),
  71. ("Just a www.example.com link.", {},
  72. u'Just a <a href="http://www.example.com">www.example.com</a> link.'),
  73. ("Just a www.example.com link.",
  74. {"require_protocol": True},
  75. u'Just a www.example.com link.'),
  76. ("A http://reallylong.com/link/that/exceedsthelenglimit.html",
  77. {"require_protocol": True, "shorten": True},
  78. u'A <a href="http://reallylong.com/link/that/exceedsthelenglimit.html"'
  79. u' title="http://reallylong.com/link/that/exceedsthelenglimit.html">http://reallylong.com/link...</a>'), # noqa: E501
  80. ("A http://reallylongdomainnamethatwillbetoolong.com/hi!",
  81. {"shorten": True},
  82. u'A <a href="http://reallylongdomainnamethatwillbetoolong.com/hi"'
  83. u' title="http://reallylongdomainnamethatwillbetoolong.com/hi">http://reallylongdomainnametha...</a>!'), # noqa: E501
  84. ("A file:///passwords.txt and http://web.com link", {},
  85. u'A file:///passwords.txt and <a href="http://web.com">http://web.com</a> link'),
  86. ("A file:///passwords.txt and http://web.com link",
  87. {"permitted_protocols": ["file"]},
  88. u'A <a href="file:///passwords.txt">file:///passwords.txt</a> and http://web.com link'),
  89. ("www.external-link.com",
  90. {"extra_params": 'rel="nofollow" class="external"'},
  91. u'<a href="http://www.external-link.com" rel="nofollow" class="external">www.external-link.com</a>'), # noqa: E501
  92. ("www.external-link.com and www.internal-link.com/blogs extra",
  93. {"extra_params": lambda href: 'class="internal"' if href.startswith("http://www.internal-link.com") else 'rel="nofollow" class="external"'}, # noqa: E501
  94. u'<a href="http://www.external-link.com" rel="nofollow" class="external">www.external-link.com</a>' # noqa: E501
  95. u' and <a href="http://www.internal-link.com/blogs" class="internal">www.internal-link.com/blogs</a> extra'), # noqa: E501
  96. ("www.external-link.com",
  97. {"extra_params": lambda href: ' rel="nofollow" class="external" '},
  98. u'<a href="http://www.external-link.com" rel="nofollow" class="external">www.external-link.com</a>'), # noqa: E501
  99. ]
  100. class EscapeTestCase(unittest.TestCase):
  101. def test_linkify(self):
  102. for text, kwargs, html in linkify_tests:
  103. linked = tornado.escape.linkify(text, **kwargs)
  104. self.assertEqual(linked, html)
  105. def test_xhtml_escape(self):
  106. tests = [
  107. ("<foo>", "&lt;foo&gt;"),
  108. (u"<foo>", u"&lt;foo&gt;"),
  109. (b"<foo>", b"&lt;foo&gt;"),
  110. ("<>&\"'", "&lt;&gt;&amp;&quot;&#39;"),
  111. ("&amp;", "&amp;amp;"),
  112. (u"<\u00e9>", u"&lt;\u00e9&gt;"),
  113. (b"<\xc3\xa9>", b"&lt;\xc3\xa9&gt;"),
  114. ]
  115. for unescaped, escaped in tests:
  116. self.assertEqual(utf8(xhtml_escape(unescaped)), utf8(escaped))
  117. self.assertEqual(utf8(unescaped), utf8(xhtml_unescape(escaped)))
  118. def test_xhtml_unescape_numeric(self):
  119. tests = [
  120. ('foo&#32;bar', 'foo bar'),
  121. ('foo&#x20;bar', 'foo bar'),
  122. ('foo&#X20;bar', 'foo bar'),
  123. ('foo&#xabc;bar', u'foo\u0abcbar'),
  124. ('foo&#xyz;bar', 'foo&#xyz;bar'), # invalid encoding
  125. ('foo&#;bar', 'foo&#;bar'), # invalid encoding
  126. ('foo&#x;bar', 'foo&#x;bar'), # invalid encoding
  127. ]
  128. for escaped, unescaped in tests:
  129. self.assertEqual(unescaped, xhtml_unescape(escaped))
  130. def test_url_escape_unicode(self):
  131. tests = [
  132. # byte strings are passed through as-is
  133. (u'\u00e9'.encode('utf8'), '%C3%A9'),
  134. (u'\u00e9'.encode('latin1'), '%E9'),
  135. # unicode strings become utf8
  136. (u'\u00e9', '%C3%A9'),
  137. ]
  138. for unescaped, escaped in tests:
  139. self.assertEqual(url_escape(unescaped), escaped)
  140. def test_url_unescape_unicode(self):
  141. tests = [
  142. ('%C3%A9', u'\u00e9', 'utf8'),
  143. ('%C3%A9', u'\u00c3\u00a9', 'latin1'),
  144. ('%C3%A9', utf8(u'\u00e9'), None),
  145. ]
  146. for escaped, unescaped, encoding in tests:
  147. # input strings to url_unescape should only contain ascii
  148. # characters, but make sure the function accepts both byte
  149. # and unicode strings.
  150. self.assertEqual(url_unescape(to_unicode(escaped), encoding), unescaped)
  151. self.assertEqual(url_unescape(utf8(escaped), encoding), unescaped)
  152. def test_url_escape_quote_plus(self):
  153. unescaped = '+ #%'
  154. plus_escaped = '%2B+%23%25'
  155. escaped = '%2B%20%23%25'
  156. self.assertEqual(url_escape(unescaped), plus_escaped)
  157. self.assertEqual(url_escape(unescaped, plus=False), escaped)
  158. self.assertEqual(url_unescape(plus_escaped), unescaped)
  159. self.assertEqual(url_unescape(escaped, plus=False), unescaped)
  160. self.assertEqual(url_unescape(plus_escaped, encoding=None),
  161. utf8(unescaped))
  162. self.assertEqual(url_unescape(escaped, encoding=None, plus=False),
  163. utf8(unescaped))
  164. def test_escape_return_types(self):
  165. # On python2 the escape methods should generally return the same
  166. # type as their argument
  167. self.assertEqual(type(xhtml_escape("foo")), str)
  168. self.assertEqual(type(xhtml_escape(u"foo")), unicode_type)
  169. def test_json_decode(self):
  170. # json_decode accepts both bytes and unicode, but strings it returns
  171. # are always unicode.
  172. self.assertEqual(json_decode(b'"foo"'), u"foo")
  173. self.assertEqual(json_decode(u'"foo"'), u"foo")
  174. # Non-ascii bytes are interpreted as utf8
  175. self.assertEqual(json_decode(utf8(u'"\u00e9"')), u"\u00e9")
  176. def test_json_encode(self):
  177. # json deals with strings, not bytes. On python 2 byte strings will
  178. # convert automatically if they are utf8; on python 3 byte strings
  179. # are not allowed.
  180. self.assertEqual(json_decode(json_encode(u"\u00e9")), u"\u00e9")
  181. if bytes is str:
  182. self.assertEqual(json_decode(json_encode(utf8(u"\u00e9"))), u"\u00e9")
  183. self.assertRaises(UnicodeDecodeError, json_encode, b"\xe9")
  184. def test_squeeze(self):
  185. self.assertEqual(squeeze(u'sequences of whitespace chars'),
  186. u'sequences of whitespace chars')
  187. def test_recursive_unicode(self):
  188. tests = {
  189. 'dict': {b"foo": b"bar"},
  190. 'list': [b"foo", b"bar"],
  191. 'tuple': (b"foo", b"bar"),
  192. 'bytes': b"foo"
  193. }
  194. self.assertEqual(recursive_unicode(tests['dict']), {u"foo": u"bar"})
  195. self.assertEqual(recursive_unicode(tests['list']), [u"foo", u"bar"])
  196. self.assertEqual(recursive_unicode(tests['tuple']), (u"foo", u"bar"))
  197. self.assertEqual(recursive_unicode(tests['bytes']), u"foo")