tests.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import gc
  2. import unittest
  3. from markupsafe import Markup, escape
  4. class MarkupTestCase(unittest.TestCase):
  5. def test_markup_operations(self):
  6. # adding two strings should escape the unsafe one
  7. unsafe = '<script type="application/x-some-script">alert("foo");</script>'
  8. safe = Markup('<em>username</em>')
  9. assert unsafe + safe == unicode(escape(unsafe)) + unicode(safe)
  10. # string interpolations are safe to use too
  11. assert Markup('<em>%s</em>') % '<bad user>' == \
  12. '<em>&lt;bad user&gt;</em>'
  13. assert Markup('<em>%(username)s</em>') % {
  14. 'username': '<bad user>'
  15. } == '<em>&lt;bad user&gt;</em>'
  16. # an escaped object is markup too
  17. assert type(Markup('foo') + 'bar') is Markup
  18. # and it implements __html__ by returning itself
  19. x = Markup("foo")
  20. assert x.__html__() is x
  21. # it also knows how to treat __html__ objects
  22. class Foo(object):
  23. def __html__(self):
  24. return '<em>awesome</em>'
  25. def __unicode__(self):
  26. return 'awesome'
  27. assert Markup(Foo()) == '<em>awesome</em>'
  28. assert Markup('<strong>%s</strong>') % Foo() == \
  29. '<strong><em>awesome</em></strong>'
  30. # escaping and unescaping
  31. assert escape('"<>&\'') == '&#34;&lt;&gt;&amp;&#39;'
  32. assert Markup("<em>Foo &amp; Bar</em>").striptags() == "Foo & Bar"
  33. assert Markup("&lt;test&gt;").unescape() == "<test>"
  34. def test_all_set(self):
  35. import markupsafe as markup
  36. for item in markup.__all__:
  37. getattr(markup, item)
  38. class MarkupLeakTestCase(unittest.TestCase):
  39. def test_markup_leaks(self):
  40. counts = set()
  41. for count in xrange(20):
  42. for item in xrange(1000):
  43. escape("foo")
  44. escape("<foo>")
  45. escape(u"foo")
  46. escape(u"<foo>")
  47. counts.add(len(gc.get_objects()))
  48. assert len(counts) == 1, 'ouch, c extension seems to leak objects'
  49. def suite():
  50. suite = unittest.TestSuite()
  51. suite.addTest(unittest.makeSuite(MarkupTestCase))
  52. # this test only tests the c extension
  53. if not hasattr(escape, 'func_code'):
  54. suite.addTest(unittest.makeSuite(MarkupLeakTestCase))
  55. return suite
  56. if __name__ == '__main__':
  57. unittest.main(defaultTest='suite')