Skip to content

Commit b7b0f84

Browse files
committed
Python: Handle @pytest.fixture decorations with arguments as well
Not the prettiest of solutions, but it seems to work well enough.
1 parent c75e66c commit b7b0f84

File tree

3 files changed

+17
-9
lines changed

3 files changed

+17
-9
lines changed

python/ql/src/Imports/UnusedImport.ql

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,24 @@ import Variables.Definition
1515
import semmle.python.ApiGraphs
1616

1717
private predicate is_pytest_fixture(Import imp, Variable name) {
18-
exists(Alias a |
18+
exists(Alias a, API::Node pytest_fixture, API::Node decorator |
19+
pytest_fixture = API::moduleImport("pytest").getMember("fixture") and
20+
// The additional `.getReturn()` is to account for the difference between
21+
// ```
22+
// @pytest.fixture
23+
// def foo():
24+
// ...
25+
// ```
26+
// and
27+
// ```
28+
// @pytest.fixture(some, args, here)
29+
// def foo():
30+
// ...
31+
// ```
32+
decorator in [pytest_fixture, pytest_fixture.getReturn()] and
1933
a = imp.getAName() and
2034
a.getAsname().(Name).getVariable() = name and
21-
API::moduleImport("pytest")
22-
.getMember("fixture")
23-
.getReturn()
24-
.getAValueReachableFromSource()
25-
.asExpr() = a.getValue()
35+
a.getValue() = decorator.getReturn().getAValueReachableFromSource().asExpr()
2636
)
2737
}
2838

python/ql/test/query-tests/Imports/unused/UnusedImport.expected

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,3 @@
66
| imports_test.py:27:1:27:25 | Import | Import of 'func2' is not used. |
77
| imports_test.py:34:1:34:14 | Import | Import of 'module2' is not used. |
88
| imports_test.py:116:1:116:41 | Import | Import of 'not_a_fixture' is not used. |
9-
| imports_test.py:118:1:118:68 | Import | Import of 'session_fixture' is not used. |
10-
| imports_test.py:118:1:118:68 | Import | Import of 'wrapped_autouse_fixture' is not used. |

python/ql/test/query-tests/Imports/unused/imports_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,4 +115,4 @@ def baz() -> Optional['subexpression_return_type']:
115115

116116
from pytest_fixtures import not_a_fixture # BAD
117117
from pytest_fixtures import fixture, wrapped_fixture # GOOD (pytest fixtures are used implicitly by pytest)
118-
from pytest_fixtures import session_fixture, wrapped_autouse_fixture # GOOD [FALSE POSITIVE]
118+
from pytest_fixtures import session_fixture, wrapped_autouse_fixture # GOOD (pytest fixtures are used implicitly by pytest)

0 commit comments

Comments
 (0)