Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add contains test #2043

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/jinja2/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,15 @@ def test_in(value: t.Any, seq: t.Container[t.Any]) -> bool:
return value in seq


def test_contains(value: t.Any, seq: t.Container[t.Any]) -> bool:
"""Check if value is in seq.
Opposite of the 'in' test, allowing use as a test in filters like 'selectattr'

.. versionadded:: 3.1.5
"""
return seq in value


TESTS = {
"odd": test_odd,
"even": test_even,
Expand All @@ -238,6 +247,7 @@ def test_in(value: t.Any, seq: t.Container[t.Any]) -> bool:
"sameas": test_sameas,
"escaped": test_escaped,
"in": test_in,
"contains": test_contains,
"==": operator.eq,
"eq": operator.eq,
"equalto": operator.eq,
Expand Down
16 changes: 16 additions & 0 deletions tests/test_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,22 @@ def test_in(self, env):
)
assert tmpl.render() == "True|True|False|True|False|True|False|True|False"

def test_contains(self, env):
tmpl = env.from_string(
'{{ "foo" is contains "o" }}|'
'{{ "foo" is contains "foo" }}|'
'{{ "foo" is contains "b" }}|'
"{{ ((1, 2)) is contains 1 }}|"
"{{ ((1, 2)) is contains 3 }}|"
"{{ [1, 2] is contains 1 }}|"
"{{ [1, 2] is contains 3 }}|"
'{{ {"foo": 1} is contains "foo" }}|'
'{{ {"bar": 1} is contains "baz" }}|'
'{{ [{"foo": "bar"}, {"foo": "fighter"}] | '
'selectattr("foo", "contains", "ba") | list | length }}'
)
assert tmpl.render() == "True|True|False|True|False|True|False|True|False|1"


def test_name_undefined(env):
with pytest.raises(TemplateAssertionError, match="No test named 'f'"):
Expand Down