tests.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # -*- coding: utf-8 -*-
  2. import gc
  3. import sys
  4. import unittest
  5. from markupsafe import Markup, escape, escape_silent
  6. from markupsafe._compat import text_type
  7. class MarkupTestCase(unittest.TestCase):
  8. def test_adding(self):
  9. # adding two strings should escape the unsafe one
  10. unsafe = '<script type="application/x-some-script">alert("foo");</script>'
  11. safe = Markup('<em>username</em>')
  12. assert unsafe + safe == text_type(escape(unsafe)) + text_type(safe)
  13. def test_string_interpolation(self):
  14. # string interpolations are safe to use too
  15. assert Markup('<em>%s</em>') % '<bad user>' == \
  16. '<em>&lt;bad user&gt;</em>'
  17. assert Markup('<em>%(username)s</em>') % {
  18. 'username': '<bad user>'
  19. } == '<em>&lt;bad user&gt;</em>'
  20. assert Markup('%i') % 3.14 == '3'
  21. assert Markup('%.2f') % 3.14 == '3.14'
  22. def test_type_behavior(self):
  23. # an escaped object is markup too
  24. assert type(Markup('foo') + 'bar') is Markup
  25. # and it implements __html__ by returning itself
  26. x = Markup("foo")
  27. assert x.__html__() is x
  28. def test_html_interop(self):
  29. # it also knows how to treat __html__ objects
  30. class Foo(object):
  31. def __html__(self):
  32. return '<em>awesome</em>'
  33. def __unicode__(self):
  34. return 'awesome'
  35. __str__ = __unicode__
  36. assert Markup(Foo()) == '<em>awesome</em>'
  37. assert Markup('<strong>%s</strong>') % Foo() == \
  38. '<strong><em>awesome</em></strong>'
  39. def test_tuple_interpol(self):
  40. self.assertEqual(Markup('<em>%s:%s</em>') % (
  41. '<foo>',
  42. '<bar>',
  43. ), Markup(u'<em>&lt;foo&gt;:&lt;bar&gt;</em>'))
  44. def test_dict_interpol(self):
  45. self.assertEqual(Markup('<em>%(foo)s</em>') % {
  46. 'foo': '<foo>',
  47. }, Markup(u'<em>&lt;foo&gt;</em>'))
  48. self.assertEqual(Markup('<em>%(foo)s:%(bar)s</em>') % {
  49. 'foo': '<foo>',
  50. 'bar': '<bar>',
  51. }, Markup(u'<em>&lt;foo&gt;:&lt;bar&gt;</em>'))
  52. def test_escaping(self):
  53. # escaping and unescaping
  54. assert escape('"<>&\'') == '&#34;&lt;&gt;&amp;&#39;'
  55. assert Markup("<em>Foo &amp; Bar</em>").striptags() == "Foo & Bar"
  56. assert Markup("&lt;test&gt;").unescape() == "<test>"
  57. def test_formatting(self):
  58. for actual, expected in (
  59. (Markup('%i') % 3.14, '3'),
  60. (Markup('%.2f') % 3.14159, '3.14'),
  61. (Markup('%s %s %s') % ('<', 123, '>'), '&lt; 123 &gt;'),
  62. (Markup('<em>{awesome}</em>').format(awesome='<awesome>'),
  63. '<em>&lt;awesome&gt;</em>'),
  64. (Markup('{0[1][bar]}').format([0, {'bar': '<bar/>'}]),
  65. '&lt;bar/&gt;'),
  66. (Markup('{0[1][bar]}').format([0, {'bar': Markup('<bar/>')}]),
  67. '<bar/>')):
  68. assert actual == expected, "%r should be %r!" % (actual, expected)
  69. # This is new in 2.7
  70. if sys.version_info >= (2, 7):
  71. def test_formatting_empty(self):
  72. formatted = Markup('{}').format(0)
  73. assert formatted == Markup('0')
  74. def test_custom_formatting(self):
  75. class HasHTMLOnly(object):
  76. def __html__(self):
  77. return Markup('<foo>')
  78. class HasHTMLAndFormat(object):
  79. def __html__(self):
  80. return Markup('<foo>')
  81. def __html_format__(self, spec):
  82. return Markup('<FORMAT>')
  83. assert Markup('{0}').format(HasHTMLOnly()) == Markup('<foo>')
  84. assert Markup('{0}').format(HasHTMLAndFormat()) == Markup('<FORMAT>')
  85. def test_complex_custom_formatting(self):
  86. class User(object):
  87. def __init__(self, id, username):
  88. self.id = id
  89. self.username = username
  90. def __html_format__(self, format_spec):
  91. if format_spec == 'link':
  92. return Markup('<a href="/user/{0}">{1}</a>').format(
  93. self.id,
  94. self.__html__(),
  95. )
  96. elif format_spec:
  97. raise ValueError('Invalid format spec')
  98. return self.__html__()
  99. def __html__(self):
  100. return Markup('<span class=user>{0}</span>').format(self.username)
  101. user = User(1, 'foo')
  102. assert Markup('<p>User: {0:link}').format(user) == \
  103. Markup('<p>User: <a href="/user/1"><span class=user>foo</span></a>')
  104. def test_all_set(self):
  105. import markupsafe as markup
  106. for item in markup.__all__:
  107. getattr(markup, item)
  108. def test_escape_silent(self):
  109. assert escape_silent(None) == Markup()
  110. assert escape(None) == Markup(None)
  111. assert escape_silent('<foo>') == Markup(u'&lt;foo&gt;')
  112. def test_splitting(self):
  113. self.assertEqual(Markup('a b').split(), [
  114. Markup('a'),
  115. Markup('b')
  116. ])
  117. self.assertEqual(Markup('a b').rsplit(), [
  118. Markup('a'),
  119. Markup('b')
  120. ])
  121. self.assertEqual(Markup('a\nb').splitlines(), [
  122. Markup('a'),
  123. Markup('b')
  124. ])
  125. def test_mul(self):
  126. self.assertEqual(Markup('a') * 3, Markup('aaa'))
  127. class MarkupLeakTestCase(unittest.TestCase):
  128. def test_markup_leaks(self):
  129. counts = set()
  130. for count in range(20):
  131. for item in range(1000):
  132. escape("foo")
  133. escape("<foo>")
  134. escape(u"foo")
  135. escape(u"<foo>")
  136. counts.add(len(gc.get_objects()))
  137. assert len(counts) == 1, 'ouch, c extension seems to leak objects'
  138. def suite():
  139. suite = unittest.TestSuite()
  140. suite.addTest(unittest.makeSuite(MarkupTestCase))
  141. # this test only tests the c extension
  142. if not hasattr(escape, 'func_code'):
  143. suite.addTest(unittest.makeSuite(MarkupLeakTestCase))
  144. return suite
  145. if __name__ == '__main__':
  146. unittest.main(defaultTest='suite')
  147. # vim:sts=4:sw=4:et: