Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(impacted-tests): a comment or docstring mention no longer names a file (#3720)

Swati Ahujaa1815732038a
diff --git a/docs/start/CI.md b/docs/start/CI.md
index 9fc64f9f7..2e129731c 100644
--- a/docs/start/CI.md
+++ b/docs/start/CI.md
@@ -256,7 +256,7 @@ a per-test coverage map (`repowise coverage add`) makes it more precise.
- It runs everything for: an empty change; a Cargo, Make, CMake, Docker or CI file; tool and runtime config (dotfiles, `.tool-versions`, root-level `*.toml`, `*.yaml` and `*.json`, shell scripts); `.repowise/config.yaml`.
- A lockfile, manifest or test runner config runs its own ecosystem's tests: for a nested `package.json`, lockfile or `go.mod`, the tests under its directory and those reaching code there; at the root, and for Python, Ruby, PHP and Gradle or Maven files (pip requirements included), `tsconfig` and jest or vitest configs, the whole ecosystem. Tests whose code names the file from outside that scope run too (a Python test reading `package.json`); a mention written with a directory names only the files its path can mean (`packages/web/package.json` does not name `packages/ui/package.json`), a bare name, `../package.json` or a path built from parts names every file of that name. A file under a fixture tree (`tests/fixtures/<name>/`) stands for the test code that names that tree or the fixtures directory; when none does, or code outside the test trees names the tree's path, everything runs. If more than 200 non-test files outside the scope name it, everything runs.
- A production package's `__init__.py` selects the tests reaching any module under it.
-- A doc, template, query, stylesheet, image or nested data file selects the tests reaching the code that names it. When no code names it, a doc, template, stylesheet or image selects its package's tests, and a query or data file runs everything. Ceiling: a test that globs docs or templates in another package is not seen.
+- A doc, template, query, stylesheet, image or nested data file selects the tests reaching the code that names it, outside comments and docstrings. When no code names it, a doc, template, stylesheet or image selects its package's tests (Markdown, reST or AsciiDoc in no package and in a top-level directory without code needs none), and a query or data file runs everything. Ceiling: a test that globs docs or templates in another package is not seen.
- 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.
diff --git a/packages/core/src/repowise/core/analysis/fixture_readers.py b/packages/core/src/repowise/core/analysis/fixture_readers.py
index 06288b714..99af780e7 100644
--- a/packages/core/src/repowise/core/analysis/fixture_readers.py
+++ b/packages/core/src/repowise/core/analysis/fixture_readers.py
@@ -81,7 +81,7 @@ def _root_readers(
names = {n for r in roots for n in _dir_names(r)}
held = holding(names) if holding else None
texts = {
- p: _code_text(p, read(p) or "").lower()
+ p: code_text(p, read(p) or "").lower()
for p in sorted({*test_code, *other_code})
if held is None or p in held
}
@@ -113,17 +113,20 @@ def _names_either(text: str, *names: str) -> bool:
)
-def _code_text(path: str, text: str) -> str:
+def code_text(path: str, text: str) -> str:
"""*text* without comments, and for Python without docstrings: what can name a path.
Python that does not tokenize is kept whole.
"""
- from ..ingestion.languages.js_config_values import strip_comments
from ..ingestion.languages.python_strings import _is_statement
+ from .security_scan import mask_comments_and_strings, mask_dialect
if not path.endswith(".py"):
- # Ceiling: not string-aware, so a "/*" inside a string can hide code up to a "*/".
- return strip_comments(text.encode("utf-8")).decode("utf-8", errors="replace")
+ # ``#`` is kept: a kept mention selects more, a ``#include`` lost selects less.
+ # Ceiling: a regex literal or a Rust lifetime holding a quote can desync the scan.
+ return mask_comments_and_strings(
+ text, strings=False, hash_comments=False, **mask_dialect(path)
+ )
try:
tokens = [
t
diff --git a/packages/core/src/repowise/core/analysis/security_scan.py b/packages/core/src/repowise/core/analysis/security_scan.py
index dfb055c71..a415fcab0 100644
--- a/packages/core/src/repowise/core/analysis/security_scan.py
+++ b/packages/core/src/repowise/core/analysis/security_scan.py
@@ -1000,12 +1000,14 @@ def mask_comments_and_strings(
strings: bool = True,
nested_comments: bool = False,
raw_backticks: bool = False,
+ hash_comments: bool = True,
) -> str:
"""Blank common comments (and strings, unless *strings* is false), keeping offsets.
Strings are still tracked when they are kept, so a ``#`` or ``//`` inside
one does not open a comment. Newlines are never blanked. *nested_comments*
- and *raw_backticks* come from :func:`mask_dialect`.
+ and *raw_backticks* come from :func:`mask_dialect`; *hash_comments* false
+ keeps a ``#`` line, which is code in C, Rust, C# or Swift (``#include``).
"""
out: list[str] = []
copied = 0
@@ -1068,7 +1070,7 @@ def mask_comments_and_strings(
i += 1
if template_depth == 0:
state = "template"
- elif char == "#" or source.startswith("//", i):
+ elif (hash_comments and char == "#") or source.startswith("//", i):
width = 1 if char == "#" else 2
blank(i, i + width)
i += width
diff --git a/packages/core/src/repowise/core/analysis/selection_scopes.py b/packages/core/src/repowise/core/analysis/selection_scopes.py
index 246ecc49f..699bc3bba 100644
--- a/packages/core/src/repowise/core/analysis/selection_scopes.py
+++ b/packages/core/src/repowise/core/analysis/selection_scopes.py
@@ -15,7 +15,9 @@ names it as a :class:`Scope`:
directory: importing one runs it, whatever the diff.
- An asset runs the tests reaching the code that names it. A doc, template,
stylesheet or image nothing names runs the tests of the package holding it;
- a query or data file nothing names keeps its full run (a test may glob it).
+ prose that nothing names, no package holds and no code shares a top-level
+ directory with needs no tests, as a doc does; a query or data file nothing
+ names keeps its full run (a test may glob it).
Other non-code files, dotfiles and root-level data configure tools, not
code, and keep their full run too.
@@ -43,6 +45,7 @@ import pathspec
from ..test_paths import is_test_related_path
from .test_selection import (
JS_SUFFIXES,
+ NO_TESTS_NEEDED,
PACKAGE_INIT_REASON,
PYTHON_SUFFIXES,
SHARED_TEST_DATA_REASON,
@@ -113,6 +116,10 @@ _OWNED = frozenset(
| {".css", ".scss", ".sass", ".less"}
| {".svg", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico"}
)
+# Prose that needs no tests when nothing names it and no package holds it, as
+# under ``docs/``. Not ``.txt``: outside docs it is mostly data read by
+# convention or a glob (a Spring ``banner.txt``, a dependency baseline).
+_PROSE = frozenset({".md", ".rst", ".adoc", ".markdown"})
# Assets only a naming file stands for: a test may glob a query or data file.
# Data only below the root: a root-level ``*.yaml`` or ``*.json`` configures a tool.
_NAMED_ONLY = frozenset({".scm", ".graphql", ".gql", ".sql"})
@@ -144,6 +151,11 @@ class Scope:
"""The files whose reaching tests the selection needs from the graph."""
return () if self.run_all else (*self.reach, *self.namers)
+ @property
+ def needs_no_tests(self) -> bool:
+ """Whether the file is skipped like documentation."""
+ return self.basis == NO_TESTS_NEEDED
+
def needs_namers(path: str, config: TestSelectionConfig) -> bool:
"""Whether :func:`trigger_scopes` needs to know who names *path*."""
@@ -215,6 +227,17 @@ class _Tree:
)
return self._under[key]
+ def beside_code(self, path: str) -> bool:
+ """Whether code shares *path*'s top-level directory (at the root: sits directly in it).
+
+ Prose there may be loaded by a directory walk (``src/pkg/prompts/*.md``
+ read by ``src/pkg/loader.py``), so it is not skipped.
+ """
+ parts = PurePosixPath(path).parts
+ if len(parts) == 1:
+ return any("/" not in p for p in self.code)
+ return bool(self.code_under(parts[0], ()))
+
def owner(self, path: str) -> str | None:
"""The deepest package root holding *path*, never the repository root."""
from ..ingestion.package_roots import module_for
@@ -335,6 +358,9 @@ def _named_scope(path: str, tree: _Tree, namers: tuple[str, ...]) -> Scope | Non
if too_many := _too_many(namers):
return Scope(f"it is named by {_some(namers)}", "named-by", run_all=too_many)
owner = tree.owner(path)
+ if not namers and owner is None and _suffix(path) in _PROSE and not tree.beside_code(path):
+ # Ceiling: a test globbing prose away from code is not seen, as under docs/.
+ return Scope("prose no code names and no package holds", NO_TESTS_NEEDED)
if namers and (owner is None or any(_is_under(n, owner) for n in namers)):
return Scope(f"it is named by {_some(namers)}", "named-by", namers=namers)
if owner is None or not (namers or _suffix(path) in _OWNED):
diff --git a/packages/core/src/repowise/core/analysis/test_ranking.py b/packages/core/src/repowise/core/analysis/test_ranking.py
index 01ec39fe0..bfc80c0fa 100644
--- a/packages/core/src/repowise/core/analysis/test_ranking.py
+++ b/packages/core/src/repowise/core/analysis/test_ranking.py
@@ -47,14 +47,15 @@ _TIER_WHY = {
"changed-test": "the change edits it",
"line": "the per-test map runs a changed line",
"file": "the per-test map runs a changed file",
- "direct": "its calls, a fixture or a direct import reach a changed file",
+ "direct": "its calls or a direct import reach a changed file",
"transitive": "reaches a changed file through other files",
"every-subset": "runs with every subset",
"rest": "not selected",
}
-# Vias where the test's own calls or fixtures reach the changed file (the call
-# walk takes a few hops; still nearer than an import closure).
-_DIRECT_VIAS = frozenset({"call-graph", "conftest-fixture"})
+# The via where the test's own calls reach the changed file (the call walk takes
+# a few hops; still nearer than an import closure). A conftest fixture reaches
+# it through the fixture module's imports, at module granularity: transitive.
+_DIRECT_VIA = "call-graph"
#: Where pytest records the node ids that failed in its last run. Its ids are
#: relative to pytest's rootdir, so a rootdir other than the repository root
@@ -159,7 +160,7 @@ def _graph_tier(row: Mapping[str, str], changed: set[str], hops: Mapping[str, in
return "transitive" # a route to the change, not a changed file
if row["via"] == "changed-test":
return "changed-test"
- if row["via"] in _DIRECT_VIAS or hops.get(row["test_file"]) == 1:
+ if row["via"] == _DIRECT_VIA or hops.get(row["test_file"]) == 1:
return "direct"
return "transitive"
diff --git a/packages/core/src/repowise/core/analysis/test_selection.py b/packages/core/src/repowise/core/analysis/test_selection.py
index 523fe4081..2348d1dfa 100644
--- a/packages/core/src/repowise/core/analysis/test_selection.py
+++ b/packages/core/src/repowise/core/analysis/test_selection.py
@@ -42,7 +42,8 @@ tests that import it, directly or through other helpers (basis
``helper-importers``), which are the files that run it: Python runs the
package file for each module in it, and pytest loads a conftest for each test
at or below it. Only documentation (``docs/`` and the root README, CHANGELOG,
-LICENSE and the like, never code) that no code names is skipped without a test.
+LICENSE and the like, never code), and Markdown, reST or AsciiDoc no package
+holds and no code sits beside, that no code names is skipped without a test.
A file whose reach is known runs a scope (:mod:`.selection_scopes`) in place of
everything: a manifest or lockfile its ecosystem's tests, a production
@@ -379,12 +380,20 @@ def _named_in(
"""The files of *by_name* that *path*'s *text* names (see :func:`file_namers`).
The text is scanned once per name held, whatever the number of files of
- that name.
+ that name. A mention in a comment or docstring names nothing: a widely
+ imported module citing a doc there would read as its reader and select
+ every test reaching it. Ceiling: a path read only through a docstring
+ (a doctest) is missed.
"""
+ from .fixture_readers import code_text
from .namer_paths import any_may_mean, mentions
- out: list[str] = []
folded = text.lower()
+ if not any(name.lower() in folded for name in by_name):
+ return [] # most sources hold no name: skip the comment strip
+ text = code_text(path, text)
+ folded = text.lower()
+ out: list[str] = []
for name, same in by_name.items():
if name.lower() not in folded:
continue
@@ -411,6 +420,7 @@ def plugin_loader(sources: Iterable[tuple[str, str]]) -> str | None:
return None
+NO_TESTS_NEEDED = "no-tests-needed"
PACKAGE_INIT_REASON = "every import of the package runs it, and those are not all tracked"
@@ -550,8 +560,11 @@ def select_tests(inp: SelectionInput) -> Selection:
"""Decide what a change must run (see the module docstring for the rules)."""
deleted = set(inp.deleted)
paths = sorted(set(inp.changed) | deleted)
- scoped = [p for p in paths if p in inp.scopes]
+ unneeded = [p for p in paths if p in inp.scopes and inp.scopes[p].needs_no_tests]
+ scoped = [p for p in paths if p in inp.scopes and p not in unneeded]
triage = _triage([p for p in paths if p not in inp.scopes], inp.config, inp.doc_readers)
+ triage.skipped = sorted([*triage.skipped, *unneeded])
+ triage.basis.update(dict.fromkeys(unneeded, NO_TESTS_NEEDED))
run_all = [*_empty_change_reasons(paths, inp.label), *triage.run_all]
walks = bool(triage.code) or any(inp.scopes[p].routes for p in scoped)
run_all += _index_reasons(inp, has_code=walks)
@@ -682,7 +695,7 @@ def _triage(
out.basis[path] = "full-run"
elif is_documentation(path):
out.skipped.append(path)
- out.basis[path] = "no-tests-needed"
+ out.basis[path] = NO_TESTS_NEEDED
elif is_test_related_path(path) and not is_code_file(path):
out.run_all.append(
f"{path} is in a test tree but is not code (data, a snapshot or a "
diff --git a/tests/unit/analysis/test_selection_scopes.py b/tests/unit/analysis/test_selection_scopes.py
index 7a95c83bd..443510a83 100644
--- a/tests/unit/analysis/test_selection_scopes.py
+++ b/tests/unit/analysis/test_selection_scopes.py
@@ -167,6 +167,24 @@ def test_an_asset_runs_what_names_it_or_its_package() -> None:
assert _scopes(["README.md"], {"README.md": ["pytest.ini"]}) == {}
+def test_prose_no_code_names_and_no_package_holds_needs_no_tests() -> None:
+ prose = ["site/content/guide.md", "UserGuide.md", ".github/CONTRIBUTING.md", "a/b.rst"]
+ sel = _select([*prose, "src/banner.txt", "site/error.html"])
+ assert sel.skipped_files == tuple(sorted(prose))
+ assert all(sel.basis[p] == "no-tests-needed" for p in prose)
+ # Data and templates still fail closed: they are read by convention or a glob.
+ assert sel.run_all
+ assert sel.reasons[0].startswith("site/error.html: no coverage")
+ assert sel.reasons[1].startswith("src/banner.txt: no coverage")
+ # Prose beside code in a single-package layout may be loaded by a directory
+ # walk (a prompt), so it fails closed too.
+ prompt = _select(["src/pkg/prompts/review.md"])
+ assert prompt.run_all and not prompt.skipped_files
+ # Named prose, and prose inside a package, keep their scope.
+ assert _scopes(["site/a.md"], {"site/a.md": ["src/other.py"]})["site/a.md"].basis == "named-by"
+ assert _scopes(["web/notes.md"])["web/notes.md"].basis == "owner-package"
+
+
def test_a_query_file_runs_the_tests_of_the_spec_naming_it() -> None:
query = "src/pkg/queries/python.scm"
scope = _scopes([query], {query: ["src/pkg/specs/python.py"]})[query]
@@ -216,7 +234,7 @@ def test_file_namers_lists_every_file_naming_one() -> None:
]
# A manifest is named only where a written directory can lead to it.
manifests = ["web/package.json", "other/package.json"]
- code = [("web/src/app.ts", "open('./web/package.json')"), ("x.py", '"package.json"')]
+ code = [("web/src/app.ts", "open('./web/package.json')"), ("x.py", 'P = "package.json"')]
exact = file_namers(manifests, code, lambda f: f.endswith("package.json"))
assert exact == {
"web/package.json": ["web/src/app.ts", "x.py"],
@@ -224,6 +242,22 @@ def test_file_namers_lists_every_file_naming_one() -> None:
}
+def test_a_mention_in_a_comment_or_docstring_names_nothing() -> None:
+ sources = [
+ ("src/hub.py", '"""Reasoning in docs/support.md."""\n# see rules.scm\nX = 1\n'),
+ ("src/hub.go", "// see docs/support.md\n/* and rules.scm */\nvar x = 1\n"),
+ ("src/spec.py", 'def f():\n """Loads a query."""\n return "rules.scm"\n'),
+ ("src/read.ts", 'readFileSync("docs/support.md") // the guide\n'),
+ # A "/*" in a string opens no comment, and a "#" line is code outside Python.
+ ("src/glob.ts", "const a = '/*'\nimport('./rules.scm')\nconst b = '**/*.ts'\n"),
+ ("src/lib.rs", '#![doc = include_str!("../docs/support.md")]\n'),
+ ]
+ assert file_namers(["docs/support.md", "q/rules.scm"], sources) == {
+ "docs/support.md": ["src/lib.rs", "src/read.ts"],
+ "q/rules.scm": ["src/glob.ts", "src/spec.py"],
+ }
+
+
def test_a_js_package_manifest_runs_its_tests_and_those_reaching_its_code() -> None:
sel = _select(["web/package.json"], _tiers(("web/src/app.ts", "tests/test_core.py")))
assert not sel.run_all, sel.reasons
diff --git a/tests/unit/analysis/test_test_ranking.py b/tests/unit/analysis/test_test_ranking.py
index bc5e4848b..8b2064e81 100644
--- a/tests/unit/analysis/test_test_ranking.py
+++ b/tests/unit/analysis/test_test_ranking.py
@@ -45,6 +45,7 @@ def test_tiers_follow_the_strength_of_the_evidence() -> None:
_row("a.py", "tests/test_call.py", "call-graph"),
_row("a.py", "tests/test_far.py", "import-graph"),
_row("route.py", "tests/test_route.py", "call-graph"),
+ _row("a.py", "tests/test_fixture.py", "conftest-fixture"),
],
}
tests = [
@@ -53,6 +54,7 @@ def test_tiers_follow_the_strength_of_the_evidence() -> None:
"tests/test_edit.py",
"tests/test_call.py",
"tests/test_far.py",
+ "tests/test_fixture.py",
"tests/test_route.py",
"tests/test_walker.py",
]
@@ -66,6 +68,8 @@ def test_tiers_follow_the_strength_of_the_evidence() -> None:
"tests/test_edit.py": "changed-test",
"tests/test_call.py": "direct",
"tests/test_far.py": "transitive",
+ # A fixture reaches the change through its module's imports, not its calls.
+ "tests/test_fixture.py": "transitive",
"tests/test_route.py": "transitive",
"tests/test_walker.py": "every-subset",
}
@@ -80,6 +84,7 @@ def test_tiers_follow_the_strength_of_the_evidence() -> None:
"tests/test_file.py::t",
"tests/test_call.py",
"tests/test_far.py",
+ "tests/test_fixture.py",
"tests/test_route.py",
"tests/test_walker.py",
]
diff --git a/tests/unit/cli/test_impacted_tests_cmd.py b/tests/unit/cli/test_impacted_tests_cmd.py
index eb551ae49..b6c77b098 100644
--- a/tests/unit/cli/test_impacted_tests_cmd.py
+++ b/tests/unit/cli/test_impacted_tests_cmd.py
@@ -450,7 +450,7 @@ def test_explain_names_the_changed_file_and_the_route(repo) -> None:
"Selected: src/a.py changed (import-graph).",
"Route: tests/test_a.py -> src/a.py",
# tests/test_a.py imports src/a.py: one hop, a direct edge.
- "Order: 1 of 1 (its calls, a fixture or a direct import reach a changed file; "
+ "Order: 1 of 1 (its calls or a direct import reach a changed file; "
"1 hop(s)).",
]
missed = _run(repo, "main...feat", "--explain", "./tests/test_b.py")
@@ -466,7 +466,7 @@ def test_explain_joins_the_json_report(repo) -> None:
"lines": [
"Selected: src/a.py changed (import-graph).",
"Route: tests/test_a.py -> src/a.py",
- "Order: 1 of 1 (its calls, a fixture or a direct import reach a changed file; "
+ "Order: 1 of 1 (its calls or a direct import reach a changed file; "
"1 hop(s)).",
],
"route": ["tests/test_a.py", "src/a.py"],
@@ -478,7 +478,7 @@ def test_explain_joins_the_json_report(repo) -> None:
"hops": 1,
"co_change": 0,
"failed_last_run": False,
- "reason": "its calls, a fixture or a direct import reach a changed file; 1 hop(s)",
+ "reason": "its calls or a direct import reach a changed file; 1 hop(s)",
},
}
assert data["selected"]["why"] == {"tests/test_a.py": "src/a.py changed (import-graph)"}
@@ -562,7 +562,7 @@ def test_selected_tests_run_in_order_and_a_last_failure_breaks_a_tie(repo) -> No
assert result.stdout == "tests/test_z.py tests/test_a.py\n"
explained = _run(repo, "main...feat", "--explain", "tests/test_z.py")
assert explained.stdout.splitlines()[-1] == (
- "Order: 1 of 2 (its calls, a fixture or a direct import reach a changed file; "
+ "Order: 1 of 2 (its calls or a direct import reach a changed file; "
"1 hop(s); failed in the last run)."
)