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): run only the tests that read a changed fixture file (#4267)
Amanf8d5c6c7f54c
diff --git a/packages/core/src/repowise/core/analysis/fixture_readers.py b/packages/core/src/repowise/core/analysis/fixture_readers.pyindex 99af780e7..eb5272679 100644--- a/packages/core/src/repowise/core/analysis/fixture_readers.py+++ b/packages/core/src/repowise/core/analysis/fixture_readers.py@@ -13,6 +13,11 @@ any namer does: a helper through the tests importing it, a conftest throughthe tests under it, and a helper no test imports runs everything. The filestays the namer, and so keeps the full run, when no test code names its treeor code outside test trees names the tree's path.++A changed data file in a fixtures directory is resolved the same way+(:func:`with_data_file_readers`): the test code naming the file, or the tree it+sits in, reads it. It keeps the full run when code outside the test trees names+the file or the tree, or when no test code does (a glob or a computed path)."""from __future__ import annotations@@ -23,6 +28,8 @@ import tokenizefrom collections.abc import Callable, Collection, Mappingfrom pathlib import PurePosixPath+from ..test_paths import is_test_related_path+# Directories holding test data, as named in ``test_paths``' support tokens.FIXTURE_DIRS = frozenset({"fixtures", "__fixtures__", "testdata"})@@ -65,6 +72,40 @@ def with_fixture_readers(return out+def with_data_file_readers(+ files: Collection[str],+ namers: Mapping[str, list[str]],+ test_code: Collection[str],+ other_code: Collection[str],+ read: Callable[[str], str | None],+ holding: Callable[[Collection[str]], Collection[str] | None] | None = None,+) -> dict[str, list[str]]:+ """``{changed fixture data file: the test code reading it}``.++ *namers* are the code files naming each of *files* by file name+ (:func:`~.test_selection.file_namers`). A file inside a fixture tree is also+ read by the test code naming the tree. A file is absent, and so keeps its+ full run, when code outside the test trees names it or its tree, or when no+ test code does: a fixture read through a glob or a computed path is the+ case that fallback protects.+ """+ trees = {f: r for f in files if (r := fixture_root(f))}+ texts = _texts(set(trees.values()), test_code, other_code, read, holding) if trees else {}+ out: dict[str, list[str]] = {}+ for f in files:+ readers = [n for n in namers.get(f, ()) if n != f]+ if not all(is_test_related_path(n) for n in readers):+ continue # production code names the file: not only tests read it+ if root := trees.get(f):+ tree = _tree_readers(root, texts, test_code, other_code)+ if tree is None:+ continue+ readers += [r for r in tree if r not in readers]+ if readers:+ out[f] = readers+ return out++def _stand_ins(namer: str, readers: Mapping[str, list[str]]) -> list[str]:root = fixture_root(namer)return readers.get(root, [namer]) if root else [namer]@@ -78,26 +119,46 @@ def _root_readers(holding: Callable[[Collection[str]], Collection[str] | None] | None,) -> dict[str, list[str]]:"""``{fixture root: test code reading it}``; a root that must keep its full run is absent."""+ texts = _texts(roots, test_code, other_code, read, holding)+ out: dict[str, list[str]] = {}+ for root in roots:+ if found := _tree_readers(root, texts, test_code, other_code):+ out[root] = found+ return out+++def _texts(+ roots: Collection[str],+ test_code: Collection[str],+ other_code: Collection[str],+ read: Callable[[str], str | None],+ holding: Callable[[Collection[str]], Collection[str] | None] | None,+) -> dict[str, str]:+ """The lowercased code text of each file that may name one of *roots*' trees."""names = {n for r in roots for n in _dir_names(r)}held = holding(names) if holding else None- texts = {+ return {p: code_text(p, read(p) or "").lower()for p in sorted({*test_code, *other_code})if held is None or p in held}- out: dict[str, list[str]] = {}- for root in roots:- leaf, parent = _dir_names(root)- if any(root.lower() in texts[p] for p in other_code if p in texts):- continue # code outside the test trees names the tree: not only tests read it- found = [- p- for p in test_code- if p in texts and fixture_root(p) is None and _names_either(texts[p], leaf, parent)- ]- if found:- out[root] = found- return out+++def _tree_readers(+ root: str,+ texts: Mapping[str, str],+ test_code: Collection[str],+ other_code: Collection[str],+) -> list[str] | None:+ """The test code naming *root*'s tree, or ``None`` when code outside the test trees names it."""+ leaf, parent = _dir_names(root)+ if any(root.lower() in texts[p] for p in other_code if p in texts):+ return None # code outside the test trees names the tree: not only tests read it+ return [+ p+ for p in test_code+ if p in texts and fixture_root(p) is None and _names_either(texts[p], leaf, parent)+ ]def _dir_names(root: str) -> tuple[str, str]:diff --git a/packages/core/src/repowise/core/analysis/selection_scopes.py b/packages/core/src/repowise/core/analysis/selection_scopes.pyindex e411e9782..b6a3b9fd8 100644--- a/packages/core/src/repowise/core/analysis/selection_scopes.py+++ b/packages/core/src/repowise/core/analysis/selection_scopes.py@@ -1,7 +1,7 @@"""Scopes: what a changed file runs when every test is more than it can reach.:func:`~.test_selection.select_tests` runs everything for a file whose tests-are unknown. For three kinds the reach is known, and :func:`trigger_scopes`+are unknown. For four kinds the reach is known, and :func:`trigger_scopes`names it as a :class:`Scope`:- A manifest, lockfile or runner config runs its ecosystem's tests. A JS@@ -20,6 +20,10 @@ names it as a :class:`Scope`:names keeps its full run (a test may glob it).Other non-code files, dotfiles and root-level data configure tools, notcode, and keep their full run too.+- A data file under ``fixtures/`` or ``testdata/`` runs the test code reading+ it: the code naming the file, or for a file in a fixture tree the code+ naming the tree (:mod:`~.fixture_readers`). It keeps its full run when no+ reader is found or code outside the test trees names it.A scope also runs the tests reaching each file that names the changed one, soa test reading ``package.json`` as data is kept. An ecosystem scope already@@ -65,6 +69,9 @@ from .test_selection import (# is the upgrade.MAX_NAMERS = 200+#: The basis of a fixture data file that runs the test code reading it.+FIXTURE_READERS = "fixture-readers"+_JVM = (".java", ".kt", ".kts", ".scala", ".groovy")# (ecosystem, test suffixes, scoped to the file's directory, gitwildmatch# patterns). Each pattern is also a full-run trigger (``_FULL_RUN_GROUPS``),@@ -160,11 +167,26 @@ class Scope:def needs_namers(path: str, config: TestSelectionConfig) -> bool:"""Whether :func:`trigger_scopes` needs to know who names *path*."""+ if is_fixture_data(path, config):+ return Trueif is_test_related_path(path) or _configured(path, config):return Falsereturn _ecosystem(path) is not None or (full_run_reason(path) is None and _is_asset(path))+def is_fixture_data(path: str, config: TestSelectionConfig) -> bool:+ """Whether *path* is a data file in a fixtures directory, which the tests reading it can name.++ Fixture code stays a full run: a test may import it by module name, which+ no file name search sees.+ """+ return (+ full_run_reason(path) == SHARED_TEST_DATA_REASON+ and not is_code_file(path)+ and not _configured(path, config)+ )++def is_manifest(path: str) -> bool:"""A manifest, lockfile or runner config: nothing includes it, so its namers write its path."""return _ecosystem(path) is not None@@ -172,7 +194,7 @@ def is_manifest(path: str) -> bool:def keeps_full_run(path: str, config: TestSelectionConfig) -> bool:"""Whether *path* runs everything whatever names it, so no namer search can help."""- if full_run_reason(path, config.full_run_on) is None:+ if full_run_reason(path, config.full_run_on) is None or is_fixture_data(path, config):return Falseif is_test_related_path(path) or _configured(path, config):return True@@ -250,10 +272,12 @@ class _Tree:def _trigger_scope(path: str, tree: _Tree, namers: tuple[str, ...], config: TestSelectionConfig) -> Scope | None:- if is_test_related_path(path) or full_run_reason(path) == SHARED_TEST_DATA_REASON:- return None # read by tests anywhere: the test-tree rule decidesif _configured(path, config):return None # the config asked for a full run+ if is_fixture_data(path, config):+ return _readers_scope(namers)+ if is_test_related_path(path) or full_run_reason(path) == SHARED_TEST_DATA_REASON:+ return None # read by tests anywhere: the test-tree rule decidesif eco := _ecosystem(path):return _ecosystem_scope(path, eco, tree, namers)why = full_run_reason(path)@@ -264,6 +288,17 @@ def _trigger_scope(return _named_scope(path, tree, namers)+def _readers_scope(readers: tuple[str, ...]) -> Scope | None:+ """The test code reading a fixture data file, or ``None`` to keep its full run.++ *readers* come from :func:`~.fixture_readers.with_data_file_readers`, which+ leaves out a file no test code reads or code outside the test trees names.+ """+ if not readers or _too_many(readers):+ return None+ return Scope(f"it is read by {_some(readers)}", FIXTURE_READERS, namers=readers)++def _configured(path: str, config: TestSelectionConfig) -> bool:return bool(config.full_run_on) and full_run_on_spec(config.full_run_on).match_file(path)diff --git a/packages/core/src/repowise/core/analysis/test_collection.py b/packages/core/src/repowise/core/analysis/test_collection.pyindex 86fc5ebf5..a27f7b074 100644--- a/packages/core/src/repowise/core/analysis/test_collection.py+++ b/packages/core/src/repowise/core/analysis/test_collection.py@@ -160,8 +160,9 @@ def plan_scopes(reading the checkout."""from ..test_paths import is_test_related_path- from .fixture_readers import with_fixture_readers+ from .fixture_readers import with_data_file_readers, with_fixture_readersfrom .selection_scopes import (+ is_fixture_data,is_manifest,keeps_full_run,needs_namers,@@ -184,6 +185,13 @@ def plan_scopes(if is_code_file(p):(test_code if is_test_related_path(p) else other).append(p)namers = with_fixture_readers(namers, test_code, other, checkout.read, checkout.holding)+ # A fixture data file runs the test code reading it; one no test code is+ # known to read, or that production code names, keeps its full run.+ if fixtures := [p for p in asked if is_fixture_data(p, config)]:+ readers = with_data_file_readers(+ fixtures, namers, test_code, other, checkout.read, checkout.holding+ )+ namers = {**{f: n for f, n in namers.items() if f not in fixtures}, **readers}scopes = trigger_scopes(paths, checkout.tracked, namers, config)routes = sorted({r for scope in scopes.values() for r in scope.routes} - set(paths))return Plan(namers, scopes, routes)diff --git a/packages/core/src/repowise/core/analysis/test_selection.py b/packages/core/src/repowise/core/analysis/test_selection.pyindex 2962b59f5..54fe71811 100644--- a/packages/core/src/repowise/core/analysis/test_selection.py+++ b/packages/core/src/repowise/core/analysis/test_selection.py@@ -273,8 +273,8 @@ class Selection:``conftest-import-check`` (one test that loads a conftest the change reachesonly through its imports), ``filename-pattern``, ``unknown``, ``none`` whennothing 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+ ``package-importers``, ``named-by``, ``fixture-readers`` or ``owner-package``.+ ``why`` says, per selected test file, what put it in: the changed file and evidence thatreached it, or the reason it runs with every subset. ``known_tests`` arethe checkout's runnable test files (empty when not read), so a selectioncan say how much of the suite it is.diff --git a/tests/unit/analysis/test_fixture_readers.py b/tests/unit/analysis/test_fixture_readers.pyindex 206bec13c..484220f62 100644--- a/tests/unit/analysis/test_fixture_readers.py+++ b/tests/unit/analysis/test_fixture_readers.py@@ -2,7 +2,23 @@from __future__ import annotations-from repowise.core.analysis.fixture_readers import fixture_root, with_fixture_readers+import subprocess++import pytest++from repowise.core.analysis.changed_lines import ChangeSet, FileDiff+from repowise.core.analysis.fixture_readers import (+ fixture_root,+ with_data_file_readers,+ with_fixture_readers,+)+from repowise.core.analysis.test_collection import plan_scopes, read_checkout+from repowise.core.analysis.test_selection import (+ SHARED_TEST_DATA_REASON,+ SelectionInput,+ TestSelectionConfig,+ select_tests,+)def test_a_fixture_root_is_the_directory_under_the_outermost_fixtures_directory() -> None:@@ -81,3 +97,164 @@ def test_grep_narrowing_gives_the_same_readers() -> None:narrowed = with_fixture_readers(namers, _TEST_CODE, _OTHER, _read, holding)assert narrowed == with_fixture_readers(namers, _TEST_CODE, _OTHER, _read)+++# --- a changed fixture data file runs the tests reading it (#4094) -----------------+++def test_a_data_file_is_read_by_the_test_code_naming_it_or_its_tree() -> None:+ files = ["tests/fixtures/ts_sample/b.json", "tests/fixtures/cases.json"]+ namers = {"tests/fixtures/cases.json": ["tests/test_other.py"]}+ out = with_data_file_readers(files, namers, _TEST_CODE, _OTHER, _read)+ # A file directly in the fixtures directory has no tree: only a name reads it.+ assert out["tests/fixtures/cases.json"] == ["tests/test_other.py"]+ assert out["tests/fixtures/ts_sample/b.json"] == [+ "tests/test_ts.py",+ "tests/test_dynamic.py",+ "tests/test_fstring.py",+ "tests/helpers.py",+ ]+++def test_a_data_file_no_test_code_names_keeps_its_full_run() -> None:+ assert with_data_file_readers(["tests/fixtures/x.json"], {}, _TEST_CODE, _OTHER, _read) == {}+++def test_a_data_file_named_by_production_code_keeps_its_full_run() -> None:+ namers = {"tests/fixtures/cases.json": ["tests/test_other.py", "src/app.py"]}+ assert (+ with_data_file_readers(["tests/fixtures/cases.json"], namers, _TEST_CODE, _OTHER, _read)+ == {}+ )+++def test_a_data_file_in_a_tree_named_by_production_code_keeps_its_full_run() -> None:+ texts = {**_TEXTS, "src/indexer.py": 'SAMPLE = "tests/fixtures/ts_sample"\n'}+ out = with_data_file_readers(+ ["tests/fixtures/ts_sample/b.json"],+ {"tests/fixtures/ts_sample/b.json": ["tests/test_other.py"]},+ _TEST_CODE,+ [*_OTHER, "src/indexer.py"],+ texts.get,+ )+ assert out == {}+++_REPO = {+ "pkg/core.py": "def add(a, b):\n return a + b\n",+ "pkg/loader.py": 'DATA = "tests/fixtures/prod.json"\n',+ "tests/test_core.py": 'CASES = json.loads((HERE / "fixtures" / "cases.json").read_text())\n',+ "tests/test_other.py": "from pkg.core import add\n",+ "tests/test_tree_a.py": 'ROOT = FIXTURES / "golden"\n',+ "tests/test_tree_b.py": 'ROOT = HERE / "fixtures" / "golden"\n',+ "tests/test_helper_user.py": "from tests.helpers import load\n",+ "tests/helpers.py": 'def load():\n return open("loose.json")\n',+ "tests/orphan_helpers.py": 'def load():\n return open("stray.json")\n',+ "tests/fixtures/cases.json": "{}",+ "tests/fixtures/orphan.json": "{}",+ "tests/fixtures/prod.json": "{}",+ "tests/fixtures/loose.json": "{}",+ "tests/fixtures/stray.json": "{}",+ "tests/fixtures/golden/a.json": "{}",+ "Cargo.lock": "",+}+_KNOWN = sorted(p for p in _REPO if p.startswith("tests/test_"))+++def _selection(tmp_path, changed, config=None, importers=None, rows=()):+ for path, text in _REPO.items():+ (tmp_path / path).parent.mkdir(parents=True, exist_ok=True)+ (tmp_path / path).write_text(text, encoding="utf-8")+ subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)+ subprocess.run(["git", "add", "-A"], cwd=tmp_path, check=True)+ config = config or TestSelectionConfig()+ change = ChangeSet(+ files={p: FileDiff(path=p) for p in changed}, deleted=set(), label="t", base=None, head=None+ )+ plan = plan_scopes(change, config, read_checkout(tmp_path))+ # What the graph answers for a route that is itself a test: that test.+ inferred = [+ {"source_file": r, "test_file": r, "via": "changed-test"}+ for r in plan.routes+ if r in _KNOWN+ ]+ inferred += [{"source_file": s, "test_file": t, "via": "import-graph"} for s, t in rows]+ tiers = {+ "covered": {},+ "inferred": inferred,+ "unknown": [],+ "helper_importers": importers or {},+ }+ inp = SelectionInput(list(changed), (), tiers, config, scopes=plan.scopes, known_tests=_KNOWN)+ return select_tests(inp)+++def test_a_fixture_file_named_by_one_test_selects_only_that_test(tmp_path) -> None:+ sel = _selection(tmp_path, ["tests/fixtures/cases.json"])+ assert not sel.run_all, sel.reasons+ assert sel.test_files == ("tests/test_core.py",)+ assert sel.basis == {"tests/fixtures/cases.json": "fixture-readers"}+ why = sel.why["tests/test_core.py"]+ assert why.startswith("tests/fixtures/cases.json changed (fixture-readers:")+ assert "read by tests/test_core.py" in why+++def test_a_fixture_file_in_a_tree_named_by_two_tests_selects_both(tmp_path) -> None:+ sel = _selection(tmp_path, ["tests/fixtures/golden/a.json"])+ assert not sel.run_all, sel.reasons+ # ``test_core.py`` names the fixtures directory itself (``HERE / "fixtures"``), which+ # lists every tree in it; ``test_other.py`` names neither and stays out.+ assert sorted(sel.test_files) == [+ "tests/test_core.py",+ "tests/test_tree_a.py",+ "tests/test_tree_b.py",+ ]+++def test_a_fixture_file_no_test_names_still_runs_everything(tmp_path) -> None:+ sel = _selection(tmp_path, ["tests/fixtures/orphan.json"])+ assert sel.run_all+ assert sel.reasons[0] == f"tests/fixtures/orphan.json changed: {SHARED_TEST_DATA_REASON}."+ assert sel.basis == {"tests/fixtures/orphan.json": "full-run"}+++def test_a_fixture_file_named_by_production_code_still_runs_everything(tmp_path) -> None:+ sel = _selection(tmp_path, ["tests/fixtures/prod.json"])+ assert sel.run_all+ assert sel.reasons[0] == f"tests/fixtures/prod.json changed: {SHARED_TEST_DATA_REASON}."+++def test_a_fixture_read_by_a_helper_a_test_imports_selects_that_test(tmp_path) -> None:+ importers = {"tests/helpers.py": ["tests/test_helper_user.py"]}+ rows = [("tests/helpers.py", "tests/test_helper_user.py")]+ sel = _selection(tmp_path, ["tests/fixtures/loose.json"], importers=importers, rows=rows)+ assert not sel.run_all, sel.reasons+ assert sel.test_files == ("tests/test_helper_user.py",)+++def test_a_fixture_read_by_a_helper_no_test_imports_still_runs_everything(tmp_path) -> None:+ sel = _selection(tmp_path, ["tests/fixtures/stray.json"])+ assert sel.run_all+ assert sel.reasons[0].startswith(+ "tests/fixtures/stray.json changed; tests/orphan_helpers.py is a test helper no test imports"+ )+++def test_a_fixture_changed_with_a_build_file_still_runs_everything(tmp_path) -> None:+ sel = _selection(tmp_path, ["tests/fixtures/cases.json", "Cargo.lock"])+ assert sel.run_all+ assert any(r.startswith("Cargo.lock changed:") for r in sel.reasons)+++def test_a_configured_full_run_still_wins_over_the_readers(tmp_path) -> None:+ config = TestSelectionConfig(full_run_on=("tests/fixtures/cases.json",))+ sel = _selection(tmp_path, ["tests/fixtures/cases.json"], config)+ assert sel.run_all+ assert sel.basis == {"tests/fixtures/cases.json": "full-run"}++[email protected]("path", ["tests/fixtures/sample.py", "tests/fixtures/mod/handler.ts"])+def test_fixture_code_keeps_its_full_run(tmp_path, path) -> None:+ """A test may import fixture code by module name, which no file name search sees."""+ sel = _selection(tmp_path, [path])+ assert sel.run_all