Skip to content
Myr

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

6 files+136 added−17 removed

modified:jinja2/_compat.py+19 added
101 unmodified lines
102try:103 from collections import abc104except ImportError:105 import collections as abc106107108try:109 from os import fspath110except ImportError:111 try:112 from pathlib import PurePath113 except ImportError:114 PurePath = None115116 def fspath(path):117 if hasattr(path, "__fspath__"):118 return path.__fspath__()119120 # Python 3.5 doesn't have __fspath__ yet, use str.121 if PurePath is not None and isinstance(path, PurePath):122 return str(path)123124 return path
modified:jinja2/loaders.py+19 added-9 removed
15 unmodified lines
16from os import path17from hashlib import sha118from jinja2.exceptions import TemplateNotFound19from jinja2.utils import open_if_exists, internalcode20from jinja2._compat import string_types, iteritems20from jinja2._compat import string_types, iteritems, fspath, abc212223def split_template_path(template):24 """Split a path into segments and perform a sanity check. If it detects
128 unmodified lines
153 To follow symbolic links, set the *followlinks* parameter to ``True``::154155 >>> loader = FileSystemLoader('/path/to/templates', followlinks=True)156157 .. versionchanged:: 2.8+158 The *followlinks* parameter was added.157 .. versionchanged:: 2.8158 The ``followlinks`` parameter was added.159 """160161 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)167168 # 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]171172 self.encoding = encoding173 self.followlinks = followlinks174175 def get_source(self, environment, template):
314 unmodified lines
490491 # create a fake module that looks for the templates in the492 # path given.493 mod = _TemplateModule(package_name)487 if isinstance(path, string_types):494495 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__ = path500501 mod.__path__ = [fspath(p) for p in path]502503 sys.modules[package_name] = weakref.proxy(mod,504 lambda x: sys.modules.pop(package_name, None))505506 # the only strong reference, the sys.modules entry is weak
30 unmodified lines
added:tests/res/templates/variable_encoding.txt+1 added
1tech
modified:tests/conftest.py+1 added
30 unmodified lines
31 'debug',32 'escapeUrlizeTarget',33 'ext',34 'extended',35 'filesystemloader',36 'filter',37 'for_loop',38 'helpers',39 'if_condition',
82 unmodified lines
modified:tests/test_loader.py+93 added-8 removed
9 unmodified lines
10"""11import os12import shutil13import sys14import time15import tempfile16import weakref1718import pytest
20 unmodified lines
39 tmpl = env.get_template('test.html')40 assert tmpl.render().strip() == 'BAR'41 pytest.raises(TemplateNotFound, env.get_template, 'missing.html')4242 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')4943 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 lines
125 pytest.raises(TemplateNotFound, split_template_path, '../foo')126127128@pytest.mark.loaders129@pytest.mark.filesystemloader130class TestFileSystemLoader(object):131 searchpath = os.path.dirname(os.path.abspath(__file__)) + '/res/templates'132133 @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')140141 def test_searchpath_as_str(self):142 filesystem_loader = loaders.FileSystemLoader(self.searchpath)143144 env = Environment(loader=filesystem_loader)145 self._test_common(env)146147 @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)151152 filesystem_loader = loaders.FileSystemLoader(searchpath)153154 env = Environment(loader=filesystem_loader)155 self._test_common(env)156157 @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)161162 filesystem_loader = loaders.FileSystemLoader(['/tmp/templates', searchpath])163164 env = Environment(loader=filesystem_loader)165 self._test_common(env)166167 def test_caches_template_based_on_mtime(self):168 filesystem_loader = loaders.FileSystemLoader(self.searchpath)169170 env = Environment(loader=filesystem_loader)171 tmpl1 = env.get_template('test.html')172 tmpl2 = env.get_template('test.html')173 assert tmpl1 is tmpl2174175 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 tmpl3181182 @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_text191192193@pytest.mark.loaders194@pytest.mark.moduleloader195class TestModuleLoader(object):196 archive = None197
105 unmodified lines
303 assert tmpl1.render() == 'BAR'304 tmpl2 = self.mod_env.get_template('DICT/test.html')305 assert tmpl2.render() == 'DICT_TEMPLATE'306307 @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)310311 mod_path = self.mod_env.loader.module.__path__[0]312313 import pathlib314 mod_loader = loaders.ModuleLoader(pathlib.Path(mod_path))315 self.mod_env = Environment(loader=mod_loader)316317 self._test_common()318319 @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)322323 mod_path = self.mod_env.loader.module.__path__[0]324325 import pathlib326 mod_loader = loaders.ModuleLoader([327 pathlib.Path(mod_path),328 '/tmp/templates'329 ])330 self.mod_env = Environment(loader=mod_loader)331332 self._test_common()333334335@pytest.fixture()336def package_dir_loader(monkeypatch):337 monkeypatch.syspath_prepend(os.path.dirname(__file__))338 return PackageLoader("res")
43 unmodified lines
modified:CHANGES.rst+3 added
47 unmodified lines
48 ``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`555657Version 2.10.358--------------
629 unmodified lines