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

👌 Fail and emit warning on filters that do not return a boolean result #964

Merged
merged 20 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from 14 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
3 changes: 3 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ Internal
* 🧪 Add testing of JS scripts using Cypress integrated into PyTest (`#1051 <https://github.com/useblocks/sphinx-needs/pull/1051>`_)
* 🧪 Add code coverage to CI testing (`#1067 <https://github.com/useblocks/sphinx-needs/pull/1067>`_)

* Bugfix: Check filter strings for correctness.
(`#964 <https://github.com/useblocks/sphinx-needs/pull/964>`_)

1.3.0
-----
Released: 16.08.2023
Expand Down
12 changes: 9 additions & 3 deletions sphinx_needs/filter_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,10 @@ def filter_needs(
return found_needs


def need_search(*args: Any, **kwargs: Any) -> bool:
return bool(re.search(*args, **kwargs))
big1hc marked this conversation as resolved.
Show resolved Hide resolved


@measure_time("filtering")
def filter_single_need(
need: NeedsInfoType,
Expand Down Expand Up @@ -327,15 +331,17 @@ def filter_single_need(
# Get needs external filter data and merge to filter_context
filter_context.update(config.filter_data)

filter_context["search"] = re.search
filter_context["search"] = need_search
result = False
try:
# Set filter_context as globals and not only locals in eval()!
# Otherwise, the vars not be accessed in list comprehensions.
if filter_compiled:
result = bool(eval(filter_compiled, filter_context))
result = eval(filter_compiled, filter_context)
else:
result = bool(eval(filter_string, filter_context))
result = eval(filter_string, filter_context)
if not isinstance(result, bool):
raise NeedsInvalidFilter(f"Filter did not evaluate to a boolean, instead {type(result)}: {result}")
except Exception as e:
raise NeedsInvalidFilter(f"Filter {filter_string} not valid. Error: {e}.")
return result