support pathlib in FileSystemLoader and ModuleLoader
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Alex Chan · committed by David Lord · parent 29d1ff4 · Browse files · 6 files·+114 added−14 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+114 added−14 removed
- tests:+95 added−8 removed
- other:+19 added−6 removed
Provenance
- Commit
1230796- Tree
506d8bd- Author
Alex Chan <alex@alexwlchan.net>- Committer
David Lord <davidism@gmail.com>- Parent
29d1ff4
6 files changed+114 added−14 removed
modified:jinja2/_compat.py+5 added
22 unmodified lines23 text_type = str24 string_types = (str,)25 integer_types = (int,)26 27+ import pathlib28+ path_types = (str, pathlib.PurePath)29+30 iterkeys = lambda d: iter(d.keys())31 itervalues = lambda d: iter(d.values())32 iteritems = lambda d: iter(d.items())33 21 unmodified lines55 range_type = xrange56 string_types = (str, unicode)57 integer_types = (int, long)58 59+ path_types = string_types60+61 iterkeys = lambda d: d.iterkeys()62 itervalues = lambda d: d.itervalues()63 iteritems = lambda d: d.iteritems()64 46 unmodified linesmodified:jinja2/loaders.py+11 added-6 removed
15 unmodified lines16 from os import path17 from hashlib import sha118 from jinja2.exceptions import TemplateNotFound19 from jinja2.utils import open_if_exists, internalcode20-from jinja2._compat import string_types, iteritems20+from jinja2._compat import string_types, path_types, iteritems21 22 23 def split_template_path(template):24 """Split a path into segments and perform a sanity check. If it detects133 unmodified lines158 The *followlinks* parameter was added.159 """160 161 def __init__(self, searchpath, encoding='utf-8', followlinks=False):162- if isinstance(searchpath, string_types):162+ if isinstance(searchpath, path_types):163 searchpath = [searchpath]164- self.searchpath = list(searchpath)164+165+ # In Python 3.5, os.path.join only supports strings, not instances166+ # of pathlib.Path. This line can be simplified to list(searchpath)167+ # when support for Python 3.5 is dropped.168+ self.searchpath = [str(path) for path in searchpath]169+170 self.encoding = encoding171 self.followlinks = followlinks172 173 def get_source(self, environment, template):314 unmodified lines488 489 # create a fake module that looks for the templates in the490 # path given.491 mod = _TemplateModule(package_name)487- if isinstance(path, string_types):488- path = [path]492+ if isinstance(path, path_types):493+ path = [str(path)]494 else:490- path = list(path)495+ path = [str(p) for p in path]496 mod.__path__ = path497 498 sys.modules[package_name] = weakref.proxy(mod,499 lambda x: sys.modules.pop(package_name, None))32 unmodified linesadded:tests/res/templates/variable_encoding.txt+1 added
1+techmodified:tests/conftest.py+1 added
30 unmodified lines31 'debug',32 'escapeUrlizeTarget',33 'ext',34 'extended',35+ 'filesystemloader',36 'filter',37 'for_loop',38 'helpers',39 'if_condition',82 unmodified linesmodified:tests/test_loader.py+93 added-8 removed
9 unmodified lines10 """11 import os12 import shutil13 import sys14+import time15 import tempfile16 import weakref17 18 import pytest20 unmodified lines39 tmpl = env.get_template('test.html')40 assert tmpl.render().strip() == 'BAR'41 pytest.raises(TemplateNotFound, env.get_template, 'missing.html')42 42- def test_filesystem_loader(self, filesystem_loader):43- env = Environment(loader=filesystem_loader)44- tmpl = env.get_template('test.html')45- assert tmpl.render().strip() == 'BAR'46- tmpl = env.get_template('foo/test.html')47- assert tmpl.render().strip() == 'FOO'48- pytest.raises(TemplateNotFound, env.get_template, 'missing.html')49-43 def test_filesystem_loader_overlapping_names(self, filesystem_loader):44 res = os.path.dirname(filesystem_loader.searchpath[0])45 t2_dir = os.path.join(res, "templates2")46 # Make "foo" show up before "foo/test.html".78 unmodified lines125 pytest.raises(TemplateNotFound, split_template_path, '../foo')126 127 128 @pytest.mark.loaders129+@pytest.mark.filesystemloader130+class TestFileSystemLoader(object):131+ searchpath = os.path.dirname(os.path.abspath(__file__)) + '/res/templates'132+133+ @staticmethod134+ def _test_common(env):135+ tmpl = env.get_template('test.html')136+ assert tmpl.render().strip() == 'BAR'137+ tmpl = env.get_template('foo/test.html')138+ assert tmpl.render().strip() == 'FOO'139+ pytest.raises(TemplateNotFound, env.get_template, 'missing.html')140+141+ def test_searchpath_as_str(self):142+ filesystem_loader = loaders.FileSystemLoader(self.searchpath)143+144+ env = Environment(loader=filesystem_loader)145+ self._test_common(env)146+147+ @pytest.mark.skipif(PY2, reason='pathlib is not available in Python 2')148+ def test_searchpath_as_pathlib(self):149+ import pathlib150+ searchpath = pathlib.Path(self.searchpath)151+152+ filesystem_loader = loaders.FileSystemLoader(searchpath)153+154+ env = Environment(loader=filesystem_loader)155+ self._test_common(env)156+157+ @pytest.mark.skipif(PY2, reason='pathlib is not available in Python 2')158+ def test_searchpath_as_list_including_pathlib(self):159+ import pathlib160+ searchpath = pathlib.Path(self.searchpath)161+162+ filesystem_loader = loaders.FileSystemLoader(['/tmp/templates', searchpath])163+164+ env = Environment(loader=filesystem_loader)165+ self._test_common(env)166+167+ def test_caches_template_based_on_mtime(self):168+ filesystem_loader = loaders.FileSystemLoader(self.searchpath)169+170+ env = Environment(loader=filesystem_loader)171+ tmpl1 = env.get_template('test.html')172+ tmpl2 = env.get_template('test.html')173+ assert tmpl1 is tmpl2174+175+ os.utime(176+ os.path.join(self.searchpath, "test.html"),177+ (time.time(), time.time())178+ )179+ tmpl3 = env.get_template('test.html')180+ assert tmpl1 is not tmpl3181+182+ @pytest.mark.parametrize('encoding, expected_text', [183+ ('utf-8', u'tech'),184+ ('utf-16', u'整档'),185+ ])186+ def test_uses_specified_encoding(self, encoding, expected_text):187+ filesystem_loader = loaders.FileSystemLoader(self.searchpath, encoding=encoding)188+ env = Environment(loader=filesystem_loader)189+ tmpl = env.get_template('variable_encoding.txt')190+ assert tmpl.render().strip() == expected_text191+192+193+@pytest.mark.loaders194 @pytest.mark.moduleloader195 class TestModuleLoader(object):196 archive = None197 105 unmodified lines303 assert tmpl1.render() == 'BAR'304 tmpl2 = self.mod_env.get_template('DICT/test.html')305 assert tmpl2.render() == 'DICT_TEMPLATE'306 307+ @pytest.mark.skipif(PY2, reason='pathlib is not available in Python 2')308+ def test_path_as_pathlib(self, prefix_loader):309+ self.compile_down(prefix_loader)310 311+ mod_path = self.mod_env.loader.module.__path__[0]312+313+ import pathlib314+ mod_loader = loaders.ModuleLoader(pathlib.Path(mod_path))315+ self.mod_env = Environment(loader=mod_loader)316+317+ self._test_common()318+319+ @pytest.mark.skipif(PY2, reason='pathlib is not available in Python 2')320+ def test_supports_pathlib_in_list_of_paths(self, prefix_loader):321+ self.compile_down(prefix_loader)322+323+ mod_path = self.mod_env.loader.module.__path__[0]324+325+ import pathlib326+ mod_loader = loaders.ModuleLoader([327+ pathlib.Path(mod_path),328+ '/tmp/templates'329+ ])330+ self.mod_env = Environment(loader=mod_loader)331+332+ self._test_common()333+334+335 @pytest.fixture()336 def package_dir_loader(monkeypatch):337 monkeypatch.syspath_prepend(os.path.dirname(__file__))338 return PackageLoader("res")43 unmodified linesmodified:CHANGES.rst+3 added
47 unmodified lines48 ``revindex0`` when looping over a generator. :issue:`459, 751, 794`,49 :pr:`993`50 - ``PackageLoader`` doesn't depend on setuptools or pkg_resources.51 :issue:`970`52+- Allow passing ``pathlib.Path`` as the search path in53+ :class:`~loader.FileSystemLoader` and54+ :class:`~loader.ModuleLoader`. :issue:`870`55 56 57 Version 2.10.358 --------------629 unmodified lines