From 0405ab15440c5e019f9a7f8db2832f137c20a04d Mon Sep 17 00:00:00 2001 From: Eric Brown Date: Mon, 14 Oct 2024 11:27:08 -0700 Subject: [PATCH] Direct assert rule to ignore asserts in test functions For several Python test frameworks, the assert builtin is required to validate the test. Precli should avoid showing results for this condition since this isn't the use case the rule is trying to find. Fixes: #638 Signed-off-by: Eric Brown --- precli/rules/python/stdlib/assert.py | 11 ++++++----- .../python/stdlib/assert/examples/assert_test_func.py | 7 +++++++ tests/unit/rules/python/stdlib/assert/test_assert.py | 1 + 3 files changed, 14 insertions(+), 5 deletions(-) create mode 100644 tests/unit/rules/python/stdlib/assert/examples/assert_test_func.py diff --git a/precli/rules/python/stdlib/assert.py b/precli/rules/python/stdlib/assert.py index f1bf6b5f..11ee206b 100644 --- a/precli/rules/python/stdlib/assert.py +++ b/precli/rules/python/stdlib/assert.py @@ -79,8 +79,9 @@ def __init__(self, id: str): ) def analyze_assert(self, context: dict) -> Optional[Result]: - return Result( - rule_id=self.id, - artifact=context["artifact"], - location=Location(context["node"]), - ) + if not context["symtab"].name().startswith("test_"): + return Result( + rule_id=self.id, + artifact=context["artifact"], + location=Location(context["node"]), + ) diff --git a/tests/unit/rules/python/stdlib/assert/examples/assert_test_func.py b/tests/unit/rules/python/stdlib/assert/examples/assert_test_func.py new file mode 100644 index 00000000..94c97a69 --- /dev/null +++ b/tests/unit/rules/python/stdlib/assert/examples/assert_test_func.py @@ -0,0 +1,7 @@ +# level: NONE +def test_foobar(a: str = None): + assert a is not None + return f"Hello {a}" + + +foobar(None) diff --git a/tests/unit/rules/python/stdlib/assert/test_assert.py b/tests/unit/rules/python/stdlib/assert/test_assert.py index df65a396..b1cb5b77 100644 --- a/tests/unit/rules/python/stdlib/assert/test_assert.py +++ b/tests/unit/rules/python/stdlib/assert/test_assert.py @@ -41,6 +41,7 @@ def test_rule_meta(self): "filename", [ "assert.py", + "assert_test_func.py", ], ) def test(self, filename):