test_loader.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. import importlib.abc
  2. import importlib.machinery
  3. import importlib.util
  4. import os
  5. import platform
  6. import shutil
  7. import sys
  8. import tempfile
  9. import time
  10. import weakref
  11. from pathlib import Path
  12. import pytest
  13. from jinja2 import Environment
  14. from jinja2 import loaders
  15. from jinja2 import PackageLoader
  16. from jinja2.exceptions import TemplateNotFound
  17. from jinja2.loaders import split_template_path
  18. import yatest.common as yc
  19. class TestLoaders:
  20. def test_dict_loader(self, dict_loader):
  21. env = Environment(loader=dict_loader)
  22. tmpl = env.get_template("justdict.html")
  23. assert tmpl.render().strip() == "FOO"
  24. pytest.raises(TemplateNotFound, env.get_template, "missing.html")
  25. def test_package_loader(self, package_loader):
  26. env = Environment(loader=package_loader)
  27. tmpl = env.get_template("test.html")
  28. assert tmpl.render().strip() == "BAR"
  29. pytest.raises(TemplateNotFound, env.get_template, "missing.html")
  30. def test_filesystem_loader_overlapping_names(self, filesystem_loader):
  31. t2_dir = Path(filesystem_loader.searchpath[0]) / ".." / "templates2"
  32. # Make "foo" show up before "foo/test.html".
  33. filesystem_loader.searchpath.insert(0, t2_dir)
  34. e = Environment(loader=filesystem_loader)
  35. e.get_template("foo")
  36. # This would raise NotADirectoryError if "t2/foo" wasn't skipped.
  37. e.get_template("foo/test.html")
  38. def test_choice_loader(self, choice_loader):
  39. env = Environment(loader=choice_loader)
  40. tmpl = env.get_template("justdict.html")
  41. assert tmpl.render().strip() == "FOO"
  42. tmpl = env.get_template("test.html")
  43. assert tmpl.render().strip() == "BAR"
  44. pytest.raises(TemplateNotFound, env.get_template, "missing.html")
  45. def test_function_loader(self, function_loader):
  46. env = Environment(loader=function_loader)
  47. tmpl = env.get_template("justfunction.html")
  48. assert tmpl.render().strip() == "FOO"
  49. pytest.raises(TemplateNotFound, env.get_template, "missing.html")
  50. def test_prefix_loader(self, prefix_loader):
  51. env = Environment(loader=prefix_loader)
  52. tmpl = env.get_template("a/test.html")
  53. assert tmpl.render().strip() == "BAR"
  54. tmpl = env.get_template("b/justdict.html")
  55. assert tmpl.render().strip() == "FOO"
  56. pytest.raises(TemplateNotFound, env.get_template, "missing")
  57. def test_caching(self):
  58. changed = False
  59. class TestLoader(loaders.BaseLoader):
  60. def get_source(self, environment, template):
  61. return "foo", None, lambda: not changed
  62. env = Environment(loader=TestLoader(), cache_size=-1)
  63. tmpl = env.get_template("template")
  64. assert tmpl is env.get_template("template")
  65. changed = True
  66. assert tmpl is not env.get_template("template")
  67. changed = False
  68. def test_no_cache(self):
  69. mapping = {"foo": "one"}
  70. env = Environment(loader=loaders.DictLoader(mapping), cache_size=0)
  71. assert env.get_template("foo") is not env.get_template("foo")
  72. def test_limited_size_cache(self):
  73. mapping = {"one": "foo", "two": "bar", "three": "baz"}
  74. loader = loaders.DictLoader(mapping)
  75. env = Environment(loader=loader, cache_size=2)
  76. t1 = env.get_template("one")
  77. t2 = env.get_template("two")
  78. assert t2 is env.get_template("two")
  79. assert t1 is env.get_template("one")
  80. env.get_template("three")
  81. loader_ref = weakref.ref(loader)
  82. assert (loader_ref, "one") in env.cache
  83. assert (loader_ref, "two") not in env.cache
  84. assert (loader_ref, "three") in env.cache
  85. def test_cache_loader_change(self):
  86. loader1 = loaders.DictLoader({"foo": "one"})
  87. loader2 = loaders.DictLoader({"foo": "two"})
  88. env = Environment(loader=loader1, cache_size=2)
  89. assert env.get_template("foo").render() == "one"
  90. env.loader = loader2
  91. assert env.get_template("foo").render() == "two"
  92. def test_dict_loader_cache_invalidates(self):
  93. mapping = {"foo": "one"}
  94. env = Environment(loader=loaders.DictLoader(mapping))
  95. assert env.get_template("foo").render() == "one"
  96. mapping["foo"] = "two"
  97. assert env.get_template("foo").render() == "two"
  98. def test_split_template_path(self):
  99. assert split_template_path("foo/bar") == ["foo", "bar"]
  100. assert split_template_path("./foo/bar") == ["foo", "bar"]
  101. pytest.raises(TemplateNotFound, split_template_path, "../foo")
  102. class TestFileSystemLoader:
  103. searchpath = (Path(yc.test_source_path()) / "res" / "templates").resolve()
  104. @staticmethod
  105. def _test_common(env):
  106. tmpl = env.get_template("test.html")
  107. assert tmpl.render().strip() == "BAR"
  108. tmpl = env.get_template("foo/test.html")
  109. assert tmpl.render().strip() == "FOO"
  110. pytest.raises(TemplateNotFound, env.get_template, "missing.html")
  111. def test_searchpath_as_str(self):
  112. filesystem_loader = loaders.FileSystemLoader(str(self.searchpath))
  113. env = Environment(loader=filesystem_loader)
  114. self._test_common(env)
  115. def test_searchpath_as_pathlib(self):
  116. filesystem_loader = loaders.FileSystemLoader(self.searchpath)
  117. env = Environment(loader=filesystem_loader)
  118. self._test_common(env)
  119. def test_searchpath_as_list_including_pathlib(self):
  120. filesystem_loader = loaders.FileSystemLoader(
  121. ["/tmp/templates", self.searchpath]
  122. )
  123. env = Environment(loader=filesystem_loader)
  124. self._test_common(env)
  125. @pytest.mark.skip("Arcadia read only")
  126. def test_caches_template_based_on_mtime(self):
  127. filesystem_loader = loaders.FileSystemLoader(self.searchpath)
  128. env = Environment(loader=filesystem_loader)
  129. tmpl1 = env.get_template("test.html")
  130. tmpl2 = env.get_template("test.html")
  131. assert tmpl1 is tmpl2
  132. os.utime(self.searchpath / "test.html", (time.time(), time.time()))
  133. tmpl3 = env.get_template("test.html")
  134. assert tmpl1 is not tmpl3
  135. @pytest.mark.parametrize(
  136. ("encoding", "expect"),
  137. [
  138. ("utf-8", "文字化け"),
  139. ("iso-8859-1", "æ\x96\x87\xe5\xad\x97\xe5\x8c\x96\xe3\x81\x91"),
  140. ],
  141. )
  142. def test_uses_specified_encoding(self, encoding, expect):
  143. loader = loaders.FileSystemLoader(self.searchpath, encoding=encoding)
  144. e = Environment(loader=loader)
  145. t = e.get_template("mojibake.txt")
  146. assert t.render() == expect
  147. def test_filename_normpath(self):
  148. """Nested template names should only contain ``os.sep`` in the
  149. loaded filename.
  150. """
  151. loader = loaders.FileSystemLoader(self.searchpath)
  152. e = Environment(loader=loader)
  153. t = e.get_template("foo/test.html")
  154. assert t.filename == str(self.searchpath / "foo" / "test.html")
  155. class TestModuleLoader:
  156. archive = None
  157. mod_env = None
  158. def compile_down(self, prefix_loader, zip="deflated"):
  159. log = []
  160. self.reg_env = Environment(loader=prefix_loader)
  161. if zip is not None:
  162. fd, self.archive = tempfile.mkstemp(suffix=".zip")
  163. os.close(fd)
  164. else:
  165. self.archive = tempfile.mkdtemp()
  166. self.reg_env.compile_templates(self.archive, zip=zip, log_function=log.append)
  167. self.mod_env = Environment(loader=loaders.ModuleLoader(self.archive))
  168. return "".join(log)
  169. def teardown_method(self):
  170. if self.archive is not None:
  171. if os.path.isfile(self.archive):
  172. os.remove(self.archive)
  173. else:
  174. shutil.rmtree(self.archive)
  175. self.archive = None
  176. self.mod_env = None
  177. def test_log(self, prefix_loader):
  178. log = self.compile_down(prefix_loader)
  179. assert (
  180. 'Compiled "a/foo/test.html" as '
  181. "tmpl_a790caf9d669e39ea4d280d597ec891c4ef0404a" in log
  182. )
  183. assert "Finished compiling templates" in log
  184. assert (
  185. 'Could not compile "a/syntaxerror.html": '
  186. "Encountered unknown tag 'endif'" in log
  187. )
  188. def _test_common(self):
  189. tmpl1 = self.reg_env.get_template("a/test.html")
  190. tmpl2 = self.mod_env.get_template("a/test.html")
  191. assert tmpl1.render() == tmpl2.render()
  192. tmpl1 = self.reg_env.get_template("b/justdict.html")
  193. tmpl2 = self.mod_env.get_template("b/justdict.html")
  194. assert tmpl1.render() == tmpl2.render()
  195. def test_deflated_zip_compile(self, prefix_loader):
  196. self.compile_down(prefix_loader, zip="deflated")
  197. self._test_common()
  198. def test_stored_zip_compile(self, prefix_loader):
  199. self.compile_down(prefix_loader, zip="stored")
  200. self._test_common()
  201. def test_filesystem_compile(self, prefix_loader):
  202. self.compile_down(prefix_loader, zip=None)
  203. self._test_common()
  204. def test_weak_references(self, prefix_loader):
  205. self.compile_down(prefix_loader)
  206. self.mod_env.get_template("a/test.html")
  207. key = loaders.ModuleLoader.get_template_key("a/test.html")
  208. name = self.mod_env.loader.module.__name__
  209. assert hasattr(self.mod_env.loader.module, key)
  210. assert name in sys.modules
  211. # unset all, ensure the module is gone from sys.modules
  212. self.mod_env = None
  213. try:
  214. import gc
  215. gc.collect()
  216. except BaseException:
  217. pass
  218. assert name not in sys.modules
  219. def test_choice_loader(self, prefix_loader):
  220. self.compile_down(prefix_loader)
  221. self.mod_env.loader = loaders.ChoiceLoader(
  222. [self.mod_env.loader, loaders.DictLoader({"DICT_SOURCE": "DICT_TEMPLATE"})]
  223. )
  224. tmpl1 = self.mod_env.get_template("a/test.html")
  225. assert tmpl1.render() == "BAR"
  226. tmpl2 = self.mod_env.get_template("DICT_SOURCE")
  227. assert tmpl2.render() == "DICT_TEMPLATE"
  228. def test_prefix_loader(self, prefix_loader):
  229. self.compile_down(prefix_loader)
  230. self.mod_env.loader = loaders.PrefixLoader(
  231. {
  232. "MOD": self.mod_env.loader,
  233. "DICT": loaders.DictLoader({"test.html": "DICT_TEMPLATE"}),
  234. }
  235. )
  236. tmpl1 = self.mod_env.get_template("MOD/a/test.html")
  237. assert tmpl1.render() == "BAR"
  238. tmpl2 = self.mod_env.get_template("DICT/test.html")
  239. assert tmpl2.render() == "DICT_TEMPLATE"
  240. def test_path_as_pathlib(self, prefix_loader):
  241. self.compile_down(prefix_loader)
  242. mod_path = self.mod_env.loader.module.__path__[0]
  243. mod_loader = loaders.ModuleLoader(Path(mod_path))
  244. self.mod_env = Environment(loader=mod_loader)
  245. self._test_common()
  246. def test_supports_pathlib_in_list_of_paths(self, prefix_loader):
  247. self.compile_down(prefix_loader)
  248. mod_path = self.mod_env.loader.module.__path__[0]
  249. mod_loader = loaders.ModuleLoader([Path(mod_path), "/tmp/templates"])
  250. self.mod_env = Environment(loader=mod_loader)
  251. self._test_common()
  252. @pytest.fixture()
  253. def package_dir_loader(monkeypatch):
  254. monkeypatch.syspath_prepend(Path(__file__).parent)
  255. return PackageLoader("res")
  256. @pytest.mark.parametrize(
  257. ("template", "expect"), [("foo/test.html", "FOO"), ("test.html", "BAR")]
  258. )
  259. def test_package_dir_source(package_dir_loader, template, expect):
  260. source, name, up_to_date = package_dir_loader.get_source(None, template)
  261. assert source.rstrip() == expect
  262. assert name.endswith(os.path.join(*split_template_path(template)))
  263. assert up_to_date()
  264. def test_package_dir_list(package_dir_loader):
  265. templates = package_dir_loader.list_templates()
  266. assert "foo/test.html" in templates
  267. assert "test.html" in templates
  268. @pytest.fixture()
  269. def package_file_loader(monkeypatch):
  270. monkeypatch.syspath_prepend(Path(__file__).parent / "res")
  271. return PackageLoader("res")
  272. @pytest.mark.parametrize(
  273. ("template", "expect"), [("foo/test.html", "FOO"), ("test.html", "BAR")]
  274. )
  275. def test_package_file_source(package_file_loader, template, expect):
  276. source, name, up_to_date = package_file_loader.get_source(None, template)
  277. assert source.rstrip() == expect
  278. assert name.endswith(os.path.join(*split_template_path(template)))
  279. assert up_to_date()
  280. def test_package_file_list(package_file_loader):
  281. templates = package_file_loader.list_templates()
  282. assert "foo/test.html" in templates
  283. assert "test.html" in templates
  284. @pytest.fixture()
  285. def package_zip_loader(monkeypatch):
  286. package_zip = (Path(yc.test_source_path()) / "res" / "package.zip").resolve()
  287. monkeypatch.syspath_prepend(package_zip)
  288. return PackageLoader("t_pack")
  289. @pytest.mark.parametrize(
  290. ("template", "expect"), [("foo/test.html", "FOO"), ("test.html", "BAR")]
  291. )
  292. def test_package_zip_source(package_zip_loader, template, expect):
  293. source, name, up_to_date = package_zip_loader.get_source(None, template)
  294. assert source.rstrip() == expect
  295. assert name.endswith(os.path.join(*split_template_path(template)))
  296. assert up_to_date is None
  297. @pytest.mark.xfail(
  298. platform.python_implementation() == "PyPy",
  299. reason="PyPy's zipimporter doesn't have a '_files' attribute.",
  300. raises=TypeError,
  301. )
  302. def test_package_zip_list(package_zip_loader):
  303. assert package_zip_loader.list_templates() == ["foo/test.html", "test.html"]
  304. @pytest.mark.parametrize("package_path", ["", ".", "./"])
  305. def test_package_zip_omit_curdir(package_zip_loader, package_path):
  306. """PackageLoader should not add or include "." or "./" in the root
  307. path, it is invalid in zip paths.
  308. """
  309. loader = PackageLoader("t_pack", package_path)
  310. assert loader.package_path == ""
  311. source, _, _ = loader.get_source(None, "templates/foo/test.html")
  312. assert source.rstrip() == "FOO"
  313. def test_pep_451_import_hook():
  314. class ImportHook(importlib.abc.MetaPathFinder, importlib.abc.Loader):
  315. def find_spec(self, name, path=None, target=None):
  316. if name != "res":
  317. return None
  318. spec = importlib.machinery.PathFinder.find_spec(name)
  319. return importlib.util.spec_from_file_location(
  320. name,
  321. spec.origin,
  322. loader=self,
  323. submodule_search_locations=spec.submodule_search_locations,
  324. )
  325. def create_module(self, spec):
  326. return None # default behaviour is fine
  327. def exec_module(self, module):
  328. return None # we need this to satisfy the interface, it's wrong
  329. # ensure we restore `sys.meta_path` after putting in our loader
  330. before = sys.meta_path[:]
  331. try:
  332. sys.meta_path.insert(0, ImportHook())
  333. package_loader = PackageLoader("res")
  334. assert "test.html" in package_loader.list_templates()
  335. finally:
  336. sys.meta_path[:] = before