test_html.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import os
  4. from datetime import datetime
  5. from django.test import SimpleTestCase
  6. from django.utils import html, safestring, six
  7. from django.utils._os import upath
  8. from django.utils.encoding import force_text
  9. from django.utils.functional import lazystr
  10. class TestUtilsHtml(SimpleTestCase):
  11. def check_output(self, function, value, output=None):
  12. """
  13. Check that function(value) equals output. If output is None,
  14. check that function(value) equals value.
  15. """
  16. if output is None:
  17. output = value
  18. self.assertEqual(function(value), output)
  19. def test_escape(self):
  20. f = html.escape
  21. items = (
  22. ('&', '&'),
  23. ('<', '&lt;'),
  24. ('>', '&gt;'),
  25. ('"', '&quot;'),
  26. ("'", '&#39;'),
  27. )
  28. # Substitution patterns for testing the above items.
  29. patterns = ("%s", "asdf%sfdsa", "%s1", "1%sb")
  30. for value, output in items:
  31. for pattern in patterns:
  32. self.check_output(f, pattern % value, pattern % output)
  33. self.check_output(f, lazystr(pattern % value), pattern % output)
  34. # Check repeated values.
  35. self.check_output(f, value * 2, output * 2)
  36. # Verify it doesn't double replace &.
  37. self.check_output(f, '<&', '&lt;&amp;')
  38. def test_format_html(self):
  39. self.assertEqual(
  40. html.format_html("{} {} {third} {fourth}",
  41. "< Dangerous >",
  42. html.mark_safe("<b>safe</b>"),
  43. third="< dangerous again",
  44. fourth=html.mark_safe("<i>safe again</i>")
  45. ),
  46. "&lt; Dangerous &gt; <b>safe</b> &lt; dangerous again <i>safe again</i>"
  47. )
  48. def test_linebreaks(self):
  49. f = html.linebreaks
  50. items = (
  51. ("para1\n\npara2\r\rpara3", "<p>para1</p>\n\n<p>para2</p>\n\n<p>para3</p>"),
  52. ("para1\nsub1\rsub2\n\npara2", "<p>para1<br />sub1<br />sub2</p>\n\n<p>para2</p>"),
  53. ("para1\r\n\r\npara2\rsub1\r\rpara4", "<p>para1</p>\n\n<p>para2<br />sub1</p>\n\n<p>para4</p>"),
  54. ("para1\tmore\n\npara2", "<p>para1\tmore</p>\n\n<p>para2</p>"),
  55. )
  56. for value, output in items:
  57. self.check_output(f, value, output)
  58. self.check_output(f, lazystr(value), output)
  59. def test_strip_tags(self):
  60. f = html.strip_tags
  61. items = (
  62. ('<p>See: &#39;&eacute; is an apostrophe followed by e acute</p>',
  63. 'See: &#39;&eacute; is an apostrophe followed by e acute'),
  64. ('<adf>a', 'a'),
  65. ('</adf>a', 'a'),
  66. ('<asdf><asdf>e', 'e'),
  67. ('hi, <f x', 'hi, <f x'),
  68. ('234<235, right?', '234<235, right?'),
  69. ('a4<a5 right?', 'a4<a5 right?'),
  70. ('b7>b2!', 'b7>b2!'),
  71. ('</fe', '</fe'),
  72. ('<x>b<y>', 'b'),
  73. ('a<p onclick="alert(\'<test>\')">b</p>c', 'abc'),
  74. ('a<p a >b</p>c', 'abc'),
  75. ('d<a:b c:d>e</p>f', 'def'),
  76. ('<strong>foo</strong><a href="http://example.com">bar</a>', 'foobar'),
  77. # caused infinite loop on Pythons not patched with
  78. # http://bugs.python.org/issue20288
  79. ('&gotcha&#;<>', '&gotcha&#;<>'),
  80. )
  81. for value, output in items:
  82. self.check_output(f, value, output)
  83. self.check_output(f, lazystr(value), output)
  84. # Some convoluted syntax for which parsing may differ between python versions
  85. output = html.strip_tags('<sc<!-- -->ript>test<<!-- -->/script>')
  86. self.assertNotIn('<script>', output)
  87. self.assertIn('test', output)
  88. output = html.strip_tags('<script>alert()</script>&h')
  89. self.assertNotIn('<script>', output)
  90. self.assertIn('alert()', output)
  91. # Test with more lengthy content (also catching performance regressions)
  92. for filename in ('strip_tags1.html', 'strip_tags2.txt'):
  93. path = os.path.join(os.path.dirname(upath(__file__)), 'files', filename)
  94. with open(path, 'r') as fp:
  95. content = force_text(fp.read())
  96. start = datetime.now()
  97. stripped = html.strip_tags(content)
  98. elapsed = datetime.now() - start
  99. self.assertEqual(elapsed.seconds, 0)
  100. self.assertIn("Please try again.", stripped)
  101. self.assertNotIn('<', stripped)
  102. def test_strip_spaces_between_tags(self):
  103. f = html.strip_spaces_between_tags
  104. # Strings that should come out untouched.
  105. items = (' <adf>', '<adf> ', ' </adf> ', ' <f> x</f>')
  106. for value in items:
  107. self.check_output(f, value)
  108. self.check_output(f, lazystr(value))
  109. # Strings that have spaces to strip.
  110. items = (
  111. ('<d> </d>', '<d></d>'),
  112. ('<p>hello </p>\n<p> world</p>', '<p>hello </p><p> world</p>'),
  113. ('\n<p>\t</p>\n<p> </p>\n', '\n<p></p><p></p>\n'),
  114. )
  115. for value, output in items:
  116. self.check_output(f, value, output)
  117. self.check_output(f, lazystr(value), output)
  118. def test_escapejs(self):
  119. f = html.escapejs
  120. items = (
  121. ('"double quotes" and \'single quotes\'', '\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027'),
  122. (r'\ : backslashes, too', '\\u005C : backslashes, too'),
  123. (
  124. 'and lots of whitespace: \r\n\t\v\f\b',
  125. 'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008'
  126. ),
  127. (r'<script>and this</script>', '\\u003Cscript\\u003Eand this\\u003C/script\\u003E'),
  128. (
  129. 'paragraph separator:\u2029and line separator:\u2028',
  130. 'paragraph separator:\\u2029and line separator:\\u2028'
  131. ),
  132. )
  133. for value, output in items:
  134. self.check_output(f, value, output)
  135. self.check_output(f, lazystr(value), output)
  136. def test_smart_urlquote(self):
  137. quote = html.smart_urlquote
  138. # Ensure that IDNs are properly quoted
  139. self.assertEqual(quote('http://öäü.com/'), 'http://xn--4ca9at.com/')
  140. self.assertEqual(quote('http://öäü.com/öäü/'), 'http://xn--4ca9at.com/%C3%B6%C3%A4%C3%BC/')
  141. # Ensure that everything unsafe is quoted, !*'();:@&=+$,/?#[]~ is considered safe as per RFC
  142. self.assertEqual(quote('http://example.com/path/öäü/'), 'http://example.com/path/%C3%B6%C3%A4%C3%BC/')
  143. self.assertEqual(quote('http://example.com/%C3%B6/ä/'), 'http://example.com/%C3%B6/%C3%A4/')
  144. self.assertEqual(quote('http://example.com/?x=1&y=2+3&z='), 'http://example.com/?x=1&y=2+3&z=')
  145. self.assertEqual(quote('http://example.com/?x=<>"\''), 'http://example.com/?x=%3C%3E%22%27')
  146. self.assertEqual(quote('http://example.com/?q=http://example.com/?x=1%26q=django'),
  147. 'http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango')
  148. self.assertEqual(quote('http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango'),
  149. 'http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango')
  150. def test_conditional_escape(self):
  151. s = '<h1>interop</h1>'
  152. self.assertEqual(html.conditional_escape(s),
  153. '&lt;h1&gt;interop&lt;/h1&gt;')
  154. self.assertEqual(html.conditional_escape(safestring.mark_safe(s)), s)
  155. def test_html_safe(self):
  156. @html.html_safe
  157. class HtmlClass(object):
  158. if six.PY2:
  159. def __unicode__(self):
  160. return "<h1>I'm a html class!</h1>"
  161. else:
  162. def __str__(self):
  163. return "<h1>I'm a html class!</h1>"
  164. html_obj = HtmlClass()
  165. self.assertTrue(hasattr(HtmlClass, '__html__'))
  166. self.assertTrue(hasattr(html_obj, '__html__'))
  167. self.assertEqual(force_text(html_obj), html_obj.__html__())
  168. def test_html_safe_subclass(self):
  169. if six.PY2:
  170. class BaseClass(object):
  171. def __html__(self):
  172. # defines __html__ on its own
  173. return 'some html content'
  174. def __unicode__(self):
  175. return 'some non html content'
  176. @html.html_safe
  177. class Subclass(BaseClass):
  178. def __unicode__(self):
  179. # overrides __unicode__ and is marked as html_safe
  180. return 'some html safe content'
  181. else:
  182. class BaseClass(object):
  183. def __html__(self):
  184. # defines __html__ on its own
  185. return 'some html content'
  186. def __str__(self):
  187. return 'some non html content'
  188. @html.html_safe
  189. class Subclass(BaseClass):
  190. def __str__(self):
  191. # overrides __str__ and is marked as html_safe
  192. return 'some html safe content'
  193. subclass_obj = Subclass()
  194. self.assertEqual(force_text(subclass_obj), subclass_obj.__html__())
  195. def test_html_safe_defines_html_error(self):
  196. msg = "can't apply @html_safe to HtmlClass because it defines __html__()."
  197. with self.assertRaisesMessage(ValueError, msg):
  198. @html.html_safe
  199. class HtmlClass(object):
  200. def __html__(self):
  201. return "<h1>I'm a html class!</h1>"
  202. def test_html_safe_doesnt_define_str(self):
  203. method_name = '__unicode__()' if six.PY2 else '__str__()'
  204. msg = "can't apply @html_safe to HtmlClass because it doesn't define %s." % method_name
  205. with self.assertRaisesMessage(ValueError, msg):
  206. @html.html_safe
  207. class HtmlClass(object):
  208. pass