Merge pull request #1064 from alexwlchan/support-pathlib
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Support paths created with pathlib in FileSystemLoader and ModuleLoader
authored by David Lord · committed by GitHub · parents 29d1ff4, b43531f · Browse files · 6 files·+136 added−17 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+136 added−17 removed
- tests:+95 added−8 removed
- other:+41 added−9 removed
Provenance
- Commit
afd6c48- Tree
ded34f7- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
29d1ff4- Parent 2
b43531f
6 files changed+136 added−17 removed
modified:jinja2/_compat.py+19 added
101 unmodified lines102 try:103 from collections import abc104 except ImportError:105 import collections as abc106+107+108+try:109+ from os import fspath110+except ImportError:111+ try:112+ from pathlib import PurePath113+ except ImportError:114+ PurePath = None115+116+ def fspath(path):117+ if hasattr(path, "__fspath__"):118+ return path.__fspath__()119+120+ # Python 3.5 doesn't have __fspath__ yet, use str.121+ if PurePath is not None and isinstance(path, PurePath):122+ return str(path)123+124+ return pathmodified:jinja2/loaders.py+19 added-9 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, iteritems, fspath, abc21 22 23 def split_template_path(template):24 """Split a path into segments and perform a sanity check. If it detects128 unmodified lines153 To follow symbolic links, set the *followlinks* parameter to ``True``::154 155 >>> loader = FileSystemLoader('/path/to/templates', followlinks=True)156 157- .. versionchanged:: 2.8+158- The *followlinks* parameter was added.157+ .. versionchanged:: 2.8158+ 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 (163+ not isinstance(searchpath, abc.Iterable)164+ or isinstance(searchpath, string_types)165+ ):166 searchpath = [searchpath]164- self.searchpath = list(searchpath)167+168+ # In Python 3.5, os.path.join doesn't support Path. This can be169+ # simplified to list(searchpath) when Python 3.5 is dropped.170+ self.searchpath = [fspath(p) for p in searchpath]171+172 self.encoding = encoding173 self.followlinks = followlinks174 175 def get_source(self, environment, template):314 unmodified lines490 491 # create a fake module that looks for the templates in the492 # path given.493 mod = _TemplateModule(package_name)487- if isinstance(path, string_types):494+495+ if (496+ not isinstance(path, abc.Iterable)497+ or isinstance(path, string_types)498+ ):499 path = [path]489- else:490- path = list(path)491- mod.__path__ = path500 501+ mod.__path__ = [fspath(p) for p in path]502+503 sys.modules[package_name] = weakref.proxy(mod,504 lambda x: sys.modules.pop(package_name, None))505 506 # the only strong reference, the sys.modules entry is weak30 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+- Support :class:`os.PathLike` objects in53+ :class:`~loader.FileSystemLoader` and :class:`~loader.ModuleLoader`.54+ :issue:`870`55 56 57 Version 2.10.358 --------------629 unmodified lines