add 'is filter' and 'is test' tests
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This required allowing tests to be decorated with '@environmentfilter'. Tests are essentially the same as filters now, the node, compiler, and environment have been refactored to extract common behavior.
authored by David Lord · committed by David Lord · parent af5d80e · Browse files · 8 files·+342 added−175 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+342 added−175 removed
- tests:+31 added−6 removed
- other:+311 added−169 removed
Provenance
- Commit
6c73360- Tree
5b06d10- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
af5d80e
8 files changed+342 added−175 removed
modified:docs/api.rst+95 added-72 removed
664 unmodified lines665 666 Custom Filters667 --------------668 669-Custom filters are just regular Python functions that take the left side of670-the filter as first argument and the arguments passed to the filter as671-extra arguments or keyword arguments.669+Filters are Python functions that take the value to the left of the670+filter as the first argument and produce a new value. Arguments passed671+to the filter are passed after the value.672 673-For example in the filter ``{{ 42|myfilter(23) }}`` the function would be674-called with ``myfilter(42, 23)``. Here for example a simple filter that can675-be applied to datetime objects to format them::673+For example, the filter ``{{ 42|myfilter(23) }}`` is called behind the674+scenes as ``myfilter(42, 23)``.675 677- def datetimeformat(value, format='%H:%M / %d-%m-%Y'):678- return value.strftime(format)676+Jinja comes with some :ref:`built-in filters <builtin-filters>`. To use677+a custom filter, write a function that takes at least a ``value``678+argument, then register it in :attr:`Environment.filters`.679 680-You can register it on the template environment by updating the681-:attr:`~Environment.filters` dict on the environment::680+Here's a filter that formats datetime objects:681 683- environment.filters['datetimeformat'] = datetimeformat682+.. code-block:: python683 685-Inside the template it can then be used as follows:684+ def datetime_format(value, format="%H:%M %d-%m-%y"):685+ return value.strftime(format)686 687+ environment.filters["datetime_format"] = datetime_format688+689+Now it can be used in templates:690+691 .. sourcecode:: jinja692 689- written on: {{ article.pub_date|datetimeformat }}690- publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}693+ {{ article.pub_date|datetimeformat }}694+ {{ article.pub_date|datetimeformat("%B %Y") }}695 692-Filters can also be passed the current template context or environment. This693-is useful if a filter wants to return an undefined value or check the current694-:attr:`~Environment.autoescape` setting. For this purpose three decorators695-exist: :func:`environmentfilter`, :func:`contextfilter` and696-:func:`evalcontextfilter`.696+Some decorators are available to tell Jinja to pass extra information to697+the filter. The object is passed as the first argument, making the value698+being filtered the second argument.699 698-Here a small example filter that breaks a text into HTML line breaks and699-paragraphs and marks the return value as safe HTML string if autoescaping is700-enabled::700+- :func:`environmentfilter` passes the :class:`Environment`.701+- :func:`evalcontextfilter` passes the :ref:`eval-context`.702+- :func:`contextfilter` passes the current703+ :class:`~jinja2.runtime.Context`.704 702- import re703- from jinja2 import evalcontextfilter, Markup, escape705+Here's a filter that converts line breaks into HTML ``<br>`` and ``<p>``706+tags. It uses the eval context to check if autoescape is currently707+enabled before escaping the input and marking the output safe.708 705- _paragraph_re = re.compile(r"(?:\r\n|\r(?!\n)|\n){2,}")709+.. code-block:: python710 711+ import re712+ from jinja2 import evalcontextfilter713+ from markupsafe import Markup, escape714+715 @evalcontextfilter716 def nl2br(eval_ctx, value):717+ br = "<br>\n"718+719+ if eval_ctx.autoescape:720+ value = escape(value)721+ br = Markup(br)722+723 result = "\n\n".join(710- f"<p>{p.replace('\n', Markup('<br>\n'))}</p>"711- for p in _paragraph_re.split(escape(value))724+ f"<p>{br.join(p.splitlines())}<\p>"725+ for p in re.split(r"(?:\r\n|\r(?!\n)|\n){2,}", value)726 )713- if eval_ctx.autoescape:714- result = Markup(result)715- return result727+ return Markup(result) if autoescape else result728 717-Context filters work the same just that the first argument is the current718-active :class:`Context` rather than the environment.729 730+.. _writing-tests:731 732+Custom Tests733+------------734+735+Test are Python functions that take the value to the left of the test as736+the first argument, and return ``True`` or ``False``. Arguments passed737+to the test are passed after the value.738+739+For example, the test ``{{ 42 is even }}`` is called behind the scenes740+as ``is_even(42)``.741+742+Jinja comes with some :ref:`built-in tests <builtin-tests>`. To use a743+custom tests, write a function that takes at least a ``value`` argument,744+then register it in :attr:`Environment.tests`.745+746+Here's a test that checks if a value is a prime number:747+748+.. code-block:: python749+750+ import math751+752+ def is_prime(n):753+ if n == 2:754+ return True755+756+ for i in range(2, int(math.ceil(math.sqrt(n))) + 1):757+ if n % i == 0:758+ return False759+760+ return True761+762+ environment.tests["prime"] = is_prime763+764+Now it can be used in templates:765+766+.. sourcecode:: jinja767+768+ {% if value is prime %}769+ {{ value }} is a prime number770+ {% else %}771+ {{ value }} is not a prime number772+ {% endif %}773+774+Some decorators are available to tell Jinja to pass extra information to775+the filter. The object is passed as the first argument, making the value776+being filtered the second argument.777+778+- :func:`environmentfunction` passes the :class:`Environment`.779+- :func:`evalcontextfunction` passes the :ref:`eval-context`.780+- :func:`contextfunction` passes the current781+ :class:`~jinja2.runtime.Context`.782+783+784 .. _eval-context:785 786 Evaluation Context787 ------------------54 unmodified lines842 `True` if the compiler cannot evaluate some expressions at compile843 time. At runtime this should always be `False`.844 845 783-.. _writing-tests:784-785-Custom Tests786-------------787-788-Tests work like filters just that there is no way for a test to get access789-to the environment or context and that they can't be chained. The return790-value of a test should be `True` or `False`. The purpose of a test is to791-give the template designers the possibility to perform type and conformability792-checks.793-794-Here a simple test that checks if a variable is a prime number::795-796- import math797-798- def is_prime(n):799- if n == 2:800- return True801- for i in range(2, int(math.ceil(math.sqrt(n))) + 1):802- if n % i == 0:803- return False804- return True805-806-807-You can register it on the template environment by updating the808-:attr:`~Environment.tests` dict on the environment::809-810- environment.tests['prime'] = is_prime811-812-A template designer can then use the test like this:813-814-.. sourcecode:: jinja815-816- {% if 42 is prime %}817- 42 is a prime number818- {% else %}819- 42 is not a prime number820- {% endif %}821-822-846 .. _global-namespace:847 848 The Global Namespace849 --------------------85 unmodified linesmodified:src/jinja2/compiler.py+66 added-29 removed
1 """Compiles nodes from the parser into Python code."""2 import typing as t3 from collections import namedtuple4+from contextlib import contextmanager5 from functools import update_wrapper6 from io import StringIO7 from itertools import chain8 from keyword import iskeyword as is_python_keyword431 unmodified lines440 self.write(", **")441 self.visit(node.dyn_kwargs, frame)442 443 def pull_dependencies(self, nodes):443- """Pull all the dependencies."""444+ """Find all filter and test names used in the template and445+ assign them to variables in the compiled namespace. Checking446+ that the names are registered with the environment is done when447+ compiling the Filter and Test nodes. If the node is in an If or448+ CondExpr node, the check is done at runtime instead.449+450+ .. versionchanged:: 3.0451+ Filters and tests in If and CondExpr nodes are checked at452+ runtime instead of compile time.453+ """454 visitor = DependencyFinderVisitor()455+456 for node in nodes:457 visitor.visit(node)458+459 for dependency in "filters", "tests":460 mapping = getattr(self, dependency)461+462 for name in getattr(visitor, dependency):463 if name not in mapping:464 mapping[name] = self.temporary_identifier()465+466 # add check during runtime that dependencies used inside of executed467 # blocks are defined, as this step may be skipped during compile time468 self.writeline("try:")469 self.indent()4 unmodified lines474 self.writeline("@internalcode")475 self.writeline(f"def {mapping[name]}(*unused):")476 self.indent()477 self.writeline(464- f'raise TemplateRuntimeError("no filter named {name!r} found")'478+ f'raise TemplateRuntimeError("No {dependency[:-1]}'479+ f' named {name!r} found.")'480 )481 self.outdent()482 self.outdent()483 1187 unmodified lines1671 if node.step is not None:1672 self.write(":")1673 self.visit(node.step, frame)1674 1660- @optimizeconst1661- def visit_Filter(self, node, frame):1675+ @contextmanager1676+ def _filter_test_common(self, node, frame, is_filter):1677+ if is_filter:1678+ compiler_map = self.filters1679+ env_map = self.environment.filters1680+ type_name = mark_name = "filter"1681+ else:1682+ compiler_map = self.tests1683+ env_map = self.environment.tests1684+ type_name = "test"1685+ # Filters use "contextfilter", tests and calls use "contextfunction".1686+ mark_name = "function"1687+1688 if self.environment.is_async:1689 self.write("await auto_await(")1690+1664- self.write(self.filters[node.name] + "(")1665- func = self.environment.filters.get(node.name)1691+ self.write(compiler_map[node.name] + "(")1692+ func = env_map.get(node.name)1693+1694+ # When inside an If or CondExpr frame, allow the filter to be1695+ # undefined at compile time and only raise an error if it's1696+ # actually called at runtime. See pull_dependencies.1697 if func is None and not frame.soft_frame:1667- self.fail(f"no filter named {node.name!r}", node.lineno)1668- if getattr(func, "contextfilter", False) is True:1698+ self.fail(f"No {type_name} named {node.name!r}.", node.lineno)1699+1700+ if getattr(func, f"context{mark_name}", False) is True:1701 self.write("context, ")1670- elif getattr(func, "evalcontextfilter", False) is True:1702+ elif getattr(func, f"evalcontext{mark_name}", False) is True:1703 self.write("context.eval_ctx, ")1672- elif getattr(func, "environmentfilter", False) is True:1704+ elif getattr(func, f"environment{mark_name}", False) is True:1705 self.write("environment, ")1706 1675- # if the filter node is None we are inside a filter block1676- # and want to write to the current buffer1677- if node.node is not None:1678- self.visit(node.node, frame)1679- elif frame.eval_ctx.volatile:1680- self.write(1681- f"(Markup(concat({frame.buffer}))"1682- f" if context.eval_ctx.autoescape else concat({frame.buffer}))"1683- )1684- elif frame.eval_ctx.autoescape:1685- self.write(f"Markup(concat({frame.buffer}))")1686- else:1687- self.write(f"concat({frame.buffer})")1707+ # Back to the visitor function to handle visiting the target of1708+ # the filter or test.1709+ yield1710+1711 self.signature(node, frame)1712 self.write(")")1713+1714 if self.environment.is_async:1715 self.write(")")1716 1717 @optimizeconst1718+ def visit_Filter(self, node, frame):1719+ with self._filter_test_common(node, frame, True):1720+ # if the filter node is None we are inside a filter block1721+ # and want to write to the current buffer1722+ if node.node is not None:1723+ self.visit(node.node, frame)1724+ elif frame.eval_ctx.volatile:1725+ self.write(1726+ f"(Markup(concat({frame.buffer}))"1727+ f" if context.eval_ctx.autoescape else concat({frame.buffer}))"1728+ )1729+ elif frame.eval_ctx.autoescape:1730+ self.write(f"Markup(concat({frame.buffer}))")1731+ else:1732+ self.write(f"concat({frame.buffer})")1733+1734+ @optimizeconst1735 def visit_Test(self, node, frame):1695- self.write(self.tests[node.name] + "(")1696- if node.name not in self.environment.tests:1697- self.fail(f"no test named {node.name!r}", node.lineno)1698- self.visit(node.node, frame)1699- self.signature(node, frame)1700- self.write(")")1736+ with self._filter_test_common(node, frame, False):1737+ self.visit(node.node, frame)1738 1739 @optimizeconst1740 def visit_CondExpr(self, node, frame):1741 frame = frame.soft()120 unmodified linesmodified:src/jinja2/environment.py+62 added-33 removed
100 unmodified lines101 result[extension.identifier] = extension(environment)102 return result103 104 105-def fail_for_missing_callable(thing, name):106- msg = f"no {thing} named {name!r}"107-108- if isinstance(name, Undefined):109- try:110- name._fail_with_undefined_error()111- except Exception as e:112- msg = f"{msg} ({e}; did you forget to quote the callable name?)"113- raise TemplateRuntimeError(msg)114-115-105 def _environment_sanity_check(environment):106 """Perform a sanity check on the environment."""107 assert issubclass(108 environment.undefined, Undefined349 unmodified lines458 return obj[attribute]459 except (TypeError, LookupError, AttributeError):460 return self.undefined(obj=obj, name=attribute)461 473- def call_filter(474- self, name, value, args=None, kwargs=None, context=None, eval_ctx=None462+ def _filter_test_common(463+ self, name, value, args, kwargs, context, eval_ctx, is_filter464 ):476- """Invokes a filter on a value the same way the compiler does.465+ if is_filter:466+ env_map = self.filters467+ type_name = mark_name = "filter"468+ else:469+ env_map = self.tests470+ type_name = "test"471+ # Filters use "contextfilter", tests and calls use "contextfunction".472+ mark_name = "function"473 478- This might return a coroutine if the filter is running from an479- environment in async mode and the filter supports async480- execution. It's your responsibility to await this if needed.474+ func = env_map.get(name)475 482- .. versionadded:: 2.7483- """484- func = self.filters.get(name)476 if func is None:486- fail_for_missing_callable("filter", name)487- args = [value] + list(args or ())488- if getattr(func, "contextfilter", False) is True:477+ msg = f"No {type_name} named {name!r}."478+479+ if isinstance(name, Undefined):480+ try:481+ name._fail_with_undefined_error()482+ except Exception as e:483+ msg = f"{msg} ({e}; did you forget to quote the callable name?)"484+485+ raise TemplateRuntimeError(msg)486+487+ args = [value, *(args if args is not None else ())]488+ kwargs = kwargs if kwargs is not None else {}489+490+ if getattr(func, f"context{mark_name}", False) is True:491 if context is None:492 raise TemplateRuntimeError(491- "Attempted to invoke context filter without context"493+ f"Attempted to invoke a context {type_name} without context."494 )495+496 args.insert(0, context)494- elif getattr(func, "evalcontextfilter", False) is True:497+ elif getattr(func, f"evalcontext{mark_name}", False) is True:498 if eval_ctx is None:499 if context is not None:500 eval_ctx = context.eval_ctx501 else:502 eval_ctx = EvalContext(self)503+504 args.insert(0, eval_ctx)501- elif getattr(func, "environmentfilter", False) is True:505+ elif getattr(func, f"environment{mark_name}", False) is True:506 args.insert(0, self)503- return func(*args, **(kwargs or {}))507 505- def call_test(self, name, value, args=None, kwargs=None):506- """Invokes a test on a value the same way the compiler does it.508+ return func(*args, **kwargs)509 510+ def call_filter(511+ self, name, value, args=None, kwargs=None, context=None, eval_ctx=None512+ ):513+ """Invoke a filter on a value the same way the compiler does.514+515+ This might return a coroutine if the filter is running from an516+ environment in async mode and the filter supports async517+ execution. It's your responsibility to await this if needed.518+519 .. versionadded:: 2.7520 """510- func = self.tests.get(name)511- if func is None:512- fail_for_missing_callable("test", name)513- return func(value, *(args or ()), **(kwargs or {}))521+ return self._filter_test_common(522+ name, value, args, kwargs, context, eval_ctx, True523+ )524 525+ def call_test(526+ self, name, value, args=None, kwargs=None, context=None, eval_ctx=None527+ ):528+ """Invoke a test on a value the same way the compiler does.529+530+ This might return a coroutine if the test is running from an531+ environment in async mode and the test supports async execution.532+ It's your responsibility to await this if needed.533+534+ .. versionchanged:: 3.0535+ Tests support ``@contextfunction``, etc. decorators. Added536+ the ``context`` and ``eval_ctx`` parameters.537+538+ .. versionadded:: 2.7539+ """540+ return self._filter_test_common(541+ name, value, args, kwargs, context, eval_ctx, False542+ )543+544 @internalcode545 def parse(self, source, name=None, filename=None):546 """Parse the sourcecode and return the abstract syntax tree. This547 tree of nodes is used by the compiler to convert the template into865 unmodified linesmodified:src/jinja2/nodes.py+40 added-35 removed
631 unmodified lines632 633 return args, kwargs634 635 636-class Filter(Expr):637- """This node applies a filter on an expression. `name` is the name of638- the filter, the rest of the fields are the same as for :class:`Call`.639-640- If the `node` of a filter is `None` the contents of the last buffer are641- filtered. Buffers are created by macros and filter blocks.642- """643-636+class _FilterTestCommon(Expr):637 fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")638+ abstract = True639+ _is_filter = True640 641 def as_const(self, eval_ctx=None):642 eval_ctx = get_eval_context(self, eval_ctx)643 649- if eval_ctx.volatile or self.node is None:644+ if eval_ctx.volatile:645 raise Impossible()646 652- filter_ = self.environment.filters.get(self.name)647+ if self._is_filter:648+ env_map = eval_ctx.environment.filters649+ mark_name = "filter"650+ else:651+ env_map = eval_ctx.environment.tests652+ # Filters use "contextfilter", tests and calls use "contextfunction".653+ mark_name = "function"654 654- if filter_ is None or getattr(filter_, "contextfilter", False) is True:655+ func = env_map.get(self.name)656+657+ if func is None or getattr(func, f"context{mark_name}", False) is True:658 raise Impossible()659 657- # We cannot constant handle async filters, so we need to make658- # sure to not go down this path. Account for both sync/async and659- # pure-async filters.660 if eval_ctx.environment.is_async and (661- getattr(filter_, "asyncfiltervariant", False)662- or inspect.iscoroutinefunction(filter_)661+ getattr(func, f"async{mark_name}variant", False)662+ or inspect.iscoroutinefunction(func)663 ):664 raise Impossible()665 666 args, kwargs = args_as_const(self, eval_ctx)667 args.insert(0, self.node.as_const(eval_ctx))668 669- if getattr(filter_, "evalcontextfilter", False) is True:669+ if getattr(func, f"evalcontext{mark_name}", False) is True:670 args.insert(0, eval_ctx)671- elif getattr(filter_, "environmentfilter", False) is True:672- args.insert(0, self.environment)671+ elif getattr(func, f"environment{mark_name}", False) is True:672+ args.insert(0, eval_ctx.environment)673 674 try:675- return filter_(*args, **kwargs)675+ return func(*args, **kwargs)676 except Exception:677 raise Impossible()678 679 680-class Test(Expr):681- """Applies a test on an expression. `name` is the name of the test, the682- rest of the fields are the same as for :class:`Call`.680+class Filter(_FilterTestCommon):681+ """Apply a filter to an expression. ``name`` is the name of the682+ filter, the other fields are the same as :class:`Call`.683+684+ If ``node`` is ``None``, the filter is being used in a filter block685+ and is applied to the content of the block.686 """687 685- fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")686-688 def as_const(self, eval_ctx=None):688- test = self.environment.tests.get(self.name)689-690- if test is None:689+ if self.node is None:690 raise Impossible()691 693- eval_ctx = get_eval_context(self, eval_ctx)694- args, kwargs = args_as_const(self, eval_ctx)695- args.insert(0, self.node.as_const(eval_ctx))692+ return super().as_const(eval_ctx=eval_ctx)693 697- try:698- return test(*args, **kwargs)699- except Exception:700- raise Impossible()694 695+class Test(_FilterTestCommon):696+ """Apply a test to an expression. ``name`` is the name of the test,697+ the other field are the same as :class:`Call`.698 699+ .. versionchanged:: 3.0700+ ``as_const`` shares the same logic for filters and tests. Tests701+ check for volatile, async, and ``@contextfunction`` etc.702+ decorators.703+ """704+705+ _is_filter = False706+707+708 class Call(Expr):709 """Calls an expression. `args` is a list of arguments, `kwargs` a list710 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`711 and `dyn_kwargs` has to be either `None` or a node that is used as355 unmodified linesmodified:src/jinja2/tests.py+43 added
3 unmodified lines4 from collections import abc5 from numbers import Number6 7 from .runtime import Undefined8+from .utils import environmentfunction9 10 number_re = re.compile(r"^-?\d+(\.\d+)?$")11 regex_type = type(number_re)12 test_callable = callable35 unmodified lines48 """Like :func:`defined` but the other way round."""49 return isinstance(value, Undefined)50 51 52+@environmentfunction53+def test_filter(env, value):54+ """Check if a filter exists by name. Useful if a filter may be55+ optionally available.56+57+ .. code-block:: jinja58+59+ {% if 'markdown' is filter %}60+ {{ value | markdown }}61+ {% else %}62+ {{ value }}63+ {% endif %}64+65+ .. versionadded:: 3.066+ """67+ return value in env.filters68+69+70+@environmentfunction71+def test_test(env, value):72+ """Check if a test exists by name. Useful if a test may be73+ optionally available.74+75+ .. code-block:: jinja76+77+ {% if 'loud' is test %}78+ {% if value is loud %}79+ {{ value|upper }}80+ {% else %}81+ {{ value|lower }}82+ {% endif %}83+ {% else %}84+ {{ value }}85+ {% endif %}86+87+ .. versionadded:: 3.088+ """89+ return value in env.tests90+91+92 def test_none(value):93 """Return true if the variable is none."""94 return value is None95 120 unmodified lines216 "even": test_even,217 "divisibleby": test_divisibleby,218 "defined": test_defined,219 "undefined": test_undefined,220+ "filter": test_filter,221+ "test": test_test,222 "none": test_none,223 "boolean": test_boolean,224 "false": test_false,225 "true": test_true,29 unmodified linesmodified:tests/test_filters.py+6 added-6 removed
776 unmodified lines777 result = t.render(s="Hello!\nThis is Jinja saying something.")778 assert result == "Hello!\nThis is Jinja saying\nsomething."779 780 def test_filter_undefined(self, env):781- with pytest.raises(TemplateAssertionError, match="no filter named 'f'"):781+ with pytest.raises(TemplateAssertionError, match="No filter named 'f'"):782 env.from_string("{{ var|f }}")783 784 def test_filter_undefined_in_if(self, env):785 t = env.from_string("{%- if x is defined -%}{{ x|f }}{%- else -%}x{% endif %}")786 assert t.render() == "x"787- with pytest.raises(TemplateRuntimeError, match="no filter named 'f'"):787+ with pytest.raises(TemplateRuntimeError, match="No filter named 'f'"):788 t.render(x=42)789 790 def test_filter_undefined_in_elif(self, env):791 t = env.from_string(792 "{%- if x is defined -%}{{ x }}{%- elif y is defined -%}"793 "{{ y|f }}{%- else -%}foo{%- endif -%}"794 )795 assert t.render() == "foo"796- with pytest.raises(TemplateRuntimeError, match="no filter named 'f'"):796+ with pytest.raises(TemplateRuntimeError, match="No filter named 'f'"):797 t.render(y=42)798 799 def test_filter_undefined_in_else(self, env):800 t = env.from_string(801 "{%- if x is not defined -%}foo{%- else -%}{{ x|f }}{%- endif -%}"802 )803 assert t.render() == "foo"804- with pytest.raises(TemplateRuntimeError, match="no filter named 'f'"):804+ with pytest.raises(TemplateRuntimeError, match="No filter named 'f'"):805 t.render(x=42)806 807 def test_filter_undefined_in_nested_if(self, env):808 t = env.from_string(1 unmodified line810 "is defined -%}{{ y|f }}{%- endif -%}{{ x }}{%- endif -%}"811 )812 assert t.render() == "foo"813 assert t.render(x=42) == "42"814- with pytest.raises(TemplateRuntimeError, match="no filter named 'f'"):814+ with pytest.raises(TemplateRuntimeError, match="No filter named 'f'"):815 t.render(x=24, y=42)816 817 def test_filter_undefined_in_condexpr(self, env):818 t1 = env.from_string("{{ x|f if x is defined else 'foo' }}")819 t2 = env.from_string("{{ 'foo' if x is not defined else x|f }}")820 assert t1.render() == t2.render() == "foo"821 822- with pytest.raises(TemplateRuntimeError, match="no filter named 'f'"):822+ with pytest.raises(TemplateRuntimeError, match="No filter named 'f'"):823 t1.render(x=42)824 t2.render(x=42)modified:tests/test_tests.py+25 added
1 import pytest2 3 from jinja2 import Environment4 from jinja2 import Markup5+from jinja2 import TemplateAssertionError6+from jinja2 import TemplateRuntimeError7 8 9 class MyDict(dict):10 pass196 unmodified lines207 '{{ "foo" is in {"foo": 1}}}|'208 '{{ "baz" is in {"bar": 1}}}'209 )210 assert tmpl.render() == "True|True|False|True|False|True|False|True|False"211+212+213+def test_name_undefined(env):214+ with pytest.raises(TemplateAssertionError, match="No test named 'f'"):215+ env.from_string("{{ x is f }}")216+217+218+def test_name_undefined_in_if(env):219+ t = env.from_string("{% if x is defined %}{{ x is f }}{% endif %}")220+ assert t.render() == ""221+222+ with pytest.raises(TemplateRuntimeError, match="No test named 'f'"):223+ t.render(x=1)224+225+226+def test_is_filter(env):227+ assert env.call_test("filter", "title")228+ assert not env.call_test("filter", "bad-name")229+230+231+def test_is_test(env):232+ assert env.call_test("test", "number")233+ assert not env.call_test("test", "bad-name")modified:CHANGES.rst+5 added
39 unmodified lines40 ``Environment.get_template(globals=...)`` even if the template was41 already loaded. :issue:`295`42 - Do not raise an error for undefined filters in unexecuted43 if-statements and conditional expressions. :issue:`842`44+- Add ``is filter`` and ``is test`` tests to test if a name is a45+ registered filter or test. This allows checking if a filter is46+ available in a template before using it. Test functions can be47+ decorated with ``@environmentfunction``, ``@evalcontextfunction``,48+ or ``@contextfunction``. :issue:`842`, :pr:`1248`49 50 51 Version 2.11.352 --------------780 unmodified lines