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
fix(selection): wire test setup files and path-named helpers into the graph (#3216)
Raghav Chamadiya40ee50897021
diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.mdindex 90bfc3cb1..89dcc469c 100644--- a/docs/layers/TEST_INTELLIGENCE.md+++ b/docs/layers/TEST_INTELLIGENCE.md@@ -165,6 +165,11 @@ Each result says how it was found, and a guess never passes for evidence:| None of the above | "unknown, run the full suite to be safe" || No map ingested at all | A prompt to run `coverage add` on a report with contexts |+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.+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`prints runner arguments, or `:all` whenever any part of the answer is unknown.diff --git a/docs/start/CI.md b/docs/start/CI.mdindex fbcda488f..1c0a9e349 100644--- a/docs/start/CI.md+++ b/docs/start/CI.md@@ -253,12 +253,13 @@ a per-test coverage map (`repowise coverage add`) makes it more precise.- It exits `0` for a subset or for everything, and `2` only when it cannot read the change or the `tests.*` config.- Branch on the run-all flag, never on `:all`: jest and vitest read it as a pattern and run nothing.- It runs everything for: an empty change; a lockfile, manifest, build, test or CI config change; `.repowise/config.yaml`; a production package's `__init__.py`.-- It also runs everything for: non-code files in a test tree; a changed file with no known test or only a filename guess; a route through a test helper no test imports; any Python test helper while a conftest or pytest config loads plugins by name.+- It also runs everything for: non-code files in a test tree; a changed file with no known test or only a filename guess; a route through a test helper no test imports, unless every known test is selected anyway (the reasons then say so); any Python test helper while a conftest or pytest config loads plugins by name.- It also runs everything for: a missing or unreadable index; a per-test map at its row cap; a deleted file no known test used.- An index built at an older commit than the change's base is used as is. Files changed in between whose imports or module-name strings moved (any change beyond whitespace, outside Python and JavaScript/TypeScript) add the tests reaching them. It runs everything instead when that commit is not in the clone, or more than 1,000 files changed in between, or one of them is a lockfile, manifest, build or test config or `.repowise/config.yaml`. CI config and test data changed in between no longer force a full run: neither is imported.- 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); 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.+- 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; `tests.always_run` is appended to every selection as written, for the runner whose language each entry is in.- With `--runner pytest`, `go` or `jest`, the arguments hold only that runner's tests, `tests.always_run` included. A repository with tests in several languages needs one job per runner: the tests a job leaves out are counted on stderr, and listed per runner under `left_out` with `--format json`. `--runner files` gets every test.diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.pyindex d47f322a4..e92e4ddca 100644--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py@@ -17,6 +17,7 @@ import refrom functools import lru_cachefrom repowise.core.code_origin import is_build_file, is_vendored_or_generated_path+from repowise.core.ingestion.languages.js_config_values import TEST_SETUP_KEYSfrom repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY# Non-code languages (registry passthrough languages plus "unknown").@@ -1013,10 +1014,7 @@ _TOOL_CONFIG_PATHS: tuple[str, ...] = ("/.changeset/config.json",)# changelog module. A path under any other key (``coverage.exclude``,# ``ignores``) or in a comment is not loaded._TOOL_CONFIG_LOAD_KEYS: tuple[str, ...] = (- "setupFiles",- "setupFilesAfterEnv",- "globalSetup",- "globalTeardown",+ *TEST_SETUP_KEYS,"entry","entryPoints","input",diff --git a/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py b/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.pyindex 6ff8d3471..49406d698 100644--- a/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py+++ b/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py@@ -52,6 +52,7 @@ from dataclasses import dataclassfrom enum import Enumfrom pathlib import PurePosixPath+from ...ingestion.languages.js_config_values import value_spansfrom ...ingestion.languages.registry import REGISTRYfrom .constants import (_BARE_NAME_USE_LANGUAGES,@@ -644,23 +645,9 @@ def _loaded(return bool(loaders) and "default" in export_shape(path, frozenset(), source_map.get(path))-#: ``<load key>: <value>`` in a tool config, the key quoted or bare; the value a-#: string, a list or an object (``input: { main: "src/a.ts" }``).-_LOAD_VALUE_RE = re.compile(- rb"""["']?\b(?:"""- + b"|".join(k.encode() for k in _TOOL_CONFIG_LOAD_KEYS)- + rb""")\b["']?\s*[:=]\s*(\[[^\]]*\]|\{[^}]*\}|"[^"]*"|'[^']*')"""-)-# Comments, so a path a config only mentions in one is not loaded. A ``//``-# after ``:`` is a URL (``https://``), not a comment.-_LINE_COMMENT_RE = re.compile(rb"(?<![:\w])//[^\n]*")-_BLOCK_COMMENT_RE = re.compile(rb"/\*.*?\*/", re.DOTALL)--def _config_loads(config: str, target: str, source_map: dict[str, bytes]) -> bool:"""Whether *config* names *target* under one of its load keys."""- text = _LINE_COMMENT_RE.sub(b"", _BLOCK_COMMENT_RE.sub(b"", source_map.get(config, b"")))- values = b"\n".join(m.group(1) for m in _LOAD_VALUE_RE.finditer(text))+ values = b"\n".join(value_spans(source_map.get(config, b""), _TOOL_CONFIG_LOAD_KEYS))wanted = {key: {target} for key in _path_keys(target)}tails = {key.rpartition("/")[2] for key in wanted}return target in _targets_in(values, wanted, tails, config.rpartition("/")[0])diff --git a/packages/core/src/repowise/core/analysis/test_selection.py b/packages/core/src/repowise/core/analysis/test_selection.pyindex 1cda446ad..58c298b88 100644--- a/packages/core/src/repowise/core/analysis/test_selection.py+++ b/packages/core/src/repowise/core/analysis/test_selection.py@@ -16,7 +16,8 @@ is chosen when any of these hold:4. a changed file is neither code the index knows nor documentation, or isdocumentation some code names (a test may read it);5. a changed code file has no known test, only a filename guess names one, or- a route to it passes through a test helper no test imports, or any Python+ a route to it passes through a test helper no test imports (unless every+ known test is selected anyway), or any Pythontest helper while a conftest or pytest config loads plugins by name (itsusers are unknown);6. the index is missing, disagrees with itself about its commit, or its graph@@ -484,7 +485,7 @@ def select_tests(inp: SelectionInput) -> Selection:)return Selection(run_all=bool(run_all),- reasons=tuple(run_all + _notes(inp, triage.skipped, always, traced)),+ reasons=tuple(run_all + evidence.notes + _notes(inp, triage.skipped, always, traced)),tests=tests,test_files=test_files,packages=_go_packages(triage.code, deleted, inp.go_test_dirs),@@ -819,6 +820,10 @@ class _Evidence:known_tests: tuple[str, ...]plugin_loader: str | Nonegap: frozenset[str] = frozenset()+ # Tests every subset runs (unplaced and detected always-run).+ every_subset: frozenset[str] = frozenset()+ # Explanations that do not force a full run, gathered while deciding.+ notes: list[str] = field(default_factory=list)@classmethoddef of(cls, inp: SelectionInput, deleted: set[str]) -> _Evidence:@@ -839,6 +844,7 @@ class _Evidence:known_tests=tuple(inp.known_tests),plugin_loader=inp.plugin_loader,gap=frozenset(inp.index_gap or ()),+ every_subset=frozenset(inp.unplaced_tests) | frozenset(inp.always_run_tests),)def found(self, path: str) -> list[_TestRef]:@@ -898,7 +904,7 @@ def _file_tests(if is_test_helper(path):return tests, "helper-importers", _own_helper_reasons(path, ev)- reasons = _helper_route_reasons(path, helpers, ev) + _unfiled_reasons(path, tests)+ reasons = _helper_route_reasons(path, helpers, tests, ev) + _unfiled_reasons(path, tests)# A deleted test needs no run of its own; the tests importing it do.if path in ev.deleted and is_runnable_test(path):basis = "deleted-test"@@ -947,16 +953,27 @@ def _plugin_reason(helper: str, ev: _Evidence) -> str | None:)-def _helper_route_reasons(path: str, helpers: list[str], ev: _Evidence) -> list[str]:+def _helper_route_reasons(+ path: str, helpers: list[str], tests: list[_TestRef], ev: _Evidence+) -> list[str]:"""A helper on a route stands for its importers, which the walk adds beside it.One no test imports is used some other way (a fixture, a plugin), so its- users are unknown.+ users are unknown, unless every known test already runs for *path*: then+ no user it could have is left out. Any language counts, since a test can+ start a helper in another language by path."""plugins = [r for h in helpers if (r := _plugin_reason(h, ev))]if plugins:return [f"{path} is reached through a test helper: {plugins[0]}"]unimported = [h for h in helpers if not ev.importers.get(h)]+ if unimported and _all_tests_selected(tests, ev):+ ev.notes.extend(+ f"{path} is reached through the test helper {h}, which no test imports, "+ "but every known test already runs for that change."+ for h in unimported+ )+ return []if not unimported:return []return [@@ -965,6 +982,12 @@ def _helper_route_reasons(path: str, helpers: list[str], ev: _Evidence) -> list[]+def _all_tests_selected(tests: list[_TestRef], ev: _Evidence) -> bool:+ """Whether *tests*, with the tests every selection runs, hold every known test."""+ selected = {f for _, f in tests if f} | ev.every_subset+ return bool(ev.known_tests) and set(ev.known_tests) <= selected++def _unfiled_reasons(path: str, tests: list[_TestRef]) -> list[str]:return [f"Coverage names {test_id} for {path}, but not its file."diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/base.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/base.pyindex a0d01ebea..dd7bfc1a2 100644--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/base.py+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/base.py@@ -47,16 +47,6 @@ class DynamicHintExtractor(ABC):@abstractmethoddef extract(self, repo_root: Path) -> list[DynamicEdge]: ...- def _source_bytes(self, abs_path: Path, rel: str) -> bytes:- """*rel*'s bytes from the attached source map, else from disk; ``b""`` if neither."""- # Same contract as ``ingestion.source_text.source_bytes``; collapse into it once both exist.- if self._source_map is not None and (data := self._source_map.get(rel)) is not None:- return data- try:- return abs_path.read_bytes()- except OSError:- return b""-def _rglob(self, root: Path, pattern: str) -> Iterator[Path]:"""Pruned replacement for :py:meth:`pathlib.Path.rglob`.diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/python_imports.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/python_imports.pyindex de43f334c..9187bf026 100644--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/python_imports.py+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/python_imports.py@@ -55,6 +55,7 @@ from pathlib import Pathfrom ...test_paths import is_test_related_pathfrom ..languages.python_modules import build_python_module_indexfrom ..languages.python_strings import PY_DYNAMIC_LOAD_MARKERS, defines_top_level, live_text+from ..source_text import source_bytesfrom .base import DynamicEdge, DynamicHintExtractor# Dotted strings only produce edges from files that load modules at run time,@@ -256,11 +257,11 @@ class PythonDynamicHints(DynamicHintExtractor):return []resolver = ModuleStringResolver(- module_index, lambda target: self._source_bytes(repo_root / target, target)+ module_index, lambda target: source_bytes(target, repo_root / target, self._source_map))edges: list[DynamicEdge] = []for abs_path, rel in rel_by_abs.items():- blob = self._source_bytes(abs_path, rel)+ blob = source_bytes(rel, abs_path, self._source_map)if not blob:continuerefs = python_dynamic_refs(rel, blob, resolver)diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.pyindex de57ac192..5158936a5 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py@@ -2,7 +2,8 @@Detects convention-based relationships (Django, FastAPI, Flask, ASP.NET, Rails,Laravel, Spring, Express/Nest, Angular, Gin/Echo/Chi, Axum/Actix/Rocket, TYPO3, Godot-``class_name`` globals, pytest ``conftest.py`` and AWS Lambda handlers) and adds+``class_name`` globals, pytest ``conftest.py``, JS/TS test-runner setup files,+helpers a test names by path, and AWS Lambda handlers) and adds``edge_type="framework"`` edges that no static import graph captures.Previously a single ``framework_edges.py`` module; split (PR 3.5) into one@@ -43,6 +44,8 @@ from . import (remix,rust,spring,+ test_path_strings,+ test_runner_setup,trpc,typo3,)@@ -58,6 +61,8 @@ if TYPE_CHECKING:# order is load-bearing because ``_add_edge_if_new`` is first-wins._HANDLERS: list[FrameworkHandler] = [*pytest_edges.HANDLERS, # always runs+ *test_runner_setup.HANDLERS,+ *test_path_strings.HANDLERS,*django.HANDLERS,*fastapi.HANDLERS,*flask.HANDLERS,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 6fdc0e561..2c8918325 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@@ -24,6 +24,8 @@ from .base import (if TYPE_CHECKING:import networkx as nx+ from ...pytest_roots import PytestRoots+# Matched at the attribute tail rather than on `pytest.`, so `@my.fixture` and# `@pytest_asyncio.fixture` are both accepted: pytest resolves the decorator by# identity, not by module path.@@ -206,8 +208,17 @@ def _fixture_scopes(parsed: Any, class_name: str | None) -> list[str | None]:CONFTEST_HINT = "pytest_conftest"-def _add_conftest_edges(graph: nx.DiGraph, path_set: set[str]) -> int:- """conftest.py -> test files in the same or child directories."""+def _add_conftest_edges(+ graph: nx.DiGraph, path_set: set[str], roots: PytestRoots | None = None+) -> int:+ """Collected tests and nested conftests -> each conftest.py at or above them.++ A helper beside the tests is not collected and sees no fixture, so it gets+ no edge: one would put the helper on the route of every change the conftest+ reaches. Collection is the configured ``python_files`` (*roots*, read once by+ the traverser). Without *roots*, collection is unknown and every test-tree+ file keeps its edge.+ """count = 0conftest_paths = [p for p in path_set if Path(p).name == "conftest.py"]@@ -217,6 +228,10 @@ def _add_conftest_edges(graph: nx.DiGraph, path_set: set[str]) -> int:for p in path_set:if p == conf:continue+ if roots is not None and not (+ Path(p).name == "conftest.py" or (p.endswith(".py") and roots.may_collect_name(p))+ ):+ continuenode = graph.nodes.get(p, {})if not node.get("is_test", False):continue@@ -386,7 +401,7 @@ class _ConftestHandler:ctx: ResolverContext,path_set: set[str],) -> int:- return _add_conftest_edges(graph, path_set)+ return _add_conftest_edges(graph, path_set, ctx.pytest_roots)HANDLERS: list[FrameworkHandler] = [_ConftestHandler(), _FixtureInjectionHandler()]diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/test_path_strings.py b/packages/core/src/repowise/core/ingestion/framework_edges/test_path_strings.pynew file mode 100644index 000000000..d88ffdb2c--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/framework_edges/test_path_strings.py@@ -0,0 +1,97 @@+"""Code files a test names by a path relative to itself.++A test that starts a helper as a subprocess or loads it by file names it with+a string, not an import: ``Path(__file__).parent / "_mock_server.py"``,+``path.join(__dirname, "fixture-server.ts")``, ``[sys.executable, script]``.+The helper's users are then invisible to the graph, so a change reaching it+has no test to stand for it. Each such string becomes an edge from the test to+the file.++Only a string that resolves against the test's own directory and names an+indexed code file counts: that is the shape ``__file__`` / ``__dirname``+anchoring produces, and it keeps a path that is only mentioned (an expected+value, a log line) from linking to a file that merely shares a name elsewhere.+Ceiling: a path split into several string arguments+(``os.path.join(here, "helpers", "server.py")``) or written relative to the+working directory is not read. Upgrade path: join adjacent literal arguments of+a path-join call before resolving.+"""++from __future__ import annotations++import posixpath+import re+from typing import TYPE_CHECKING, Any++from ...test_paths import is_test_path+from ..resolvers import ResolverContext+from ..source_text import source_bytes+from .base import DetectionContext, FrameworkHandler, _add_edge_if_new++if TYPE_CHECKING:+ import networkx as nx++# Stamped on the edge so consumers that mean "imports" can tell it apart.+PATH_STRING_HINT = "test_path_string"++# Extensions a runner or interpreter executes; a data file named by path is+# read, not run, and is no route.+_CODE_EXTS = (".py", ".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts")+# Loaded for a whole directory already, and the names tests most often give a+# scratch file they write (``tmp_path / "__init__.py"``).+_DIR_SCOPED = ("__init__.py", "conftest.py")+_PATH_LITERAL_RE = re.compile(+ rb"""["'`]((?:[\w@~+\-]+/|\.{1,2}/)*[\w@~+.\-]+\.(?:py|js|jsx|mjs|cjs|ts|tsx|mts|cts))["'`]"""+)+++def _is_helper(target: str) -> bool:+ """Not a directory-scoped file, and not test-named: a test already runs on its own."""+ name = posixpath.basename(target)+ return name not in _DIR_SCOPED and not is_test_path(name)+++def path_string_targets(path: str, text: bytes, path_set: set[str]) -> list[str]:+ """Indexed code files *text*, the source of *path*, names relative to its directory."""+ base = posixpath.dirname(path)+ found: dict[str, None] = {}+ for match in _PATH_LITERAL_RE.finditer(text):+ spec = match.group(1).decode("ascii", errors="ignore")+ target = posixpath.normpath(posixpath.join(base, spec))+ if target in path_set and _is_helper(target) and target != path:+ found[target] = None+ return list(found)+++def _add_path_string_edges(+ graph: nx.DiGraph, parsed_files: dict[str, Any], ctx: ResolverContext, path_set: set[str]+) -> int:+ count = 0+ for path in sorted(path_set):+ if not (path.endswith(_CODE_EXTS) and parsed_files[path].file_info.is_test):+ continue+ text = source_bytes(path, parsed_files[path].file_info.abs_path, ctx.source_map)+ for target in path_string_targets(path, text, path_set):+ if _add_edge_if_new(graph, path, target):+ graph[path][target]["hint_source"] = PATH_STRING_HINT+ count += 1+ return count+++class _PathStringHandler:+ """Tests run helpers they name by a path relative to themselves."""++ def detect(self, dctx: DetectionContext) -> bool:+ return True++ def add_edges(+ self,+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+ path_set: set[str],+ ) -> int:+ return _add_path_string_edges(graph, parsed_files, ctx, path_set)+++HANDLERS: list[FrameworkHandler] = [_PathStringHandler()]diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/test_runner_setup.py b/packages/core/src/repowise/core/ingestion/framework_edges/test_runner_setup.pynew file mode 100644index 000000000..1139d2864--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/framework_edges/test_runner_setup.py@@ -0,0 +1,176 @@+"""JS/TS test-runner setup files named in runner configs.++A runner config (``vitest.config.ts``, ``jest.config.js``, a ``jest`` block in+``package.json``) loads the files under its setup keys+(:data:`~..languages.js_config_values.TEST_SETUP_KEYS`) before the tests it+runs, so a change to one, or to anything it imports, can break each of those+tests. No import statement says so. This is the runner's counterpart of a+``conftest.py``, and it gets the same edge: from each test the config runs to+the setup file.++Configs are read, not evaluated (:mod:`~..languages.js_config_values`): every+string literal in a setup key's value that resolves to an indexed file counts.+Which tests a config runs is not evaluated either; a config stands for the+JS/TS tests under its package (the nearest directory holding a+``package.json``), or under the whole repository when a ``root`` / ``dir`` /+``testDir`` / ``rootDir`` / ``roots`` value climbs out of the config's+directory with ``..``. Ceiling: ``include`` globs that narrow a config to part+of its package are not honoured, which over-selects but never misses. Upgrade+path: honour literal ``include`` / ``root`` values when every entry is a+literal.++Configs are found by name over the indexed path set, not by the TS workspace+scan: that walk collects only ``vitest.config.*`` / ``vite.config.*``, and the+configs that name setup files are often shared or scoped modules+(``vitest.shared.config.ts``, ``jest.config.js``, ``package.json``).+"""++from __future__ import annotations++import posixpath+from typing import TYPE_CHECKING, Any++from ...test_paths import is_test_path+from ..languages.js_config_values import TEST_SETUP_KEYS, string_literals, value_spans+from ..resolvers import ResolverContext+from ..source_text import source_bytes+from .base import DetectionContext, FrameworkHandler, _add_edge_if_new++if TYPE_CHECKING:+ import networkx as nx++# Stamped on the test -> setup file edge, as conftest edges are, so consumers+# that mean "imports" can tell the two apart.+SETUP_FILE_HINT = "test_runner_setup"++_JS_EXTS = (".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts")+_CONFIG_PREFIXES = ("vitest.", "vite.", "jest.", "playwright.")+# Keys that move where a runner looks for tests.+_TEST_ROOT_KEYS = ("root", "dir", "testDir", "rootDir", "roots")+_SETUP_KEY_BYTES = tuple(k.encode() for k in TEST_SETUP_KEYS)+++def is_runner_config(path: str) -> bool:+ """A file that may configure a JS/TS test runner's setup files."""+ name = path.rpartition("/")[2]+ if name == "package.json":+ return True+ return name.startswith(_CONFIG_PREFIXES) and name.endswith((*_JS_EXTS, ".json"))+++def setup_specs(text: bytes) -> list[str]:+ """The string literals inside every setup key's value in a config's *text*."""+ specs = [s for span in value_spans(text, TEST_SETUP_KEYS) for s in string_literals(span)]+ return list(dict.fromkeys(specs))+++def leaves_its_directory(text: bytes) -> bool:+ """Whether the config points its test root above its own directory."""+ return any(+ ".." in s for span in value_spans(text, _TEST_ROOT_KEYS) for s in string_literals(span)+ )+++def _package_dir(config: str, path_set: set[str]) -> str:+ """The nearest directory at or above *config* holding a ``package.json``; ``""`` for none."""+ d = posixpath.dirname(config)+ while d:+ if f"{d}/package.json" in path_set:+ return d+ d = posixpath.dirname(d)+ return ""+++def resolve_setup_spec(spec: str, config: str, ctx: ResolverContext) -> str | None:+ """The indexed file *spec*, written in *config*, names, or ``None``.++ A runner resolves a relative setup path against its root, which may be the+ config's directory or any directory above it (a config under+ ``test/vitest/`` with ``root`` set to the repository), so each is tried,+ nearest first. ``<rootDir>/`` is the package directory.+ """+ from ..resolvers.typescript import resolve_ts_js_import++ if spec.startswith("<rootDir>/"):+ bases = [_package_dir(config, ctx.path_set)]+ spec = spec[len("<rootDir>/") :]+ else:+ bases = []+ d = posixpath.dirname(config)+ while True:+ bases.append(d)+ if not d:+ break+ d = posixpath.dirname(d)+ if not spec or spec.startswith("/") or "\n" in spec:+ return None+ for base in bases:+ joined = posixpath.normpath(posixpath.join(base, spec))+ if joined.startswith(".."):+ continue+ resolved = resolve_ts_js_import(f"./{joined}", "_", ctx)+ if resolved and not resolved.startswith("external:") and resolved != config:+ return resolved+ return None+++def _setups_by_scope(+ parsed_files: dict[str, Any], ctx: ResolverContext, path_set: set[str]+) -> dict[str, set[str]]:+ """``{directory whose tests run them: setup files}`` over every runner config."""+ setups: dict[str, set[str]] = {}+ for path in sorted(path_set):+ if not is_runner_config(path):+ continue+ text = source_bytes(path, parsed_files[path].file_info.abs_path, ctx.source_map)+ if not any(k in text for k in _SETUP_KEY_BYTES):+ continue+ targets = {t for s in setup_specs(text) if (t := resolve_setup_spec(s, path, ctx))}+ if targets:+ scope = "" if leaves_its_directory(text) else _package_dir(path, path_set)+ setups.setdefault(scope, set()).update(targets)+ return setups+++def _add_setup_edges(+ graph: nx.DiGraph, parsed_files: dict[str, Any], ctx: ResolverContext, path_set: set[str]+) -> int:+ setups = _setups_by_scope(parsed_files, ctx, path_set)+ if not setups:+ return 0+ # Each test once: the setup files of every scope at or above its directory.+ count = 0+ # A runnable test is named like one; a helper under a test directory is not.+ tests = (p for p in path_set if p.endswith(_JS_EXTS) and is_test_path(posixpath.basename(p)))+ for test in sorted(tests):+ targets: set[str] = set()+ d = posixpath.dirname(test)+ while True:+ targets |= setups.get(d, set())+ if not d:+ break+ d = posixpath.dirname(d)+ for target in sorted(targets):+ if _add_edge_if_new(graph, test, target):+ graph[test][target]["hint_source"] = SETUP_FILE_HINT+ count += 1+ return count+++class _SetupFilesHandler:+ """Runner configs load their setup files before every test they run."""++ def detect(self, dctx: DetectionContext) -> bool:+ return any(p.endswith(_JS_EXTS) for p in dctx.path_set)++ def add_edges(+ self,+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+ path_set: set[str],+ ) -> int:+ return _add_setup_edges(graph, parsed_files, ctx, path_set)+++HANDLERS: list[FrameworkHandler] = [_SetupFilesHandler()]diff --git a/packages/core/src/repowise/core/ingestion/graph/_edges.py b/packages/core/src/repowise/core/ingestion/graph/_edges.pyindex 4a39b664e..b52dd4a61 100644--- a/packages/core/src/repowise/core/ingestion/graph/_edges.py+++ b/packages/core/src/repowise/core/ingestion/graph/_edges.py@@ -226,6 +226,7 @@ class EdgesMixin:# reads the bytes ingestion already has instead of a second pass# over the tree. Empty unless ``set_source_map`` was called.source_map=self._source_map,+ pytest_roots=self._pytest_roots,)# The .NET project index ``build()`` already made; handlers that scopediff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.pyindex 6839a64e2..705e9a7dc 100644--- a/packages/core/src/repowise/core/ingestion/graph/builder.py+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py@@ -81,6 +81,7 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd# Launcher names the traverser read from pyproject.toml; set by the# pipelines that walk the repo, empty for a builder fed files directly.self.console_scripts: frozenset[str] = frozenset()+ self._pytest_roots: Any | None = Noneself._built = False# Resolver-built DotNetProjectIndex, stashed by build() for the# dynamic-hints phase to reuse (see build()).@@ -242,6 +243,10 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd"""self._source_map = source_map or {}+ def set_pytest_roots(self, roots: Any) -> None:+ """Hand the builder where pytest collects (the traverser's ``pytest_roots``)."""+ self._pytest_roots = roots+def add_file(self, parsed: ParsedFile) -> None:"""Register one parsed file and its symbols in the graph."""path = parsed.file_info.pathdiff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.pyindex da4f81bc3..3784aca32 100644--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py@@ -229,26 +229,14 @@ def _read_warmup_source(parsed: Any,source_map: dict[str, bytes] | None,) -> str | None:- """Text of *path* for a marker scan, from *source_map* if it has it.+ """Text of *path* for a marker scan, preferring the bytes ingestion already read.- Neither ``ParsedFile`` nor ``FileInfo`` carries the source, so before- ``source_map`` existed these scans always re-opened the file. Decoding- matches what the disk fallback below does (utf-8 / replace) so a hit and- a miss can never disagree about the same bytes. Returns None when the- file is unavailable, which the callers treat as "no markers".+ None when the file is unavailable, which the callers treat as "no markers"."""- if source_map is not None:- data = source_map.get(path)- if data is not None:- return data.decode("utf-8", errors="replace")- abs_path = getattr(parsed.file_info, "abs_path", None)- if not abs_path:- return None- try:- with open(abs_path, encoding="utf-8", errors="replace") as f:- return f.read()- except OSError:- return None+ from .source_text import source_text++ abs_path = getattr(parsed.file_info, "abs_path", None) or ""+ return source_text(path, abs_path, source_map, errors="replace")def _mark_cpp_entry_point_files(diff --git a/packages/core/src/repowise/core/ingestion/languages/js_config_values.py b/packages/core/src/repowise/core/ingestion/languages/js_config_values.pynew file mode 100644index 000000000..1bbe395b2--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/languages/js_config_values.py@@ -0,0 +1,103 @@+"""The values a JS/TS tool config gives named keys, read as text.++Tool configs are code (spread base configs, helper factories, env-chosen+values), so nothing here evaluates them. A key's value is the expression after+``key:`` / ``key =``, up to the first ``,`` / ``;`` / unmatched closing+bracket or line end outside brackets; the string literals inside it are what+the config names. Comments are dropped first, so a path a config only mentions+in one is not read. Dead-code analysis (files a config loads) and the+test-runner setup edges both read configs through this module.+"""++from __future__ import annotations++import re+from functools import lru_cache++#: Keys whose value names files a test runner loads before the tests it runs.+TEST_SETUP_KEYS: tuple[str, ...] = (+ "setupFiles",+ "setupFilesAfterEnv",+ "globalSetup",+ "globalTeardown",+)++# A ``//`` after ``:`` is a URL (``https://``), not a comment.+_LINE_COMMENT_RE = re.compile(rb"(?<![:\w])//[^\n]*")+_BLOCK_COMMENT_RE = re.compile(rb"/\*.*?\*/", re.DOTALL)+_OPEN, _CLOSE, _QUOTES = b"([{", b")]}", b"\"'`"+++def strip_comments(text: bytes) -> bytes:+ """*text* without ``//`` and ``/* */`` comments."""+ return _LINE_COMMENT_RE.sub(b"", _BLOCK_COMMENT_RE.sub(b"", text))+++@lru_cache(maxsize=16)+def _key_re(keys: tuple[str, ...]) -> re.Pattern[bytes]:+ names = b"|".join(re.escape(k.encode()) for k in keys)+ return re.compile(rb"""["']?\b(?:""" + names + rb""")\b["']?\s*[:=](?!=)""")+++def value_spans(text: bytes, keys: tuple[str, ...]) -> list[bytes]:+ """The value expression of every occurrence of *keys* in a config's *text*."""+ text = strip_comments(text)+ return [text[m.end() : _value_end(text, m.end())] for m in _key_re(keys).finditer(text)]+++def string_literals(span: bytes) -> list[str]:+ """The string literals in *span*, in order; a template literal with a hole is skipped."""+ out: list[str] = []+ i = 0+ while i < len(span):+ if span[i] in _QUOTES:+ end = _string_end(span, i)+ body = span[i + 1 : end]+ if not (span[i] == ord("`") and b"${" in body):+ out.append(body.decode("utf-8", errors="replace"))+ i = end + 1+ continue+ i += 1+ return out+++def _value_end(text: bytes, start: int) -> int:+ """Where the value expression starting at *start* ends.++ A line end before the value starts does not end it, so a key with its value+ on the next line still reads.+ """+ depth = 0+ started = False+ i = start+ while i < len(text):+ ch = text[i]+ if depth == 0 and (ch in b",;" or (ch == ord("\n") and started)):+ return i+ if ch in _QUOTES:+ i = _string_end(text, i) + 1+ started = True+ continue+ if ch in _OPEN:+ depth += 1+ elif ch in _CLOSE:+ if depth == 0:+ return i+ depth -= 1+ started = started or not chr(ch).isspace()+ i += 1+ return i+++def _string_end(text: bytes, start: int) -> int:+ """Index of the quote closing the string opened at *start* (or the text's end)."""+ quote = text[start]+ i = start + 1+ while i < len(text):+ if text[i] == ord("\\"):+ i += 2+ continue+ if text[i] == quote:+ return i+ i += 1+ return len(text)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/context.py b/packages/core/src/repowise/core/ingestion/resolvers/context.pyindex 16984393a..c1e967cae 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/context.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/context.py@@ -45,6 +45,9 @@ class ResolverContext:# a second read; None (or a missing key) means read from disk.source_map: dict[str, bytes] | None = field(default=None, repr=False)compile_commands_cache: dict[str, dict] | None = field(default=None, repr=False)+ # Where pytest collects (``pytest_roots.PytestRoots``), from the traverser's+ # config pass. None when the caller did not walk the repo: collection unknown.+ pytest_roots: Any | None = field(default=None, repr=False)# Lazy per-language indexes are stashed via getattr/setattr (e.g.# ``_php_psr4_map``, ``_composer_manifests``, ``_ts_workspace_map``,# ``_kotlin_index``, ``_ruby_rails_index``, ``_swift_targets``,diff --git a/packages/core/src/repowise/core/ingestion/source_text.py b/packages/core/src/repowise/core/ingestion/source_text.pyindex 93abe1634..13406791a 100644--- a/packages/core/src/repowise/core/ingestion/source_text.py+++ b/packages/core/src/repowise/core/ingestion/source_text.py@@ -57,3 +57,16 @@ def source_text(return Path(abs_path).read_text(encoding=encoding, errors=errors)except OSError:return None+++def source_bytes(rel_path: str, abs_path: str | Path, source_map: dict[str, bytes] | None) -> bytes:+ """Raw bytes of one file, from *source_map* if it holds it, else from disk; ``b""`` if neither.++ For byte-level scans that decode nothing, so no codec choice applies.+ """+ if source_map is not None and (data := source_map.get(rel_path)) is not None:+ return data+ try:+ return Path(abs_path).read_bytes()+ except OSError:+ return b""diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.pyindex 02866316d..d7afaf47e 100644--- a/packages/core/src/repowise/core/ingestion/traverser.py+++ b/packages/core/src/repowise/core/ingestion/traverser.py@@ -31,7 +31,13 @@ from pathspec.patterns.gitwildmatch import GitWildMatchPattern, GitWildMatchPattfrom ..code_origin import is_generated_headerfrom ..entry_candidacy import conventional_entry_stems, not_an_execution_start-from ..pytest_roots import PYTEST_CONFIG_NAMES, PytestRoots, pytest_options, pytest_roots+from ..pytest_roots import (+ PYTEST_CONFIG_NAMES,+ PytestRoots,+ parse_pytest_options,+ pytest_options,+ pytest_roots,+)from ..test_paths import is_test_related_pathfrom .languages.registry import REGISTRY as _LANG_REGISTRYfrom .languages.specs.cpp import INCLUDE_FRAGMENT_EXTENSIONS@@ -446,6 +452,11 @@ class FileTraverser:)return self._console_scripts+ @property+ def pytest_roots(self) -> PytestRoots:+ """Where pytest collects, from the configs the console-script pass read."""+ return self._console_script_tables().pytest_roots+@propertydef _console_script_names(self) -> frozenset[str]:return self._console_script_tables().names@@ -1171,6 +1182,7 @@ def _collect_console_scripts(distributions: set[str] = set()inits: set[str] = set()pytest_configs: list[tuple[str, dict]] = []+ unreadable: list[str] = []try:config_files = list(iter_glob(repo_root, tuple(PYTEST_CONFIG_NAMES), prune_nested_git=prune_nested_git)@@ -1178,9 +1190,12 @@ def _collect_console_scripts(except OSError:return ConsoleScriptTables(frozenset(), frozenset(), frozenset(), frozenset())for config_file in config_files:- project, options = _read_python_config(config_file)+ project, options, parsed = _read_python_config(config_file)+ rel = config_file.relative_to(repo_root).as_posix()if options is not None:- pytest_configs.append((config_file.relative_to(repo_root).as_posix(), options))+ pytest_configs.append((rel, options))+ if not parsed:+ unreadable.append(rel)if project is None:continuedist = project.get("name")@@ -1194,7 +1209,7 @@ def _collect_console_scripts(frozenset(modules),frozenset(distributions),frozenset(inits),- pytest_roots(pytest_configs),+ pytest_roots(pytest_configs, unreadable),)@@ -1213,20 +1228,24 @@ def _distribution_init(repo_root: Path, base: Path, dist: str) -> str | None:return init.relative_to(repo_root).as_posix()-def _read_python_config(config_file: Path) -> tuple[dict | None, dict | None]:- """``([project] table, pytest options)`` of one config, each None if absent or unreadable."""+def _read_python_config(config_file: Path) -> tuple[dict | None, dict | None, bool]:+ """``([project] table, pytest options, parsed)`` of one config.++ The first two are None if absent or unreadable; *parsed* is False when the+ file could not be read or parsed, so what it collects is unknown.+ """import tomllibtry:text = config_file.read_text(encoding="utf-8")if config_file.name != "pyproject.toml":- return None, pytest_options(config_file.name, text)+ return None, parse_pytest_options(config_file.name, text), Truedata = tomllib.loads(text)except Exception:- return None, None+ return None, None, Falseproject = data.get("project")options = pytest_options(config_file.name, toml=data)- return (project if isinstance(project, dict) else None), options+ return (project if isinstance(project, dict) else None), options, Truedef _add_script_targets(project: dict, names: set[str], modules: set[str]) -> None:diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex 15fc58911..9aee343c0 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -194,6 +194,7 @@ def build_repo_graph(include_nested_repos=include_nested_repos,)graph_builder.set_source_map(source_map)+ graph_builder.set_pytest_roots(traverser.pytest_roots)graph_builder.build()if timings is not None:timings.stop("rebuild.graph")diff --git a/packages/core/src/repowise/core/pipeline/phases/ingestion.py b/packages/core/src/repowise/core/pipeline/phases/ingestion.pyindex 190838257..b7e50790e 100644--- a/packages/core/src/repowise/core/pipeline/phases/ingestion.py+++ b/packages/core/src/repowise/core/pipeline/phases/ingestion.py@@ -607,6 +607,7 @@ async def _run_ingestion(# Lend the just-read bytes to the builder so the language warmups that# scan file text during build() don't re-read the repo.graph_builder.set_source_map(source_map)+ graph_builder.set_pytest_roots(traverser.pytest_roots)_phase_done(progress, "parse")# ---- tsconfig path-alias resolver (before graph build) ------------------diff --git a/packages/core/src/repowise/core/pytest_roots.py b/packages/core/src/repowise/core/pytest_roots.pyindex 1f09e071d..003e1eab0 100644--- a/packages/core/src/repowise/core/pytest_roots.py+++ b/packages/core/src/repowise/core/pytest_roots.py@@ -46,6 +46,12 @@ PYTEST_CONFIG_SECTIONS: tuple[tuple[str, str | None], ...] = ()PYTEST_CONFIG_NAMES: frozenset[str] = frozenset(name for name, _ in PYTEST_CONFIG_SECTIONS)_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")+++class PytestConfigUnreadableError(ValueError):+ """A pytest config file that does not parse."""@dataclass(frozen=True, slots=True)@@ -59,6 +65,25 @@ class PytestRoots:"""``testpaths`` and ``python_files`` for each directory holding a pytest config."""by_dir: Mapping[str, _Collection] = field(default_factory=dict)+ # Directories holding a pytest config that did not parse: what it collects is unknown.+ unreadable: frozenset[str] = frozenset()++ def may_collect_name(self, path: str) -> bool:+ """Whether *path*'s file name matches ``python_files`` of a config at or above it.++ pytest's default applies where no config sets it. True under a config+ that did not parse, and for a pattern with a directory part, so a doubt+ keeps the file collectable.+ """+ p = PurePosixPath(path)+ dirs = ["" if str(parent) == "." else str(parent) for parent in p.parents]+ if any(d in self.unreadable for d in dirs):+ return True+ governing = [rules for d in dirs if (rules := self.by_dir.get(d)) is not None]+ patterns = {pat for r in governing for pat in r.python_files or DEFAULT_PYTHON_FILES}+ return any(+ "/" in pat or fnmatchcase(p.name, pat) for pat in patterns or DEFAULT_PYTHON_FILES+ )def collects(self, path: str) -> bool | None:"""Whether a bare ``pytest`` run collects *path*; ``None`` when no config governs it.@@ -93,8 +118,19 @@ def pytest_options(*toml* is ``pyproject.toml`` already parsed, so a caller that read it foranother table does not parse it twice. A file that does not parse yields- ``None``, as it would leave pytest to its defaults here.+ ``None``, as it would leave pytest to its defaults here; a caller that must+ tell the two apart uses :func:`parse_pytest_options`."""+ try:+ return parse_pytest_options(name, text, toml=toml)+ except PytestConfigUnreadableError:+ return None+++def parse_pytest_options(+ name: str, text: str = "", *, toml: Mapping[str, Any] | None = None+) -> dict[str, Any] | None:+ """:func:`pytest_options`, raising :class:`PytestConfigUnreadableError` on a file that does not parse."""section = dict(PYTEST_CONFIG_SECTIONS).get(name, "")if section == "":return None@@ -105,17 +141,20 @@ def pytest_options(return block if isinstance(block, dict) else Noneparser = configparser.ConfigParser(interpolation=None)parser.read_string(text)- except (tomllib.TOMLDecodeError, configparser.Error, AttributeError):- return None+ except (tomllib.TOMLDecodeError, configparser.Error, AttributeError) as exc:+ raise PytestConfigUnreadableError(f"{name}: {exc}") from excif not parser.has_section(section):return {} if name == "pytest.ini" else Nonereturn dict(parser.items(section))-def pytest_roots(configs: Iterable[tuple[str, Mapping[str, Any]]]) -> PytestRoots:+def pytest_roots(+ configs: Iterable[tuple[str, Mapping[str, Any]]], unreadable: Iterable[str] = ()+) -> PytestRoots:"""Build from ``(config path, options)`` pairs (:func:`pytest_options`).- The highest-precedence config in each directory wins.+ The highest-precedence config in each directory wins. *unreadable* are the+ paths of pytest configs that did not parse."""chosen: dict[str, tuple[int, Mapping[str, Any]]] = {}for path, options in configs:@@ -131,10 +170,15 @@ def pytest_roots(configs: Iterable[tuple[str, Mapping[str, Any]]]) -> PytestRoot_words(o.get("python_files")),)for key, (_, o) in chosen.items()- }+ },+ frozenset(_dir_key(PurePosixPath(u)) for u in unreadable),)+def _dir_key(path: PurePosixPath) -> str:+ return "" if str(path.parent) == "." else str(path.parent)++def read_pytest_roots(texts: Iterable[tuple[str, str]]) -> PytestRoots:""":func:`pytest_roots` from ``(config path, text)`` pairs."""return pytest_roots(diff --git a/tests/unit/analysis/test_test_selection.py b/tests/unit/analysis/test_test_selection.pyindex 10e37ef9d..44f6b1fcb 100644--- a/tests/unit/analysis/test_test_selection.py+++ b/tests/unit/analysis/test_test_selection.py@@ -326,6 +326,62 @@ def test_any_route_through_a_test_helper_runs_everything() -> None:assert "src/a.py is reached through the test helper tests/helpers.py, and no test" in sel.reasons[0]+def test_an_unimported_helper_adds_nothing_when_every_known_test_runs() -> None:+ """Its unknown users are tests, and all of them are selected already."""+ changed = "src/env.ts"+ tiers = _tiers(+ inferred=[+ _inferred(changed, "test/setup.ts", "import-graph"),+ _inferred(changed, "src/a.test.ts", "import-graph"),+ _inferred(changed, "src/b.test.ts", "import-graph"),+ _inferred(changed, "extensions/tw/test/setup.ts", "import-graph"),+ ]+ )+ tiers["helper_importers"] = {"test/setup.ts": ["src/a.test.ts", "src/b.test.ts"]}+ known = ["src/a.test.ts", "src/b.test.ts"]+ sel = _select([changed], tiers, known_tests=known)+ assert not sel.run_all+ assert sel.test_files == ("src/a.test.ts", "src/b.test.ts")+ assert sel.reasons[0] == (+ f"{changed} is reached through the test helper extensions/tw/test/setup.ts, which "+ "no test imports, but every known test already runs for that change."+ )+ # --explain names the change behind a test a setup-file route added.+ assert sel.why["src/a.test.ts"] == f"{changed} changed (import-graph)"+ # A test in another language may start the helper by path: it must run too.+ sel = _select([changed], tiers, known_tests=[*known, "tests/test_launch.py"])+ assert sel.run_all+ assert "no test imports that helper" in sel.reasons[0]+++def test_an_unimported_helper_still_runs_everything_when_a_peer_is_not_selected() -> None:+ tiers = _tiers(+ inferred=[+ _inferred("src/a.py", "tests/test_a.py", "import-graph"),+ _inferred("src/a.py", "tests/helpers.py", "import-graph"),+ ]+ )+ sel = _select(["src/a.py"], tiers, known_tests=["tests/test_a.py", "tests/test_b.py"])+ assert sel.run_all+ assert "reached through the test helper tests/helpers.py, and no test" in sel.reasons[0]+ # A test the graph cannot see into runs with every selection, so it counts.+ sel = _select(+ ["src/a.py"],+ tiers,+ known_tests=["tests/test_a.py", "tests/test_b.py"],+ unplaced_tests=["tests/test_b.py"],+ )+ assert not sel.run_all+ # So does a detected always-run test.+ sel = _select(+ ["src/a.py"],+ tiers,+ known_tests=["tests/test_a.py", "tests/test_b.py"],+ always_run_tests={"tests/test_b.py": "it runs the CLI in a subprocess"},+ )+ assert not sel.run_all++def test_coverage_does_not_hide_a_helper_route() -> None:tiers = _tiers(covered={diff --git a/tests/unit/ingestion/test_pytest_fixture_edges.py b/tests/unit/ingestion/test_pytest_fixture_edges.pyindex 5e8d7b920..e7b3db1e6 100644--- a/tests/unit/ingestion/test_pytest_fixture_edges.py+++ b/tests/unit/ingestion/test_pytest_fixture_edges.py@@ -441,3 +441,55 @@ def test_conftest_edge_is_marked_as_a_convention_not_an_import() -> None:}assert "hint_source" not in graph["tests/test_db.py"]["tests/conftest.py"]assert not graph.has_edge("app.py", "tests/conftest.py")+++def _conftest_graph(*nodes: str) -> nx.DiGraph:+ graph = nx.DiGraph()+ for node in nodes:+ graph.add_node(node, is_test=True)+ return graph+++def test_a_helper_beside_the_tests_gets_no_conftest_edge() -> None:+ """pytest collects only test files; a helper sees no fixture, so no route through it."""+ from repowise.core.ingestion.framework_edges.pytest_edges import _add_conftest_edges+ from repowise.core.pytest_roots import PytestRoots++ graph = _conftest_graph(+ "tests/conftest.py",+ "tests/lsp/conftest.py",+ "tests/lsp/test_client.py",+ "tests/lsp/_mock_server.py",+ "tests/lsp/__init__.py",+ )+ _add_conftest_edges(graph, set(graph.nodes), PytestRoots())++ assert graph.has_edge("tests/lsp/test_client.py", "tests/conftest.py")+ assert graph.has_edge("tests/lsp/conftest.py", "tests/conftest.py")+ assert not graph.has_edge("tests/lsp/_mock_server.py", "tests/conftest.py")+ assert not graph.has_edge("tests/lsp/__init__.py", "tests/conftest.py")+++def test_conftest_edges_follow_the_configured_python_files() -> None:+ """A Django-style ``tests.py`` collected by ``python_files`` keeps its conftest edge."""+ from repowise.core.ingestion.framework_edges.pytest_edges import _add_conftest_edges+ from repowise.core.pytest_roots import read_pytest_roots++ roots = read_pytest_roots([("pytest.ini", "[pytest]\npython_files = tests.py check_*.py\n")])+ graph = _conftest_graph("app/conftest.py", "app/tests.py", "app/check_api.py", "app/helpers.py")+ _add_conftest_edges(graph, set(graph.nodes), roots)++ assert graph.has_edge("app/tests.py", "app/conftest.py")+ assert graph.has_edge("app/check_api.py", "app/conftest.py")+ assert not graph.has_edge("app/helpers.py", "app/conftest.py")+++def test_unknown_collection_keeps_every_conftest_edge() -> None:+ """A config that did not parse, or no traverser roots at all: collection is unknown."""+ from repowise.core.ingestion.framework_edges.pytest_edges import _add_conftest_edges+ from repowise.core.pytest_roots import pytest_roots++ for roots in (pytest_roots([], unreadable=["pyproject.toml"]), 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")diff --git a/tests/unit/ingestion/test_test_wiring_edges.py b/tests/unit/ingestion/test_test_wiring_edges.pynew file mode 100644index 000000000..8c8199b7c--- /dev/null+++ b/tests/unit/ingestion/test_test_wiring_edges.py@@ -0,0 +1,182 @@+"""Test wiring no import states: runner setup files and helpers named by path."""++from __future__ import annotations++from types import SimpleNamespace++import networkx as nx+import pytest++from repowise.core.ingestion.framework_edges.test_path_strings import (+ PATH_STRING_HINT,+ _add_path_string_edges,+ path_string_targets,+)+from repowise.core.ingestion.framework_edges.test_runner_setup import (+ SETUP_FILE_HINT,+ _add_setup_edges,+ is_runner_config,+ leaves_its_directory,+ resolve_setup_spec,+ setup_specs,+)+from repowise.core.ingestion.resolvers.context import ResolverContext+from repowise.core.test_paths import is_test_related_path+++def _ctx(sources: dict[str, str]) -> tuple[nx.DiGraph, dict, ResolverContext]:+ graph = nx.DiGraph()+ graph.add_nodes_from(sources)+ parsed = {+ p: SimpleNamespace(file_info=SimpleNamespace(is_test=is_test_related_path(p), abs_path=p))+ for p in sources+ }+ ctx = ResolverContext(+ path_set=set(sources),+ stem_map={},+ graph=graph,+ source_map={p: s.encode() for p, s in sources.items()},+ )+ return graph, parsed, ctx+++# -- runner setup files ---------------------------------------------------------+++ ("text", "specs"),+ [+ ('export default { test: { setupFiles: ["./setup.ts"] } }', ["./setup.ts"]),+ ("setupFiles: './a.ts', include: ['src/**']", ["./a.ts"]),+ ('setupFiles: [resolveRoot("test/setup.ts")],', ["test/setup.ts"]),+ (+ 'setupFiles: [\n ...new Set([...(base.setupFiles ?? []), "test/rt.ts"].map(f)),\n],',+ ["test/rt.ts"],+ ),+ ('const setupFiles = [\n ...(o ? [] : ["test/rt.ts"]),\n];', ["test/rt.ts"]),+ ('"setupFilesAfterEnv": ["<rootDir>/jest.setup.js"]', ["<rootDir>/jest.setup.js"]),+ ("globalSetup:\n './global.ts',", ["./global.ts"]),+ ("setupFiles: base.setupFiles,\ninclude: ['x.ts']", []),+ ("// setupFiles: ['./old.ts']\n", []),+ ("setupFiles: [`${root}/setup.ts`]", []),+ ("coverage: { exclude: ['./setup.ts'] }", []),+ ],+)+def test_setup_specs_reads_the_strings_in_a_setup_value(text: str, specs: list[str]) -> None:+ assert setup_specs(text.encode()) == specs+++ ("path", "expected"),+ [+ ("vitest.config.ts", True),+ ("test/vitest/vitest.scoped-config.ts", True),+ ("packages/a/jest.config.cjs", True),+ ("packages/a/package.json", True),+ ("src/setup.ts", False),+ ("eslint.config.js", False),+ ],+)+def test_runner_configs_are_named_for_their_runner(path: str, expected: bool) -> None:+ assert is_runner_config(path) is expected+++def test_a_setup_path_resolves_against_the_config_or_any_directory_above() -> None:+ _, _, ctx = _ctx(+ {+ "test/setup.ts": "",+ "test/vitest/vitest.unit.config.ts": "",+ "web/package.json": "{}",+ "web/jest.setup.js": "",+ "web/config/jest.config.js": "",+ }+ )+ assert resolve_setup_spec("test/setup.ts", "test/vitest/vitest.unit.config.ts", ctx) == (+ "test/setup.ts"+ )+ assert resolve_setup_spec("../setup", "test/vitest/vitest.unit.config.ts", ctx) == (+ "test/setup.ts"+ )+ assert resolve_setup_spec("<rootDir>/jest.setup.js", "web/config/jest.config.js", ctx) == (+ "web/jest.setup.js"+ )+ assert resolve_setup_spec("@testing-library/jest-dom", "web/config/jest.config.js", ctx) is None+++def test_tests_a_config_runs_get_an_edge_to_its_setup_files() -> None:+ graph, parsed, ctx = _ctx(+ {+ "package.json": "{}",+ "vitest.config.ts": 'export default { test: { setupFiles: ["./test/setup.ts"] } }',+ "test/setup.ts": "",+ "src/a.test.ts": "",+ "ui/package.json": "{}",+ "ui/vitest.config.ts": "export default { test: { globalSetup: './g.ts' } }",+ "ui/g.ts": "",+ "ui/b.spec.ts": "",+ "src/a.ts": "",+ }+ )+ added = _add_setup_edges(graph, parsed, ctx, ctx.path_set)++ assert added == 3+ assert graph["src/a.test.ts"]["test/setup.ts"]["hint_source"] == SETUP_FILE_HINT+ assert graph["src/a.test.ts"]["test/setup.ts"]["edge_type"] == "framework"+ assert graph.has_edge("ui/b.spec.ts", "test/setup.ts")+ assert graph.has_edge("ui/b.spec.ts", "ui/g.ts")+ # The ui config runs only the tests of its own package.+ assert not graph.has_edge("src/a.test.ts", "ui/g.ts")+ assert not graph.has_edge("src/a.ts", "test/setup.ts")+++def test_a_config_whose_test_root_climbs_out_links_every_test() -> None:+ assert leaves_its_directory(b'export default { test: { dir: "../tests" } }')+ assert not leaves_its_directory(b'export default { test: { dir: "extensions" } }')+ graph, parsed, ctx = _ctx(+ {+ "web/package.json": "{}",+ "web/vitest.config.ts": "export default { root: '..', test: { setupFiles: ['./s.ts'] } }",+ "web/s.ts": "",+ "tests/a.test.ts": "",+ }+ )+ assert _add_setup_edges(graph, parsed, ctx, ctx.path_set) == 1+ assert graph.has_edge("tests/a.test.ts", "web/s.ts")+++# -- helpers named by path -------------------------------------------------------+++def test_a_helper_named_relative_to_the_test_is_linked() -> None:+ path_set = {+ "tests/lsp/test_client.py",+ "tests/lsp/_mock_server.py",+ "tests/lsp/__init__.py",+ "tests/fixture-server.ts",+ "tests/data/sample.json",+ "src/server.py",+ }+ py = b'MOCK = str(Path(__file__).parent / "_mock_server.py")\nopen("../data/sample.json")\n'+ assert path_string_targets("tests/lsp/test_client.py", py, path_set) == [+ "tests/lsp/_mock_server.py"+ ]+ js = b'spawn(process.execPath, [path.join(__dirname, "../fixture-server.ts")])'+ assert path_string_targets("tests/lsp/x.test.ts", js, path_set) == ["tests/fixture-server.ts"]+ # A name that only matches elsewhere, a scratch file named like a package+ # marker, a data file and another test are not routes.+ path_set.add("tests/lsp/test_other.py")+ other = b'"server.py" "__init__.py" "../data/sample.json" "test_other.py"'+ assert path_string_targets("tests/lsp/test_client.py", other, path_set) == []+++def test_path_string_edges_leave_from_test_files_only() -> None:+ graph, parsed, ctx = _ctx(+ {+ "tests/test_client.py": 'SERVER = Path(__file__).parent / "_mock_server.py"',+ "tests/_mock_server.py": "",+ "src/run.py": '"helper.py"',+ "src/helper.py": "",+ }+ )+ assert _add_path_string_edges(graph, parsed, ctx, ctx.path_set) == 1+ assert graph["tests/test_client.py"]["tests/_mock_server.py"]["hint_source"] == PATH_STRING_HINTdiff --git a/tests/unit/test_pytest_roots.py b/tests/unit/test_pytest_roots.pyindex 961801e6a..60eb7cd30 100644--- a/tests/unit/test_pytest_roots.py+++ b/tests/unit/test_pytest_roots.py@@ -72,3 +72,20 @@ def test_options_come_from_an_already_parsed_pyproject() -> None:parsed = {"tool": {"pytest": {"ini_options": {"testpaths": ["t"]}}}}assert pytest_options("pyproject.toml", toml=parsed) == {"testpaths": ["t"]}assert pytest_options("README.md", "[pytest]") is None+++def test_a_config_that_does_not_parse_is_recorded_as_unknown() -> None:+ from repowise.core.pytest_roots import (+ PytestConfigUnreadableError,+ parse_pytest_options,+ pytest_options,+ pytest_roots,+ )++ with pytest.raises(PytestConfigUnreadableError):+ parse_pytest_options("tox.ini", "[pytest\npython_files = x")+ assert pytest_options("tox.ini", "[pytest\npython_files = x") is None+ roots = pytest_roots([], unreadable=["pkg/tox.ini"])+ 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")