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(health): keep the test named for a file when a validation list is capped (#2515)

Raghav Chamadiyaa4c450d7c525
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
index 7a27ca17a..233692eb4 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
@@ -20,6 +20,7 @@ from repowise.core.analysis.health.grading import TARGET_SCORE
from repowise.core.analysis.test_reachability import (
ReachedBy,
load_test_files,
+ rank_tests,
tests_matching_by_name,
tests_reaching_by_tier,
)
@@ -380,7 +381,7 @@ def _validation_target(
identities_complete = (
reached is None or reached.all_tests is not None or total == len(labels)
)
- ordered = sorted(labels)
+ ordered = rank_tests(file_path, labels)
return (
ValidationTarget(
file_path=file_path,
@@ -405,13 +406,13 @@ def build_validation_plan(
"""Resolve target evidence in strict measured/call/import precedence."""
cap = max(0, test_limit)
target_rows: list[ValidationTarget] = []
- union: set[str] = set()
+ ranked: dict[str, None] = {}
identities_complete = True
for file_path, lines in sorted(_line_ranges(suggestion).items()):
target, labels, target_complete = _validation_target(
file_path, lines, measured, inferred, cap
)
- union.update(labels)
+ ranked.update(dict.fromkeys(rank_tests(file_path, labels)))
identities_complete = identities_complete and target_complete
target_rows.append(target)
@@ -424,7 +425,7 @@ def build_validation_plan(
aggregate_via: ValidationVia | None = (
None if not vias else next(iter(vias)) if len(vias) == 1 else "mixed"
)
- ordered_tests = sorted(union)
+ ordered_tests = list(ranked)
aggregate_total = (
len(ordered_tests)
if identities_complete
diff --git a/packages/core/src/repowise/core/analysis/test_reachability.py b/packages/core/src/repowise/core/analysis/test_reachability.py
index 9fdf8c1c8..ab7b396ed 100644
--- a/packages/core/src/repowise/core/analysis/test_reachability.py
+++ b/packages/core/src/repowise/core/analysis/test_reachability.py
@@ -196,6 +196,7 @@ __all__ = [
"call_graph_from_graph",
"files_reached_by_tests",
"load_test_files",
+ "rank_tests",
"tests_matching_by_name",
"tests_reaching",
"tests_reaching_by_tier",
@@ -211,9 +212,9 @@ class ReachedBy:
``total`` is how many the walk actually found, before
``MAX_TESTS_PER_TARGET`` trimmed ``tests``. A surface that prints
- ``len(tests)`` as the answer is stating a cap as a measurement, and the cut
- is alphabetical, so *which* ones survive is arbitrary. Carry the total and
- say the bound.
+ ``len(tests)`` as the answer is stating a cap as a measurement. The cut keeps
+ the test named for the target and its directory neighbours first
+ (:func:`rank_tests`). Carry the total and say the bound.
"""
tests: list[str]
@@ -386,7 +387,7 @@ async def tests_reaching_by_tier(
session, repo_id, seeds, test_files, call_depth, symbol_seeds=symbol_seeds
)
for seed, tests in found.items():
- ordered = tuple(sorted(tests))
+ ordered = tuple(rank_tests(seed, tests))
out[seed] = ReachedBy(
list(ordered[:MAX_TESTS_PER_TARGET]), "call-graph", len(ordered), ordered
)
@@ -395,7 +396,7 @@ async def tests_reaching_by_tier(
if unanswered and import_depth >= 1:
found = await _import_reaching(session, repo_id, unanswered, test_files, import_depth)
for seed, tests in found.items():
- ordered = tuple(sorted(tests))
+ ordered = tuple(rank_tests(seed, tests))
out[seed] = ReachedBy(
list(ordered[:MAX_TESTS_PER_TARGET]), "import-graph", len(ordered), ordered
)
@@ -579,6 +580,19 @@ async def _edges_into(
return [(s, t) for s, t in rows]
+def rank_tests(target: str, tests: Collection[str]) -> list[str]:
+ """*tests* with the one named for *target* first, then by how much of its directory
+ path each mirrors, so a capped list keeps the test most likely to exercise it."""
+ names = paired_test_names(target)
+ dirs = set(target.split("/")[:-1])
+
+ def key(test: str) -> tuple[bool, int, str]:
+ path = test.split("::", 1)[0]
+ return path.rsplit("/", 1)[-1] not in names, -len(dirs & set(path.split("/")[:-1])), test
+
+ return sorted(tests, key=key)
+
+
def tests_matching_by_name(targets: list[str], test_files: Collection[str]) -> dict[str, ReachedBy]:
"""Tests named for each target by convention: the fallback when no edge answered.
@@ -591,8 +605,8 @@ def tests_matching_by_name(targets: list[str], test_files: Collection[str]) -> d
by_name.setdefault(path.rsplit("/", 1)[-1], []).append(path)
out: dict[str, ReachedBy] = {}
for target in targets:
- found = sorted(
- path for name in paired_test_names(target) for path in by_name.get(name, ())
+ found = rank_tests(
+ target, [path for name in paired_test_names(target) for path in by_name.get(name, ())]
)
if found:
out[target] = ReachedBy(
diff --git a/tests/unit/health/test_paired_test_basenames.py b/tests/unit/health/test_paired_test_basenames.py
index 5a456b643..f30868320 100644
--- a/tests/unit/health/test_paired_test_basenames.py
+++ b/tests/unit/health/test_paired_test_basenames.py
@@ -155,13 +155,21 @@ class TestPascalPairing:
def test_name_match_tier_finds_tests_named_for_a_target_anywhere():
from repowise.core.analysis.test_reachability import tests_matching_by_name
- tests = {"tests/unit/test_jira_links.py", "tests/other/test_jira_links.py", "web/a.test.ts"}
+ tests = {"tests/unit/test_jira_links.py", "tests/app/test_jira_links.py", "web/a.test.ts"}
found = tests_matching_by_name(["app/jira_links.py", "web/a.ts", "app/none.py"], tests)
+ # Same name twice: the one whose directories mirror the target's leads.
assert found["app/jira_links.py"].tests == [
- "tests/other/test_jira_links.py",
+ "tests/app/test_jira_links.py",
"tests/unit/test_jira_links.py",
]
assert found["app/jira_links.py"].via == "name-match"
assert found["web/a.ts"].total == 1
assert "app/none.py" not in found
+
+
+def test_unnamed_tests_rank_by_the_directories_they_share_with_the_target():
+ from repowise.core.analysis.test_reachability import rank_tests
+
+ ranked = rank_tests("pkg/a/b/mod.py", ["pkg/x/test_other.py", "pkg/a/b/test_sibling.py"])
+ assert ranked == ["pkg/a/b/test_sibling.py", "pkg/x/test_other.py"]
diff --git a/tests/unit/health/test_recommendations.py b/tests/unit/health/test_recommendations.py
index 9b9685d2a..84db09e11 100644
--- a/tests/unit/health/test_recommendations.py
+++ b/tests/unit/health/test_recommendations.py
@@ -187,6 +187,13 @@ def test_capped_test_list_keeps_true_total_and_stable_order() -> None:
assert validation.targets[0].total == 9
+def test_the_test_named_for_the_file_survives_the_cap() -> None:
+ plan = _plan("named")
+ reached = ReachedBy(["tests/a/test_other.py", "tests/unit/test_core.py"], "import-graph", 2)
+ validation = build_validation_plan(plan, {}, {"src/core.py": reached}, test_limit=1)
+ assert validation.tests == ["tests/unit/test_core.py"]
+
+
def test_aggregate_validation_total_deduplicates_tests_across_targets() -> None:
plan = _plan("shared", file_path="src/a.py")
plan.blast_radius = {"files": ["src/b.py"]}