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.

16.4 KB
Raw Blame
"""Workspace-level tests for .NET / C# support added in Batch 5.

Covers:
- ASP.NET HTTP contract extraction (provider attributes + minimal API +
  HttpClient consumer)
- gRPC-dotnet contract extraction (MapGrpcService, generated-base
  inheritance, generated-Client consumers)
- Cross-repo .NET package dependency scanner: ProjectReference and
  internal-NuGet (PackageReference id matching a sibling AssemblyName).
"""

from __future__ import annotations

from pathlib import Path
from textwrap import dedent

import pytest

from repowise.core import fs_walk
from repowise.core.workspace.extractors.grpc import GrpcExtractor
from repowise.core.workspace.extractors.http import HttpExtractor
from repowise.core.workspace.manifests import (
    _index_manifests,
    _scan_csproj,
    detect_package_dependencies,
)

# ---------------------------------------------------------------------------
# HTTP — ASP.NET
# ---------------------------------------------------------------------------


class TestAspNetHttpExtraction:
    def test_attribute_routing_with_class_prefix(self, tmp_path: Path) -> None:
        (tmp_path / "Controllers").mkdir()
        (tmp_path / "Controllers" / "UsersController.cs").write_text(
            dedent(
                """\
                using Microsoft.AspNetCore.Mvc;
                namespace Acme.Api;

                [ApiController]
                [Route("api/users")]
                public class UsersController : ControllerBase
                {
                    [HttpGet("{id:int}")]
                    public IActionResult Get(int id) => Ok();

                    [HttpPost]
                    public IActionResult Create() => Ok();
                }
                """
            )
        )
        contracts = HttpExtractor().extract(tmp_path, repo_alias="api")
        provider_paths = {
            (c.meta["method"], c.meta["path"]) for c in contracts if c.role == "provider"
        }
        assert ("GET", "/api/users/{param}") in provider_paths
        assert ("POST", "/api/users") in provider_paths

    def test_minimal_api(self, tmp_path: Path) -> None:
        (tmp_path / "Program.cs").write_text(
            dedent(
                """\
                var app = WebApplication.CreateBuilder(args).Build();
                app.MapGet("/health", () => "ok");
                app.MapPost("/orders", (Order o) => Results.Created());
                """
            )
        )
        contracts = HttpExtractor().extract(tmp_path, repo_alias="api")
        paths = {(c.meta["method"], c.meta["path"]) for c in contracts if c.role == "provider"}
        assert ("GET", "/health") in paths
        assert ("POST", "/orders") in paths

    def test_httpclient_consumer(self, tmp_path: Path) -> None:
        (tmp_path / "OrderClient.cs").write_text(
            dedent(
                """\
                public class OrderClient {
                    private readonly HttpClient _http;
                    public async Task Pull() {
                        await _http.GetAsync("/api/orders/123");
                    }
                }
                """
            )
        )
        contracts = HttpExtractor().extract(tmp_path, repo_alias="web")
        consumers = [c for c in contracts if c.role == "consumer"]
        assert any(
            c.meta["client"] == "httpclient"
            and c.meta["method"] == "GET"
            and c.meta["path"] == "/api/orders/123"
            for c in consumers
        )


class TestAzureFunctionsHttpTriggers:
    def _providers(self, tmp_path: Path, source: str) -> set[tuple[str, str]]:
        (tmp_path / "Orders.cs").write_text(dedent(source))
        contracts = HttpExtractor().extract(tmp_path, repo_alias="fn")
        return {
            (c.meta["method"], c.meta["path"])
            for c in contracts
            if c.role == "provider" and c.meta.get("framework") == "azure-functions"
        }

    def test_route_and_methods_are_served_under_the_api_prefix(self, tmp_path: Path) -> None:
        found = self._providers(
            tmp_path,
            """\
            public static class Orders {
                [FunctionName("GetOrder")]
                public static Task<IActionResult> Run(
                    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "orders/{id:int?}")] HttpRequest req) => null;
            }
            """,
        )
        assert found == {("GET", "/api/orders/{param}"), ("POST", "/api/orders/{param}")}

    def test_without_a_route_the_function_name_is_the_route(self, tmp_path: Path) -> None:
        found = self._providers(
            tmp_path,
            """\
            public class Orders {
                [Function(nameof(ListOrders))]
                public HttpResponseData ListOrders([HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequestData req) => null;

                [Function("Ping")]
                public HttpResponseData Ping([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequestData req) => null;
            }
            """,
        )
        assert found == {("GET", "/api/listorders"), ("GET", "/api/ping")}

    def test_a_trigger_that_cannot_be_spelled_is_skipped(self, tmp_path: Path) -> None:
        found = self._providers(
            tmp_path,
            """\
            public class Orders {
                [Function("Any")]
                public HttpResponseData AnyVerb([HttpTrigger(AuthorizationLevel.Anonymous, Route = "any")] HttpRequestData req) => null;

                [Function(Names.Hidden)]
                public HttpResponseData Hidden([HttpTrigger(AuthorizationLevel.Anonymous, "delete")] HttpRequestData req) => null;

                // [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = "commented")]

                [Function("Nightly")]
                public void Nightly([TimerTrigger("0 0 * * *")] TimerInfo t) { }
                public HttpResponseData Unnamed([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "")] HttpRequestData req) => null;
            }
            """,
        )
        # No method: every verb, no single route. A trigger whose own name is
        # unreadable or missing never borrows another member's.
        assert found == set()

    def test_an_optional_minimal_api_parameter_keeps_the_path(self, tmp_path: Path) -> None:
        (tmp_path / "Program.cs").write_text(
            'app.MapGet("/items/type/{typeId}/brand/{brandId?}", GetItems);\n'
        )
        contracts = HttpExtractor().extract(tmp_path, repo_alias="api")
        assert [c.meta["path"] for c in contracts if c.role == "provider"] == [
            "/items/type/{param}/brand/{param}"
        ]


# ---------------------------------------------------------------------------
# gRPC-dotnet
# ---------------------------------------------------------------------------


class TestGrpcDotnetExtraction:
    def test_map_grpc_service_provider(self, tmp_path: Path) -> None:
        (tmp_path / "Program.cs").write_text(
            dedent(
                """\
                builder.Services.AddGrpc();
                var app = builder.Build();
                app.MapGrpcService<GreeterService>();
                """
            )
        )
        contracts = GrpcExtractor().extract(tmp_path, repo_alias="api")
        provider_services = {c.meta["service"] for c in contracts if c.role == "provider"}
        # MapGrpcService<T>() captures the literal type-arg name. Either
        # `Greeter` (raw) or `GreeterService` (suffixed) is correct here.
        assert "GreeterService" in provider_services or "Greeter" in provider_services

    def test_generated_base_provider(self, tmp_path: Path) -> None:
        (tmp_path / "GreeterImpl.cs").write_text(
            dedent(
                """\
                namespace Acme;
                public class GreeterImpl : Greeter.GreeterBase
                {
                }
                """
            )
        )
        contracts = GrpcExtractor().extract(tmp_path, repo_alias="api")
        assert any(c.role == "provider" and c.meta["service"] == "Greeter" for c in contracts)

    def test_generated_client_consumer(self, tmp_path: Path) -> None:
        (tmp_path / "Caller.cs").write_text(
            dedent(
                """\
                using Grpc.Net.Client;
                public class Caller {
                    public void Go() {
                        var channel = GrpcChannel.ForAddress("https://api");
                        var client = new GreeterClient(channel);
                    }
                }
                """
            )
        )
        contracts = GrpcExtractor().extract(tmp_path, repo_alias="web")
        consumers = [c for c in contracts if c.role == "consumer"]
        assert any(c.meta["service"] == "Greeter" for c in consumers)


# ---------------------------------------------------------------------------
# Cross-repo .NET dependencies
# ---------------------------------------------------------------------------


def _csproj(
    deps: list[str] = (), assembly_name: str | None = None, packages: list[str] = ()
) -> str:
    refs = "\n".join(f'    <ProjectReference Include="{p}" />' for p in deps)
    pkgs = "\n".join(f'    <PackageReference Include="{p}" Version="1.0.0" />' for p in packages)
    asm = f"<AssemblyName>{assembly_name}</AssemblyName>" if assembly_name else ""
    return dedent(
        f"""\
        <Project Sdk="Microsoft.NET.Sdk">
          <PropertyGroup>
            <TargetFramework>net8.0</TargetFramework>
            {asm}
          </PropertyGroup>
          <ItemGroup>
        {refs}
        {pkgs}
          </ItemGroup>
        </Project>
        """
    )


class TestScanCsproj:
    def _two_repo_workspace(self, root: Path) -> dict[str, Path]:
        api = root / "api-service"
        shared = root / "shared-libs"
        (api / "src" / "Api").mkdir(parents=True)
        (shared / "src" / "Common").mkdir(parents=True)
        (shared / "src" / "Common" / "Common.csproj").write_text(
            _csproj(assembly_name="Acme.Common")
        )
        return {"api": api, "shared": shared}

    def test_project_reference_emits_cross_repo_dep(self, tmp_path: Path) -> None:
        repos = self._two_repo_workspace(tmp_path)
        # api references shared via relative ProjectReference
        (repos["api"] / "src" / "Api" / "Api.csproj").write_text(
            _csproj(deps=[r"..\..\..\shared-libs\src\Common\Common.csproj"])
        )
        deps = _scan_csproj(repos["api"], repos, alias="api")
        assert any(
            d.source_repo == "api" and d.target_repo == "shared" and d.kind == "dotnet_project_ref"
            for d in deps
        )

    def test_internal_nuget_emits_cross_repo_dep(self, tmp_path: Path) -> None:
        repos = self._two_repo_workspace(tmp_path)
        # api consumes the published Acme.Common NuGet package whose
        # AssemblyName lives in `shared-libs`.
        (repos["api"] / "src" / "Api" / "Api.csproj").write_text(_csproj(packages=["Acme.Common"]))
        deps = _scan_csproj(repos["api"], repos, alias="api")
        assert any(
            d.source_repo == "api"
            and d.target_repo == "shared"
            and d.kind == "dotnet_nuget_internal"
            for d in deps
        )

    def test_external_nuget_does_not_emit_cross_repo_dep(self, tmp_path: Path) -> None:
        repos = self._two_repo_workspace(tmp_path)
        (repos["api"] / "src" / "Api" / "Api.csproj").write_text(
            _csproj(packages=["Newtonsoft.Json"])
        )
        deps = _scan_csproj(repos["api"], repos, alias="api")
        assert not any(d.kind == "dotnet_nuget_internal" for d in deps)

    def test_detect_package_dependencies_includes_csproj_scanner(self, tmp_path: Path) -> None:
        repos = self._two_repo_workspace(tmp_path)
        (repos["api"] / "src" / "Api" / "Api.csproj").write_text(
            _csproj(deps=[r"..\..\..\shared-libs\src\Common\Common.csproj"])
        )
        deps = detect_package_dependencies(repos)
        kinds = {d.kind for d in deps}
        assert "dotnet_project_ref" in kinds

    def test_detect_package_dependencies_walks_each_repo_once(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """The .csproj scan must not re-walk every tree once per repo.

        The assembly-name map spans the whole workspace but does not depend on
        the repo being scanned, so building it per repo cost R*R + R tree
        walks. One walk per repo is the floor: each repo's project files have
        to be found once.
        """
        repos = self._two_repo_workspace(tmp_path)
        (repos["api"] / "src" / "Api" / "Api.csproj").write_text(_csproj(packages=["Acme.Common"]))

        walked: list[Path] = []
        real_walk_repo = fs_walk.walk_repo

        def counting_walk_repo(root, **kwargs):
            walked.append(Path(root))
            return real_walk_repo(root, **kwargs)

        monkeypatch.setattr(fs_walk, "walk_repo", counting_walk_repo)

        deps = detect_package_dependencies(repos)

        assert len(walked) == len(repos), (
            f"expected one project-manifest walk per repo ({len(repos)}), "
            f"got {len(walked)}: {walked}"
        )
        # The saving must not have cost us the dependency itself.
        assert any(d.kind == "dotnet_nuget_internal" for d in deps)

    def test_shared_walk_ignores_csproj_files_in_packages_cache(self, tmp_path: Path) -> None:
        repos = self._two_repo_workspace(tmp_path)
        cached = repos["api"] / "packages" / "cached"
        cached.mkdir(parents=True)
        (cached / "Cached.csproj").write_text(
            _csproj(assembly_name="Acme.Cached", packages=["Acme.Common"])
        )

        index = _index_manifests(repos)
        deps = detect_package_dependencies(repos)

        assert all("packages" not in path.parts for path in index.by_repo["api"])
        assert all(dep.source_manifest != "packages/cached/Cached.csproj" for dep in deps)

    def test_shared_index_matches_standalone_scan(self, tmp_path: Path) -> None:
        """A shared index must produce exactly what an isolated scan produces."""
        repos = self._two_repo_workspace(tmp_path)
        (repos["api"] / "src" / "Api" / "Api.csproj").write_text(
            _csproj(
                deps=[r"..\..\..\shared-libs\src\Common\Common.csproj"],
                packages=["Acme.Common", "Newtonsoft.Json"],
            )
        )

        standalone = _scan_csproj(repos["api"], repos, alias="api")
        shared = _scan_csproj(
            repos["api"], repos, alias="api", csproj_index=_index_manifests(repos)
        )

        assert standalone == shared
        assert standalone  # guard against both sides being vacuously empty

    def test_assembly_name_collision_resolves_to_last_repo(self, tmp_path: Path) -> None:
        """Two repos publishing one assembly name: the later repo wins.

        The shared index builds this map once instead of per repo, so pin the
        ordering it depends on — a map rebuilt in a different order would
        silently retarget the edge at the other repo.
        """
        repos = self._two_repo_workspace(tmp_path)
        rival = tmp_path / "rival-libs"
        (rival / "src" / "Common").mkdir(parents=True)
        (rival / "src" / "Common" / "Rival.csproj").write_text(_csproj(assembly_name="Acme.Common"))
        (repos["api"] / "src" / "Api" / "Api.csproj").write_text(_csproj(packages=["Acme.Common"]))
        # "shared" then "rival": last one to claim the name owns it.
        ordered = {"api": repos["api"], "shared": repos["shared"], "rival": rival}

        deps = detect_package_dependencies(ordered)
        nuget = [d for d in deps if d.kind == "dotnet_nuget_internal"]
        assert [d.target_repo for d in nuget] == ["rival"]

    def test_scan_uses_the_repo_path_it_is_given(self, tmp_path: Path) -> None:
        """A repo_path disagreeing with repo_paths[alias] must still be scanned.

        The shared index is keyed by alias, so a caller passing a different
        tree for that alias must not silently get the indexed tree's results.
        """
        repos = self._two_repo_workspace(tmp_path)
        other = tmp_path / "other-api"
        (other / "src" / "Api").mkdir(parents=True)
        (other / "src" / "Api" / "Other.csproj").write_text(_csproj(packages=["Acme.Common"]))
        # repo_paths["api"] holds no .csproj at all; the scanned tree does.
        deps = _scan_csproj(other, repos, alias="api", csproj_index=_index_manifests(repos))
        assert [d.target_repo for d in deps] == ["shared"]
        assert deps[0].source_manifest == "src/Api/Other.csproj"