test_html.py 9.4 KB

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