Coverage for tests/unused_fixtures.py: 0%
27 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
1import ast
2import inspect
3import textwrap
4from collections.abc import Callable
5from pathlib import Path
6from typing import Any
8import pytest
10# Run as `pytest --collect-only -q -m "" -p tests.unused_fixtures`: collection sees
11# connected tests without a broker, so nothing here depends on what a CI job ran.
12TESTS_ROOT = Path(__file__).parent
15@pytest.hookimpl(trylast=True)
16def pytest_collection_finish(session: pytest.Session) -> None:
17 problems = [
18 *(f"{name} -- never requested" for name in _never_requested(session)),
19 *(f"{name} -- requested, never read" for name in _requested_not_read(session)),
20 ]
22 if problems:
23 pytest.exit("Unused fixtures:\n" + "\n".join(problems), returncode=1)
26def _never_requested(session: pytest.Session) -> list[str]:
27 used = {
28 fixturedef
29 for item in _tests(session)
30 for fixturedefs in item._fixtureinfo.name2fixturedefs.values()
31 for fixturedef in fixturedefs
32 }
34 return sorted(
35 f"{fixturedef.argname} @ {_location(fixturedef.func)}"
36 for fixturedefs in session._fixturemanager._arg2fixturedefs.values()
37 for fixturedef in fixturedefs
38 if fixturedef not in used
39 and TESTS_ROOT in Path(inspect.getfile(fixturedef.func)).parents
40 )
43def _requested_not_read(session: pytest.Session) -> list[str]:
44 # a fixture wanted for its side effect belongs in `@pytest.mark.usefixtures`
45 unread: dict[str, list[str]] = {}
47 for item in _tests(session):
48 # decorators such as `freeze_time` wrap the test in their own module
49 func = inspect.unwrap(item.function)
50 if TESTS_ROOT not in Path(inspect.getfile(func)).parents:
51 continue
53 location = _location(func)
54 if location in unread:
55 continue
57 fixtures = set(item._fixtureinfo.argnames) - {"request"}
58 if callspec := getattr(item, "callspec", None):
59 fixtures -= set(callspec.params)
61 node = ast.parse(textwrap.dedent(inspect.getsource(func))).body[0]
62 read = {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
63 unread[location] = sorted(fixtures - read)
65 return sorted(
66 f"{', '.join(names)} @ {location}" for location, names in unread.items() if names
67 )
70def _tests(session: pytest.Session) -> list[pytest.Function]:
71 return [item for item in session.items if isinstance(item, pytest.Function)]
74def _location(func: Callable[..., Any] | None) -> str:
75 if func is None:
76 return ""
77 path = Path(inspect.getfile(func)).relative_to(TESTS_ROOT.parent)
78 return f"{path}:{inspect.getsourcelines(func)[1]}"