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
feat(refactoring): run a plan's C# tests with dotnet test (#3583)
Raghav Chamadiya784b80e68ae8
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex ae267ce64..e3d7ca9b0 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -77,6 +77,10 @@ Go, Rust, Java, Kotlin and Ruby tests get a command too, for the package that owthem: `go test ./internal/cart`, `cargo test -p parser`, `./mvnw -pl core -am test`or `./gradlew :app:test`, and `bundle exec rspec` or `bundle exec rake test`. A testwhose build file or runner the repository does not have gets no command.+A C# test runs `dotnet test` on the test project that holds it+(`dotnet test tests/Shop.Tests/Shop.Tests.csproj`), narrowed with `--filter` to+the named tests, or on the repository's solution when no single test project+does. With neither, the plan has no command.In a plan with several steps, such as a performance fix at several call sites,plan detail adds a `verify` to each step whose tests differ from the plan's: thediff --git a/packages/core/src/repowise/core/analysis/health/refactoring/commands.py b/packages/core/src/repowise/core/analysis/health/refactoring/commands.pyindex 742413433..e438d9c38 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/commands.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/commands.py@@ -12,7 +12,8 @@ from pathlib import Pathfrom typing import Anyfrom ....ingestion.external_systems.maven_model import load_maven_reactor-from ....ingestion.package_roots import owning_package+from ....ingestion.package_roots import module_for, owning_package+from ....ingestion.resolvers.dotnet.msbuild import MSBuildProject, parse_csprojfrom ....ingestion.resolvers.jvm_gradle import parse_settingsfrom ....ingestion.workspace_members import (declared_workspace_members,@@ -37,6 +38,8 @@ JsPackages = Mapping[str, str | None]#: gets no command.TestRuns = Mapping[str, Sequence[str | None]]+_SOLUTIONS = (".sln", ".slnx")+def _file(test: str) -> str:return test.split("::", 1)[0]@@ -83,6 +86,10 @@ class _Checkout:path, self.manifests, name, accepts or (lambda directory: self.has(directory, name)))+ @cached_property+ def dotnet(self) -> _DotnetLayout:+ return _dotnet_layout(self.root, self.manifests)+@cached_propertydef cargo_members(self) -> set[str]:return declared_workspace_members(self.root).get("Cargo.toml", set())@@ -140,6 +147,141 @@ def js_test_packages(}+#: NuGet ids that make a project a test project: the test SDK and each+#: framework's runner.+_TEST_PACKAGES = frozenset(+ {+ "microsoft.net.test.sdk",+ "mstest",+ "mstest.testadapter",+ "nunit3testadapter",+ "tunit",+ "xunit",+ "xunit.runner.visualstudio",+ "xunit.v3",+ "xunit.v3.mtp-v1",+ "xunit.v3.mtp-v2",+ }+)+#: MSBuild files every project below their directory imports.+_SHARED_BUILD_FILES = ("Directory.Build.props", "Directory.Build.targets")+#: The .NET test project naming convention (``Shop.Tests``, ``Shop.UnitTests``,+#: ``Shop.Test``, ``Shop.Specs``).+_TEST_PROJECT_NAME = re.compile(r"(Tests|\.Test|\.Specs)$", re.IGNORECASE)+++def _declares_tests(is_test_project: bool, packages: Iterable[str]) -> bool:+ return is_test_project or not _TEST_PACKAGES.isdisjoint(p.lower() for p in packages)+++def _shared_declares_tests(root: Path, directory: str, seen: dict[str, bool]) -> bool:+ """Whether a ``Directory.Build`` file in *directory* declares tests outside+ any ``Condition``, each directory read once per call (*seen*)."""+ if directory not in seen:+ parsed = [+ parse_csproj(root / directory / name)+ for name in _SHARED_BUILD_FILES+ if (root / directory / name).is_file()+ ]+ seen[directory] = any(+ _declares_tests(p.is_test_project, p.unconditional_package_references)+ for p in parsed+ if p is not None+ )+ return seen[directory]+++def _declared_test_project(+ root: Path, project: str, parsed: MSBuildProject, seen: dict[str, bool]+) -> bool:+ """Whether *project* (*parsed*) says it runs tests, itself or through a+ shared build file on its path from the repository root."""+ if _declares_tests(parsed.is_test_project, parsed.package_references):+ return True+ parts = project.split("/")[:-1]+ return any(+ _shared_declares_tests(root, "/".join(parts[:i]), seen) for i in range(len(parts) + 1)+ )+++def _project_graph(root: Path, projects: list[str]) -> tuple[dict[str, set[str]], set[str]]:+ """Over *projects* (repo-relative ``.csproj`` paths): each referenced one+ mapped to the projects whose ``ProjectReference`` names it, and the+ projects that declare tests (:func:`_declared_test_project`).+ Ceiling: one parse per project and shared build file, per call."""+ by_path = {(root / project).resolve(): project for project in projects}+ referrers: dict[str, set[str]] = {}+ declared: set[str] = set()+ seen: dict[str, bool] = {}+ for project in projects:+ parsed = parse_csproj(root / project)+ if parsed is None:+ continue+ if _declared_test_project(root, project, parsed, seen):+ declared.add(project)+ for target in parsed.project_references:+ if target in by_path:+ referrers.setdefault(by_path[target], set()).add(project)+ return referrers, declared+++def _root_files(root: Path) -> tuple[list[str], str | None]:+ """The ``.csproj`` files at the repository root, which the package scan+ leaves out, and its solution: the only one, or the one named after the+ checkout; None when there is none or the choice is a guess."""+ try:+ names = sorted(p.name for p in root.iterdir())+ except OSError:+ return [], None+ projects = [name for name in names if name.lower().endswith(".csproj")]+ solutions = [name for name in names if Path(name).suffix.lower() in _SOLUTIONS]+ if len(solutions) > 1:+ solutions = [name for name in solutions if Path(name).stem.lower() == root.name.lower()]+ return projects, solutions[0] if len(solutions) == 1 else None+++def _test_project(path: str, layout: _DotnetLayout) -> str | None:+ """The test project that runs C# file *path*: the one project in its+ directory (the root's when no deeper one holds it) when it declares tests+ or is named as a test project, else the only project declaring tests that+ references it (*path* is in a test helper library); None otherwise. An app+ or library with neither signal runs no tests."""+ by_dir = layout.by_dir+ owner = module_for(path, by_dir.keys())+ projects = by_dir.get(owner, []) if owner in by_dir else by_dir.get("", [])+ if len(projects) != 1:+ return None+ if projects[0] in layout.test_projects or _TEST_PROJECT_NAME.search(Path(projects[0]).stem):+ return projects[0]+ users = [u for u in layout.referrers.get(projects[0], ()) if u in layout.test_projects]+ return users[0] if len(users) == 1 else None+++@dataclass(frozen=True)+class _DotnetLayout:+ """A checkout's C# projects (``by_dir``: directory to ``.csproj`` paths,+ ``""`` for the root), who references whom, the test projects, and the+ root solution."""++ by_dir: dict[str, list[str]]+ referrers: dict[str, set[str]]+ test_projects: set[str]+ solution: str | None+++def _dotnet_layout(root: Path, manifests: Mapping[str, frozenset[str]]) -> _DotnetLayout:+ """The layout from the ``.csproj`` names *manifests* (the package scan)+ records, plus the root's own files, which the scan leaves out."""+ root_projects, solution = _root_files(root)+ by_dir: dict[str, list[str]] = {"": root_projects} if root_projects else {}+ for directory, names in manifests.items():+ for name in sorted(names):+ if name.lower().endswith(".csproj"):+ by_dir.setdefault(directory, []).append(f"{directory}/{name}")+ referrers, test_projects = _project_graph(root, [p for ps in by_dir.values() for p in ps])+ 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 alater read (batches, a served plan) needs no checkout. Empty without a map."""@@ -292,6 +434,27 @@ def _ruby_run(repo: _Checkout, test: str) -> Run | None:return None+def _dotnet_filter(test: str) -> str | None:+ """``Class.Method`` for a ``file::...::Class::Method`` id: a substring of+ the test's fully qualified name, so a namespace or an outer class in front+ still matches. None for a file, or a name the filter syntax would misread."""+ name = ".".join(test.split("::")[1:][-2:])+ return name if re.fullmatch(r"\w+(\.\w+)?", name) else None+++def _dotnet_run(repo: _Checkout, test: str) -> Run | None:+ """``dotnet test`` on the test project holding the test (else the root+ solution), filtered to the named test. Coverage collection is off: a+ coverage gate (coverlet's threshold) fails any filtered run."""+ project = _test_project(_file(test), repo.dotnet) or repo.dotnet.solution+ if project is None:+ return None+ name = _dotnet_filter(test)+ return f"dotnet test {_arg(project)} -p:CollectCoverage=false", (+ f"--filter={name}" if name else None+ )++#: Test-file suffixes and the function naming the run, per language whose#: runner works per package. A runner gets the whole test id, ``::`` name#: included, so one that can select a single test can narrow to it.@@ -300,6 +463,7 @@ _RUNNERS: tuple[tuple[tuple[str, ...], Callable[[_Checkout, str], Run | None]],((".rs",), _rust_run),((".java", ".kt"), _jvm_run),((".rb",), _ruby_run),+ ((".cs",), _dotnet_run),)@@ -394,8 +558,8 @@ def commands_for_tests(its tests: with none found, a bare ``pytest`` or ``npm test`` would run awhole suite as if it guarded the change. A JS/TS test runs from the packagewhose ``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 or- Ruby test runs its package, or the narrower target *runs* names for it. Any+ 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. Anyother test, or one *runs* does not hold, gets none in place of a guess thatwould fail when run."""diff --git a/packages/core/src/repowise/core/ingestion/languages/registry.py b/packages/core/src/repowise/core/ingestion/languages/registry.pyindex 53c5487b1..f71b1ea12 100644--- a/packages/core/src/repowise/core/ingestion/languages/registry.py+++ b/packages/core/src/repowise/core/ingestion/languages/registry.py@@ -209,6 +209,10 @@ class LanguageRegistry:if f not in s.build_config_manifests)+ def package_manifest_globs(self) -> frozenset[str]:+ """Glob patterns that mark their directory as a package root (``*.csproj``)."""+ return frozenset(g for s in self._specs.values() for g in s.manifest_globs)+def blocked_dirs(self) -> frozenset[str]:"""Return the union of all per-language blocked directories."""return frozenset(d for s in self._specs.values() for d in s.blocked_dirs)diff --git a/packages/core/src/repowise/core/ingestion/languages/spec.py b/packages/core/src/repowise/core/ingestion/languages/spec.pyindex 7ff4d26f8..1bfd34a92 100644--- a/packages/core/src/repowise/core/ingestion/languages/spec.py+++ b/packages/core/src/repowise/core/ingestion/languages/spec.py@@ -138,6 +138,10 @@ class LanguageSpec:# -- Ecosystem -------------------------------------------------------entry_point_patterns: tuple[str, ...] = () # ("main.py", "app.py")manifest_files: tuple[str, ...] = () # ("pyproject.toml",)+ # Package manifests whose name varies per package, as globs matched+ # case-insensitively by the package-root scan only. Exact-name readers of+ # ``manifest_files`` never see them.+ manifest_globs: tuple[str, ...] = () # ("*.csproj",)# The subset of ``manifest_files`` that configures a build rather than# declaring a distributable unit. Every name in ``manifest_files`` and not# here is a *package root*: it marks its directory as a package boundarydiff --git a/packages/core/src/repowise/core/ingestion/languages/specs/csharp.py b/packages/core/src/repowise/core/ingestion/languages/specs/csharp.pyindex 8f1d7c518..c656c613f 100644--- a/packages/core/src/repowise/core/ingestion/languages/specs/csharp.py+++ b/packages/core/src/repowise/core/ingestion/languages/specs/csharp.py@@ -51,6 +51,7 @@ SPEC = LanguageSpec("nuget.config","NuGet.Config",),+ manifest_globs=("*.csproj",),# None of these declare a package — the .csproj does. They are MSBuild /# NuGet settings that sit at a solution root and are re-declared under# tests/, templates/ and misc/, so treating them as package roots woulddiff --git a/packages/core/src/repowise/core/ingestion/package_roots.py b/packages/core/src/repowise/core/ingestion/package_roots.pyindex 1efda8caa..81f6fcc2c 100644--- a/packages/core/src/repowise/core/ingestion/package_roots.py+++ b/packages/core/src/repowise/core/ingestion/package_roots.py@@ -15,19 +15,21 @@ monorepos silently got the top-level-directory fallback. Reading the manifests'*paths* off disk needs no parse, no embedding and no ingestion: a package rootis a directory name, and nothing here opens a manifest.-.NET is **not** among the languages this fixes, and deliberately so: the file-that declares a .NET package is the ``.csproj``, which is a glob and therefore-cannot live in a spec's exact-filename ``manifest_files``. Every name C# does-declare is MSBuild/NuGet configuration and is excluded as such, so C#-contributes no package roots and a .NET monorepo keeps the top-level fallback.-Closing that needs glob support in the manifest list, which is its own change.+A manifest whose name varies per package, the .NET ``.csproj``, is a glob+(:meth:`LanguageRegistry.package_manifest_globs`) matched in the same walk, and+the scan records the matching file names (``Shop.csproj``). Exact-name readers+of the manifest list (monorepo detection among them) never see these names."""from __future__ import annotations+import fnmatchimport os+import reimport subprocess-from collections.abc import Callable, Mapping+from collections.abc import Callable, Collection, Mapping+from collections.abc import Set as AbstractSet+from functools import cachefrom pathlib import Pathfrom ..fs_walk import walk_repo@@ -39,6 +41,20 @@ def package_manifest_names() -> frozenset[str]:return _LANG_REGISTRY.package_manifest_filenames()+@cache+def _glob_manifest() -> Callable[[str], re.Match[str] | None]:+ """Matches a file name against every manifest glob, ignoring case."""+ globs = sorted(_LANG_REGISTRY.package_manifest_globs())+ if not globs:+ return lambda _name: None+ return re.compile("|".join(map(fnmatch.translate, globs)), re.IGNORECASE).match+++def _manifests_in(filenames: Collection[str], names: frozenset[str]) -> frozenset[str]:+ """The package manifests among *filenames*: exact *names* and glob matches."""+ return names.intersection(filenames).union(filter(_glob_manifest(), filenames))++def _default_prune(repo_root: Path) -> Callable[[Path], bool]:"""Traversal's own boundary test, imported lazily to avoid a cycle.@@ -152,14 +168,14 @@ def _walk_manifests(dirnames[:] = [d for d in dirnames if not prune(rel_dir / d)]if rel_dir == Path():continue- matched = names.intersection(filenames)+ matched = _manifests_in(filenames, names)if matched:roots[rel_dir.as_posix()] = matchedreturn roots-def module_for(rel_path: str, package_roots: set[str]) -> str | None:+def module_for(rel_path: str, package_roots: AbstractSet[str]) -> str | None:"""The package boundary *rel_path* belongs to, or its top-level directory.``module`` is the directory/package axis and nothing else. It used to be@@ -229,6 +245,6 @@ def package_roots_from_paths(all_paths: set[str]) -> set[str]:if "/" not in norm:continuehead, base = norm.rsplit("/", 1)- if base in names:+ if _manifests_in((base,), names):roots.add(head)return rootsdiff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.pyindex 5b06e8bbd..e42a7ba33 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py@@ -68,6 +68,13 @@ class MSBuildProject:#: same as an explicit <IsPackable>false</IsPackable>.is_packable: bool | None = Nonegenerate_package_on_build: bool = False+ #: A literal ``<IsTestProject>true</IsTestProject>`` outside any+ #: ``Condition``, or the MSTest SDK, which sets it.+ is_test_project: bool = False+ #: The ``package_references`` declared outside any ``Condition``: a shared+ #: build file that adds test packages only ``Condition="'$(IsTestProject)'+ #: == 'true'"`` does not make every project below it a test project.+ unconditional_package_references: set[str] = field(default_factory=set)@propertydef name(self) -> str:@@ -119,6 +126,16 @@ def _compile_items(include: str | None) -> list[str]:return [item for item in items if item and "*" not in item]+def _conditioned(root: ET.Element) -> set[int]:+ """Ids of the elements a ``Condition`` applies to, itself or an ancestor's."""+ return {+ id(element)+ for scope in root.iter()+ if scope.get("Condition") is not None+ for element in scope.iter()+ }++def parse_csproj(csproj_path: Path) -> MSBuildProject | None:"""Parse a single .csproj file. Returns None on parse failure."""try:@@ -129,6 +146,8 @@ def parse_csproj(csproj_path: Path) -> MSBuildProject | None:project = MSBuildProject(path=csproj_path.resolve(), project_dir=csproj_path.parent.resolve())root = tree.getroot()+ project.is_test_project = "mstest.sdk" in (root.get("Sdk") or "").lower()+ conditioned = _conditioned(root)for elem in root.iter():tag = _local(elem.tag)@@ -148,6 +167,8 @@ def parse_csproj(csproj_path: Path) -> MSBuildProject | None:project.is_packable = packableelif tag == "GeneratePackageOnBuild" and elem.text:project.generate_package_on_build = _bool(elem.text)+ elif tag == "IsTestProject" and elem.text and id(elem) not in conditioned:+ project.is_test_project = _bool(elem.text)elif tag == "ProjectReference":include = elem.get("Include")if include:@@ -162,6 +183,8 @@ def parse_csproj(csproj_path: Path) -> MSBuildProject | None:pkg = elem.get("Include")if pkg:project.package_references.add(pkg.strip())+ if id(elem) not in conditioned:+ project.unconditional_package_references.add(pkg.strip())elif tag in ("Using", "Import"):# <Using Include="X"/> is the C# form, <Import Include="X"/> the VB# one; MSBuild's own <Import Project="..."/> carries no Include.diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.pyindex d7afaf47e..c51beb3d0 100644--- a/packages/core/src/repowise/core/ingestion/traverser.py+++ b/packages/core/src/repowise/core/ingestion/traverser.py@@ -285,7 +285,8 @@ _BLOCKED_FILENAME_SPEC: pathspec.PathSpec = pathspec.PathSpec.from_lines(_GENERATED_SUFFIXES: tuple[str, ...] = tuple(_LANG_REGISTRY.generated_suffixes())# Package-root manifests for monorepo detection, from the language registry.-# .NET is absent: its ``.csproj`` glob is not an exact filename.+# Exact names only: a .NET project (``*.csproj``) is a package root for module+# attribution but not a monorepo package, which reads a manifest by its name._MANIFEST_FILES: frozenset[str] = _LANG_REGISTRY.package_manifest_filenames()# Entry-point evidence from the registry: exact filenames, "*"-prefixed@@ -861,8 +862,8 @@ class FileTraverser:for rel_pkg, found in sorted(self.package_manifests().items()):pkg_dir = self.repo_root / rel_pkg- manifests = sorted(found)- if is_test_or_example_path(f"{rel_pkg}/{manifests[0]}"):+ manifests = sorted(found & _MANIFEST_FILES)+ if not manifests or is_test_or_example_path(f"{rel_pkg}/{manifests[0]}"):continuedeclaring = [m for m in manifests if rel_pkg in members.get(m, ())]if not declaring and (diff --git a/tests/unit/health/test_refactoring_commands_dotnet.py b/tests/unit/health/test_refactoring_commands_dotnet.pynew file mode 100644index 000000000..36b1e6d22--- /dev/null+++ b/tests/unit/health/test_refactoring_commands_dotnet.py@@ -0,0 +1,265 @@+"""A plan's C# tests run through ``dotnet test`` on the test project that holds them."""++from __future__ import annotations++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,+)+from repowise.core.analysis.health.refactoring.recommendations import (+ ValidationEvidence,+ build_validation_plan,+)+from repowise.core.analysis.health.refactoring.serving import validation_from_profile+from repowise.core.analysis.test_reachability import ReachedBy+from repowise.core.ingestion.package_roots import scan_package_manifests+from tests.unit.health.test_recommendations import _plan++SHOP = "src/Shop/Shop.csproj"+TESTS = "tests/Shop.Tests/Shop.Tests.csproj"+CART_TESTS = "tests/Shop.Tests/CartTests.cs"+XUNIT = '<PackageReference Include="Microsoft.NET.Test.Sdk" /><PackageReference Include="xunit" />'+NO_COVERAGE = "-p:CollectCoverage=false"+++def _project(root: Path, path: str, *, refs: tuple[str, ...] = (), body: str = "") -> None:+ project = root / path+ project.parent.mkdir(parents=True, exist_ok=True)+ items = "".join(f'<ProjectReference Include="{ref}" />' for ref in refs)+ project.write_text(+ f'<Project Sdk="Microsoft.NET.Sdk"><ItemGroup>{items}{body}</ItemGroup></Project>',+ encoding="utf-8",+ )+++def _shop(root: Path) -> None:+ """The issue's repro: a library and an xUnit project referencing it."""+ (root / "Shop.sln").write_text("", encoding="utf-8")+ _project(root, SHOP)+ _project(root, TESTS, refs=("..\\..\\src\\Shop\\Shop.csproj",), body=XUNIT)+++def _build_props(root: Path, directory: str, body: str) -> None:+ (root / directory).mkdir(parents=True, exist_ok=True)+ (root / directory / "Directory.Build.props").write_text(+ f"<Project>{body}</Project>", encoding="utf-8"+ )+++def _runs(root: Path, tests: list[str]) -> dict[str, list[str | None]]:+ return runs_for_tests(root, scan_package_manifests(root), tests)+++def _targets(root: Path, tests: list[str]) -> dict[str, str | None]:+ """The project or solution each test runs through; None for no command."""+ runs = _runs(root, tests)+ return {test: str(runs[test][0]).split()[2] if test in runs else None for test in tests}+++def _commands(root: Path, tests: list[str]) -> list[str]:+ return commands_for_tests(tests, runs=_runs(root, tests))+++def test_a_test_runs_through_its_own_test_project(tmp_path: Path) -> None:+ _shop(tmp_path)+ one = f"{CART_TESTS}::CartTests::TotalIsZero"+ two = "tests/Shop.Tests/Pricing/PriceTests.cs::PriceTests::Rounds"+ assert _runs(tmp_path, [one]) == {+ one: [f"dotnet test {TESTS} {NO_COVERAGE}", "--filter=CartTests.TotalIsZero"]+ }+ assert _commands(tmp_path, [one]) == [+ f'dotnet test {TESTS} {NO_COVERAGE} --filter "CartTests.TotalIsZero"'+ ]+ assert _commands(tmp_path, [one, two]) == [+ f'dotnet test {TESTS} {NO_COVERAGE} --filter "CartTests.TotalIsZero|PriceTests.Rounds"'+ ]+++def test_a_file_runs_the_whole_project(tmp_path: Path) -> None:+ _shop(tmp_path)+ tests = [f"{CART_TESTS}::CartTests::TotalIsZero", CART_TESTS, "tests/test_a.py"]+ assert _commands(tmp_path, tests) == [+ "pytest tests/test_a.py",+ f"dotnet test {TESTS} {NO_COVERAGE}",+ ]+ # A capped list widens to files, so the filter goes too.+ capped = [f"{CART_TESTS}::CartTests::TotalIsZero"]+ runs = _runs(tmp_path, [*capped, CART_TESTS])+ assert commands_for_tests(capped, total=5, runs=runs) == [f"dotnet test {TESTS} {NO_COVERAGE}"]+++def test_a_helper_library_runs_through_the_test_project_that_references_it(+ tmp_path: Path,+) -> None:+ _shop(tmp_path)+ _project(+ tmp_path,+ "tests/Shop.TestUtils/Shop.TestUtils.csproj",+ refs=("..\\..\\src\\Shop\\Shop.csproj",),+ )+ _project(+ tmp_path,+ TESTS,+ refs=("..\\..\\src\\Shop\\Shop.csproj", "..\\Shop.TestUtils\\Shop.TestUtils.csproj"),+ body=XUNIT,+ )+ helper = "tests/Shop.TestUtils/FakeClock.cs"+ assert _targets(tmp_path, [helper]) == {helper: TESTS}+++def test_a_test_project_another_one_references_keeps_its_own_tests(tmp_path: Path) -> None:+ # eShopOnWeb: IntegrationTests references UnitTests, whose tests stay put.+ _project(tmp_path, "tests/UnitTests/UnitTests.csproj", body=XUNIT)+ _project(+ tmp_path,+ "tests/IntegrationTests/IntegrationTests.csproj",+ refs=("..\\UnitTests\\UnitTests.csproj",),+ body=XUNIT,+ )+ test = "tests/UnitTests/BasketTests.cs::BasketTests::Adds"+ assert _targets(tmp_path, [test]) == {test: "tests/UnitTests/UnitTests.csproj"}+++def test_no_single_test_project_falls_back_to_the_root_solution(tmp_path: Path) -> None:+ _shop(tmp_path)+ _project(tmp_path, "tests/Shop.TestUtils/Shop.TestUtils.csproj")+ for name in ("A", "B"):+ _project(+ tmp_path,+ f"tests/{name}/{name}.csproj",+ refs=("..\\Shop.TestUtils\\Shop.TestUtils.csproj",),+ body=XUNIT,+ )+ shared = "tests/Shared/StrongNameTests.cs::StrongNameTests::Signed" # under no project+ helper = "tests/Shop.TestUtils/Fakes.cs" # referenced by two test projects+ assert _targets(tmp_path, [shared, helper]) == {shared: "Shop.sln", helper: "Shop.sln"}+ assert _commands(tmp_path, [shared, helper]) == [f"dotnet test Shop.sln {NO_COVERAGE}"]+++def test_no_project_and_no_solution_gets_no_command(tmp_path: Path) -> None:+ test = f"{CART_TESTS}::CartTests::TotalIsZero"+ assert _runs(tmp_path, [test]) == {}+ assert _commands(tmp_path, [test]) == []+ # Without a map no project is known, so no command either.+ assert commands_for_tests([test]) == []+++def test_two_solutions_pick_the_one_named_after_the_checkout(tmp_path: Path) -> None:+ root = tmp_path / "Shop"+ root.mkdir()+ for name in ("Shop.slnx", "Samples.slnx"):+ (root / name).write_text("", encoding="utf-8")+ assert _targets(root, ["tests/X.cs"]) == {"tests/X.cs": "Shop.slnx"}+ (root / "Shop.slnx").unlink()+ (root / "Other.slnx").write_text("", encoding="utf-8")+ assert _targets(root, ["tests/X.cs"]) == {"tests/X.cs": None}+++def test_the_plan_stores_its_run_and_reads_it_back(tmp_path: Path) -> None:+ _shop(tmp_path)+ suggestion = _plan("Total", file_path="src/Shop/Cart.cs")+ inferred = {suggestion.file_path: ReachedBy([CART_TESTS], "import-graph", 1)}+ runs = _runs(tmp_path, [CART_TESTS])+ plan = build_validation_plan(+ suggestion, {}, inferred, evidence=ValidationEvidence(test_runs=runs)+ )+ run = f"dotnet test {TESTS} {NO_COVERAGE}"+ assert plan.commands == [run]+ stored = plan.as_dict()+ 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"]+++def test_a_batch_runs_its_tests_through_the_stored_run() -> None:+ run = f"dotnet test {TESTS} {NO_COVERAGE}"+ tests = [f"{CART_TESTS}::CartTests::Case{n}" for n in range(2)]+ detail = {+ "refactoring_type": "extract_method",+ "validation": {+ "tests": tests,+ "total": 2,+ "test_runs": {test: [run, f"--filter=CartTests.{test[-5:]}"] for test in tests},+ },+ }+ batches = stage_batches(detail, [{"n": n, "action": "extract"} for n in range(1, 8)])+ assert batches is not None+ assert batches[0]["commands"] == [f'{run} --filter "CartTests.Case0|CartTests.Case1"']+++def test_an_unreferenced_app_is_not_a_test_project(tmp_path: Path) -> None:+ # A console app nothing references holds a test-named file; it runs no tests.+ _project(tmp_path, "src/Tool/Tool.csproj")+ test = "src/Tool/Tests/ToolTests.cs"+ assert _targets(tmp_path, [test]) == {test: None}+ (tmp_path / "Shop.sln").write_text("", encoding="utf-8")+ assert _targets(tmp_path, [test]) == {test: "Shop.sln"}+++def test_a_project_that_says_it_is_a_test_project_is_one(tmp_path: Path) -> None:+ project = tmp_path / "test/Specs/Specs.csproj"+ project.parent.mkdir(parents=True)+ project.write_text(+ "<Project><PropertyGroup><IsTestProject>true</IsTestProject></PropertyGroup></Project>",+ encoding="utf-8",+ )+ test = "test/Specs/RetryCases.cs"+ assert _targets(tmp_path, [test]) == {test: "test/Specs/Specs.csproj"}+++def test_a_root_level_test_project_runs_its_tests(tmp_path: Path) -> None:+ _project(tmp_path, "Shop.csproj", body=XUNIT)+ _project(tmp_path, "lib/Lib.csproj")+ assert _targets(tmp_path, ["CartTests.cs", "Unit/PriceTests.cs", "lib/LibTests.cs"]) == {+ "CartTests.cs": "Shop.csproj",+ "Unit/PriceTests.cs": "Shop.csproj",+ "lib/LibTests.cs": None,+ }+ _project(tmp_path, "Shop.csproj") # no longer declares a test package+ assert _targets(tmp_path, ["CartTests.cs"]) == {"CartTests.cs": None}+++def test_a_shared_build_file_that_declares_tests_makes_test_projects(tmp_path: Path) -> None:+ # The test packages live in a shared build file under test/, not the project.+ _build_props(tmp_path, "test", f"<ItemGroup>{XUNIT}</ItemGroup>")+ _project(tmp_path, "test/Core/Core.csproj")+ _project(tmp_path, "src/App/App.csproj")+ tests = ["test/Core/RetryCases.cs", "src/App/AppTests.cs"]+ assert _targets(tmp_path, tests) == {+ "test/Core/RetryCases.cs": "test/Core/Core.csproj",+ "src/App/AppTests.cs": None,+ }+++def test_a_conditional_shared_test_package_does_not_make_every_project_a_test_project(+ tmp_path: Path,+) -> None:+ _build_props(+ tmp_path,+ "",+ "<ItemGroup Condition=\"'$(IsTestProject)' == 'true'\">"+ f"{XUNIT}</ItemGroup>"+ "<PropertyGroup><IsTestProject Condition=\"$(MSBuildProjectName.EndsWith('Tests'))\">"+ "true</IsTestProject></PropertyGroup>",+ )+ _project(tmp_path, "src/Tool/Tool.csproj")+ assert _targets(tmp_path, ["src/Tool/ToolTests.cs"]) == {"src/Tool/ToolTests.cs": None}+++def test_a_project_named_for_tests_runs_its_own_files_only(tmp_path: Path) -> None:+ _project(tmp_path, "tests/Shop.Specs/Shop.Specs.csproj", refs=("../Helpers/Helpers.csproj",))+ _project(tmp_path, "tests/Helpers/Helpers.csproj")+ tests = ["tests/Shop.Specs/CartSpecs.cs", "tests/Helpers/FakeClock.cs"]+ assert _targets(tmp_path, tests) == {+ "tests/Shop.Specs/CartSpecs.cs": "tests/Shop.Specs/Shop.Specs.csproj",+ # The name vouches only for the project's own files, not a library it uses.+ "tests/Helpers/FakeClock.cs": None,+ }diff --git a/tests/unit/ingestion/test_package_roots.py b/tests/unit/ingestion/test_package_roots.pyindex f600758b3..069425652 100644--- a/tests/unit/ingestion/test_package_roots.py+++ b/tests/unit/ingestion/test_package_roots.py@@ -7,9 +7,9 @@ inferred from the indexed file list — because the traverser drops 18 manifestnames it cannot language-detect, which silently cost Go, Maven, Groovy-Gradle,Ruby, Scala, Clojure and Erlang monorepos any package attribution at all.-.NET is not among them: its package file is the ``.csproj`` glob, which an-exact-filename list cannot express, so every name C# declares is build-configuration and is excluded as such.+.NET's package file is the ``.csproj`` glob, which an exact-filename list+cannot express: the scan matches it in the same walk and records each project's+file name, while every exact name C# declares stays build configuration."""from __future__ import annotations@@ -20,6 +20,8 @@ from repowise.core.ingestion.languages.registry import REGISTRYfrom repowise.core.ingestion.package_roots import (module_for,package_manifest_names,+ package_roots_from_paths,+ scan_package_manifests,scan_package_roots,)from repowise.core.ingestion.traverser import FileTraverser@@ -118,6 +120,33 @@ def test_a_directory_with_only_build_config_is_not_a_root(tmp_path):assert scan_package_roots(tmp_path) == {"app"}+def test_a_csproj_directory_is_a_root_holding_its_project_file(tmp_path):+ """The glob is matched in the same walk, ignoring case, and records the file+ name, which is what a ``dotnet test`` command needs."""+ _write(tmp_path, "src/Shop/Shop.csproj", "<Project/>")+ _write(tmp_path, "tests/Shop.Tests/Shop.Tests.CSPROJ", "<Project/>")+ _write(tmp_path, "solution/Directory.Build.props", "<Project/>")+ _write(tmp_path, "Root.csproj", "<Project/>")+ assert scan_package_manifests(tmp_path) == {+ "src/Shop": frozenset({"Shop.csproj"}),+ "tests/Shop.Tests": frozenset({"Shop.Tests.CSPROJ"}),+ }+ assert module_for("src/Shop/Models/Cart.cs", scan_package_roots(tmp_path)) == "src/Shop"+ assert package_roots_from_paths({"src/Shop/Shop.csproj", "src/Shop/Cart.cs"}) == {"src/Shop"}+ assert not any("csproj" in name for name in package_manifest_names())+++def test_a_csproj_is_not_a_monorepo_package(tmp_path):+ """Monorepo detection reads a manifest by its exact name; a project file+ adds a module root, never a package to the repo structure."""+ _write(tmp_path, "src/Shop/Shop.csproj", "<Project/>")+ _write(tmp_path, "src/Api/Api.csproj", "<Project/>")+ _write(tmp_path, "web/package.json", '{"name":"web"}')+ structure = FileTraverser(tmp_path).get_repo_structure()+ assert [p.path for p in structure.packages] == ["web"]+ assert structure.is_monorepo is False++def test_a_nested_package_is_found_at_any_depth(tmp_path):"""``RepoStructure.packages`` stops at depth 2; module attribution must not.