handle Undefined in get/select_template
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 9176fbd · Browse files · 5 files·+95 added−25 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+95 added−25 removed
- tests:+25 added−0 removed
- other:+70 added−25 removed
Provenance
- Commit
2ec62dc- Tree
d1fc038- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
9176fbd
5 files changed+95 added−25 removed
modified:jinja2/environment.py+12 added-4 removed
23 unmodified lines24 from jinja2.nodes import EvalContext25 from jinja2.compiler import generate, CodeGenerator26 from jinja2.runtime import Undefined, new_context, Context27 from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \28- TemplatesNotFound, TemplateRuntimeError28+ TemplatesNotFound, TemplateRuntimeError, UndefinedError29 from jinja2.utils import import_string, LRUCache, Markup, missing, \30 concat, consume, internalcode, have_async_gen31 from jinja2._compat import imap, ifilter, string_types, iteritems, \32 text_type, reraise, implements_iterator, implements_to_string, \778 unmodified lines811 """Works like :meth:`get_template` but tries a number of templates812 before it fails. If it cannot find any of the templates, it will813 raise a :exc:`TemplatesNotFound` exception.814 815- .. versionadded:: 2.3815+ .. versionchanged:: 2.11816+ If names is :class:`Undefined`, an :exc:`UndefinedError` is817+ raised instead. If no templates were found and names818+ contains :class:`Undefined`, the message is more helpful.819 820 .. versionchanged:: 2.4821 If `names` contains a :class:`Template` object it is returned822 from the function unchanged.823+824+ .. versionadded:: 2.3825 """826+ if isinstance(names, Undefined):827+ names._fail_with_undefined_error()828+829 if not names:830 raise TemplatesNotFound(message=u'Tried to select from an empty list '831 u'of templates.')832 globals = self.make_globals(globals)3 unmodified lines836 if parent is not None:837 name = self.join_path(name, parent)838 try:839 return self._load_template(name, globals)832- except TemplateNotFound:840+ except (TemplateNotFound, UndefinedError):841 pass842 raise TemplatesNotFound(names)843 844 @internalcode4 unmodified lines849 :meth:`get_template`.850 851 .. versionadded:: 2.3852 """845- if isinstance(template_name_or_list, string_types):853+ if isinstance(template_name_or_list, (string_types, Undefined)):854 return self.get_template(template_name_or_list, parent, globals)855 elif isinstance(template_name_or_list, Template):856 return template_name_or_list857 return self.select_template(template_name_or_list, parent, globals)407 unmodified linesmodified:jinja2/exceptions.py+28 added-2 removed
41 unmodified lines42 43 44 @implements_to_string45 class TemplateNotFound(IOError, LookupError, TemplateError):46- """Raised if a template does not exist."""46+ """Raised if a template does not exist.47 48+ .. versionchanged:: 2.1149+ If the given name is :class:`Undefined` and no message was50+ provided, an :exc:`UndefinedError` is raised.51+ """52+53 # looks weird, but removes the warning descriptor that just54 # bogusly warns us about message being deprecated55 message = None56 57 def __init__(self, name, message=None):58 IOError.__init__(self, name)59+60 if message is None:61+ from jinja2.runtime import Undefined62+63+ if isinstance(name, Undefined):64+ name._fail_with_undefined_error()65+66 message = name67+68 self.message = message69 self.name = name70 self.templates = [name]71 5 unmodified lines77 """Like :class:`TemplateNotFound` but raised if multiple templates78 are selected. This is a subclass of :class:`TemplateNotFound`79 exception, so just catching the base exception will catch both.80 81+ .. versionchanged:: 2.1182+ If a name in the list of names is :class:`Undefined`, a message83+ about it being undefined is shown rather than the empty string.84+85 .. versionadded:: 2.286 """87 88 def __init__(self, names=(), message=None):89 if message is None:90+ from jinja2.runtime import Undefined91+92+ parts = []93+94+ for name in names:95+ if isinstance(name, Undefined):96+ parts.append(name._undefined_message)97+ else:98+ parts.append(name)99+100 message = u'none of the templates given were found: ' + \75- u', '.join(imap(text_type, names))101+ u', '.join(imap(text_type, parts))102 TemplateNotFound.__init__(self, names and names[-1] or None, message)103 self.templates = list(names)104 105 67 unmodified linesmodified:jinja2/runtime.py+25 added-18 removed
666 unmodified lines667 self._undefined_obj = obj668 self._undefined_name = name669 self._undefined_exception = exc670 671+ @property672+ def _undefined_message(self):673+ """Build a message about the undefined value based on how it was674+ accessed.675+ """676+ if self._undefined_hint:677+ return self._undefined_hint678+679+ if self._undefined_obj is missing:680+ return '%r is undefined' % self._undefined_name681+682+ if not isinstance(self._undefined_name, string_types):683+ return '%s has no element %r' % (684+ object_type_repr(self._undefined_obj),685+ self._undefined_name686+ )687+688+ return '%r has no attribute %r' % (689+ object_type_repr(self._undefined_obj),690+ self._undefined_name691+ )692+693 @internalcode694 def _fail_with_undefined_error(self, *args, **kwargs):673- """Regular callback function for undefined objects that raises an674- `UndefinedError` on call.695+ """Raise an :exc:`UndefinedError` when operations are performed696+ on the undefined value.697 """676- if self._undefined_hint is None:677- if self._undefined_obj is missing:678- hint = '%r is undefined' % self._undefined_name679- elif not isinstance(self._undefined_name, string_types):680- hint = '%s has no element %r' % (681- object_type_repr(self._undefined_obj),682- self._undefined_name683- )684- else:685- hint = '%r has no attribute %r' % (686- object_type_repr(self._undefined_obj),687- self._undefined_name688- )689- else:690- hint = self._undefined_hint691- raise self._undefined_exception(hint)698+ raise self._undefined_exception(self._undefined_message)699 700 @internalcode701 def __getattr__(self, name):702 if name[:2] == '__':204 unmodified linesmodified:tests/test_api.py+25 added
15 unmodified lines16 import pytest17 from jinja2 import Environment, Undefined, ChainableUndefined, \18 DebugUndefined, StrictUndefined, UndefinedError, meta, \19 is_undefined, Template, DictLoader, make_logging_undefined20+from jinja2 import TemplatesNotFound21 from jinja2.compiler import CodeGenerator22 from jinja2.runtime import Context23 from jinja2.utils import Cycler24 from jinja2.utils import contextfunction100 unmodified lines125 assert env.select_template([t]) is t126 assert env.get_or_select_template([t]) is t127 assert env.get_or_select_template(t) is t128 129+ def test_get_template_undefined(self, env):130+ """Passing Undefined to get/select_template raises an131+ UndefinedError or shows the undefined message in the list.132+ """133+ env.loader=DictLoader({})134+ t = Undefined(name="no_name_1")135+136+ with pytest.raises(UndefinedError):137+ env.get_template(t)138+139+ with pytest.raises(UndefinedError):140+ env.get_or_select_template(t)141+142+ with pytest.raises(UndefinedError):143+ env.select_template(t)144+145+ with pytest.raises(TemplatesNotFound) as exc_info:146+ env.select_template([t, "no_name_2"])147+148+ exc_message = str(exc_info.value)149+ assert "'no_name_1' is undefined" in exc_message150+ assert "no_name_2" in exc_message151+152+153 def test_autoescape_autoselect(self, env):154 def select_autoescape(name):155 if name is None or '.' not in name:156 return False284 unmodified linesmodified:CHANGES.rst+5 added-1 removed
92 unmodified lines93 - Constant folding during compilation is applied to some node types94 that were previously overlooked. :issue:`733`95 - ``TemplateSyntaxError.source`` is not empty when raised from an96 included template. :issue:`457`97+- Passing an ``Undefined`` value to ``get_template`` (such as through98+ ``extends``, ``import``, or ``include``), raises an99+ ``UndefinedError`` consistently. ``select_template`` will show the100+ undefined message in the list of attempts rather than the empty101+ string. :issue:`1037`102 98-103 Version 2.10.3104 --------------105 106 Released 2019-10-04627 unmodified lines