utils.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # -*- coding: utf-8 -*-
  2. """
  3. jinja2.testsuite.utils
  4. ~~~~~~~~~~~~~~~~~~~~~~
  5. Tests utilities jinja uses.
  6. :copyright: (c) 2010 by the Jinja Team.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import gc
  10. import unittest
  11. import pickle
  12. from jinja2.testsuite import JinjaTestCase
  13. from jinja2.utils import LRUCache, escape, object_type_repr
  14. class LRUCacheTestCase(JinjaTestCase):
  15. def test_simple(self):
  16. d = LRUCache(3)
  17. d["a"] = 1
  18. d["b"] = 2
  19. d["c"] = 3
  20. d["a"]
  21. d["d"] = 4
  22. assert len(d) == 3
  23. assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d
  24. def test_pickleable(self):
  25. cache = LRUCache(2)
  26. cache["foo"] = 42
  27. cache["bar"] = 23
  28. cache["foo"]
  29. for protocol in range(3):
  30. copy = pickle.loads(pickle.dumps(cache, protocol))
  31. assert copy.capacity == cache.capacity
  32. assert copy._mapping == cache._mapping
  33. assert copy._queue == cache._queue
  34. class HelpersTestCase(JinjaTestCase):
  35. def test_object_type_repr(self):
  36. class X(object):
  37. pass
  38. self.assert_equal(object_type_repr(42), 'int object')
  39. self.assert_equal(object_type_repr([]), 'list object')
  40. self.assert_equal(object_type_repr(X()),
  41. 'jinja2.testsuite.utils.X object')
  42. self.assert_equal(object_type_repr(None), 'None')
  43. self.assert_equal(object_type_repr(Ellipsis), 'Ellipsis')
  44. class MarkupLeakTestCase(JinjaTestCase):
  45. def test_markup_leaks(self):
  46. counts = set()
  47. for count in range(20):
  48. for item in range(1000):
  49. escape("foo")
  50. escape("<foo>")
  51. escape(u"foo")
  52. escape(u"<foo>")
  53. counts.add(len(gc.get_objects()))
  54. assert len(counts) == 1, 'ouch, c extension seems to leak objects'
  55. def suite():
  56. suite = unittest.TestSuite()
  57. suite.addTest(unittest.makeSuite(LRUCacheTestCase))
  58. suite.addTest(unittest.makeSuite(HelpersTestCase))
  59. # this test only tests the c extension
  60. if not hasattr(escape, 'func_code'):
  61. suite.addTest(unittest.makeSuite(MarkupLeakTestCase))
  62. return suite