Python: Handle @pytest.fixture decorations with arguments as well

Not the prettiest of solutions, but it seems to work well enough.
This commit is contained in:
Taus
2024-06-14 15:03:40 +00:00
parent c75e66c433
commit b7b0f84e8b
3 changed files with 17 additions and 9 deletions

View File

@@ -15,14 +15,24 @@ import Variables.Definition
import semmle.python.ApiGraphs
private predicate is_pytest_fixture(Import imp, Variable name) {
exists(Alias a |
exists(Alias a, API::Node pytest_fixture, API::Node decorator |
pytest_fixture = API::moduleImport("pytest").getMember("fixture") and
// The additional `.getReturn()` is to account for the difference between
// ```
// @pytest.fixture
// def foo():
// ...
// ```
// and
// ```
// @pytest.fixture(some, args, here)
// def foo():
// ...
// ```
decorator in [pytest_fixture, pytest_fixture.getReturn()] and
a = imp.getAName() and
a.getAsname().(Name).getVariable() = name and
API::moduleImport("pytest")
.getMember("fixture")
.getReturn()
.getAValueReachableFromSource()
.asExpr() = a.getValue()
a.getValue() = decorator.getReturn().getAValueReachableFromSource().asExpr()
)
}

View File

@@ -6,5 +6,3 @@
| imports_test.py:27:1:27:25 | Import | Import of 'func2' is not used. |
| imports_test.py:34:1:34:14 | Import | Import of 'module2' is not used. |
| imports_test.py:116:1:116:41 | Import | Import of 'not_a_fixture' is not used. |
| imports_test.py:118:1:118:68 | Import | Import of 'session_fixture' is not used. |
| imports_test.py:118:1:118:68 | Import | Import of 'wrapped_autouse_fixture' is not used. |

View File

@@ -115,4 +115,4 @@ def baz() -> Optional['subexpression_return_type']:
from pytest_fixtures import not_a_fixture # BAD
from pytest_fixtures import fixture, wrapped_fixture # GOOD (pytest fixtures are used implicitly by pytest)
from pytest_fixtures import session_fixture, wrapped_autouse_fixture # GOOD [FALSE POSITIVE]
from pytest_fixtures import session_fixture, wrapped_autouse_fixture # GOOD (pytest fixtures are used implicitly by pytest)