test_bytecode_cache.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import pytest
  2. from jinja2 import Environment
  3. from jinja2.bccache import Bucket
  4. from jinja2.bccache import FileSystemBytecodeCache
  5. from jinja2.bccache import MemcachedBytecodeCache
  6. from jinja2.exceptions import TemplateNotFound
  7. @pytest.fixture
  8. def env(package_loader, tmp_path):
  9. bytecode_cache = FileSystemBytecodeCache(str(tmp_path))
  10. return Environment(loader=package_loader, bytecode_cache=bytecode_cache)
  11. class TestByteCodeCache:
  12. def test_simple(self, env):
  13. tmpl = env.get_template("test.html")
  14. assert tmpl.render().strip() == "BAR"
  15. pytest.raises(TemplateNotFound, env.get_template, "missing.html")
  16. class MockMemcached:
  17. class Error(Exception):
  18. pass
  19. key = None
  20. value = None
  21. timeout = None
  22. def get(self, key):
  23. return self.value
  24. def set(self, key, value, timeout=None):
  25. self.key = key
  26. self.value = value
  27. self.timeout = timeout
  28. def get_side_effect(self, key):
  29. raise self.Error()
  30. def set_side_effect(self, *args):
  31. raise self.Error()
  32. class TestMemcachedBytecodeCache:
  33. def test_dump_load(self):
  34. memcached = MockMemcached()
  35. m = MemcachedBytecodeCache(memcached)
  36. b = Bucket(None, "key", "")
  37. b.code = "code"
  38. m.dump_bytecode(b)
  39. assert memcached.key == "jinja2/bytecode/key"
  40. b = Bucket(None, "key", "")
  41. m.load_bytecode(b)
  42. assert b.code == "code"
  43. def test_exception(self):
  44. memcached = MockMemcached()
  45. memcached.get = memcached.get_side_effect
  46. memcached.set = memcached.set_side_effect
  47. m = MemcachedBytecodeCache(memcached)
  48. b = Bucket(None, "key", "")
  49. b.code = "code"
  50. m.dump_bytecode(b)
  51. m.load_bytecode(b)
  52. m.ignore_memcache_errors = False
  53. with pytest.raises(MockMemcached.Error):
  54. m.dump_bytecode(b)
  55. with pytest.raises(MockMemcached.Error):
  56. m.load_bytecode(b)