Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(selection): narrow a conftest reached only through its imports (#3262)
Raghav Chamadiya2dd8855be1bb
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdindex 140a0019c..bf804e0a5 100644--- a/docs/architecture/language-support.md+++ b/docs/architecture/language-support.md@@ -146,7 +146,7 @@ ingestion/dynamic_hints/ # Per-language dynamic-edge extractorsbase.py # DynamicHintExtractor + DynamicEdgeregistry.py # HintRegistry- django.py pytest_hints.py python_imports.py node.py dotnet.py+ django.py python_imports.py node.py dotnet.pyspring.py ruby.py php.py scala.py swift.py c.py cpp.py luau.py go.py jvm.pysfc_source.py # Multi-language-file (SFC) projection (see below)parser.py # ASTParser (language-agnostic orchestration)diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.mdindex 89dcc469c..31bf9a902 100644--- a/docs/layers/TEST_INTELLIGENCE.md+++ b/docs/layers/TEST_INTELLIGENCE.md@@ -168,7 +168,9 @@ Each result says how it was found, and a guess never passes for evidence:The graph also carries test wiring no import states: runner setup files(`setupFiles`, `globalSetup` and the like) link to the tests their config runs,a helper a test starts by a path relative to itself links to that test, and a-`conftest.py` links to the files pytest collects.+`conftest.py` links to the files pytest collects. Each fixture request links+the test to the fixture, so a change a conftest reaches only through its+imports selects the tests whose fixtures use it, plus one import check.With `--format list` the caveats go to stderr so the pipe stays clean. Thecommand exits `0` in every case: it reports, it does not gate. `--format args`diff --git a/docs/start/CI.md b/docs/start/CI.mdindex 9eb6c7cbe..9470b7f9c 100644--- a/docs/start/CI.md+++ b/docs/start/CI.md@@ -262,6 +262,10 @@ a per-test coverage map (`repowise coverage add`) makes it more precise.- Only `docs/` and root README-like files (README, CHANGELOG, LICENSE, CONTRIBUTING) are skipped, and only when no code names them (a test that reads `README.md` names it, and then runs); an empty line means only those changed.- Tests the graph cannot see into run with every subset, and the reasons say how many and why: a test not indexed or importing nothing it resolves; a Python, JavaScript or TypeScript test that lists and reads files under a source directory (the working directory, a module's location, or its own location climbed out of the test directory; never its fixtures, sibling data or a temporary directory); one that runs the project's own command, `python -m` module, code importing the project, or package `bin` in a child process. The indexer finds them once from each test's source and stores the reason, so selection reads it without opening test files. An index built before this check runs everything until `repowise update` checks its tests. A Python module named like a test but outside every test directory is not a test when the nearest pytest config's `testpaths` or `python_files` leaves it out, as a bare `pytest` does: it is selected through like any other code. The rule follows a bare `pytest` run, so a test that CI only names explicitly on the command line outside `testpaths` is not seen as one: list it in `tests.always_run`.- A changed `conftest.py`, test package `__init__.py` or imported test helper selects the tests under or importing it, not everything.+- A change that reaches a `conftest.py` only through its imports selects the tests that ask for a fixture using that change (directly, through other fixtures, `usefixtures` or `getfixturevalue`), plus one test under the conftest as an import check.+ - Every test under the conftest still runs when an autouse fixture, a `pytest_*` hook or module-level code uses the change, or when the conftest imports it only for side effects.+ - It also runs everything there when a fixture request cannot be read from the code (a computed name, a mark kept in a variable, a config `usefixtures`), when the conftest loads plugins or cannot be read, and on an index built before this was recorded. The reasons name the cause.+ - Ceiling: a change that only alters what the changed module does at import time, seen by a test that does not import it, is caught by the import check alone.- Wiring no import states counts as a use: a JS/TS setup file named under `setupFiles`, `setupFilesAfterEnv`, `globalSetup` or `globalTeardown` in a `vitest.*`, `jest.*`, `vite.*` or `playwright.*` config or a `package.json` stands for the tests in that config's package, and a helper a test names by a path relative to itself (`Path(__file__).parent / "server.py"`, `path.join(__dirname, "server.ts")`) stands for that test. A `conftest.py` links only the files pytest collects (its `python_files`), so a helper beside the tests is not on every route the conftest reaches.- Without a range, in CI it reads the pull request's change; locally, the staged changes.- `tests.full_run_on` (gitignore patterns) adds run-everything paths, and a path it matches is never scoped; `tests.always_run` is appended to every selection as written, for the runner whose language each entry is in.diff --git a/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py b/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.pyindex 3477d047e..7275b808b 100644--- a/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py+++ b/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py@@ -145,7 +145,17 @@ def impacted_tests_command(checkout = _read_checkout(repo_path)plan = _plan_scopes(repo_path, change, config, checkout) if config is not None else Noneroutes = plan.routes if plan else []- result = run_async(_collect(repo_path, change, checkout.roots, config, explain, routes))+ result = run_async(+ _collect(+ repo_path,+ change,+ checkout.roots,+ config,+ explain,+ routes,+ dict(checkout.pytest_texts),+ )+ )result["diff"] = change.labelif plan is not None:result["selection"] = _select(repo_path, change, result, config, checkout, plan)@@ -240,6 +250,7 @@ async def _collect(config=None,explain: str | None = None,scope_routes: list[str] | tuple[str, ...] = (),+ pytest_texts: dict | None = None,) -> dict:"""Resolve the change's files to impacted tests + labelled fallbacks.@@ -247,7 +258,9 @@ async def _collect(walked too, so selection can add the tests reaching them; so are*scope_routes*, the files a scope runs the tests of (:func:`_plan_scopes`).With *explain*, the import route from that test to a changed file is- looked up as well.+ looked up as well. *pytest_texts* are the checkout's conftests and pytest+ configs by path (``_read_checkout``); without them no conftest route is+ narrowed."""from repowise.core.persistence.crud import (get_health_metrics,@@ -280,7 +293,14 @@ async def _collect(routes = [] if config is None else _gap_routes(repo_path, change, config, repo_keys, out)routes = sorted({*routes, *scope_routes})await _resolve_impacted(- session, repo_id, _query_lines(change, measured), repo_keys, out, roots, routes+ session,+ repo_id,+ _query_lines(change, measured),+ repo_keys,+ out,+ roots,+ routes,+ pytest_texts,)await _place_tests(session, repo_id, out)if explain:@@ -419,6 +439,7 @@ def _empty_result(changed_files: int) -> dict:"always_run_tests": {},"explain_route": [],"helper_importers": {},+ "conftest_notes": [],"changed_files": changed_files,"covered": {}, # test_id -> {test_file, source_files: [...]}"inferred": [], # {source_file, test_file, via}@@ -434,6 +455,7 @@ async def _resolve_impacted(out: dict,roots: PytestRoots | None = None,routes: tuple[str, ...] | list[str] = (),+ pytest_texts: dict | None = None,) -> dict:"""Classify each changed file: covered tests, inferred tests, or unknown.@@ -491,12 +513,15 @@ async def _resolve_impacted(return outtry:- candidates, importers = await _graph_candidates(session, repo_id, graph_targets, roots)+ candidates, importers, notes = await _graph_candidates(+ session, repo_id, graph_targets, roots, pytest_texts=pytest_texts+ )except Exception as exc:# Nothing the graph said can be trusted; selection runs everything.out["graph_error"] = f"{type(exc).__name__}: {exc}"- candidates, importers = {}, {}+ candidates, importers, notes = {}, {}, []out["helper_importers"] = importers+ out["conftest_notes"] = notesfor source_file in graph_targets:found = candidates.get(source_file)if found:@@ -521,12 +546,20 @@ async def _resolve_impacted(async def _graph_candidates(- session, repo_id: str, targets: list[str], roots: PytestRoots | None = None-) -> tuple[dict[str, list], dict[str, list[str]]]:- """``{target: [(test file, via), ...]}`` from the graph, and each test file's importers.+ session,+ repo_id: str,+ targets: list[str],+ roots: PytestRoots | None = None,+ *,+ pytest_texts: dict | None = None,+) -> tuple[dict[str, list], dict[str, list[str]], list[str]]:+ """``{target: [(test file, via), ...]}`` from the graph, each test file's importers, notes.Candidates come strongest tier first. The importers map says, for every- test file the walk met, which test files import it.+ test file the walk met, which test files import it. A conftest reached only+ through its imports stands for the tests it can break+ (:mod:`repowise.core.analysis.conftest_routes`), read from *pytest_texts*;+ the notes say what was decided.One walk per tier for every target rather than one per file: the seed setis what makes it cheap. Uncapped, since a trimmed list would drop tests a@@ -536,15 +569,27 @@ async def _graph_candidates(node: a JSON or golden file the index flags as test material is data, not aroute. A read failure raises."""+ from repowise.core.analysis.conftest_routes import scoped_candidatesfrom repowise.core.analysis.test_reachability import load_test_files- from repowise.core.analysis.test_selection import is_code_file+ from repowise.core.analysis.test_selection import is_code_file, plugin_loader+ texts = pytest_texts or {}test_files = {f for f in await load_test_files(session, repo_id) if is_code_file(f)}- found = await _tier_picks(session, repo_id, targets, test_files, roots)+ found, entries = await _tier_picks(session, repo_id, targets, test_files, roots)seeds = {t for picks in found.values() for t in picks}- parents = await _test_importers(session, repo_id, seeds, test_files)- out = {target: _with_importers(picks, parents) for target, picks in found.items()}- return out, {test: sorted(found_by) for test, found_by in parents.items()}+ parents, parent_entries = await _test_importers(session, repo_id, seeds, test_files)+ out, notes = await scoped_candidates(+ session,+ repo_id,+ found,+ entries,+ parents,+ parent_entries,+ test_files,+ texts.get,+ plugin_loader=plugin_loader(texts.items()),+ )+ return out, {test: sorted(found_by) for test, found_by in parents.items()}, notesdef _all_tests(reached) -> tuple[str, ...]:@@ -554,8 +599,12 @@ def _all_tests(reached) -> tuple[str, ...]:async def _tier_picks(session, repo_id: str, targets: list[str], test_files: set[str], roots: PytestRoots | None-) -> dict[str, dict[str, str]]:- """``{target: {test file: via}}``: a changed test itself, then the call and import walks."""+) -> tuple[dict[str, dict[str, str]], dict[str, dict]]:+ """``{target: {test file: via}}``: a changed test itself, then the call and import walks.++ Also ``{target: {test file: the files it was reached through}}`` from the+ import walk.+ """from repowise.core.analysis.test_reachability import tests_reaching_by_tierfrom repowise.core.analysis.test_selection import is_runnable_test@@ -569,6 +618,7 @@ async def _tier_picks(test_files=test_files,)found: dict[str, dict[str, str]] = {}+ entries = {t: dict(r.entries or {}) for t, r in importers.items()}for target in targets:picks = found.setdefault(target, {})# A test the index has not seen yet (new in this change) is still its own pick.@@ -577,16 +627,20 @@ async def _tier_picks(for reached, via in ((reaching.get(target), None), (importers.get(target), "import-graph")):for t in _all_tests(reached) if reached else ():picks.setdefault(t, via or reached.via)- return found+ return found, entriesasync def _test_importers(session, repo_id: str, seeds: set[str], test_files: set[str]-) -> dict[str, set[str]]:- """``{test file: test files importing it}``, walked until nothing new appears."""+) -> tuple[dict[str, set[str]], dict[str, dict]]:+ """``{test file: test files importing it}``, walked until nothing new appears.++ Also ``{test file: {importer: the files it imports on that route}}``.+ """from repowise.core.analysis.test_reachability import tests_reaching_by_tierparents: dict[str, set[str]] = {}+ routes: dict[str, dict] = {}frontier, seen = set(seeds), set(seeds)while frontier:walked = await tests_reaching_by_tier(@@ -600,19 +654,10 @@ async def _test_importers(frontier = set()for test, reached in walked.items():parents.setdefault(test, set()).update(_all_tests(reached))+ routes.setdefault(test, {}).update(reached.entries or {})frontier.update(set(_all_tests(reached)) - seen)seen |= frontier- return parents---def _with_importers(picks: dict[str, str], parents: dict[str, set[str]]) -> list:- """*picks* plus every test importing one of them, transitively, as ``import-graph``."""- stack = list(picks)- while stack:- fresh = [p for p in sorted(parents.get(stack.pop(), ())) if p not in picks]- picks.update(dict.fromkeys(fresh, "import-graph"))- stack.extend(fresh)- return list(picks.items())+ return parents, routesdef _select(repo_path, change, result: dict, config, checkout: _Checkout, plan: _Plan):diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex f8a4126ed..9e8b24227 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -1583,9 +1583,12 @@ def _run_full_health_rescore(# Share the rebuild path with the incremental update so both produce the# same graph (same parser, same framework-aware synthetic edges).with timed(timings, "rebuild"):+ # Sources too: the framework-edge pass reads them, and a file it cannot+ # read makes test selection keep every test under its conftests.parsed_files, _source_map, graph_builder, _repo_structure, _file_count = _build_repo_graph(repo_path,exclude_patterns,+ collect_sources=True,include_submodules=bool(state.get("include_submodules", False)),include_nested_repos=bool(state.get("include_nested_repos", False)),)diff --git a/packages/core/src/repowise/core/analysis/conftest_routes.py b/packages/core/src/repowise/core/analysis/conftest_routes.pynew file mode 100644index 000000000..8a22403be--- /dev/null+++ b/packages/core/src/repowise/core/analysis/conftest_routes.py@@ -0,0 +1,738 @@+"""Which tests under a ``conftest.py`` a change reaching it through its imports can break.++pytest loads a conftest for every test at or below its directory, so the graph+links each of those tests to it, and a change anywhere in the conftest's import+closure used to select all of them. On a suite whose root conftest imports a+few hub modules, that is the whole suite for most changes.++A conftest contributes two things to a test, and a change that reaches it only+through its imports can break a test through either:++1. **Import time.** The conftest's imports run when pytest collects any test+ under it. A change that breaks them (a syntax error, a failing module body)+ breaks collection for every one of those tests, so running any one of them+ detects it. The selection adds one such test per conftest when none is+ selected already, chosen as the first by path (an import check). Autouse+ fixtures run for that test too, so a patch an autouse fixture applies to a+ module on the route (``monkeypatch.setattr(mod, "x", ...)``) that stops+ working fails there as well.+2. **What the conftest does with the module.** A fixture, a hook or+ module-level code that names something from a module on the route, in any+ way but as the ``setattr`` target in an autouse fixture or hook,+ can change what a test sees: calling it, reading a constant, comparing,+ iterating or formatting it all do. An autouse fixture, a ``pytest_*`` hook,+ module-level code (class bodies included) and a fixture or hook defined in+ a class keep every test. A fixture a test asks for affects the tests that+ ask for it, directly, through other fixtures, through ``usefixtures`` or by+ ``getfixturevalue``; the index records each of those requests as a fixture+ edge, and those tests are selected.++Granularity is the module, not the function: a fixture that names anything in+a module on the route to the change counts as reaching it, however deep the+change is. A binding the conftest never reads (``import app.models #+registers them``) is imported for its side effects, which every test sees, so+it keeps every test.++Fails closed, keeping every test under the conftest with the reason, when the+conftest does not parse, loads plugins, star-imports a module on the route, has+a route the analysis cannot tie to one of its imports, when a test or conftest+asks for its fixtures in a way the index cannot record+(``pytest_edges.UNRECORDED_HINT``), when some file imports a conftest by a+name the index could not resolve, or when the index predates fixture-request+edges.++Ceiling: an import-time side effect of the changed module itself (it registers+itself in a shared registry) that a test observes without any import route of+its own to that module is seen only through the import check. Upgrade path: a+per-test map built from a coverage run, which records what each test executed.+"""++from __future__ import annotations++import ast+from collections.abc import Callable, Collection, Iterator, Mapping+from dataclasses import dataclass, field+from pathlib import PurePosixPath+from typing import Any++from sqlalchemy import text+from sqlalchemy.ext.asyncio import AsyncSession++from ..ingestion.framework_edges.pytest_edges import (+ CONFTEST_HINT,+ FIXTURE_HINT,+ UNRECORDED_HINT,+ fixture_declaration,+)+from ..ingestion.languages.python_modules import module_parts+from .test_reachability import _in_clause+from .test_selection import is_runnable_test, scope_kind++# The call whose first argument is the object an attribute is patched on:+# naming a module there in an autouse fixture is caught by the import check.+# Probing (`hasattr`) or removing (`delattr`) depends on the module, so counts.+_TARGET_CALLS = frozenset({"setattr"})+_DEFS = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)+++@dataclass(frozen=True)+class ConftestUse:+ """What a conftest does with the modules on a change's route.++ *run_all* says why every test under it stays selected; otherwise+ *fixtures* are the requested fixtures (function names) that reach the+ change, and *declared* every module-level fixture it defines.+ """++ run_all: str | None = None+ fixtures: frozenset[str] = frozenset()+ declared: frozenset[str] = frozenset()+++@dataclass+class _Unit:+ """A module-level function or class of the conftest, as parsed."""++ node: ast.AST+ params: list[str] = field(default_factory=list)+ fixture: str | None = None+ autouse: bool = False+ # A class holding a fixture or a hook, which pytest may run for any test.+ holds_hooks: bool = False+ refs: set[str] = field(default_factory=set)+ loads: list[ast.Name] = field(default_factory=list)+ imports: list[ast.Import | ast.ImportFrom] = field(default_factory=list)+++@dataclass+class _Reach:+ """How one unit uses the modules on one route."""++ run: str | None = None+ patch: str | None = None+ imports: str | None = None++ def uses(self) -> str | None:+ return self.run or self.patch or self.imports+++def _names(module: tuple[str, ...], entry: tuple[str, ...], *, package: bool) -> bool:+ """Whether *module* names *entry*: its tail, or with *package* a package above it."""+ n = len(module)+ return n > 0 and any(+ entry[k : k + n] == module and (package or k + n == len(entry))+ for k in range(len(entry) - n + 1)+ )+++def _bindings(+ node: ast.Import | ast.ImportFrom, here: tuple[str, ...], entries: list[tuple[str, ...]]+) -> tuple[dict[str, tuple[str, ...]], set[tuple[str, ...]], bool]:+ """``({bound name: entry}, entries matched, star-imports an entry)`` for one import."""+ bound: dict[str, tuple[str, ...]] = {}+ matched: set[tuple[str, ...]] = set()+ star = False++ def hit(module: tuple[str, ...], *, package: bool) -> tuple[str, ...] | None:+ return next((e for e in entries if _names(module, e, package=package)), None)++ if isinstance(node, ast.Import):+ for alias in node.names:+ parts = tuple(alias.name.split("."))+ prefixes = [parts[:i] for i in range(1, len(parts))]+ e = hit(parts, package=True) or next(+ (h for p in prefixes if (h := hit(p, package=False))), None+ )+ if e:+ bound[alias.asname or parts[0]] = e+ matched.add(e)+ return bound, matched, star++ base = here[: len(here) - (node.level - 1)] if node.level else ()+ module = base + tuple((node.module or "").split(".")) if node.module else base+ for alias in node.names:+ if alias.name == "*":+ e = hit(module, package=True)+ star = star or e is not None+ continue+ e = hit((*module, alias.name), package=True) or hit(module, package=False)+ if e:+ bound[alias.asname or alias.name] = e+ matched.add(e)+ return bound, matched, star+++def _parents(tree: ast.AST) -> dict[int, ast.AST]:+ out: dict[int, ast.AST] = {}+ for node in ast.walk(tree):+ for child in ast.iter_child_nodes(node):+ out[id(child)] = node+ return out+++def _patch_target(name: ast.Name, parents: Mapping[int, ast.AST]) -> bool:+ """Whether the name is the first argument of an attribute patch or probe call."""+ par = parents.get(id(name))+ if not (isinstance(par, ast.Call) and par.args and par.args[0] is name):+ return False+ func = par.func+ called = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "")+ return called in _TARGET_CALLS+++def _fixture_info(node: ast.AST) -> tuple[str | None, bool]:+ """``(registered name, autouse)`` for a fixture definition, ``(None, False)`` otherwise."""+ decorators = [f"@{ast.unparse(d)}" for d in getattr(node, "decorator_list", ())]+ declared = fixture_declaration(getattr(node, "name", ""), decorators)+ return declared if declared else (None, False)+++def _import_time(stmt: ast.stmt) -> list[ast.AST]:+ """What a definition evaluates when the module is imported: decorators, defaults, bases."""+ out: list[ast.AST] = list(stmt.decorator_list)+ if isinstance(stmt, ast.ClassDef):+ out += [*stmt.bases, *(k.value for k in stmt.keywords)]+ # A class body runs at import; only its methods' bodies wait for a call.+ for inner in stmt.body:+ out += _import_time(inner) if isinstance(inner, _DEFS) else [inner]+ else:+ out += [d for d in [*stmt.args.defaults, *stmt.args.kw_defaults] if d]+ return out+++def _module_level(body: list[ast.stmt]) -> tuple[list[ast.AST], list[ast.AST], list[ast.AST]]:+ """``(imports, definitions, import-time code)`` at module level, through compound statements."""+ imports: list[ast.AST] = []+ defs: list[ast.AST] = []+ code: list[ast.AST] = []+ for stmt in body:+ if isinstance(stmt, (ast.Import, ast.ImportFrom)):+ imports.append(stmt)+ elif isinstance(stmt, _DEFS):+ defs.append(stmt)+ code.extend(_import_time(stmt))+ elif isinstance(stmt, (ast.If, ast.Try, ast.With, ast.For, ast.While)):+ # The block's own expressions run at import time; its statements+ # are module level like any other.+ code.extend(_header_expressions(stmt))+ nested = [+ *getattr(stmt, "body", []),+ *getattr(stmt, "orelse", []),+ *getattr(stmt, "finalbody", []),+ *(s for h in getattr(stmt, "handlers", []) for s in h.body),+ ]+ sub = _module_level(nested)+ imports += sub[0]+ defs += sub[1]+ code += sub[2]+ else:+ code.append(stmt)+ return imports, defs, code+++def _header_expressions(stmt: ast.stmt) -> list[ast.AST]:+ """The expressions a compound statement evaluates outside its body."""+ if isinstance(stmt, (ast.If, ast.While)):+ return [stmt.test]+ if isinstance(stmt, ast.For):+ return [stmt.iter]+ if isinstance(stmt, ast.With):+ return [item.context_expr for item in stmt.items]+ return [h.type for h in getattr(stmt, "handlers", []) if h.type is not None]+++def _body_nodes(node: ast.AST) -> Iterator[ast.AST]:+ """Every node inside a definition, its import-time decorators and defaults excluded."""+ skip = {id(d) for d in getattr(node, "decorator_list", ())}+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):+ skip |= {id(d) for d in [*node.args.defaults, *node.args.kw_defaults] if d}+ stack = [c for c in ast.iter_child_nodes(node) if id(c) not in skip]+ while stack:+ cur = stack.pop()+ yield cur+ stack.extend(ast.iter_child_nodes(cur))+++def _params(node: ast.AST) -> list[str]:+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):+ return []+ args = node.args+ positional = [*args.posonlyargs, *args.args]+ plain = positional[: len(positional) - len(args.defaults)]+ keyword = [a for a, d in zip(args.kwonlyargs, args.kw_defaults, strict=True) if d is None]+ return [a.arg for a in plain + keyword]+++def _holds_hooks(node: ast.AST) -> bool:+ return isinstance(node, ast.ClassDef) and any(+ isinstance(m, (ast.FunctionDef, ast.AsyncFunctionDef))+ and (m.name.startswith("pytest_") or _fixture_info(m)[0] is not None)+ for m in node.body+ )+++@dataclass+class ConftestFacts:+ """A conftest's parse, made once and asked about any number of routes (:meth:`use`)."""++ path: str+ error: str | None = None+ here: tuple[str, ...] = ()+ parents: dict[int, ast.AST] = field(default_factory=dict)+ imports: list[Any] = field(default_factory=list)+ units: dict[str, _Unit] = field(default_factory=dict)+ code_loads: list[ast.Name] = field(default_factory=list)+ exported: set[str] = field(default_factory=set)++ @classmethod+ def parse(cls, source: str, path: str) -> ConftestFacts:+ try:+ tree = ast.parse(source)+ except (SyntaxError, ValueError):+ return cls(path, error=f"{path} does not parse")+ facts = cls(path, here=module_parts(path)[:-1], parents=_parents(tree))+ imports, defs, code = _module_level(tree.body)+ facts.imports = imports+ for node in defs:+ unit = _Unit(node, params=_params(node), holds_hooks=_holds_hooks(node))+ unit.fixture, unit.autouse = _fixture_info(node)+ facts.units[node.name] = unit+ for name, unit in facts.units.items():+ for sub in _body_nodes(unit.node):+ if isinstance(sub, (ast.Import, ast.ImportFrom)):+ unit.imports.append(sub)+ elif isinstance(sub, ast.Name) and isinstance(sub.ctx, ast.Load):+ unit.loads.append(sub)+ if sub.id in facts.units and sub.id != name:+ unit.refs.add(sub.id)+ for node in code:+ for sub in ast.walk(node):+ if isinstance(sub, ast.Name) and isinstance(sub.ctx, ast.Load):+ facts.code_loads.append(sub)+ if isinstance(sub, ast.Name) and sub.id == "pytest_plugins":+ facts.error = f"{path} loads pytest plugins"+ if isinstance(sub, ast.Name) and sub.id == "__all__":+ # Re-exported for the tests that import the conftest, which+ # the selection adds as its importers.+ value = getattr(facts.parents.get(id(sub)), "value", None)+ facts.exported |= {+ e.value+ for e in getattr(value, "elts", ())+ if isinstance(e, ast.Constant) and isinstance(e.value, str)+ }+ return facts++ def use(self, entries: Collection[str]) -> ConftestUse:+ """What the conftest does with *entries*, the files it imports on a route."""+ if self.error:+ return ConftestUse(run_all=self.error)+ targets = [module_parts(e) for e in entries]+ hot: dict[str, tuple[str, ...]] = {}+ matched: set[tuple[str, ...]] = set()+ for node in self.imports:+ bound, hits, star = _bindings(node, self.here, targets)+ if star:+ return ConftestUse(run_all=f"{self.path} star-imports a module on the route")+ hot.update(bound)+ matched |= hits++ reach: dict[str, _Reach] = {}+ loaded = set(self.exported)+ for name, unit in self.units.items():+ r = reach[name] = _Reach()+ local: dict[str, tuple[str, ...]] = {}+ for node in unit.imports:+ bound, hits, star = _bindings(node, self.here, targets)+ if star:+ return ConftestUse(run_all=f"{self.path} star-imports a module on the route")+ local.update(bound)+ matched |= hits+ r.imports = next(iter(local), None)+ seen = {n.id for n in unit.loads}+ loaded |= seen+ for load in unit.loads:+ if load.id not in local and load.id not in hot:+ continue+ if _patch_target(load, self.parents):+ r.patch = r.patch or load.id+ else:+ r.run = r.run or load.id+ # A local import nothing reads is there for its side effects.+ if r.run is None and (unread := sorted(set(local) - seen)):+ r.run = unread[0]++ if missed := [e for e in targets if e not in matched]:+ return ConftestUse(+ run_all=f"{self.path} reaches {'/'.join(missed[0])} by a route none of its "+ "imports names"+ )++ module_refs: set[str] = set()+ for load in self.code_loads:+ loaded.add(load.id)+ if load.id in hot and not _patch_target(load, self.parents):+ return ConftestUse(run_all=f"module-level code in {self.path} uses {load.id}")+ if load.id in self.units:+ module_refs.add(load.id)+ if unread := sorted(set(hot) - loaded):+ return ConftestUse(+ run_all=f"{self.path} imports {unread[0]} without using it, so for its side effects"+ )+ self._propagate(reach)+ return self._decide(reach, module_refs)++ def _propagate(self, reach: dict[str, _Reach]) -> None:+ """A unit uses what the units it names and the fixtures it requests use."""+ by_fixture = {u.fixture: n for n, u in self.units.items() if u.fixture}+ changed = True+ while changed:+ changed = False+ for name, unit in self.units.items():+ deps = [*unit.refs]+ if unit.fixture:+ deps += [by_fixture[p] for p in unit.params if p in by_fixture]+ mine = reach[name]+ for dep in deps:+ other = reach[dep]+ # Calling a helper that patches a module runs that patch.+ other_run = other.run or other.patch+ if other_run and not mine.run:+ mine.run, changed = other_run, True+ if other.imports and not mine.imports:+ mine.imports, changed = other.imports, True++ def _decide(self, reach: Mapping[str, _Reach], module_refs: set[str]) -> ConftestUse:+ fixtures: set[str] = set()+ for name, unit in self.units.items():+ r = reach[name]+ if name in module_refs and r.run:+ return ConftestUse(run_all=f"module-level code in {self.path} calls {name}")+ if unit.holds_hooks and r.uses():+ return ConftestUse(+ run_all=f"{self.path}'s class {name} defines fixtures or hooks and uses "+ f"{r.uses()}"+ )+ if r.run and (unit.autouse or name.startswith("pytest_")):+ kind = "autouse fixture" if unit.autouse else "hook"+ return ConftestUse(run_all=f"{self.path}'s {kind} {name} uses {r.run}")+ # A requested fixture reaches its users however it names the module;+ # a helper reaches tests through the units that call it or through+ # the tests importing the conftest, which the selection adds.+ if unit.fixture and not unit.autouse and r.uses():+ fixtures.add(name)+ return ConftestUse(+ fixtures=frozenset(fixtures),+ declared=frozenset(n for n, u in self.units.items() if u.fixture),+ )+++def conftest_use(source: str, path: str, entries: Collection[str]) -> ConftestUse:+ """What the conftest at *path* (text *source*) does with *entries*. Pure."""+ return ConftestFacts.parse(source, path).use(entries)+++@dataclass(frozen=True)+class _Edge:+ source: str+ target: str+ edge_type: str+ hint: str | None+++async def _edges_into_scopes(+ session: AsyncSession, repo_id: str, targets: list[str]+) -> list[_Edge]:+ """Edges arriving at the conftests and their fixtures, and unresolved conftest imports.++ One query. The second part is a range on the indexed target column: an+ import of ``conftest`` the resolver could not place lands on an+ ``external:`` node, and the importer it hides must not be dropped.+ """+ if not targets:+ return []+ params: dict[str, Any] = {"repo_id": repo_id}+ tgt = _in_clause("p", targets, params)+ rows = await session.execute(+ text(+ "SELECT DISTINCT source_node_id, target_node_id, edge_type, hint_source "+ "FROM graph_edges WHERE repository_id = :repo_id AND ("+ f"(target_node_id IN ({tgt}) "+ "AND edge_type IN ('framework', 'framework_binds', 'calls')) "+ "OR (target_node_id >= 'external:' AND target_node_id < 'external;' "+ "AND target_node_id LIKE '%conftest' AND edge_type = 'imports'))"+ ),+ params,+ )+ return [_Edge(*row) for row in rows]+++async def _records_fixture_requests(session: AsyncSession, repo_id: str) -> bool:+ """Whether the index was built by a version that stamps fixture requests."""+ row = await session.execute(+ text(+ "SELECT 1 FROM graph_edges WHERE repository_id = :repo_id "+ "AND edge_type = 'framework_binds' AND hint_source = :hint LIMIT 1"+ ),+ {"repo_id": repo_id, "hint": FIXTURE_HINT},+ )+ return row.first() is not None+++def with_importers(+ picks: dict[str, str], parents: Mapping[str, Collection[str]], blocked: Collection[str] = ()+) -> list[tuple[str, str]]:+ """*picks* plus every test importing one of them, transitively, as ``import-graph``.++ A *blocked* file is never added: a conftest the change reaches only through+ its imports stands for the tests :func:`scoped_candidates` chose instead.+ """+ stack = list(picks)+ while stack:+ fresh = [+ p for p in sorted(parents.get(stack.pop(), ())) if p not in picks and p not in blocked+ ]+ picks.update(dict.fromkeys(fresh, "import-graph"))+ stack.extend(fresh)+ return list(picks.items())+++@dataclass+class _Route:+ """One conftest on one target's routes."""++ entries: frozenset[str]+ # Found by a walk with no import route at all (a call).+ direct: bool+ use: ConftestUse | None = None+ reason: str | None = None+++async def scoped_candidates(+ session: AsyncSession,+ repo_id: str,+ found: Mapping[str, dict[str, str]],+ entries: Mapping[str, Mapping[str, Collection[str]]],+ parents: Mapping[str, Collection[str]],+ parent_entries: Mapping[str, Mapping[str, Collection[str]]],+ test_files: Collection[str],+ read: Callable[[str], str | None],+ *,+ plugin_loader: str | None = None,+) -> tuple[dict[str, list[tuple[str, str]]], list[str]]:+ """Each target's ``[(test file, via)]`` with conftest routes narrowed, and the notes.++ *found* are the walks' picks per target and *entries* the files each was+ reached through; *parents* the test files importing each test file and+ *parent_entries* the files each importer reached it through; *read* returns+ a conftest's text. Every conftest on a route that this+ module cannot narrow keeps today's answer: every test under it.+ """+ routes: dict[str, dict[str, _Route]] = {}+ for target, picks in found.items():+ full = dict(picks)+ with_importers(full, parents)+ for conf in sorted(t for t in full if scope_kind(t) == "conftest" and t != target):+ via = set(entries.get(target, {}).get(conf, ()))+ for h in full:+ if h != conf and conf in parents.get(h, ()):+ via |= set(parent_entries.get(h, {}).get(conf, ()))+ # A parent conftest is not an import: pytest links a nested+ # conftest to it, and that parent's own decision covers the route.+ own = frozenset(v for v in via if scope_kind(v) != "conftest")+ routes.setdefault(target, {})[conf] = _Route(own, conf in picks and not via)++ # One parse per conftest; each distinct route through it is matched against it.+ facts: dict[str, ConftestFacts | None] = {}+ uses: dict[tuple[str, frozenset[str]], ConftestUse] = {}+ for by_conf in routes.values():+ for conf, route in by_conf.items():+ if conf not in facts:+ source = read(conf)+ facts[conf] = None if source is None else ConftestFacts.parse(source, conf)+ parsed = facts[conf]+ if plugin_loader:+ route.reason = f"{plugin_loader} loads pytest plugins by name"+ elif not route.entries:+ route.reason = f"{conf} is reached by a call alone" if route.direct else None+ elif parsed is None:+ route.reason = f"{conf} could not be read"+ else:+ key = (conf, route.entries)+ if key not in uses:+ uses[key] = parsed.use(route.entries)+ route.use = uses[key]+ route.reason = route.use.run_all++ narrowable = {+ conf+ for by_conf in routes.values()+ for conf, r in by_conf.items()+ if r.use is not None and r.reason is None+ }+ declared = {+ f"{conf}::{name}"+ for by_conf in routes.values()+ for conf, r in by_conf.items()+ if conf in narrowable and r.use is not None+ for name in r.use.declared+ }+ edges = await _edges_into_scopes(session, repo_id, sorted(narrowable | declared))+ stamped = {e.target for e in edges if e.hint == FIXTURE_HINT}+ unstamped = any(+ r.use is not None+ and r.use.fixtures+ and not any(f"{conf}::{n}" in stamped for n in r.use.declared)+ for by_conf in routes.values()+ for conf, r in by_conf.items()+ if conf in narrowable+ )+ # Asked only when a conftest's fixtures show no recorded request at all.+ recorded = await _records_fixture_requests(session, repo_id) if unstamped else True+ scope = _Scope(edges, parents, test_files, recorded)++ out: dict[str, list[tuple[str, str]]] = {}+ notes: dict[tuple[str, str], list[str]] = {}+ for target, picks in found.items():+ out[target] = _narrow(target, dict(picks), routes.get(target, {}), scope, notes)+ return out, [_note(key, targets) for key, targets in notes.items()]+++def _note(key: tuple[str, str], targets: list[str]) -> str:+ """One line per conftest outcome, however many changed files share it."""+ who = targets[0] if len(targets) == 1 else f"{len(targets)} changed files (e.g. {targets[0]})"+ return f"{key[0]}{who}{key[1]}."+++@dataclass(frozen=True)+class _Scope:+ """What every target's narrowing reads: the fetched edges and the test-file facts."""++ edges: list[_Edge]+ parents: Mapping[str, Collection[str]]+ test_files: Collection[str]+ # The index stamps fixture requests (see :func:`_records_fixture_requests`).+ recorded: bool++ def unresolved_conftest_import(self) -> str | None:+ return next((e.source for e in self.edges if e.target.startswith("external:")), None)+++def _narrow(+ target: str,+ picks: dict[str, str],+ routes: Mapping[str, _Route],+ scope: _Scope,+ notes: dict[tuple[str, str], list[str]],+) -> list[tuple[str, str]]:+ """One target's picks, each narrowable conftest replaced by the tests it can break."""+ blocked: set[str] = set()+ added: dict[str, str] = {}+ narrowed: list[str] = []+ hidden_importer = scope.unresolved_conftest_import()+ for conf, route in routes.items():+ reason = route.reason+ if reason is None and route.use is not None and hidden_importer:+ reason = (+ f"{hidden_importer} imports a conftest by a name the index could not "+ "resolve, so that importer is not known"+ )+ users: set[str] = set()+ if reason is None and route.use is not None:+ found = _fixture_users(conf, route.use, scope)+ reason, users = (found, set()) if isinstance(found, str) else (None, found)+ if reason is not None:+ _add_note(notes, (f"{conf} keeps every test under it for ", f": {reason}"), target)+ continue+ if route.use is None:+ # Reached only through another conftest's tests, which decide it.+ blocked.add(conf)+ continue+ blocked.add(conf)+ narrowed.append(conf)+ framework = {+ e.source+ for e in scope.edges+ if e.target == conf+ and e.edge_type == "framework"+ and e.hint in (CONFTEST_HINT, UNRECORDED_HINT)+ }+ importers = set(scope.parents.get(conf, ())) - framework - {conf}+ for test in sorted(users | importers):+ added.setdefault(test, "conftest-fixture")+ kept = {t: v for t, v in picks.items() if t not in blocked}+ for test, via in added.items():+ kept.setdefault(test, via)+ result = dict(with_importers(kept, scope.parents, blocked))+ for conf in narrowed:+ prefix = _dir_prefix(conf)+ if any(t.startswith(prefix) and is_runnable_test(t) for t in result):+ check = None+ else:+ check = min(+ (t for t in scope.test_files if t.startswith(prefix) and is_runnable_test(t)),+ default=None,+ )+ if check:+ result.setdefault(check, "conftest-import-check")+ _add_note(notes, _narrow_note(conf, routes[conf], check), target)+ return list(result.items())+++def _add_note(notes: dict[tuple[str, str], list[str]], key: tuple[str, str], target: str) -> None:+ """Record that *target* got the outcome *key* (the note's text around the target)."""+ targets = notes.setdefault(key, [])+ if target not in targets:+ targets.append(target)+++def _dir_prefix(conf: str) -> str:+ d = str(PurePosixPath(conf).parent)+ return "" if d == "." else f"{d}/"+++def _narrow_note(conf: str, route: _Route, check: str | None) -> tuple[str, str]:+ use = route.use+ fixtures = sorted(use.fixtures) if use else []+ what = (+ f"the tests requesting {', '.join(fixtures)}" if fixtures else "no fixture-requesting test"+ )+ tail = f"; {check} runs as its import check" if check else ""+ return "", f" reaches {conf} only through its imports: selected {what}{tail}"+++def _fixture_users(conf: str, use: ConftestUse, scope: _Scope) -> set[str] | str:+ """Test files (and conftests, standing for their tests) using the reaching fixtures.++ A reason string instead when the users cannot be known. A conftest whose+ fixtures no recorded request names has no users: nothing asks for them.+ """+ if not use.fixtures:+ return set()+ if not scope.recorded:+ return "the index was built before fixture requests were recorded; run `repowise update`"+ hidden = next(+ (+ e.source+ for e in scope.edges+ if e.target == conf and e.edge_type == "framework" and e.hint == UNRECORDED_HINT+ ),+ None,+ )+ if hidden:+ return (+ f"{hidden} asks for fixtures in a way the index cannot record, and "+ f"{', '.join(sorted(use.fixtures))} reach the change"+ )+ wanted = {f"{conf}::{n}" for n in use.fixtures}+ users: set[str] = set()+ for edge in scope.edges:+ if edge.target not in wanted or edge.edge_type == "framework":+ continue+ source_file = edge.source.split("::", 1)[0]+ if source_file == conf:+ continue+ if is_runnable_test(source_file) or scope_kind(source_file) == "conftest":+ users.add(source_file)+ else:+ return f"{edge.source} uses its fixture {edge.target.rsplit('::', 1)[1]}"+ return usersdiff --git a/packages/core/src/repowise/core/analysis/dead_code/module_strings.py b/packages/core/src/repowise/core/analysis/dead_code/module_strings.pyindex e1d387273..2370dfb45 100644--- a/packages/core/src/repowise/core/analysis/dead_code/module_strings.py+++ b/packages/core/src/repowise/core/analysis/dead_code/module_strings.py@@ -34,6 +34,7 @@ from collections.abc import Iterable, Iteratorfrom dataclasses import dataclassfrom pathlib import PurePosixPath+from ...ingestion.languages.python_modules import module_partsfrom ...ingestion.languages.python_strings import defines_top_level, is_python, live_textfrom ...test_paths import is_test_related_pathfrom .models import DeadCodeFindingData, DeadCodeKind@@ -44,12 +45,6 @@ _MODULE_STRING_RE = re.compile()-def _module_parts(path: str) -> tuple[str, ...]:- """The dotted-path segments of a Python file (a package for ``__init__``)."""- parts = PurePosixPath(path).with_suffix("").parts- return parts[:-1] if parts and parts[-1] == "__init__" else parts--class _ModuleIndex:"""The candidate modules, keyed by every dotted tail and by bare name."""@@ -57,7 +52,7 @@ class _ModuleIndex:self.by_tail: dict[str, set[str]] = {}self.by_name: dict[str, set[str]] = {}for path in paths:- parts = _module_parts(path)+ parts = module_parts(path)if not parts:continuefor start in range(len(parts) - 1):diff --git a/packages/core/src/repowise/core/analysis/test_reachability.py b/packages/core/src/repowise/core/analysis/test_reachability.pyindex 02df2f611..492819541 100644--- a/packages/core/src/repowise/core/analysis/test_reachability.py+++ b/packages/core/src/repowise/core/analysis/test_reachability.py@@ -242,6 +242,9 @@ class ReachedBy:# How close each test came, for the call tier only: the import and name# tiers have no hop count to report.reach: Mapping[str, ReachDistance] | None = None+ # Import tier only: the files each test was reached through, i.e. the+ # dependencies of that test on the route to the target.+ entries: Mapping[str, frozenset[str]] | None = Nonedef call_graph_from_graph(graph: Any) -> CallGraphView:@@ -594,11 +597,17 @@ async def tests_reaching_by_tier(unanswered = [seed for seed in seeds if seed not in out]if unanswered and import_depth >= 1:- found = await _import_reaching(session, repo_id, unanswered, test_files, import_depth)+ found, entries = await _import_reaching(+ session, repo_id, unanswered, test_files, import_depth+ )for seed, tests in found.items():ordered = tuple(rank_tests(seed.split("::", 1)[0], tests))out[seed] = ReachedBy(- list(ordered[:MAX_TESTS_PER_TARGET]), "import-graph", len(ordered), ordered+ list(ordered[:MAX_TESTS_PER_TARGET]),+ "import-graph",+ len(ordered),+ ordered,+ entries={t: frozenset(via) for t, via in entries[seed].items()},)return out@@ -772,10 +781,14 @@ async def _import_reaching(seeds: list[str],test_files: set[str],max_depth: int,-) -> dict[str, set[str]]:- """Tests that import each seed file, directly or within *max_depth* hops."""+) -> tuple[dict[str, set[str]], dict[str, dict[str, set[str]]]]:+ """Tests that import each seed file, directly or within *max_depth* hops.++ Also ``{seed: {test: the files it imports on a route to the seed}}``.+ """origins: dict[str, set[str]] = {s: {s} for s in seeds}found: dict[str, set[str]] = {}+ entries: dict[str, dict[str, set[str]]] = {}seed_set = set(seeds)frontier = list(seeds)@@ -793,6 +806,7 @@ async def _import_reaching(if dependent in test_files:for seed in carried:found.setdefault(seed, set()).add(dependent)+ entries.setdefault(seed, {}).setdefault(dependent, set()).add(dependency)continueif dependent in seed_set:continue@@ -807,7 +821,7 @@ async def _import_reaching(if dependent not in queued:queued.add(dependent)frontier.append(dependent)- return found+ return found, entriesasync def direct_dependents(@@ -833,6 +847,15 @@ async def direct_dependents(return out+# Indexes built before the conftest -> test hint was removed still hold edges+# that point from a conftest to each test using one of its fixtures, which made+# the conftest read as that test's importer. The test -> conftest edge already+# records the relation. Upgrade path: drop this once such indexes are rebuilt.+_LEGACY_CONFTEST_FILTER = (+ " AND NOT (edge_type = 'dynamic_uses' AND COALESCE(hint_source, '') = 'pytest_conftest')"+)++def _in_clause(prefix: str, values: list[str], params: dict[str, Any]) -> str:"""Bind *values* as ``:prefix0, :prefix1, ...`` and return the clause body."""params.update({f"{prefix}{i}": v for i, v in enumerate(values)})@@ -889,6 +912,7 @@ async def _edges_into("SELECT DISTINCT source_node_id, target_node_id FROM graph_edges ""WHERE repository_id = :repo_id "f"AND target_node_id IN ({tgt}) AND edge_type IN ({ets}){origin_filter}"+ f"{_LEGACY_CONFTEST_FILTER}"),params,)diff --git a/packages/core/src/repowise/core/analysis/test_selection.py b/packages/core/src/repowise/core/analysis/test_selection.pyindex ec7ff23e1..063f12f83 100644--- a/packages/core/src/repowise/core/analysis/test_selection.py+++ b/packages/core/src/repowise/core/analysis/test_selection.py@@ -266,11 +266,14 @@ class Selection:names, per changed or deleted file, what decided it: ``full-run``,``no-tests-needed``, ``deleted-test``, ``test-tree``, ``test-package``,``conftest``, ``helper-importers``, ``coverage``,- ``changed-test``, ``call-graph``, ``import-graph``, ``filename-pattern``,- ``unknown``, ``none`` when nothing was asked (no index), or a scope's- ``ecosystem``, ``package-importers``, ``named-by`` or ``owner-package``.- ``why`` says, per selected test file, what put it in: the changed file- and evidence that reached it, or the reason it runs with every subset.+ ``changed-test``, ``call-graph``, ``import-graph``, ``conftest-fixture``+ (a test using a conftest fixture that reaches the change),+ ``conftest-import-check`` (one test that loads a conftest the change reaches+ only through its imports), ``filename-pattern``, ``unknown``, ``none`` when+ nothing was asked (no index), or a scope's ``ecosystem``,+ ``package-importers``, ``named-by`` or ``owner-package``. ``why`` says, per+ selected test file, what put it in: the changed file and evidence that+ reached it, or the reason it runs with every subset."""run_all: bool@@ -585,10 +588,22 @@ def _why(for _, test_file in tests:if test_file and test_file not in out:via = "coverage" if test_file in covered else vias.get(test_file, basis)- out[test_file] = f"{path} changed ({via})"+ out[test_file] = f"{path} changed ({_VIA_WHY.get(via, via)})"return out+# The two vias a narrowed conftest route adds (``conftest_routes``), spelled out.+_VIA_WHY = {+ "conftest-fixture": (+ "conftest-fixture: it asks for a conftest fixture whose code runs into the change"+ ),+ "conftest-import-check": (+ "conftest-import-check: the change reaches a conftest above it only through the "+ "conftest's imports, and this test is that conftest's import check"+ ),+}++def selected_by_change(selection: Selection, test: str) -> bool:"""Whether a changed file (not a rule) put *test* in the selection."""why = selection.why.get(test.split("::", 1)[0])@@ -754,6 +769,8 @@ def _notes()if skipped:out.append(f"{len(skipped)} changed file(s) are documentation: no tests needed.")+ # How each conftest on a route was decided (``conftest_routes``).+ out.extend(inp.tiers.get("conftest_notes") or ())return out@@ -1147,6 +1164,16 @@ def expand_test_scopes(tests: Iterable[str], test_files: Collection[str]) -> lisreturn list(out)+_VIAS = (+ "changed-test",+ "call-graph",+ "import-graph",+ "conftest-fixture",+ "conftest-import-check",+ "filename-pattern",+)++def _basis(path: str,covered: Mapping[str, Any],@@ -1157,7 +1184,7 @@ def _basis(if path in covered:return "coverage"vias = {via for _, via in inferred.get(path, ())}- for via in ("changed-test", "call-graph", "import-graph", "filename-pattern"):+ for via in _VIAS:if via in vias:return viareturn "unknown" if path in unknown else "none"diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/pytest_hints.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/pytest_hints.pydeleted file mode 100644index bbb3795d8..000000000--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/pytest_hints.py+++ /dev/null@@ -1,105 +0,0 @@-from __future__ import annotations--import ast-from pathlib import Path--from .base import DynamicEdge, DynamicHintExtractor---def _get_fixture_names(tree: ast.AST) -> set[str]:- """Walk an AST and return the names of all @pytest.fixture / @fixture decorated functions."""- names: set[str] = []- for node in ast.walk(tree):- if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):- continue- for decorator in node.decorator_list:- if _is_fixture_decorator(decorator):- names.append(node.name)- break- return set(names)---def _is_fixture_decorator(decorator: ast.expr) -> bool:- """Return True if the decorator is @fixture or @pytest.fixture (with or without call)."""- # @fixture or @pytest.fixture- if isinstance(decorator, ast.Name) and decorator.id == "fixture":- return True- if isinstance(decorator, ast.Attribute) and decorator.attr == "fixture":- return True- # @fixture(...) or @pytest.fixture(...)- if isinstance(decorator, ast.Call):- return _is_fixture_decorator(decorator.func)- return False---def _get_test_function_params(tree: ast.AST) -> set[str]:- """Return all parameter names of test_* functions in the AST."""- params: set[str] = set()- for node in ast.walk(tree):- if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):- continue- if not node.name.startswith("test_"):- continue- for arg in node.args.args + node.args.posonlyargs + node.args.kwonlyargs:- params.add(arg.arg)- if node.args.vararg:- params.add(node.args.vararg.arg)- if node.args.kwarg:- params.add(node.args.kwarg.arg)- return params---class PytestDynamicHints(DynamicHintExtractor):- name = "pytest_conftest"-- def extract(self, repo_root: Path) -> list[DynamicEdge]:- edges: list[DynamicEdge] = []-- for conftest in self._rglob(repo_root, "conftest.py"):- try:- source = conftest.read_text(encoding="utf-8", errors="ignore")- tree = ast.parse(source, filename=str(conftest))- rel_conftest = conftest.relative_to(repo_root).as_posix()- except Exception:- continue-- fixture_names = _get_fixture_names(tree)- if not fixture_names:- continue-- conftest_dir = conftest.parent- seen_targets: set[str] = set()-- # Find all test files under the conftest's parent directory- for pattern in ("test_*.py", "*_test.py"):- for test_file in self._rglob(conftest_dir, pattern):- if test_file == conftest:- continue- try:- rel_test = test_file.relative_to(repo_root).as_posix()- except ValueError:- continue-- if rel_test in seen_targets:- continue-- try:- test_source = test_file.read_text(encoding="utf-8", errors="ignore")- test_tree = ast.parse(test_source, filename=str(test_file))- except Exception:- continue-- # Check if any test function uses a fixture from this conftest- test_params = _get_test_function_params(test_tree)- if test_params & fixture_names:- seen_targets.add(rel_test)- edges.append(- DynamicEdge(- source=rel_conftest,- target=rel_test,- edge_type="dynamic_uses",- hint_source=self.name,- )- )-- return edgesdiff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.pyindex d5d9a2151..d59c81393 100644--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py@@ -32,7 +32,6 @@ from .jvm import JvmDynamicHintsfrom .luau import LuauDynamicHintsfrom .node import NodeDynamicHintsfrom .php import PhpDynamicHints-from .pytest_hints import PytestDynamicHintsfrom .python_imports import PythonDynamicHintsfrom .ruby import RubyDynamicHintsfrom .rust import RustDynamicHints@@ -58,7 +57,6 @@ class HintRegistry:) -> None:self._extractors = extractors or [DjangoDynamicHints(),- PytestDynamicHints(),PythonDynamicHints(),NodeDynamicHints(),AlpineDynamicHints(),diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/pytest_edges.py b/packages/core/src/repowise/core/ingestion/framework_edges/pytest_edges.pyindex 2c8918325..c2f9e95e5 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/pytest_edges.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/pytest_edges.py@@ -1,18 +1,40 @@"""pytest conftest convention edges.Two conventions, both invisible to a static import graph: a ``conftest.py`` is-imported by collection rather than by any statement, and a test's parameter+imported by collection, not by any statement, and a test's parameternames are fixture requests resolved at run time.++Every way a test or fixture asks for a fixture by name becomes a+``framework_binds`` edge stamped :data:`FIXTURE_HINT`: a test's parameters, a+fixture's own parameters, ``@pytest.mark.usefixtures(...)`` on a test or its+class, a module's ``pytestmark`` usefixtures, and ``request.getfixturevalue``+with a literal name. Test selection reads these edges to find every test that+uses a fixture, and trusts them only when the stamp shows all of these forms+were recorded. A request no edge can record (a computed name, a test inherited+from a base class declared elsewhere, a class-level ``pytestmark``, marks inside+``pytest.param``, a parametrize call in a hook, any other code use of a+request name such as an aliased mark, ``add_marker`` or ``fixturenames``, a+config ``usefixtures`` or ``python_functions``, a helper asking for a fixture,+a file whose text is not available) is stamped+:data:`UNRECORDED_HINT` on the conftest edges it could reach, and selection+keeps every test under those conftests."""from __future__ import annotations+import ioimport re+import tokenize+from collections import Counter+from collections.abc import Callable, Iterable+from dataclasses import dataclass, fieldfrom fnmatch import fnmatchfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any+from ...pytest_roots import DEFAULT_PYTHON_FUNCTIONSfrom ..resolvers import ResolverContext+from ..source_text import decode_source, source_textfrom ..type_names import strip_type_argumentsfrom .base import (DetectionContext,@@ -36,6 +58,40 @@ _QUOTED_RE = re.compile(r"""["']([^"']*)["']""")# top-level keyword only: a `name=` nested in a params list is not the# fixture's name._NAME_KWARG_ARG_RE = re.compile(r"""^name\s*=\s*["']([^"']+)["']$""")+_USEFIXTURES_RE = re.compile(r"^@(?:[\w.]+\.)?usefixtures\b")+# A module-level `pytestmark = pytest.mark.usefixtures("a")` (or a list of+# marks): the statement up to the next top-level line.+_PYTESTMARK_RE = re.compile(r"^pytestmark\b[^\n]*(?:\n[ \t)\]][^\n]*)*", re.MULTILINE)+_USEFIXTURES_CALL_RE = re.compile(r"usefixtures\(([^)]*)\)")+# The name is captured only when it is a literal alone in the call.+_GETFIXTUREVALUE_RE = re.compile(r"""getfixturevalue\(\s*(?:["'](\w+)["']\s*(?=\)))?""")+# Names through which code can ask for a fixture. A use of one that is not a+# form this module records (a literal decorator, a module ``pytestmark``, a+# literal ``getfixturevalue`` call in a test or fixture) hides a request.+_REQUEST_NAMES = frozenset(+ {"usefixtures", "getfixturevalue", "add_marker", "applymarker", "fixturenames",+ "lazy_fixture", "fixture_ref"}+)+_AUTOUSE_KWARG_RE = re.compile(r"^autouse\s*=\s*(.+)$")+_INDIRECT_KWARG_RE = re.compile(r"^indirect\s*=")+_LITERAL_RE = re.compile(r"""(["'])\w+\1""")+_LITERAL_LIST_RE = re.compile(r"""[\[(]\s*(?:(["'])\w+\1\s*,?\s*)*[\])]""")+# A `pytestmark` inside a class body, and a parametrize called instead of+# applied as a decorator (`metafunc.parametrize(..., indirect=True)`).+_CLASS_PYTESTMARK_RE = re.compile(r"^[ \t]+pytestmark\b", re.MULTILINE)+_CALL_PARAMETRIZE_RE = re.compile(r"^[ \t]*[^@\s#][^\n]*\bparametrize\(", re.MULTILINE)+# Bases a test class may name without carrying fixture requests of its own.+_PLAIN_BASES = frozenset(+ {"object", "ABC", "abc.ABC", "TestCase", "unittest.TestCase", "IsolatedAsyncioTestCase",+ "unittest.IsolatedAsyncioTestCase"}+)++# Stamped on every fixture-request edge, so a reader can tell an index that+# records all request forms from one built before they were recorded.+FIXTURE_HINT = "pytest_fixture"+# Stamped instead of the conftest hint on a test -> conftest edge when the test+# (or the conftest) may request that conftest's fixtures in a way no edge records.+UNRECORDED_HINT = "pytest_conftest_unrecorded"# pytest's own `python_files` default, and deliberately not the shared# `is_test_path`. A fixture is injected only into a file pytest actually@@ -44,10 +100,8 @@ _NAME_KWARG_ARG_RE = re.compile(r"""^name\s*=\s*["']([^"']+)["']$""")# `tests/helpers.py` and every non-Python spec layout. Widening it would inject# fixture parameters into files that are never collected.#-# Ceiling: `python_files` is configurable and this assumes the default, unlike-# `_DEFAULT_TEST_CLASS_GLOBS` below, which reads the setting because assuming it-# cost 346 of celery's 359 bindings. No corpus repo overrides `python_files`, so-# the same mistake is not yet demonstrable here.+# Used only when the traverser's pytest roots are not known; with them, the+# configured `python_files` decide._TEST_FILE_RE = re.compile(r"(?:^|/)(?:test_[^/]*|[^/]*_test)\.py$")# pytest collects methods only from classes matching `python_classes`, so a@@ -243,61 +297,102 @@ def _add_conftest_edges(return count-def _registered_name(sym: Any, decorator: str) -> str:- """The name pytest registers the fixture under.+def fixture_declaration(name: str, decorators: Iterable[str]) -> tuple[str, bool] | None:+ """``(registered name, autouse)`` when *decorators* declare a pytest fixture.- ``name=`` must be read as a top-level keyword, not found anywhere in the- text: ``@pytest.fixture(params=[dict(name="alice")])`` otherwise registers- the fixture as ``alice``, which both loses the real request and mints a- fabricated one.+ ``name=`` and ``autouse=`` are read as top-level keywords only:+ ``@pytest.fixture(params=[dict(name="alice")])`` registers the fixture+ under its own name. An ``autouse`` that is not the literal ``False`` may be+ true, so it counts as autouse."""- for arg in _call_arguments(decorator):- match = _NAME_KWARG_ARG_RE.match(arg)- if match:- return match.group(1)- return sym.name+ for dec in decorators:+ if not _FIXTURE_DECORATOR_RE.match(dec.strip()):+ continue+ registered, autouse = name, False+ for arg in _call_arguments(dec):+ if match := _NAME_KWARG_ARG_RE.match(arg):+ registered = match.group(1)+ elif match := _AUTOUSE_KWARG_RE.match(arg):+ autouse = match.group(1).strip() not in ("False", "0", "None")+ return registered, autouse+ return Nonedef _declared_fixtures(parsed: Any) -> dict[tuple[str | None, str], str]:"""``{(owning class or None, fixture name): symbol id}``.- Keyed by scope rather than by name alone. A fixture declared inside a test- class serves that class only, and flattening the two makes every sibling- class share it — which is a wrong edge whichever way the collision is- resolved.+ Keyed by scope as well as by name. A fixture declared inside a test class+ serves that class only, and flattening the two makes every sibling class+ share it, which is a wrong edge whichever way the collision is resolved."""out: dict[tuple[str | None, str], str] = {}for sym in parsed.symbols:if sym.kind not in ("function", "method"):continue- for dec in sym.decorators:- if not _FIXTURE_DECORATOR_RE.match(dec.strip()):- continue- out.setdefault((sym.parent_name, _registered_name(sym, dec)), sym.id)- break+ if declared := fixture_declaration(sym.name, sym.decorators):+ out.setdefault((sym.parent_name, declared[0]), sym.id)return out-def _requested_fixtures(sym: Any) -> list[str]:- """The parameter names *sym* asks pytest to inject.+@dataclass+class _Requests:+ """What a list of decorators asks for: names it supplies, names it requests."""- Reads the recorded signature rather than re-parsing: a second pass over- every test file is the cost of running inside the build rather than beside- it.- """- supplied: set[str] = set()- for dec in sym.decorators:- if not _PARAMETRIZE_RE.match(dec.strip()):+ supplied: set[str] = field(default_factory=set)+ requested: list[str] = field(default_factory=list)+ # A request the text does not name (a computed ``indirect`` or usefixtures argument).+ unknown: bool = False+++def _argnames(spec: str) -> list[str]:+ return [p.strip() for token in _QUOTED_RE.findall(spec) for p in token.split(",") if p.strip()]+++def _decorator_requests(decorators: Iterable[str]) -> _Requests:+ """Supplied argnames, and fixtures requested by ``usefixtures`` or ``indirect`` parametrize."""+ out = _Requests()+ for dec in decorators:+ dec = dec.strip()+ if _USEFIXTURES_RE.match(dec):+ for arg in _call_arguments(dec):+ if _LITERAL_RE.fullmatch(arg):+ out.requested.append(arg[1:-1])+ else:+ out.unknown = True+ continue+ if not _PARAMETRIZE_RE.match(dec):continue- # Only the first argument is the argnames spec. Reading the whole- # decorator instead makes every parametrize *value* look like a name- # the test supplies, so a real fixture request whose name is also a- # common literal is silently refused.+ # Only the first argument is the argnames spec: reading the whole+ # decorator makes every parametrize value look like a supplied name.args = _call_arguments(dec)- if args:- for token in _QUOTED_RE.findall(args[0]):- supplied.update(p.strip() for p in token.split(","))+ if not args:+ continue+ names = _argnames(args[0])+ indirect = next(+ (a.split("=", 1)[1].strip() for a in args[1:] if _INDIRECT_KWARG_RE.match(a)),+ args[2] if len(args) > 2 and "=" not in args[2] else None,+ )+ # `indirect` hands the value to the fixture of that name: a request.+ if indirect in (None, "False"):+ out.supplied.update(names)+ elif indirect == "True":+ out.requested.extend(names)+ elif _LITERAL_LIST_RE.fullmatch(indirect):+ via = set(_QUOTED_RE.findall(indirect))+ out.requested.extend(n for n in names if n in via)+ out.supplied.update(n for n in names if n not in via)+ else:+ out.requested.extend(names)+ out.unknown = True+ return out+++def _requested_fixtures(sym: Any, supplied: set[str] = frozenset()) -> list[str]:+ """The parameter names *sym* asks pytest to inject, minus *supplied* argnames.+ Reads the recorded signature: a second parse of every test file is the cost+ of running inside the build, not beside it.+ """names = []for raw in _call_arguments(sym.signature or ""):# A defaulted parameter is never injected -- pytest skips any argument@@ -306,23 +401,95 @@ def _requested_fixtures(sym: Any) -> list[str]:if raw.startswith("*") or _has_default(raw):continuename = raw.split(":")[0].strip()- if not name or name in ("self", "cls", "/"):- continue- if name in supplied:+ if not name or name in ("self", "cls", "/") or name in supplied:continuenames.append(name)return names+def _module_usefixtures(text: str) -> tuple[list[str], bool]:+ """Fixture names a module-level ``pytestmark`` applies, and whether any is computed."""+ names: list[str] = []+ unknown = False+ for mark in _PYTESTMARK_RE.findall(text):+ for call in _USEFIXTURES_CALL_RE.findall(mark):+ args = _call_arguments(f"({call})")+ # `usefixtures(*names())` stops the capture early and parses to nothing.+ unknown = unknown or (bool(call.strip()) and not args)+ for arg in args:+ if _LITERAL_RE.fullmatch(arg):+ names.append(arg[1:-1])+ else:+ unknown = True+ return names, unknown+++def _request_name_uses(text: str) -> Counter[str] | None:+ """How often code (not strings or comments) uses each of :data:`_REQUEST_NAMES`.++ ``None`` when the text does not tokenize, which hides whatever it holds.+ A substring check first, so the lexer runs only on the few files that+ mention one.+ """+ if not any(name in text for name in _REQUEST_NAMES):+ return Counter()+ try:+ tokens = tokenize.generate_tokens(io.StringIO(text).readline)+ return Counter(+ t.string for t in tokens if t.type == tokenize.NAME and t.string in _REQUEST_NAMES+ )+ except (tokenize.TokenError, SyntaxError):+ return None+++def _hidden_request(text: str) -> str | None:+ """A request form the edges below cannot record, found in a test file's or conftest's text."""+ if _CLASS_PYTESTMARK_RE.search(text):+ return "a class-level pytestmark"+ if "marks=" in text and "usefixtures" in text:+ return "usefixtures inside pytest.param marks"+ if "indirect" in text and _CALL_PARAMETRIZE_RE.search(text):+ return "a parametrize call outside a decorator"+ return None+++def _runtime_requests(text: str, symbols: list[Any]) -> tuple[list[tuple[Any, str]], bool]:+ """``(enclosing function, name)`` per literal ``getfixturevalue``, and whether any is computed."""+ out: list[tuple[Any, str]] = []+ unknown = False+ functions = [s for s in symbols if s.kind in ("function", "method")]+ for match in _GETFIXTUREVALUE_RE.finditer(text):+ name = match.group(1)+ line = text.count("\n", 0, match.start()) + 1+ enclosing = [s for s in functions if s.start_line <= line <= s.end_line]+ if name is None or not enclosing:+ unknown = True+ continue+ out.append((max(enclosing, key=lambda s: s.start_line), name))+ return out, unknown++def _add_fixture_injection_edges(- graph: nx.DiGraph, parsed_files: dict[str, Any], repo_path: Path | None = None+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ repo_path: Path | None = None,+ read: Callable[[str], str | None] | None = None,+ roots: PytestRoots | None = None,+ helper_text: Callable[[str], str | None] | None = None,) -> int:- """Link each test function to the fixture it asks for by name.-- Scope follows pytest's own rule, innermost first: the test's own class, then- its module, then the nearest ``conftest.py`` at or above it. Nothing else is- searched, so a plugin-provided fixture stays unclaimed rather than being- bound to a same-named local one.+ """Link each test and fixture to every fixture it asks for by name.++ Scope follows pytest's own rule, innermost first: the requester's own class,+ then its module, then the nearest ``conftest.py`` at or above it. Nothing+ else is searched, so a plugin-provided fixture stays unclaimed instead of+ being bound to a same-named local one. A fixture asking for its own name+ (an override) gets the next one out. *read* returns a file's text, for the+ forms only the text shows; *roots* say which files pytest collects;+ *helper_text* returns the text of any other Python file from the bytes+ ingestion already holds (``None`` when it does not hold it).++ A request no edge can record is stamped on the requester's conftest edges+ instead (:data:`UNRECORDED_HINT`, see :func:`_stamp_unrecorded`)."""# Only a conftest's module-level fixtures are visible to other files; one# declared inside a class there serves that class alone.@@ -338,38 +505,176 @@ def _add_fixture_injection_edges(conftests[Path(path).parent.as_posix()] = declaredclass_globs = _test_class_globs(repo_path)-+ unrecorded: set[str] = set()+ everywhere = Falsecount = 0for path, parsed in parsed_files.items():- if parsed.file_info.language != "python" or not _TEST_FILE_RE.search(path):+ if parsed.file_info.language != "python":continue+ is_conftest = Path(path).name == "conftest.py"+ collected = roots.may_collect_name(path) if roots else bool(_TEST_FILE_RE.search(path))+ if not (is_conftest or collected):+ # Code a test calls may ask for a fixture by name, for whichever test+ # calls it. Read from the bytes ingestion holds, never from disk: a+ # file missing there is not known to be free of requests.+ text = helper_text(path) if helper_text is not None else None+ uses = None if text is None else _request_name_uses(text)+ everywhere = everywhere or uses is None or bool(uses)+ continue+ added, hidden, anywhere = _link_file(graph, path, parsed, conftests, class_globs, read)+ count += added+ everywhere = everywhere or anywhere+ if hidden:+ unrecorded.add(path)+ hidden_dirs = roots.hidden_request_dirs() if roots else []+ _stamp_unrecorded(graph, unrecorded, hidden_dirs, everywhere=everywhere)+ return count- own = _declared_fixtures(parsed)- # Nearest-first: the deepest conftest directory that is a prefix of this- # file's directory shadows the ones above it, as pytest does.- chain = sorted(- (d for d in conftests if path.startswith(f"{d}/") or d == "."),- key=len,- reverse=True,- )- for sym in parsed.symbols:- if sym.kind not in ("function", "method") or not sym.name.startswith("test_"):- continue- if sym.parent_name and not any(- fnmatch(sym.parent_name, g) for g in class_globs- ):+def _stamp_unrecorded(+ graph: nx.DiGraph, files: set[str], dirs: list[str], *, everywhere: bool+) -> None:+ """Mark the conftest edges whose fixtures may be requested in a way no edge records.++ A file's requests resolve among the conftests above it, so its edges to them+ are marked; a conftest's own unrecorded requests mark the edges into it too.+ *dirs* hold a pytest config that requests fixtures for every test under it.+ """+ for conf in [n for n in graph.nodes if str(n).endswith("conftest.py")]:+ for source in list(graph.predecessors(conf)):+ data = graph[source][conf]+ if data.get("hint_source") != CONFTEST_HINT:continue- scopes = _fixture_scopes(parsed, sym.parent_name)- for name in _requested_fixtures(sym):- target = next(- (own[(s, name)] for s in scopes if (s, name) in own), None- ) or next(- (conftests[d][name] for d in chain if name in conftests[d]), None- )- if target and add_symbol_edge(graph, sym.id, target):- count += 1- return count+ under_dir = any(d == "" or str(source).startswith(f"{d}/") for d in dirs)+ if everywhere or under_dir or source in files or conf in files:+ data["hint_source"] = UNRECORDED_HINT+++def _link_file(+ graph: nx.DiGraph,+ path: str,+ parsed: Any,+ conftests: dict[str, dict[str, str]],+ class_globs: tuple[str, ...],+ read: Callable[[str], str | None] | None,+) -> tuple[int, bool, bool]:+ """The fixture-request edges leaving one test module or conftest, and whether some cannot be.++ The second value is true when the file asks for a fixture in a way no edge+ records: a computed name, a test inherited from a base class this file does+ not declare, or a request form only the text shows (:func:`_hidden_request`).+ The third is true when a helper asks for one, for whichever test calls it.+ """+ is_conftest = Path(path).name == "conftest.py"+ own = _declared_fixtures(parsed)+ fixture_ids = set(own.values())+ # Nearest-first: the deepest conftest directory that is a prefix of this+ # file's directory shadows the ones above it, as pytest does.+ chain = sorted(+ (d for d in conftests if path.startswith(f"{d}/") or d == "."),+ key=len,+ reverse=True,+ )++ def link(sym: Any, names: Iterable[str]) -> int:+ scopes = _fixture_scopes(parsed, sym.parent_name)+ added = 0+ for name in names:+ hits = [own[(s, name)] for s in scopes if (s, name) in own]+ hits += [conftests[d][name] for d in chain if name in conftests[d]]+ target = next((h for h in hits if h != sym.id), None)+ if target and add_symbol_edge(graph, sym.id, target):+ graph[sym.id][target]["hint_source"] = FIXTURE_HINT+ added += 1+ return added++ classes = {sym.name: sym for sym in parsed.symbols if sym.kind == "class"}+ collected = {c for c in classes if any(fnmatch(c, g) for g in class_globs)}+ # A collected class runs the tests of every base it names, with their marks.+ inherited = {s for c in collected for s in _fixture_scopes(parsed, c) if s}+ hidden = any(b not in classes and b not in _PLAIN_BASES for b in inherited)+ marks = {c: _decorator_requests(classes[c].decorators) for c in inherited if c in classes}+ hidden = hidden or any(r.unknown for r in marks.values())++ # Decorator uses of `usefixtures` this file records (the computed ones are+ # flagged by `_decorator_requests` itself).+ recorded = Counter(+ "usefixtures"+ for sym in parsed.symbols+ for dec in sym.decorators+ if _USEFIXTURES_RE.match(dec.strip())+ )+ count = 0+ tests = []+ for sym in parsed.symbols:+ if sym.kind not in ("function", "method"):+ continue+ own_requests = _decorator_requests(sym.decorators)+ hidden = hidden or own_requests.unknown+ if sym.id in fixture_ids:+ names = _requested_fixtures(sym, own_requests.supplied) + own_requests.requested+ count += link(sym, names)+ continue+ if is_conftest or not sym.name.startswith(DEFAULT_PYTHON_FUNCTIONS):+ continue+ if sym.parent_name and sym.parent_name not in collected | inherited:+ continue+ tests.append(sym)+ scoped = [marks[s] for s in _fixture_scopes(parsed, sym.parent_name) if s in marks]+ supplied = own_requests.supplied.union(*(r.supplied for r in scoped))+ names = _requested_fixtures(sym, supplied) + own_requests.requested+ count += link(sym, names + [n for r in scoped for n in r.requested])++ text = read(path) if read is not None else None+ everywhere = False+ if text is None:+ # Unread, the file may hold any request form.+ return count, True, everywhere+ hidden = hidden or _hidden_request(text) is not None+ if "pytestmark" in text:+ module_marks, unknown = _module_usefixtures(text)+ hidden = hidden or unknown+ recorded["usefixtures"] += sum(+ len(_USEFIXTURES_CALL_RE.findall(m)) for m in _PYTESTMARK_RE.findall(text)+ )+ for sym in tests:+ count += link(sym, module_marks)+ if "getfixturevalue" in text:+ runtime, unknown = _runtime_requests(text, parsed.symbols)+ hidden = hidden or unknown+ for sym, name in runtime:+ if sym in tests or sym.id in fixture_ids:+ count += link(sym, [name])+ recorded["getfixturevalue"] += 1+ else:+ # A helper asking for a fixture serves whichever test calls it.+ everywhere = True+ # Any other use (an alias, a mark stored in a variable, `add_marker`,+ # `request.fixturenames`, a lazy-fixture plugin) is a request no edge records.+ uses = _request_name_uses(text)+ hidden = hidden or uses is None or any(n > recorded[name] for name, n in uses.items())+ return count, hidden, everywhere+++def _source_reader(ctx: ResolverContext) -> Callable[[str], str | None]:+ """Text of an indexed file, from the bytes ingestion already read, else from disk."""++ def read(path: str) -> str | None:+ if ctx.repo_path is None and path not in (ctx.source_map or {}):+ return None+ return source_text(path, (ctx.repo_path or Path()) / path, ctx.source_map)++ return read+++def _held_text(ctx: ResolverContext) -> Callable[[str], str | None]:+ """Text of an indexed file from the bytes ingestion already read only; ``None`` if not held."""++ def read(path: str) -> str | None:+ data = (ctx.source_map or {}).get(path)+ return None if data is None else decode_source(data)++ return readclass _FixtureInjectionHandler:@@ -385,7 +690,14 @@ class _FixtureInjectionHandler:ctx: ResolverContext,path_set: set[str],) -> int:- return _add_fixture_injection_edges(graph, parsed_files, ctx.repo_path)+ return _add_fixture_injection_edges(+ graph,+ parsed_files,+ ctx.repo_path,+ _source_reader(ctx),+ ctx.pytest_roots,+ _held_text(ctx),+ )class _ConftestHandler:diff --git a/packages/core/src/repowise/core/ingestion/languages/python_modules.py b/packages/core/src/repowise/core/ingestion/languages/python_modules.pyindex a9027910f..efaa3d4f0 100644--- a/packages/core/src/repowise/core/ingestion/languages/python_modules.py+++ b/packages/core/src/repowise/core/ingestion/languages/python_modules.py@@ -78,6 +78,16 @@ def _is_package_dir(dir_posix: str, path_set: frozenset[str] | set[str]) -> boolreturn init in path_set+def module_parts(path: str) -> tuple[str, ...]:+ """The dotted-path segments of a Python file from the repository root (a package for ``__init__``).++ Every tail of the result is a name the file may be imported under; which+ one depends on the source root, which this does not decide.+ """+ parts = PurePosixPath(path).with_suffix("").parts+ return parts[:-1] if parts and parts[-1] == "__init__" else parts++def dotted_module_for(path: str, path_set: frozenset[str] | set[str]) -> str | None:"""Return the dotted module name *path* is importable as, or ``None``.diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex 9aee343c0..67e6d397d 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -68,7 +68,8 @@ def build_repo_graph(Files that fail to read/parse are skipped and reported as a count rather thanswallowed silently. ``source_map`` is populated only when ``collect_sources``- is set (the re-score path doesn't need the raw bytes).+ is set; every path that persists the graph sets it, since the framework-edge+pass reads the sources.``timings`` is the run's shared :class:`PhaseTimings` table; each stepbelow records into it under a ``rebuild.*`` name. ``None`` records nothing.diff --git a/packages/core/src/repowise/core/pytest_roots.py b/packages/core/src/repowise/core/pytest_roots.pyindex 003e1eab0..880f074b3 100644--- a/packages/core/src/repowise/core/pytest_roots.py+++ b/packages/core/src/repowise/core/pytest_roots.py@@ -48,6 +48,8 @@ PYTEST_CONFIG_NAMES: frozenset[str] = frozenset(name for name, _ in PYTEST_CONFI_PRECEDENCE = {name: rank for rank, (name, _) in enumerate(PYTEST_CONFIG_SECTIONS)}# pytest's own ``python_files`` default.DEFAULT_PYTHON_FILES: tuple[str, ...] = ("test_*.py", "*_test.py")+# pytest's own ``python_functions`` default: a name prefix, so ``testFoo`` counts.+DEFAULT_PYTHON_FUNCTIONS: tuple[str, ...] = ("test",)class PytestConfigUnreadableError(ValueError):@@ -58,6 +60,9 @@ class PytestConfigUnreadableError(ValueError):class _Collection:testpaths: tuple[str, ...]python_files: tuple[str, ...]+ # Options that request fixtures or pick test functions without a name in+ # the test's own source: ``usefixtures`` and a non-default ``python_functions``.+ hidden_requests: bool = False@dataclass(frozen=True, slots=True)@@ -85,6 +90,15 @@ class PytestRoots:"/" in pat or fnmatchcase(p.name, pat) for pat in patterns or DEFAULT_PYTHON_FILES)+ def hidden_request_dirs(self) -> list[str]:+ """Directories whose config requests fixtures or collects functions outside the source.++ ``usefixtures`` names fixtures for every test, and ``python_functions``+ collects functions not named ``test*``; a config that did not parse may+ do either.+ """+ return sorted({d for d, r in self.by_dir.items() if r.hidden_requests} | self.unreadable)+def collects(self, path: str) -> bool | None:"""Whether a bare ``pytest`` run collects *path*; ``None`` when no config governs it.@@ -168,6 +182,8 @@ def pytest_roots(key: _Collection(tuple(v.strip("/").removeprefix("./") or "." for v in _words(o.get("testpaths"))),_words(o.get("python_files")),+ bool(_words(o.get("usefixtures")))+ or _words(o.get("python_functions")) not in ((), DEFAULT_PYTHON_FUNCTIONS),)for key, (_, o) in chosen.items()},diff --git a/tests/unit/analysis/test_conftest_routes.py b/tests/unit/analysis/test_conftest_routes.pynew file mode 100644index 000000000..baac03efe--- /dev/null+++ b/tests/unit/analysis/test_conftest_routes.py@@ -0,0 +1,270 @@+"""What a conftest does with the modules on a change's route decides which of its tests run."""++from __future__ import annotations++from textwrap import dedent++import pytest++from repowise.core.analysis.conftest_routes import ConftestFacts, conftest_use++ROUTE = ["src/app/store.py"]+++def _use(source: str, entries: list[str] = ROUTE, path: str = "tests/conftest.py"):+ return conftest_use(dedent(source), path, entries)+++def test_an_autouse_fixture_that_calls_the_route_keeps_every_test() -> None:+ use = _use(+ """+ import pytest+ from app import store++ @pytest.fixture(autouse=True)+ def _reset():+ store.reset()+ """+ )+ assert use.run_all and "autouse fixture _reset uses store" in use.run_all+++def test_patching_or_lazily_importing_from_an_autouse_fixture_is_import_time_only() -> None:+ """The import check runs every autouse fixture, so a patch that stops working fails there."""+ use = _use(+ """+ import pytest++ @pytest.fixture(autouse=True)+ def _isolate(monkeypatch):+ import app.store as store+ monkeypatch.setattr(store, "_cache", None)+ """+ )+ assert use.run_all is None+ assert use.fixtures == frozenset()+++ "line",+ [+ 'monkeypatch.setenv("HOME", str(tmp_path / store.DIR_NAME))',+ "assert store.SIZE * 2",+ "if store.FLAG:\n pass",+ 'x = store.REGISTRY["a"]',+ "for item in store.ITEMS:\n pass",+ 'x = f"{store.NAME}"',+ "x = store.LEVEL > 3",+ "store._other = None",+ 'if hasattr(store, "_other"):\n pass',+ 'monkeypatch.delattr(store, "_other")',+ ],+)+def test_reading_a_module_value_in_an_autouse_fixture_keeps_every_test(line: str) -> None:+ """A changed constant changes what the fixture does for every test."""+ use = _use(+ f"""+ import pytest+ from app import store++ @pytest.fixture(autouse=True)+ def _isolate(monkeypatch, tmp_path):+ {line}+ """+ )+ assert use.run_all and "autouse fixture _isolate uses store" in use.run_all+++def test_a_requested_fixture_that_only_patches_the_route_still_reaches_its_users() -> None:+ """Only autouse fixtures run in the import check, so a requested one's patch must."""+ use = _use(+ """+ import pytest+ from app import store++ @pytest.fixture+ def quiet(monkeypatch):+ monkeypatch.setattr(store, "_cache", None)+ """+ )+ assert use.fixtures == {"quiet"}+++def test_a_class_body_or_a_fixture_in_a_class_using_the_route_keeps_every_test() -> None:+ body = _use(+ """+ from app import store++ class Settings:+ SIZE = store.SIZE+ """+ )+ assert body.run_all and "module-level code" in body.run_all+ nested = _use(+ """+ import pytest+ from app import store++ class Fixtures:+ @pytest.fixture+ def db(self):+ return store.open()+ """+ )+ assert nested.run_all and "class Fixtures defines fixtures or hooks" in nested.run_all+++def test_a_requested_fixture_that_calls_the_route_is_named() -> None:+ use = _use(+ """+ import pytest+ from app.store import Store++ @pytest.fixture+ def store():+ return Store()++ @pytest.fixture+ def unrelated():+ return 1+ """+ )+ assert use.run_all is None+ assert use.fixtures == {"store"}+ assert use.declared == {"store", "unrelated"}+++def test_a_fixture_requesting_a_reaching_fixture_or_calling_a_reaching_helper_reaches_too() -> None:+ use = _use(+ """+ import pytest+ from app import store++ def _make():+ return store.Store()++ @pytest.fixture+ def base():+ return _make()++ @pytest.fixture(name="client")+ def client_fixture(base):+ return base++ @pytest.fixture+ def other(tmp_path):+ return tmp_path+ """+ )+ assert use.fixtures == {"base", "client_fixture"}+++def test_a_lazy_import_in_a_requested_fixture_counts_as_reaching() -> None:+ """The import runs when the fixture does, so its users, not the import check, find it."""+ returned = _use(+ """+ import pytest++ @pytest.fixture+ def store():+ from app import store+ return store+ """+ )+ assert returned.fixtures == {"store"}+ unread = _use(+ """+ import pytest++ @pytest.fixture+ def models():+ import app.store # registers the models+ yield+ """+ )+ assert unread.fixtures == {"models"}+ autouse = _use(+ """+ import pytest++ @pytest.fixture(autouse=True)+ def models():+ import app.store # registers the models+ yield+ """+ )+ assert autouse.run_all and "autouse fixture models" in autouse.run_all+++def test_one_parse_answers_every_route() -> None:+ facts = ConftestFacts.parse(+ "import pytest\nfrom app import store, other\n\n"+ "@pytest.fixture\ndef a():\n return store.x\n\n"+ "@pytest.fixture\ndef b():\n return other.y\n",+ "tests/conftest.py",+ )+ assert facts.use(["src/app/store.py"]).fixtures == {"a"}+ assert facts.use(["src/app/other.py"]).fixtures == {"b"}+++def test_module_level_code_using_the_route_keeps_every_test() -> None:+ use = _use(+ """+ from app.store import configure+ configure()+ """+ )+ assert use.run_all and "module-level code" in use.run_all+++def test_an_import_nothing_reads_is_a_side_effect_import() -> None:+ use = _use("import app.store # registers the models\n")+ assert use.run_all and "side effects" in use.run_all+++def test_a_re_export_listed_in_all_is_read_by_its_importers() -> None:+ use = _use(+ """+ from app.store import Store+ __all__ = ["Store"]+ """+ )+ assert use.run_all is None+++def test_a_hook_that_calls_the_route_keeps_every_test() -> None:+ use = _use(+ """+ from app import store++ def pytest_configure(config):+ store.setup()+ """+ )+ assert use.run_all and "hook pytest_configure" in use.run_all+++def test_a_route_none_of_its_imports_names_fails_closed() -> None:+ use = _use("import os\n", entries=["src/app/other.py"])+ assert use.run_all and "none of its imports" in use.run_all+++def test_relative_imports_resolve_against_the_conftest() -> None:+ use = _use(+ """+ import pytest+ from .helpers import build++ @pytest.fixture+ def thing():+ return build()+ """,+ entries=["tests/helpers.py"],+ )+ assert use.fixtures == {"thing"}+++def test_star_imports_plugins_and_unparsable_files_fail_closed() -> None:+ assert _use("from app.store import *\n").run_all+ assert _use("from app import store\npytest_plugins = ['x']\nstore.X\n").run_all+ assert _use("def broken(:\n").run_alldiff --git a/tests/unit/analysis/test_test_selection.py b/tests/unit/analysis/test_test_selection.pyindex 44f6b1fcb..a6b389853 100644--- a/tests/unit/analysis/test_test_selection.py+++ b/tests/unit/analysis/test_test_selection.py@@ -876,6 +876,15 @@ def test_explain_says_what_selected_a_test_or_that_nothing_did() -> None:)++def test_explain_names_a_conftest_import_check() -> None:+ from repowise.core.analysis.test_selection import explain_test++ tiers = _tiers(inferred=[_inferred("src/a.py", "tests/test_a.py", "conftest-import-check")])+ selected, lines = explain_test(_select(["src/a.py"], tiers), "tests/test_a.py")+ assert selected+ assert "this test is that conftest's import check" in lines[0]+def test_a_test_named_module_pytest_does_not_collect_is_not_runnable() -> None:"""``core/test_paths.py`` is test-shaped, but a bare pytest never collects it."""config = '[tool.pytest.ini_options]\ntestpaths = ["tests"]\n'diff --git a/tests/unit/ingestion/test_dynamic_hints_file_feed.py b/tests/unit/ingestion/test_dynamic_hints_file_feed.pyindex cd7ae3322..eb5528482 100644--- a/tests/unit/ingestion/test_dynamic_hints_file_feed.py+++ b/tests/unit/ingestion/test_dynamic_hints_file_feed.py@@ -39,12 +39,6 @@ def repo(tmp_path: Path) -> Path:_write(tmp_path, "config/settings/base.py", 'INSTALLED_APPS = ["myapp"]\n')_write(tmp_path, "package.json", '{"name": "x", "main": "./index.js"}\n')_write(tmp_path, "index.js", "module.exports = {}\n")- _write(- tmp_path,- "conftest.py",- "import pytest\[email protected]\ndef db():\n return 1\n",- )- _write(tmp_path, "test_app.py", "def test_x(db):\n assert db\n")_write(tmp_path, "src/Foo.cs", "public class Foo { }\npublic interface IFoo { }\n")_write(tmp_path,@@ -70,7 +64,6 @@ class TestFileFeedEquivalence:sources = {e.hint_source for e in walked}assert "django_settings" in sourcesassert "node_package" in sources- assert "pytest_conftest" in sourcesassert any(s.startswith("dotnet") for s in sources)def test_excluded_files_emit_no_edges(self, repo: Path) -> None:diff --git a/tests/unit/ingestion/test_pytest_fixture_edges.py b/tests/unit/ingestion/test_pytest_fixture_edges.pyindex e7b3db1e6..e99371a52 100644--- a/tests/unit/ingestion/test_pytest_fixture_edges.py+++ b/tests/unit/ingestion/test_pytest_fixture_edges.py@@ -10,6 +10,7 @@ from datetime import datetimefrom pathlib import Pathimport networkx as nx+import pytestfrom repowise.core.ingestion import GraphBuilderfrom repowise.core.ingestion.framework_edges import add_framework_edges@@ -33,7 +34,8 @@ def _file_info(rel: str, abs_path: str) -> FileInfo:)-def _build(repo: Path) -> nx.DiGraph:+def _build(repo: Path, roots=None) -> nx.DiGraph:+ """The graph with framework edges; files under ``tests/`` or named for pytest are tests."""parser = ASTParser()parsed: dict[str, ParsedFile] = {}for src in sorted(repo.rglob("*.py")):@@ -44,13 +46,22 @@ def _build(repo: Path) -> nx.DiGraph:for pf in parsed.values():builder.add_file(pf)graph = builder.build()+ for rel in parsed:+ name = Path(rel).name+ if rel.startswith("tests/") or name.startswith("test_") or name == "conftest.py":+ graph.nodes[rel]["is_test"] = Truepath_set = set(parsed)stem_map: dict[str, list[str]] = {}for p in path_set:stem_map.setdefault(Path(p).stem.lower(), []).append(p)ctx = ResolverContext(- path_set=path_set, stem_map=stem_map, graph=graph, repo_path=repo+ path_set=path_set,+ stem_map=stem_map,+ graph=graph,+ repo_path=repo,+ pytest_roots=roots,+ source_map={rel: (repo / rel).read_bytes() for rel in parsed},)add_framework_edges(graph, parsed, ctx, [])return graph@@ -493,3 +504,224 @@ def test_unknown_collection_keeps_every_conftest_edge() -> None:graph = _conftest_graph("tests/conftest.py", "tests/helpers.py")_add_conftest_edges(graph, set(graph.nodes), roots)assert graph.has_edge("tests/helpers.py", "tests/conftest.py")+++class TestEveryRequestForm:+ """Each way of asking for a fixture is an edge, stamped so selection can trust the set."""++ def _stamped(self, graph: nx.DiGraph) -> set[tuple[str, str]]:+ return {+ (s, t)+ for s, t, d in graph.edges(data=True)+ if d.get("edge_type") == "framework_binds" and d.get("hint_source") == "pytest_fixture"+ }++ def test_fixture_parameters_usefixtures_pytestmark_and_getfixturevalue(+ self, tmp_path: Path+ ) -> None:+ (tmp_path / "conftest.py").write_text(+ "import pytest\n\n\n"+ "@pytest.fixture\ndef db():\n return 1\n\n\n"+ "@pytest.fixture\ndef client(db):\n return db\n\n\n"+ "@pytest.fixture\ndef env():\n return 2\n"+ )+ (tmp_path / "test_marks.py").write_text(+ "import pytest\n\n"+ 'pytestmark = pytest.mark.usefixtures("env")\n\n\n'+ '@pytest.mark.usefixtures("db")\ndef test_marked():\n pass\n\n\n'+ '@pytest.mark.usefixtures("client")\nclass TestGroup:\n'+ " def test_in_class(self):\n pass\n\n\n"+ "def test_runtime(request):\n"+ ' request.getfixturevalue("client")\n'+ )+ stamped = self._stamped(_build(tmp_path))++ assert ("conftest.py::client", "conftest.py::db") in stamped+ assert ("test_marks.py::test_marked", "conftest.py::db") in stamped+ assert ("test_marks.py::test_marked", "conftest.py::env") in stamped+ assert ("test_marks.py::TestGroup::test_in_class", "conftest.py::client") in stamped+ assert ("test_marks.py::test_runtime", "conftest.py::client") in stamped++ def test_an_overriding_fixture_requests_the_one_it_overrides(self, tmp_path: Path) -> None:+ (tmp_path / "conftest.py").write_text(+ "import pytest\n\n\[email protected]\ndef db():\n return 1\n"+ )+ (tmp_path / "sub").mkdir()+ (tmp_path / "sub" / "conftest.py").write_text(+ "import pytest\n\n\[email protected]\ndef db(db):\n return db\n"+ )+ stamped = self._stamped(_build(tmp_path))++ assert ("sub/conftest.py::db", "conftest.py::db") in stamped+++class TestIndirectParametrize:+ """``indirect`` hands a parametrize value to the fixture of that name: a request."""++ def _bound_for(self, tmp_path: Path, decorator: str) -> set[tuple[str, str]]:+ (tmp_path / "conftest.py").write_text(+ "import pytest\n\n\[email protected]\ndef db(request):\n return request.param\n"+ )+ (tmp_path / "test_x.py").write_text(+ f"import pytest\n\n\n{decorator}\ndef test_x(db):\n assert db\n"+ )+ return _bound(_build(tmp_path))++ def test_indirect_true_and_named_lists_keep_the_request(self, tmp_path: Path) -> None:+ for decorator in (+ '@pytest.mark.parametrize("db", [1], indirect=True)',+ '@pytest.mark.parametrize("db", [1], indirect=["db"])',+ '@pytest.mark.parametrize("db", [1], indirect=FLAGS)',+ ):+ assert ("test_x.py::test_x", "conftest.py::db") in self._bound_for(tmp_path, decorator)++ def test_a_plain_or_other_indirect_argname_is_supplied(self, tmp_path: Path) -> None:+ for decorator in (+ '@pytest.mark.parametrize("db", [1])',+ '@pytest.mark.parametrize("db,other", [(1, 2)], indirect=["other"])',+ ):+ assert ("test_x.py::test_x", "conftest.py::db") not in self._bound_for(+ tmp_path, decorator+ )+++class TestUnrecordedRequests:+ """A request no edge can record marks the conftest edges it could reach."""++ def _hints(self, graph: nx.DiGraph) -> dict[str, str]:+ return {+ s: d.get("hint_source")+ for s, t, d in graph.edges(data=True)+ if t == "tests/conftest.py" and d.get("edge_type") == "framework"+ }++ def _repo(self, tmp_path: Path, body: str, helper: str = "") -> nx.DiGraph:+ tests = tmp_path / "tests"+ tests.mkdir()+ (tests / "conftest.py").write_text(+ "import pytest\n\n\[email protected]\ndef db():\n return 1\n"+ )+ (tests / "test_plain.py").write_text("def test_plain(db):\n assert db\n")+ (tests / "test_odd.py").write_text(body)+ if helper:+ (tmp_path / "helpers.py").write_text(helper)+ return _build(tmp_path)++ @pytest.mark.parametrize(+ "body",+ [+ "def test_x(request):\n request.getfixturevalue(NAME)\n",+ "import pytest\n\n\[email protected](*NAMES)\ndef test_x():\n pass\n",+ "from base import Base\n\n\nclass TestX(Base):\n pass\n",+ "class TestX:\n pytestmark = [MARK]\n\n def test_x(self):\n pass\n",+ "import pytest\n\n\[email protected]('a', [pytest.param(1, "+ "marks=pytest.mark.usefixtures('db'))])\ndef test_x(a):\n pass\n",+ # A mark kept in a variable, and the other ways to ask at run time.+ "import pytest\n\nneeds_db = pytest.mark.usefixtures('db')\n\n\n"+ "@needs_db\ndef test_x():\n pass\n",+ "def test_x(request):\n request.node.add_marker('m')\n",+ "def test_x(request):\n assert 'db' in request.fixturenames\n",+ "def test_x(request):\n gfv = request.getfixturevalue\n gfv('db')\n",+ "import pytest\n\npytestmark = pytest.mark.usefixtures(*names())\n\n\n"+ "def test_x():\n pass\n",+ ],+ )+ def test_a_hidden_request_marks_its_own_edge(self, tmp_path: Path, body: str) -> None:+ hints = self._hints(self._repo(tmp_path, body))+ assert hints["tests/test_odd.py"] == "pytest_conftest_unrecorded"+ assert hints["tests/test_plain.py"] == "pytest_conftest"++ def test_a_helper_asking_for_a_fixture_marks_every_edge(self, tmp_path: Path) -> None:+ graph = self._repo(+ tmp_path,+ "def test_x():\n pass\n",+ helper="def get(request):\n return request.getfixturevalue('db')\n",+ )+ assert set(self._hints(graph).values()) == {"pytest_conftest_unrecorded"}++ def test_naming_the_call_in_prose_marks_nothing(self, tmp_path: Path) -> None:+ graph = self._repo(+ tmp_path,+ "def test_x():\n pass\n",+ helper='"""Reads ``request.getfixturevalue`` names."""\n',+ )+ assert self._hints(graph)["tests/test_plain.py"] == "pytest_conftest"++ def test_an_inherited_base_in_the_same_file_is_recorded(self, tmp_path: Path) -> None:+ body = (+ "import pytest\n\n\[email protected]('db')\nclass Base:\n"+ " def test_shared(self):\n pass\n\n\nclass TestX(Base):\n pass\n"+ )+ graph = self._repo(tmp_path, body)+ assert self._hints(graph)["tests/test_odd.py"] == "pytest_conftest"+ assert ("tests/test_odd.py::Base::test_shared", "tests/conftest.py::db") in _bound(graph)++ def test_a_config_requesting_fixtures_marks_the_tests_under_it(self, tmp_path: Path) -> None:+ from repowise.core.pytest_roots import read_pytest_roots++ roots = read_pytest_roots([("pytest.ini", "[pytest]\nusefixtures = db\n")])+ tests = tmp_path / "tests"+ tests.mkdir()+ (tests / "conftest.py").write_text(+ "import pytest\n\n\[email protected]\ndef db():\n return 1\n"+ )+ (tests / "test_plain.py").write_text("def test_plain():\n pass\n")+ hints = self._hints(_build(tmp_path, roots))+ assert hints["tests/test_plain.py"] == "pytest_conftest_unrecorded"++ def test_configured_python_files_are_linked(self, tmp_path: Path) -> None:+ from repowise.core.pytest_roots import read_pytest_roots++ roots = read_pytest_roots([("pytest.ini", "[pytest]\npython_files = check_*.py\n")])+ tests = tmp_path / "tests"+ tests.mkdir()+ (tests / "conftest.py").write_text(+ "import pytest\n\n\[email protected]\ndef db():\n return 1\n"+ )+ (tests / "check_api.py").write_text("def test_api(db):\n assert db\n")+ graph = _build(tmp_path, roots)+ assert ("tests/check_api.py::test_api", "tests/conftest.py::db") in _bound(graph)+++def test_a_camel_case_test_is_linked(tmp_path: Path) -> None:+ """pytest's default `python_functions` is the prefix `test`, so `testFoo` is collected."""+ (tmp_path / "conftest.py").write_text(+ "import pytest\n\n\[email protected]\ndef db():\n return 1\n"+ )+ (tmp_path / "test_api.py").write_text("def testGet(db):\n assert db\n")+ assert ("test_api.py::testGet", "conftest.py::db") in _bound(_build(tmp_path))+++def test_unreadable_test_text_and_unheld_helpers_count_as_hidden(tmp_path: Path) -> None:+ from repowise.core.ingestion.framework_edges.pytest_edges import (+ _add_fixture_injection_edges,+ )++ parser = ASTParser()+ files = {+ "tests/conftest.py": b"import pytest\n\n\[email protected]\ndef db():\n return 1\n",+ "tests/test_a.py": b"def test_a(db):\n assert db\n",+ "helpers.py": b"x = 1\n",+ }+ parsed = {}+ for rel, data in files.items():+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)+ (tmp_path / rel).write_bytes(data)+ parsed[rel] = parser.parse_file(_file_info(rel, str(tmp_path / rel)), data)+ def text(path: str) -> str | None:+ return files[path].decode()++ def unreadable(path: str) -> str | None:+ return None if path == "tests/test_a.py" else text(path)++ graph = _build(tmp_path)+ graph["tests/test_a.py"]["tests/conftest.py"]["hint_source"] = "pytest_conftest"+ _add_fixture_injection_edges(graph, parsed, tmp_path, unreadable, None, text)+ hint = graph["tests/test_a.py"]["tests/conftest.py"]["hint_source"]+ assert hint == "pytest_conftest_unrecorded"++ graph = _build(tmp_path)+ graph["tests/test_a.py"]["tests/conftest.py"]["hint_source"] = "pytest_conftest"+ _add_fixture_injection_edges(graph, parsed, tmp_path, text, None, lambda p: None)+ hint = graph["tests/test_a.py"]["tests/conftest.py"]["hint_source"]+ assert hint == "pytest_conftest_unrecorded"diff --git a/tests/unit/persistence/test_impacted_tests_resolution.py b/tests/unit/persistence/test_impacted_tests_resolution.pyindex b91a1efc7..66a757a4b 100644--- a/tests/unit/persistence/test_impacted_tests_resolution.py+++ b/tests/unit/persistence/test_impacted_tests_resolution.py@@ -313,3 +313,217 @@ async def test_data_files_are_not_routes_and_helper_importers_are_reported("tests/test_a.py": "import-graph",}assert out["helper_importers"]["tests/helpers.py"] == ["tests/test_a.py"]+++_CONFTEST = '''+import pytest+from app import store++[email protected](autouse=True)+def _isolate(monkeypatch):+ monkeypatch.setattr(store, "_cache", None)+++def db():+ return store.open()+'''+++async def _conftest_graph(session, repo_id, *, stamped: bool) -> None:+ """A conftest importing ``store``, one test asking for its ``db`` fixture, two not."""+ from repowise.core.persistence.models import GraphEdge, GraphNode++ tests = ["tests/test_a.py", "tests/test_b.py", "tests/test_c.py"]+ await _graph(+ session,+ repo_id,+ tests={*tests, "tests/conftest.py"},+ files={"src/app/store.py", "src/app/util.py"},+ imports=[("src/app/store.py", "src/app/util.py"), ("tests/conftest.py", "src/app/store.py")],+ )+ for sym in ("tests/conftest.py::db", "tests/conftest.py::_isolate", "tests/test_a.py::test_x"):+ session.add(GraphNode(repository_id=repo_id, node_id=sym, node_type="symbol"))+ for test in tests:+ session.add(+ GraphEdge(+ repository_id=repo_id,+ source_node_id=test,+ target_node_id="tests/conftest.py",+ edge_type="framework",+ hint_source="pytest_conftest",+ )+ )+ session.add(+ GraphEdge(+ repository_id=repo_id,+ source_node_id="tests/test_a.py::test_x",+ target_node_id="tests/conftest.py::db",+ edge_type="framework_binds",+ hint_source="pytest_fixture" if stamped else None,+ )+ )+ await session.commit()+++async def test_a_conftest_reached_through_its_imports_runs_only_the_tests_it_can_break(+ async_session,+) -> None:+ """Only ``db`` runs the changed code; the autouse fixture just patches it."""+ repo = await insert_repo(async_session)+ await _conftest_graph(async_session, repo.id, stamped=True)++ out = _empty_result(1)+ await _resolve_impacted(+ async_session,+ repo.id,+ {"src/app/util.py": None},+ set(),+ out,+ pytest_texts={"tests/conftest.py": _CONFTEST},+ )++ assert _pairs(out, "src/app/util.py") == {"tests/test_a.py": "conftest-fixture"}+ assert any("only through its imports" in n for n in out["conftest_notes"])+++async def test_an_index_without_stamped_fixture_requests_keeps_every_test(async_session) -> None:+ repo = await insert_repo(async_session)+ await _conftest_graph(async_session, repo.id, stamped=False)++ out = _empty_result(1)+ await _resolve_impacted(+ async_session,+ repo.id,+ {"src/app/util.py": None},+ set(),+ out,+ pytest_texts={"tests/conftest.py": _CONFTEST},+ )++ assert "tests/conftest.py" in _pairs(out, "src/app/util.py")+ assert any("before fixture requests were recorded" in n for n in out["conftest_notes"])+++async def test_a_conftest_only_patching_the_route_runs_one_import_check(async_session) -> None:+ repo = await insert_repo(async_session)+ await _conftest_graph(async_session, repo.id, stamped=True)+ source = _CONFTEST.split("@pytest.fixture\ndef db")[0]++ out = _empty_result(1)+ await _resolve_impacted(+ async_session,+ repo.id,+ {"src/app/util.py": None},+ set(),+ out,+ pytest_texts={"tests/conftest.py": source},+ )++ assert _pairs(out, "src/app/util.py") == {"tests/test_a.py": "conftest-import-check"}+++async def _add_edge(session, repo_id, source, target, edge_type, hint=None) -> None:+ from repowise.core.persistence.models import GraphEdge++ session.add(+ GraphEdge(+ repository_id=repo_id,+ source_node_id=source,+ target_node_id=target,+ edge_type=edge_type,+ hint_source=hint,+ )+ )+ await session.commit()+++async def _narrowed(session, repo_id) -> dict[str, str]:+ out = _empty_result(1)+ await _resolve_impacted(+ session,+ repo_id,+ {"src/app/util.py": None},+ set(),+ out,+ pytest_texts={"tests/conftest.py": _CONFTEST},+ )+ return out+++async def test_a_request_the_index_cannot_record_keeps_every_test(async_session) -> None:+ from sqlalchemy import update++ from repowise.core.persistence.models import GraphEdge++ repo = await insert_repo(async_session)+ await _conftest_graph(async_session, repo.id, stamped=True)+ await async_session.execute(+ update(GraphEdge)+ .where(GraphEdge.source_node_id == "tests/test_b.py")+ .values(hint_source="pytest_conftest_unrecorded")+ )+ await async_session.commit()++ out = await _narrowed(async_session, repo.id)++ assert "tests/conftest.py" in _pairs(out, "src/app/util.py")+ assert any("tests/test_b.py asks for fixtures" in n for n in out["conftest_notes"])+++async def test_an_unresolved_conftest_import_keeps_every_test(async_session) -> None:+ repo = await insert_repo(async_session)+ await _conftest_graph(async_session, repo.id, stamped=True)+ await _add_edge(async_session, repo.id, "tests/test_c.py", "external:conftest", "imports")++ out = await _narrowed(async_session, repo.id)++ assert "tests/conftest.py" in _pairs(out, "src/app/util.py")+ assert any("could not resolve" in n for n in out["conftest_notes"])+++async def test_a_resolved_conftest_import_keeps_its_importer(async_session) -> None:+ """``from conftest import helper`` is an import: that test runs whatever it reaches."""+ from sqlalchemy import update++ from repowise.core.persistence.models import GraphEdge++ repo = await insert_repo(async_session)+ await _conftest_graph(async_session, repo.id, stamped=True)+ await async_session.execute(+ update(GraphEdge)+ .where(GraphEdge.source_node_id == "tests/test_c.py", GraphEdge.edge_type == "framework")+ .values(edge_type="imports", hint_source=None)+ )+ await async_session.commit()++ out = await _narrowed(async_session, repo.id)++ assert _pairs(out, "src/app/util.py") == {+ "tests/test_a.py": "conftest-fixture",+ "tests/test_c.py": "conftest-fixture",+ }+++async def test_a_reaching_fixture_nobody_requests_selects_only_the_import_check(+ async_session,+) -> None:+ from sqlalchemy import delete++ from repowise.core.persistence.models import GraphEdge++ repo = await insert_repo(async_session)+ await _conftest_graph(async_session, repo.id, stamped=True)+ await async_session.execute(+ delete(GraphEdge).where(GraphEdge.target_node_id == "tests/conftest.py::db")+ )+ # Another fixture request elsewhere shows the index records them.+ await _add_edge(+ async_session, repo.id, "tests/test_b.py::test_x", "tests/other.py::f",+ "framework_binds", "pytest_fixture",+ )++ out = await _narrowed(async_session, repo.id)++ assert _pairs(out, "src/app/util.py") == {"tests/test_a.py": "conftest-import-check"}diff --git a/tests/unit/test_pytest_roots.py b/tests/unit/test_pytest_roots.pyindex 60eb7cd30..f35b9a709 100644--- a/tests/unit/test_pytest_roots.py+++ b/tests/unit/test_pytest_roots.py@@ -89,3 +89,14 @@ def test_a_config_that_does_not_parse_is_recorded_as_unknown() -> None:assert roots.may_collect_name("pkg/tests/helpers.py")assert not roots.may_collect_name("other/tests/helpers.py")assert roots.may_collect_name("other/tests/test_x.py")+++def test_hidden_request_dirs_name_configs_requesting_fixtures_or_renaming_tests() -> None:+ roots = read_pytest_roots(+ [+ ("pytest.ini", "[pytest]\nusefixtures = db\n"),+ ("pkg/setup.cfg", "[tool:pytest]\npython_functions = check_*\n"),+ ("plain/pytest.ini", "[pytest]\npython_functions = test\n"),+ ]+ )+ assert roots.hidden_request_dirs() == ["", "pkg"]