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.

refactor(refactoring): store JS/TS test commands in validation.test_runs (#3613)

Raghav Chamadiya375cb96c52af
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/batches.py b/packages/core/src/repowise/core/analysis/health/refactoring/batches.py
index 517fa7fd1..541e2ca27 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/batches.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/batches.py
@@ -12,7 +12,7 @@ from __future__ import annotations
from collections.abc import Mapping, Sequence
from typing import Any
-from .commands import commands_for_tests
+from .commands import commands_for_tests, stored_runs
#: The most stages one batch holds.
BATCH_MAX_STAGES = 5
@@ -74,15 +74,8 @@ def stage_batches(
return None
lead = [s["n"] for s in steps if s["n"] < numbers[0]]
tests, total = _batch_tests(detail)
- # Each test runs from the package the plan stored for it.
- packages = _validation(detail).get("js_packages")
- runs = _validation(detail).get("test_runs")
- commands = commands_for_tests(
- tests,
- total=total,
- packages=packages if isinstance(packages, Mapping) else None,
- runs=runs if isinstance(runs, Mapping) else None,
- )
+ # Each test runs the way the plan stored for it.
+ commands = commands_for_tests(tests, total=total, runs=stored_runs(_validation(detail)))
check = _check(tests, detail)
sizes = _sizes(len(numbers))
out: list[dict[str, Any]] = []
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/commands.py b/packages/core/src/repowise/core/analysis/health/refactoring/commands.py
index e438d9c38..3b1559beb 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/commands.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/commands.py
@@ -22,13 +22,6 @@ from ....ingestion.workspace_members import (
)
from ...test_selection import JS_SUFFIXES, PYTHON_SUFFIXES
-#: Each JS/TS test file's package: the directory (``""`` is the repository
-#: root) whose package.json declares a ``test`` script, or None when no
-#: package.json above the file does. A file the map does not hold is None too.
-#: JS keeps this map because it predates :data:`TestRuns`; folding it in is a
-#: follow-up that must keep reading plans stored with it.
-JsPackages = Mapping[str, str | None]
-
#: Each test (an id, or the file a capped list collapses to) of a language in
#: :data:`_RUNNERS`, mapped to ``[run, arg]``: the command that runs its package
#: from the repository root, and the argument narrowing it to the test's target,
@@ -129,22 +122,47 @@ def _declares_test(manifest: Path) -> bool:
return isinstance(script, str) and bool(script) and "no test specified" not in script
-def js_test_packages(
- root: Path, manifests: Mapping[str, frozenset[str]], tests: Iterable[str]
-) -> dict[str, str | None]:
- """The package that runs each JS/TS test in *tests*: the nearest package
- root (*manifests*, from :func:`scan_package_manifests`) whose package.json
- declares a test script. Blocking file reads: an async caller uses a thread.
- """
- repo = _Checkout(root, manifests)
+def _npm(owner: str) -> str:
+ return f"npm --prefix {_arg(owner)} test --" if owner else "npm test --"
- def accepts(directory: str) -> bool:
- return repo.memo(_declares_test, root / directory / "package.json")
- return {
- path: repo.owner(path, "package.json", accepts)
- for path in {_file(test) for test in tests if _is_js(test)}
- }
+def _js_run(repo: _Checkout, test: str) -> Run | None:
+ """``npm test`` from the nearest package whose package.json declares a
+ test script, on the test file's path relative to that package."""
+ path = _file(test)
+ owner = repo.owner(
+ path, "package.json", lambda d: repo.memo(_declares_test, repo.root / d / "package.json")
+ )
+ return None if owner is None else (_npm(owner), _arg(_relative(path, owner)))
+
+
+def js_root_runs(tests: Iterable[str]) -> dict[str, list[str | None]]:
+ """Each JS/TS test in *tests* run from the repository root: the guess when
+ no checkout is there to read its package from."""
+ return {path: [_npm(""), _arg(path)] for path in {_file(t) for t in tests if _is_js(t)}}
+
+
+def keeps_runs(tests: Iterable[str], runs: TestRuns) -> bool:
+ """Whether a plan stores its *runs* map: when it holds any, or is empty
+ beside a JS/TS test, so a later read does not take the plan for one stored
+ before runs existed and guess a root ``npm test`` (:func:`stored_runs`)."""
+ return bool(runs) or any(_is_js(test) for test in tests)
+
+
+def stored_runs(validation: Mapping[str, Any]) -> dict[str, list[str | None]]:
+ """The ``test_runs`` a stored *validation* holds, plus the run of each JS/TS
+ test a plan stored before JS joined them keeps in ``js_packages``. A plan
+ stored with neither ran its JS/TS tests from the root, and still does."""
+ runs = validation.get("test_runs")
+ if runs is None and validation.get("js_packages") is None:
+ tests = validation.get("tests")
+ return js_root_runs(t for t in tests if isinstance(t, str)) if isinstance(tests, list) else {}
+ out = {k: list(v) for k, v in runs.items()} if isinstance(runs, Mapping) else {}
+ packages = validation.get("js_packages")
+ for path, owner in packages.items() if isinstance(packages, Mapping) else ():
+ if isinstance(owner, str):
+ out.setdefault(path, [_npm(owner), _arg(_relative(path, owner))])
+ return out
#: NuGet ids that make a project a test project: the test SDK and each
@@ -282,14 +300,6 @@ def _dotnet_layout(root: Path, manifests: Mapping[str, frozenset[str]]) -> _Dotn
return _DotnetLayout(by_dir, referrers, test_projects, solution)
-def plan_packages(tests: Iterable[str], packages: JsPackages | None) -> dict[str, str | None]:
- """The part of *packages* a plan's *tests* use, stored on the plan so a
- later read (batches, a served plan) needs no checkout. Empty without a map."""
- if packages is None:
- return {}
- return {path: packages.get(path) for path in {_file(test) for test in tests if _is_js(test)}}
-
-
Run = tuple[str, str | None]
@@ -464,6 +474,7 @@ _RUNNERS: tuple[tuple[tuple[str, ...], Callable[[_Checkout, str], Run | None]],
((".java", ".kt"), _jvm_run),
((".rb",), _ruby_run),
((".cs",), _dotnet_run),
+ (JS_SUFFIXES, _js_run),
)
@@ -490,7 +501,8 @@ def _run_key(runs: TestRuns, test: str) -> str | None:
def plan_runs(tests: Iterable[str], runs: TestRuns | None) -> dict[str, list[str | None]]:
- """The part of *runs* a plan's *tests* use, stored like :func:`plan_packages`."""
+ """The part of *runs* a plan's *tests* use, stored on the plan so a later
+ read (batches, a served plan) needs no checkout."""
if runs is None:
return {}
keys = {key for test in tests if (key := _run_key(runs, test)) is not None}
@@ -522,29 +534,19 @@ def _package_commands(tests: list[str], runs: TestRuns) -> list[str]:
groups[run] = None
elif (args := groups.setdefault(run, set())) is not None:
args.add(arg)
- return [" ".join([run, *_merged(args or ())]) for run, args in sorted(groups.items())]
+ return [" ".join([run, *_merged(groups[run] or ())]) for run in sorted(groups, key=_order)]
-def _js_commands(tests: list[str], packages: JsPackages | None) -> list[str]:
- """``npm test`` from the package each test belongs to; a test no package
- can run gets no command. Without *packages* every test runs from the root."""
- groups: dict[str, list[str]] = {}
- for test in tests:
- owner = packages.get(_file(test)) if packages is not None else ""
- if owner is not None:
- groups.setdefault(owner, []).append(test[len(owner) + 1 :] if owner else test)
- return [
- ("npm test -- " if not owner else f"npm --prefix {_arg(owner)} test -- ")
- + " ".join(map(_arg, paths))
- for owner, paths in sorted(groups.items())
- ]
+def _order(run: str) -> tuple[bool, bool, str]:
+ # JS runs first and the root package's first among them, as before JS joined
+ # the runs: with no Python test, Fix first quotes this first command.
+ return not run.startswith("npm "), run != _npm(""), run
def commands_for_tests(
tests: list[str],
*,
total: int | None = None,
- packages: JsPackages | None = None,
runs: TestRuns | None = None,
) -> list[str]:
"""A command that runs at least everything the plan says validates it.
@@ -556,32 +558,28 @@ def commands_for_tests(
An empty list means the plan has no command to suggest. Every command names
its tests: with none found, a bare ``pytest`` or ``npm test`` would run a
- whole suite as if it guarded the change. A JS/TS test runs from the package
- whose ``test`` script owns it (*packages*), with its path relative to that
- package; a test no package.json can run gets no command. A Go, Rust, JVM,
- Ruby or C# test runs its package, or the narrower target *runs* names for it. Any
- other test, or one *runs* does not hold, gets none in place of a guess that
- would fail when run.
+ whole suite as if it guarded the change. A JS/TS, Go, Rust, JVM, Ruby or C#
+ test runs its package, or the narrower target *runs* names for it. Any other
+ test, or one *runs* does not hold, gets none in place of a guess that would
+ fail when run.
"""
if total is not None and total > len(tests):
tests = sorted({_file(test) for test in tests})
python_tests = sorted(test for test in tests if _file(test).endswith(PYTHON_SUFFIXES))
- js_tests = sorted(test for test in tests if _is_js(test))
commands: list[str] = []
if python_tests:
commands.append("pytest " + " ".join(map(_arg, python_tests)))
- commands.extend(_js_commands(js_tests, packages))
if runs:
commands.extend(_package_commands(tests, runs))
return commands
__all__ = [
- "JsPackages",
"TestRuns",
"commands_for_tests",
- "js_test_packages",
- "plan_packages",
+ "js_root_runs",
+ "keeps_runs",
"plan_runs",
"runs_for_tests",
+ "stored_runs",
]
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 d4cda67fa..9904a43f1 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
@@ -41,7 +41,7 @@ from repowise.core.code_origin import ship_rank
from repowise.core.test_paths import is_test_support_path, names_test_for, paired_test_names
from .annotations import PlanAnnotations, partner_rows
-from .commands import JsPackages, TestRuns, commands_for_tests, plan_packages, plan_runs
+from .commands import TestRuns, commands_for_tests, keeps_runs, plan_runs
from .models import RefactoringSuggestion
from .render import list_plan
@@ -309,10 +309,8 @@ class ValidationPlan:
# differs from the plan's, else ``None``; empty when none differs. Kept out
# of :meth:`as_dict`, which every list serves; plan detail reads it.
step_verify: list[dict[str, Any] | None] = field(default_factory=list)
- # The package each shown JS/TS test runs from (``commands.JsPackages``),
+ # How each shown JS/TS, Go, Rust, JVM, Ruby or C# test runs (``commands.TestRuns``),
# so a later read builds the same commands without a checkout.
- js_packages: dict[str, str | None] = field(default_factory=dict)
- # How each shown Go, Rust, JVM or Ruby test runs (``commands.TestRuns``).
test_runs: dict[str, list[str | None]] = field(default_factory=dict)
def as_dict(self) -> dict[str, Any]:
@@ -328,8 +326,7 @@ class ValidationPlan:
"targets": [target.as_dict() for target in self.targets],
"reasons": self.reasons,
"prerequisite": self.prerequisite,
- **({"js_packages": self.js_packages} if self.js_packages else {}),
- **({"test_runs": self.test_runs} if self.test_runs else {}),
+ **({"test_runs": self.test_runs} if keeps_runs(self.tests, self.test_runs) else {}),
}
@@ -347,8 +344,8 @@ class ValidationEvidence:
(``function_facts.tests_json``); an absent id was never mapped.
``hubs`` are the files no reach walk passes through (:func:`hub_files`), and
``siblings`` each directory's files, which decide whose test a name is.
- ``js_packages`` is the package each JS/TS test runs from; absent, from the root.
- ``test_runs`` is how each Go, Rust, JVM or Ruby test runs; absent, it gets no command.
+ ``test_runs`` is how each JS/TS, Go, Rust, JVM, Ruby or C# test runs; absent,
+ it gets no command.
"""
symbols: Mapping[str, Sequence[SymbolSpan]] = field(default_factory=dict)
@@ -357,7 +354,6 @@ class ValidationEvidence:
function_tests: Mapping[str, tuple[MappedTest, ...]] = field(default_factory=dict)
hubs: frozenset[str] = frozenset()
siblings: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
- js_packages: JsPackages | None = None
test_runs: TestRuns | None = None
@@ -919,14 +915,13 @@ def build_validation_plan(
# and it runs at least the tests the plan quotes.
commands = commands_for_tests(
sorted({test.split("::", 1)[0] for test in shown}),
- packages=facts.js_packages,
runs=facts.test_runs,
)
else:
shown = ordered_tests[:cap]
reasons = {test: best[test][1] for test in shown}
commands = commands_for_tests(
- shown, total=aggregate_total, packages=facts.js_packages, runs=facts.test_runs
+ shown, total=aggregate_total, runs=facts.test_runs
)
files = affected_files(suggestion)
return ValidationPlan(
@@ -940,7 +935,6 @@ def build_validation_plan(
commands=commands,
targets=target_rows,
reasons=reasons if order_tests else {},
- js_packages=plan_packages(shown, facts.js_packages),
test_runs=plan_runs(shown, facts.test_runs),
# Also when tests reach the file but none reaches a function it changes.
prerequisite=(
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/serving.py b/packages/core/src/repowise/core/analysis/health/refactoring/serving.py
index cdb4ac853..72b2e61ab 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/serving.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/serving.py
@@ -21,6 +21,7 @@ from repowise.core.analysis.health.effort import EFFORT_ORDER
from repowise.core.analysis.health.queue_rules import Facet, FilterRule, SortKeys
from repowise.core.analysis.health.rows import detail_map, field
+from .commands import stored_runs
from .recommendations import _loads_dict
# ``refactoring_view`` predates the opportunity. Both old values keep working
@@ -533,6 +534,7 @@ def validation_from_profile(profile: Mapping[str, Any]) -> Any:
for target in (profile.get("targets") or [])
if isinstance(target, dict)
]
+ values["test_runs"] = stored_runs(profile)
return ValidationPlan(**values)
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_recommendations.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_recommendations.py
index 8cf915df6..baa5ecdb2 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_recommendations.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_recommendations.py
@@ -18,9 +18,8 @@ from sqlalchemy import or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.refactoring.commands import (
- JsPackages,
TestRuns,
- js_test_packages,
+ js_root_runs,
runs_for_tests,
)
from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion
@@ -85,7 +84,7 @@ async def hydrate_recommendations(
read never rebuilds it and serves the plan-level answer. Finalize also
passes the repository's *findings*, so a plan that leaves a function at
the break-up bar is marked and ranked after the rest. Index-time callers
- pass the *checkout*, so each JS/TS test's command runs from its package.
+ pass the *checkout*, so each test's command runs from its package.
"""
if not rows:
return []
@@ -175,8 +174,8 @@ async def validation_inputs(
"""Measured coverage and the tiered reachability walk for every plan's files.
*in_degree* is the stored fan-in a caller already read; without it, read here.
- With the *checkout*, each JS/TS test's package is read, for the plans to
- store; without it, commands run from the repository root.
+ With the *checkout*, each test's package is read, for the plans to store;
+ without it, JS/TS tests run from the repository root and others get no command.
"""
measured = await tests_covering_files(session, repository_id, set(target_files))
@@ -213,7 +212,7 @@ async def validation_inputs(
path: _expand_scopes(path, reached, narrowed[path]) for path, reached in inferred.items()
}
hub_targets = [path for path in target_files if path in hubs]
- js_packages, runs = await _test_packages(checkout, test_files)
+ runs = await _test_runs(checkout, test_files)
evidence = await _validation_evidence(
session,
repository_id,
@@ -227,7 +226,6 @@ async def validation_inputs(
siblings=_siblings(in_degree),
symbols=await _symbol_spans(session, repository_id, target_files),
function_tests=await tests_in_files(session, repository_id, target_files),
- js_packages=js_packages,
test_runs=runs,
),
)
@@ -274,19 +272,14 @@ async def repository_checkout(session: AsyncSession, repository_id: str) -> str
return await session.scalar(select(Repository.local_path).where(Repository.id == repository_id))
-async def _test_packages(
- checkout: str | None, test_files: set[str]
-) -> tuple[JsPackages | None, TestRuns | None]:
+async def _test_runs(checkout: str | None, test_files: set[str]) -> TestRuns:
"""Where each test runs, from one scan of the checkout's package roots."""
root = Path(checkout) if checkout else None
if root is None or not root.is_dir():
- return None, None
+ return js_root_runs(test_files)
# The health pass already scanned this commit's package roots; this reuses it.
manifests = await asyncio.to_thread(scan_package_manifests, root)
- return (
- await asyncio.to_thread(js_test_packages, root, manifests, test_files),
- await asyncio.to_thread(runs_for_tests, root, manifests, test_files),
- )
+ return await asyncio.to_thread(runs_for_tests, root, manifests, test_files)
async def _symbol_spans(
diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.ts
index 97170053f..f246d3534 100644
--- a/packages/types/src/refactoring.ts
+++ b/packages/types/src/refactoring.ts
@@ -44,14 +44,10 @@ export interface RecommendationValidation {
/** Set when no test reaches the change: the step to take before the edit.
* Absent on a payload from an older server. */
prerequisite?: string | null;
- /** The package directory each shown JS/TS test runs from ("" is the root,
- * null when none can run it). Absent when the plan was validated without
- * a checkout or names no JS/TS test. */
- js_packages?: Record<string, string | null>;
- /** How each shown Go, Rust, JVM or Ruby test runs: the command that runs its
- * package from the repository root and the argument narrowing it to the
- * file's target (null runs the whole package). Absent when the plan was
- * validated without a checkout or names no such test. */
+ /** How each shown JS/TS, Go, Rust, JVM, Ruby or C# test runs: the command
+ * that runs its package from the repository root and the argument narrowing
+ * it to the test's target (null runs the whole package). Absent when the
+ * plan names no test any of them can run. */
test_runs?: Record<string, [string, string | null]>;
}
diff --git a/tests/unit/health/test_refactoring_commands.py b/tests/unit/health/test_refactoring_commands.py
index df8facff3..5f124c505 100644
--- a/tests/unit/health/test_refactoring_commands.py
+++ b/tests/unit/health/test_refactoring_commands.py
@@ -5,12 +5,14 @@ from __future__ import annotations
import json
from pathlib import Path
+import pytest
+
from repowise.core.agent_prompts import render_plan
from repowise.core.analysis.health.refactoring.batches import stage_batches
from repowise.core.analysis.health.refactoring.commands import (
commands_for_tests,
- js_test_packages,
- plan_packages,
+ js_root_runs,
+ runs_for_tests,
)
from repowise.core.analysis.health.refactoring.recommendations import (
ValidationEvidence,
@@ -22,8 +24,8 @@ from repowise.core.ingestion.package_roots import owning_package, scan_package_m
from tests.unit.health.test_recommendations import _plan
-def _packages(root: Path, tests: list[str]) -> dict[str, str | None]:
- return js_test_packages(root, scan_package_manifests(root), tests)
+def _runs(root: Path, tests: list[str]) -> dict[str, list[str | None]]:
+ return runs_for_tests(root, scan_package_manifests(root), tests)
def _package(root: Path, directory: str, scripts: dict[str, str] | None = None) -> None:
@@ -34,15 +36,17 @@ def _package(root: Path, directory: str, scripts: dict[str, str] | None = None)
NESTED = "ui-tui/src/__tests__/virtualHeights.test.ts"
+RUN = ["npm --prefix ui-tui test --", "src/__tests__/virtualHeights.test.ts"]
+COMMAND = "npm --prefix ui-tui test -- src/__tests__/virtualHeights.test.ts"
def test_nested_package_runs_from_its_own_directory(tmp_path: Path) -> None:
# The root declares workspaces but no test script, as in the reported repo.
_package(tmp_path, "", None)
_package(tmp_path, "ui-tui", {"test": "vitest run"})
- packages = _packages(tmp_path, [NESTED])
- assert packages == {NESTED: "ui-tui"}
- assert commands_for_tests([NESTED], packages=packages) == [
+ runs = _runs(tmp_path, [NESTED])
+ assert runs == {NESTED: RUN}
+ assert commands_for_tests([NESTED], runs=runs) == [
"npm --prefix ui-tui test -- src/__tests__/virtualHeights.test.ts"
]
@@ -50,9 +54,9 @@ def test_nested_package_runs_from_its_own_directory(tmp_path: Path) -> None:
def test_root_package_keeps_the_root_command(tmp_path: Path) -> None:
_package(tmp_path, "", {"test": "jest"})
tests = ["src/a.test.ts", "tests/test_b.py"]
- packages = _packages(tmp_path, tests)
- assert packages == {"src/a.test.ts": ""}
- assert commands_for_tests(tests, packages=packages) == [
+ runs = _runs(tmp_path, tests)
+ assert runs == {"src/a.test.ts": ["npm test --", "src/a.test.ts"]}
+ assert commands_for_tests(tests, runs=runs) == [
"pytest tests/test_b.py",
"npm test -- src/a.test.ts",
]
@@ -62,10 +66,9 @@ def test_nearest_package_without_a_script_defers_to_the_one_above(tmp_path: Path
_package(tmp_path, "web", {"test": "vitest run"})
_package(tmp_path, "web/packages/ink", None)
test = "web/packages/ink/src/x.test.tsx"
- packages = _packages(tmp_path, [f"{test}::renders"])
- assert packages == {test: "web"}
- assert commands_for_tests([f"{test}::renders"], packages=packages) == [
- "npm --prefix web test -- packages/ink/src/x.test.tsx::renders"
+ # npm takes the file; a name after ``::`` is no path it can run.
+ assert commands_for_tests([f"{test}::renders"], runs=_runs(tmp_path, [test])) == [
+ "npm --prefix web test -- packages/ink/src/x.test.tsx"
]
@@ -73,58 +76,123 @@ def test_no_package_with_a_test_script_gets_no_command(tmp_path: Path) -> None:
_package(tmp_path, "", {"test": 'echo "Error: no test specified" && exit 1'})
_package(tmp_path, "app", {"build": "tsc"})
tests = ["app/src/a.test.ts", "tests/test_b.py"]
- packages = _packages(tmp_path, tests)
- assert packages == {"app/src/a.test.ts": None}
- assert commands_for_tests(tests, packages=packages) == ["pytest tests/test_b.py"]
+ runs = _runs(tmp_path, tests)
+ assert runs == {}
+ assert commands_for_tests(tests, runs=runs) == ["pytest tests/test_b.py"]
def test_two_packages_get_one_command_each(tmp_path: Path) -> None:
_package(tmp_path, "web", {"test": "vitest run"})
_package(tmp_path, "ui-tui", {"test": "vitest run"})
tests = ["web/a.test.ts", NESTED]
- commands = commands_for_tests(tests, packages=_packages(tmp_path, tests))
+ commands = commands_for_tests(tests, runs=_runs(tmp_path, tests))
assert commands == [
"npm --prefix ui-tui test -- src/__tests__/virtualHeights.test.ts",
"npm --prefix web test -- a.test.ts",
]
+def test_the_root_package_runs_before_the_others() -> None:
+ runs = {
+ "web/b.test.ts": ["npm --prefix web test --", "b.test.ts"],
+ "src/a.test.ts": ["npm test --", "src/a.test.ts"],
+ "a_test.go": ["go test", "."],
+ }
+ assert commands_for_tests(sorted(runs), runs=runs) == [
+ "npm test -- src/a.test.ts",
+ "npm --prefix web test -- b.test.ts",
+ "go test .",
+ ]
+
+
def test_without_a_checkout_the_command_runs_from_the_root() -> None:
- assert commands_for_tests([NESTED]) == [f"npm test -- {NESTED}"]
- assert plan_packages([NESTED], None) == {}
+ runs = js_root_runs([NESTED, "tests/test_b.py"])
+ assert commands_for_tests([NESTED], runs=runs) == [f"npm test -- {NESTED}"]
def test_a_test_the_map_does_not_hold_gets_no_command() -> None:
- assert commands_for_tests(["web/a.test.ts", NESTED], packages={NESTED: "ui-tui"}) == [
- "npm --prefix ui-tui test -- src/__tests__/virtualHeights.test.ts"
- ]
+ assert commands_for_tests(["web/a.test.ts", NESTED], runs={NESTED: RUN}) == [COMMAND]
+ assert commands_for_tests([NESTED]) == []
def test_suffixes_decide_the_runner_not_substrings() -> None:
tests = ["fixtures/data.json", "fixtures/rows.jsonl", "stubs/mod.pyi", "tests/test_a.py"]
- assert commands_for_tests(tests, packages={}) == ["pytest tests/test_a.py"]
+ assert commands_for_tests(tests, runs={}) == ["pytest tests/test_a.py"]
-def test_a_path_with_a_space_is_quoted() -> None:
- packages = {"my app/a.test.ts": "my app"}
- assert commands_for_tests(["my app/a.test.ts", "tests/test b.py"], packages=packages) == [
+def test_a_path_with_a_space_is_quoted(tmp_path: Path) -> None:
+ _package(tmp_path, "my app", {"test": "jest"})
+ runs = _runs(tmp_path, ["my app/a.test.ts"])
+ assert commands_for_tests(["my app/a.test.ts", "tests/test b.py"], runs=runs) == [
'pytest "tests/test b.py"',
'npm --prefix "my app" test -- a.test.ts',
]
-def test_the_plan_stores_its_packages_and_reads_them_back() -> None:
+def test_the_plan_stores_its_runs_and_reads_them_back() -> None:
suggestion = _plan("estimatedMsgHeight", file_path="ui-tui/src/lib/virtualHeights.ts")
inferred = {suggestion.file_path: ReachedBy([NESTED], "import-graph", 1)}
plan = build_validation_plan(
- suggestion, {}, inferred, evidence=ValidationEvidence(js_packages={NESTED: "ui-tui"})
+ suggestion, {}, inferred, evidence=ValidationEvidence(test_runs={NESTED: RUN})
)
- assert plan.commands == ["npm --prefix ui-tui test -- src/__tests__/virtualHeights.test.ts"]
+ assert plan.commands == [COMMAND]
stored = plan.as_dict()
- assert stored["js_packages"] == {NESTED: "ui-tui"}
- assert validation_from_profile(stored).js_packages == {NESTED: "ui-tui"}
- unmapped = build_validation_plan(suggestion, {}, inferred)
- assert "js_packages" not in unmapped.as_dict()
+ assert stored["test_runs"] == {NESTED: RUN}
+ assert "js_packages" not in stored
+ assert validation_from_profile(stored).test_runs == {NESTED: RUN}
+ # Built without a run for its JS test, the plan says so, so no read guesses one.
+ unmapped = build_validation_plan(suggestion, {}, inferred).as_dict()
+ assert unmapped["commands"] == [] and unmapped["test_runs"] == {}
+ assert validation_from_profile(unmapped).test_runs == {}
+ assert stage_batches(
+ {"refactoring_type": "extract_method", "validation": unmapped},
+ [{"n": n, "action": "extract"} for n in range(1, 8)],
+ )[0]["commands"] == []
+
+
+def test_a_plan_stored_with_neither_map_runs_its_js_tests_from_the_root() -> None:
+ # Stored before either map existed, or without a checkout: main ran it from the root.
+ legacy = {
+ "basis": "inferred",
+ "via": "import-graph",
+ "total": 2,
+ "tests": [NESTED, "tests/test_b.py"],
+ "truncated": False,
+ "affected_files": [],
+ "affected_symbols": [],
+ "commands": [],
+ }
+ root = {NESTED: ["npm test --", NESTED]}
+ assert validation_from_profile(legacy).test_runs == root
+ batches = stage_batches(
+ {"refactoring_type": "extract_method", "validation": legacy},
+ [{"n": n, "action": "extract"} for n in range(1, 8)],
+ )
+ assert batches is not None
+ assert batches[0]["commands"] == ["pytest tests/test_b.py", f"npm test -- {NESTED}"]
+
+
+def test_a_plan_stored_with_js_packages_serves_the_same_runs() -> None:
+ # A plan stored before JS runs joined ``test_runs`` keeps its package map.
+ legacy = {
+ "basis": "inferred",
+ "via": "import-graph",
+ "total": 3,
+ "tests": [NESTED, "src/a.test.ts", "app/b.test.ts"],
+ "truncated": False,
+ "affected_files": [],
+ "affected_symbols": [],
+ "commands": [],
+ "js_packages": {NESTED: "ui-tui", "src/a.test.ts": "", "app/b.test.ts": None},
+ "test_runs": {"a_test.go": ["go test", "."]},
+ }
+ served = validation_from_profile(legacy).as_dict()
+ assert "js_packages" not in served
+ assert served["test_runs"] == {
+ NESTED: RUN,
+ "src/a.test.ts": ["npm test --", "src/a.test.ts"],
+ "a_test.go": ["go test", "."],
+ }
def test_a_plan_no_package_can_run_renders_without_a_run_block() -> None:
@@ -139,7 +207,7 @@ def test_a_plan_no_package_can_run_renders_without_a_run_block() -> None:
"validation": {
"tests": ["app/src/a.test.ts"],
"total": 1,
- "commands": commands_for_tests(["app/src/a.test.ts"], packages={}),
+ "commands": commands_for_tests(["app/src/a.test.ts"], runs={}),
"basis": "inferred",
},
}
@@ -149,23 +217,19 @@ def test_a_plan_no_package_can_run_renders_without_a_run_block() -> None:
assert "Run:" not in text and "```" not in text
-def test_a_batch_runs_its_tests_from_the_plans_package() -> None:
+ "stored", [{"test_runs": {NESTED: RUN}}, {"js_packages": {NESTED: "ui-tui"}}]
+)
+def test_a_batch_runs_its_tests_from_the_plans_package(stored: dict) -> None:
tests = [f"{NESTED}::case{n}" for n in range(4)]
detail = {
"refactoring_type": "extract_method",
- "validation": {
- "tests": tests,
- "total": 4,
- "commands": ["npm --prefix ui-tui test -- src/__tests__/virtualHeights.test.ts"],
- "js_packages": {NESTED: "ui-tui"},
- },
+ "validation": {"tests": tests, "total": 4, "commands": [COMMAND], **stored},
}
steps = [{"n": n, "action": "extract"} for n in range(1, 8)]
batches = stage_batches(detail, steps)
assert batches is not None
- assert batches[0]["commands"] == [
- "npm --prefix ui-tui test -- src/__tests__/virtualHeights.test.ts"
- ]
+ assert batches[0]["commands"] == [COMMAND]
def test_the_owner_lookup_takes_any_manifest() -> None:
diff --git a/tests/unit/health/test_refactoring_commands_dotnet.py b/tests/unit/health/test_refactoring_commands_dotnet.py
index 36b1e6d22..2a8da096c 100644
--- a/tests/unit/health/test_refactoring_commands_dotnet.py
+++ b/tests/unit/health/test_refactoring_commands_dotnet.py
@@ -7,7 +7,6 @@ from pathlib import Path
from repowise.core.analysis.health.refactoring.batches import stage_batches
from repowise.core.analysis.health.refactoring.commands import (
commands_for_tests,
- plan_packages,
plan_runs,
runs_for_tests,
)
@@ -174,8 +173,6 @@ def test_the_plan_stores_its_run_and_reads_it_back(tmp_path: Path) -> None:
assert stored["test_runs"] == {CART_TESTS: [run, None]}
assert "js_packages" not in stored
assert validation_from_profile(stored).test_runs == stored["test_runs"]
- # The JS map holds no C# test.
- assert plan_packages([CART_TESTS], {}) == {}
assert plan_runs([CART_TESTS, "tests/test_a.py"], runs) == stored["test_runs"]
diff --git a/tests/unit/health/test_refactoring_package_commands.py b/tests/unit/health/test_refactoring_package_commands.py
index 2c4c3aa7a..e36b8e083 100644
--- a/tests/unit/health/test_refactoring_package_commands.py
+++ b/tests/unit/health/test_refactoring_package_commands.py
@@ -254,15 +254,15 @@ def test_the_wire_type_lists_every_stored_validation_field() -> None:
fields = set(re.findall(r"^\s*(\w+)\??:", body, re.MULTILINE))
plan = ValidationPlan(
"unknown", None, 0, [], False, [], [], [],
- js_packages={"a.test.ts": ""}, test_runs={"a_test.go": ["go test", "."]},
+ test_runs={"a_test.go": ["go test", "."]},
)
assert fields == set(plan.as_dict())
def test_python_and_js_commands_are_unchanged_beside_other_languages() -> None:
- runs = {"a/a_test.go": ["go test", "./a"]}
+ runs = {"a/a_test.go": ["go test", "./a"], "web/a.test.ts": ["npm test --", "web/a.test.ts"]}
tests = ["tests/test_a.py", "web/a.test.ts", "a/a_test.go"]
- assert commands_for_tests(tests, packages={"web/a.test.ts": ""}, runs=runs) == [
+ assert commands_for_tests(tests, runs=runs) == [
"pytest tests/test_a.py",
"npm test -- web/a.test.ts",
"go test ./a",