diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e941e6b..c72ab9a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -72,3 +72,23 @@ jobs: - name: Run the dogfooding architecture tests run: dotnet test tests/ArchUnitSharp.Dogfood.Tests --no-restore + + packages: + runs-on: ${{ matrix.os }} + needs: build + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + - uses: actions/setup-python@v5 + with: + python-version: '3.x' + - name: Pack complete dependency graph + run: dotnet pack ArchUnitSharp.sln -c Release -p:Version=3.0.0-beta.1 -o artifacts/packages + - name: Inspect packages and test isolated consumer + run: python eng/verify-packages.py --version 3.0.0-beta.1 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..82b75b8 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,95 @@ +name: prepare or publish packages + +on: + workflow_dispatch: + inputs: + version: + description: Coordinated SemVer package version + required: true + default: 3.0.0-beta.1 + publish: + description: Publish the validated artifacts (requires resolved license and NuGet environment) + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: nuget-release + cancel-in-progress: false + +jobs: + prepare: + runs-on: ubuntu-latest + env: + RELEASE_VERSION: ${{ inputs.version }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + - uses: actions/setup-python@v5 + with: + python-version: '3.x' + - name: Validate version + run: | + python - <<'PY' + import os, re + if not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?', os.environ['RELEASE_VERSION']): + raise SystemExit('Expected a plain SemVer release version.') + PY + - name: Restore and build + run: | + dotnet restore ArchUnitSharp.sln -p:Version="$RELEASE_VERSION" + dotnet build ArchUnitSharp.sln -c Release --no-restore -p:Version="$RELEASE_VERSION" + - name: Check formatting and tests + run: | + dotnet format ArchUnitSharp.sln --verify-no-changes --no-restore + dotnet test ArchUnitSharp.sln -c Release --no-build --no-restore -p:Version="$RELEASE_VERSION" + - name: Pack and test isolated consumer + run: | + dotnet pack ArchUnitSharp.sln -c Release --no-build --no-restore -p:Version="$RELEASE_VERSION" -o artifacts/packages + python eng/verify-packages.py --version "$RELEASE_VERSION" + - uses: actions/upload-artifact@v4 + with: + name: nuget-packages + path: artifacts/packages/*.nupkg + if-no-files-found: error + + publish: + if: inputs.publish && github.ref == 'refs/heads/main' + needs: prepare + runs-on: ubuntu-latest + environment: nuget + env: + RELEASE_VERSION: ${{ inputs.version }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + - uses: actions/setup-python@v5 + with: + python-version: '3.x' + - uses: actions/download-artifact@v4 + with: + name: nuget-packages + path: artifacts/packages + - name: Require confirmed license in every package + run: python eng/verify-packages.py --version "$RELEASE_VERSION" --require-license --inspect-only + - name: Publish the validated artifacts + env: + NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }} + run: | + test -n "$NUGET_API_KEY" || { echo 'Configure NUGET_API_KEY in the nuget environment.'; exit 1; } + dotnet nuget push 'artifacts/packages/*.nupkg' --source https://api.nuget.org/v3/index.json --api-key "$NUGET_API_KEY" --skip-duplicate + - name: Verify public installation + run: | + for attempt in 1 2 3 4 5; do + if python eng/verify-packages.py --version "$RELEASE_VERSION" --require-license --public; then + exit 0 + fi + sleep 30 + done + exit 1 diff --git a/.gitignore b/.gitignore index 6c31c1c..321c417 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ TestResults/ .idea/ docs/_site/ docs/api/ +artifacts/ diff --git a/NOTES.md b/NOTES.md index b84bfe9..9ce4937 100644 --- a/NOTES.md +++ b/NOTES.md @@ -664,3 +664,7 @@ restore, build (0 warnings, 0 errors), format --verify-no-changes, 112 extractio tests passed (test-attribute count 166 at base -> 213 now, nothing removed, nothing skipped), no vulnerable packages. The crash is the reviewer-tooling hang class already noted in Round 2, not a code defect; there is nothing to fix. + +WHY: Issue #53 packaging preparation uses the proposed ArchUnit 3.0.0-beta.1 identity with coordinated ArchUnitSharp.* dependencies and retains net10.0/namespaces; public publication is explicitly gated on a reviewed LICENSE because neither promoted repository supplies a confirmed license and the legacy package's declaration cannot be assumed. +WHY: Issue #54 is addressed only for the demonstrated trailing-/** base-folder omission; broader sibling glob compatibility choices remain open rather than changing unrelated selector semantics in a release-packaging PR. +WHY: Issue #51 adds Testing→Metrics to format structured metric violations; the dogfood dependency table now permits that acyclic edge while Metrics remains Common-only. No architecture checks are skipped. diff --git a/README.md b/README.md index 00c8564..ef056e7 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,10 @@ # ArchUnit.NET -The canonical repository is [LukasNiessen/ArchUnitNET](https://github.com/LukasNiessen/ArchUnitNET). +The canonical repository is [dragonsec-ai/ArchUnitNET](https://github.com/dragonsec-ai/ArchUnitNET). This implementation was developed by [Robey Beswick](https://github.com/RobeyBeswick) as ArchUnitSharp and promoted here on 5 October 2026. Its project names and C# namespaces remain -`ArchUnitSharp` while the package and API transition is planned. The previous implementation, +`ArchUnitSharp`. The proposed package transition is documented in the +[migration guide](docs/guide/migration.md). The previous implementation, including its branches and release tags, is preserved in [Deprecated-ArchUnitNET](https://github.com/LukasNiessen/Deprecated-ArchUnitNET). @@ -44,6 +45,11 @@ the composition root and the assertion adapter to your test project: use the framework-agnostic helper `ArchUnitSharp.Testing.RuleAssert.Passes(rule)` / `RuleAssert.Fails(rule)`; it works with every framework and needs no configuration. +The proposed `3.0.0-beta.1` packages can be built and tested with an isolated consumer using +the [release guide](docs/guide/release.md). Public publication remains blocked until the promoted +implementation's license is confirmed. This is a breaking .NET 10/API transition, not an +in-place upgrade of the existing NuGet package. + ## A first rule in ten lines A rule is checked from a test. The entry point locates your project by walking up from the current diff --git a/docs/guide/migration.md b/docs/guide/migration.md new file mode 100644 index 0000000..33eb215 --- /dev/null +++ b/docs/guide/migration.md @@ -0,0 +1,146 @@ +# Migrating from ArchUnit 2.4.0-alpha.2 + +The promoted implementation is a breaking replacement, developed by Robey Beswick as +ArchUnitSharp and adopted on 5 October 2026. Historical packages and tags are unchanged; +the previous source is preserved in [Deprecated-ArchUnitNET](https://github.com/LukasNiessen/Deprecated-ArchUnitNET). + +## Distribution and runtime + +The proposed first release is `3.0.0-beta.1`. It is **not yet published**. The source and +packages require .NET 10; a .NET 8 or 9 test project cannot reference them. The application +being inspected is a C# source tree and need not itself target .NET 10. + +The composition-root package keeps the `ArchUnit` install identity. Its assembly and +namespaces are `ArchUnitSharp`. Ten supporting `ArchUnitSharp.*` packages carry the same +version. For xUnit, install `ArchUnit` and `ArchUnitSharp.Testing.Xunit`; for a generic +assertion helper, install `ArchUnit` and `ArchUnitSharp.Testing`. All other module +dependencies restore transitively. There are no current native NUnit or MSTest adapters. + +To try the locally built packages before publication, follow [the release guide](release.md). +Once the exact version is publicly available, the equivalent xUnit installation is: + +```sh +dotnet add package ArchUnit --version 3.0.0-beta.1 +dotnet add package ArchUnitSharp.Testing.Xunit --version 3.0.0-beta.1 +``` + +## API changes + +| Previous implementation | Promoted implementation | +| --- | --- | +| `using ArchUnitNet;` | `using ArchUnitSharp;` | +| `ArchUnit.ProjectFiles(path)` | `Project.ProjectFiles(ProjectLocator.Locate(path))` | +| `DependOnFiles()` | `DependOn()` | +| `await rule.CheckAsync()` | `rule.Check()` | +| `await rule.PassesAsync()` | `rule.AssertPasses()` from `ArchUnitSharp.Testing.Xunit` | +| Framework-specific old adapters | xUnit adapter or `RuleAssert.Passes(rule)` | +| `Metrics()` | Source selection with `Project.Metrics(location)`; type-scoped entry is unsupported | +| `{Layer}` / `{Slice}` grouping | Explicit named layer definitions / slice glob captures | + +The following examples belong inside tests with these imports and a location pointing to +the source project. `eng/package-consumer/ArchitectureTests.cs` compiles and exercises the +new files, layers, slices, metrics and assertion surfaces using packages alone. + +```csharp +using ArchUnitSharp; +using ArchUnitSharp.Extraction; +using ArchUnitSharp.Testing; +using ArchUnitSharp.Testing.Xunit; + +var location = ProjectLocator.Locate("/path/to/source-project"); +``` + +### Files and assertions + +Replace `ArchUnit.ProjectFiles(path).InFolder("src/App").ShouldNot().DependOnFiles()` +and its asynchronous assertion with: + +```csharp +var rule = Project.ProjectFiles(location) + .InFolder("src/App/**").ShouldNot().DependOn().InFolder("src/Storage/**"); +rule.AssertPasses(); +// Alternative without a framework-native adapter: +RuleAssert.Passes(rule); +// Or inspect structured violations directly: +var violations = rule.Check(); +``` + +`InFolder("src/App/**")` includes the base folder and its descendants. Dependencies +still follow local `using` imports, not every semantic type reference (issue #47). +Repeated checks cache extraction within a process. If a tool edits the source between +checks, use the documented `CheckOptions.ClearCache` option or `GraphCache.Clear()`. + +### Layers + +The previous `{Layer}` extraction and `Where(Layer.Defined(...)).MayOnlyDependOn(...)` +becomes explicit declarations and a named constraint: + +```csharp +Project.Layers(location) + .Layer("App").DefinedByFolder("src/App") + .Layer("Models").DefinedByFolder("src/Models") + .WhereLayer("App").MayOnlyDependOnLayers("Models") + .AssertPasses(); +``` + +### Slices and cycles + +`DefinedBy("src/{Slice}/**").Should().BeAcyclic()` has no direct slice-cycle equivalent +in this implementation. Use slice dependency constraints where appropriate: + +```csharp +Project.Slices(location).DefinedBy("src/(**)/*.cs") + .ShouldNot().ContainDependency("src/Models/**", "src/App/**") + .AssertPasses(); +``` + +File cycles are supported separately; they are not the same as cycles in a collapsed +slice graph: + +```csharp +Project.ProjectFiles(location).Should().HaveNoCycles().AssertPasses(); +``` + +### Metrics + +Replace reflection/type-scoped metrics and old threshold method names with a source +selection and the new threshold grammar. For example: + +```csharp +Project.Metrics(location).Count().LinesOfCode().ShouldBeBelowOrEqual(300).AssertPasses(); +Project.Metrics(location).Count().MethodCount().ShouldBeBelow(20).AssertPasses(); +``` + +Lines of code counts non-blank source lines. `ShouldBeBelow` is strict; use +`ShouldBeBelowOrEqual` for an inclusive maximum. Failed metric assertions now format +the measured value and expected condition through both generic and xUnit helpers. + +## Legacy feature status + +| Legacy feature | Current status | +| --- | --- | +| File boundaries, naming, file cycles | Replaced by the current files DSL | +| Named layers | Replaced by explicit declarations and layer constraints | +| Slice grouping and dependency rules | Replaced by capture globs and current slice rules | +| Slice-level cycle API | Deferred; file-cycle checks are not equivalent | +| Count/cohesion metrics | Replaced by source-based count/LCOM rules; review metric definitions | +| Architecture presets | Deferred; express policies explicitly | +| JSON configuration | Deferred; declare rules in C# | +| Baselines/snapshots | Deferred; no migrated baseline API | +| SARIF/JSON/text/HTML violation exports | Deferred; graph exports and metric HTML reports are separate features | +| Graph reports | Current DOT/Mermaid/D2/CSV/JSON/HTML exporters | +| Profiling API | Deferred | +| xUnit integration | Replaced by synchronous `AssertPasses` / `AssertFails` | +| Native NUnit/MSTest adapters | Deferred; use framework-neutral `RuleAssert` | + +Empty selections fail by default. Do not use `AllowEmptyTests` to conceal a migration +that selects the wrong files. Known selector differences beyond trailing `/**` remain +tracked in issue #54; this release does not claim glob compatibility with every sibling. + +## Remaining release work + +Issue #53 stays open until the promoted implementation's license/provenance is confirmed, +the package identity/version choices are reviewed, the complete package graph is published +and publicly verified, and the website accurately reflects this API and runtime boundary. +The owner of the former `RobeyBeswick/ArchUnitSharp` repository must also coordinate its +redirect or retirement; this change does not claim that owner action is complete. diff --git a/docs/guide/release.md b/docs/guide/release.md new file mode 100644 index 0000000..e4bd726 --- /dev/null +++ b/docs/guide/release.md @@ -0,0 +1,65 @@ +# Building and releasing packages + +The packaging proposal keeps the root NuGet ID `ArchUnit`, with `ArchUnitSharp` assemblies +and namespaces and ten `ArchUnitSharp.*` supporting packages. All eleven share one version, +currently `3.0.0-beta.1`, and target .NET 10. The legacy `2.4.0-alpha.2` package is unchanged. +The original implementation is attributed to Robey Beswick in every package. + +## Local verification + +With .NET 10 and Python 3.9 or newer: + +```sh +dotnet restore ArchUnitSharp.sln -p:Version=3.0.0-beta.1 +dotnet build ArchUnitSharp.sln -c Release --no-restore -p:Version=3.0.0-beta.1 +dotnet format ArchUnitSharp.sln --verify-no-changes --no-restore +dotnet test ArchUnitSharp.sln -c Release --no-build --no-restore -p:Version=3.0.0-beta.1 +dotnet pack ArchUnitSharp.sln -c Release --no-build --no-restore -p:Version=3.0.0-beta.1 -o artifacts/packages +python eng/verify-packages.py --version 3.0.0-beta.1 +``` + +Use an empty output directory when changing versions: the verifier rejects unexpected +or missing packages. It inspects IDs, versions, all internal dependencies, net10.0 DLLs, +XML documentation, repository metadata, README and attribution. It then copies the xUnit +consumer outside this checkout, uses a fresh NuGet package cache, maps all ArchUnit package +IDs exclusively to the local feed, and restores external dependencies from nuget.org. +No project references or source-built DLL paths are permitted in that consumer. + +The consumer tests forbidden dependencies, cycles and LOC limits through failure and +repair, plus layer/slice/graph examples. CI repeats package consumption on Linux, Windows +and macOS. This is a prerequisite for release, not a claim of complete platform coverage. + +## License and publication gate + +The promoted source currently has no confirmed license declaration. Both the canonical +and former repositories lack a recognized license. The old package's Apache-2.0 metadata +does not establish the rewrite's license. **Publication remains blocked under issue #53.** + +After resolving provenance with the implementation owner, commit the reviewed root +`LICENSE` text. Shared package metadata includes it as a NuGet file license automatically. +The publication job requires that license in every artifact; it does not infer an SPDX +identifier or silently reuse the old license. Local inspection artifacts are for evaluating +the packaging and are not a completed public release. + +## Workflow + +The `prepare or publish packages` workflow is manual. Its default `publish=false` runs +formatting, the full test suite, package inspection and the isolated consumer, and retains +the exact package artifacts. Review these before enabling publication. + +For publication, run from `main` with the approved version and `publish=true`. Configure +the repository's `nuget` environment and its `NUGET_API_KEY` with publishing rights for +all eleven IDs. Confirm ownership of new IDs before release. The job downloads the +already-tested artifacts, enforces the license gate, pushes them and checks installation +from public NuGet with a fresh cache. Indexing retries are bounded; inspect failures rather +than declaring a successful publication merely from a push response. + +Publish the complete graph: `ArchUnit`, `ArchUnitSharp.Common`, `ArchUnitSharp.Extraction`, +`ArchUnitSharp.Projection`, `ArchUnitSharp.Files`, `ArchUnitSharp.Graph`, +`ArchUnitSharp.Layers`, `ArchUnitSharp.Slices`, `ArchUnitSharp.Metrics`, +`ArchUnitSharp.Testing`, and `ArchUnitSharp.Testing.Xunit`. + +After public installation is verified, update the README's unpublished status and the +website's package version, .NET 10 requirement, namespaces, synchronous examples, adapter +list, license and feature claims. Keep historical NuGet download totals labelled as +historical. Do not advertise the new implementation as published before this succeeds. diff --git a/docs/toc.yml b/docs/toc.yml index cf85abd..c3f3454 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -4,6 +4,10 @@ items: - name: Getting started href: guide/getting-started.md + - name: Migrating from the previous implementation + href: guide/migration.md + - name: Building and releasing packages + href: guide/release.md - name: The fluent grammar href: guide/fluent-grammar.md - name: Files @@ -21,4 +25,4 @@ - name: Limitations href: guide/limitations.md - name: API reference - href: api/ArchUnitSharp.yml \ No newline at end of file + href: api/ArchUnitSharp.yml diff --git a/eng/package-consumer/ArchitectureTests.cs b/eng/package-consumer/ArchitectureTests.cs new file mode 100644 index 0000000..8af56c3 --- /dev/null +++ b/eng/package-consumer/ArchitectureTests.cs @@ -0,0 +1,112 @@ +using ArchUnitSharp; +using ArchUnitSharp.Common.Extraction; +using ArchUnitSharp.Extraction; +using ArchUnitSharp.Metrics; +using ArchUnitSharp.Testing; +using ArchUnitSharp.Testing.Xunit; +using Xunit; + +public sealed class ArchitectureTests +{ + [Fact] + public void Forbidden_dependency_fails_then_passes_after_removing_the_import() + { + using var fixture = new SourceProject(); + fixture.Write("src/Domain/Order.cs", "using Demo.Storage; namespace Demo.Domain; public class Order { }"); + fixture.Write("src/Storage/Store.cs", "namespace Demo.Storage; public class Store { }"); + + ICheckable Rule() => Project.ProjectFiles(fixture.Location) + .InFolder("src/Domain/**").ShouldNot().DependOn().InFolder("src/Storage/**"); + + Assert.Single(Rule().Check()); + Rule().AssertFails(); + Assert.ThrowsAny(() => Rule().AssertPasses()); + RuleAssert.Fails(Rule()); + Assert.Throws(() => RuleAssert.Passes(Rule())); + + fixture.Write("src/Domain/Order.cs", "namespace Demo.Domain; public class Order { }"); + Assert.Empty(Rule().Check()); + Rule().AssertPasses(); + RuleAssert.Passes(Rule()); + } + + [Fact] + public void Cycle_fails_then_passes_after_removing_one_edge() + { + using var fixture = new SourceProject(); + fixture.Write("src/Orders/Order.cs", "using Demo.Receipts; namespace Demo.Orders; public class Order { }"); + fixture.Write("src/Receipts/Receipt.cs", "using Demo.Orders; namespace Demo.Receipts; public class Receipt { }"); + + ICheckable Rule() => Project.ProjectFiles(fixture.Location).Should().HaveNoCycles(); + + Assert.Single(Rule().Check()); + Rule().AssertFails(); + Assert.ThrowsAny(() => Rule().AssertPasses()); + fixture.Write("src/Receipts/Receipt.cs", "namespace Demo.Receipts; public class Receipt { }"); + Assert.Empty(Rule().Check()); + Rule().AssertPasses(); + } + + [Fact] + public void Lines_of_code_failure_has_a_diagnostic_and_passes_after_shortening_the_file() + { + using var fixture = new SourceProject(); + fixture.Write("src/Orders/Order.cs", "namespace Demo.Orders;\npublic class Order\n{\n public int Id;\n}\n"); + + ICheckable Rule() => Project.Metrics(fixture.Location).Count().LinesOfCode().ShouldBeBelowOrEqual(3); + + var violation = Assert.IsType(Assert.Single(Rule().Check())); + Assert.Equal(5, violation.Value); + Rule().AssertFails(); + RuleAssert.Fails(Rule()); + var error = Assert.ThrowsAny(() => Rule().AssertPasses()); + Assert.Contains("src/Orders/Order.cs", error.Message); + Assert.Contains("5", error.Message); + Assert.Contains("3", error.Message); + Assert.Throws(() => RuleAssert.Passes(Rule())); + + fixture.Write("src/Orders/Order.cs", "namespace Demo.Orders;\npublic class Order { public int Id; }\n"); + Assert.Empty(Rule().Check()); + Rule().AssertPasses(); + RuleAssert.Passes(Rule()); + } + + [Fact] + public void Migration_examples_for_layers_slices_and_graph_work_from_packages() + { + using var fixture = new SourceProject(); + fixture.Write("src/App/Order.cs", "using Demo.Models; namespace Demo.App; public class Order { }"); + fixture.Write("src/Models/Model.cs", "namespace Demo.Models; public class Model { }"); + var location = fixture.Location; + + Project.Layers(location) + .Layer("App").DefinedByFolder("src/App") + .Layer("Models").DefinedByFolder("src/Models") + .WhereLayer("App").MayOnlyDependOnLayers("Models") + .AssertPasses(); + Project.Slices(location).DefinedBy("src/(**)/*.cs") + .ShouldNot().ContainDependency("src/Models/**", "src/App/**") + .AssertPasses(); + Assert.Contains("Order.cs", Project.Graph(location).ToMermaid()); + } + + private sealed class SourceProject : IDisposable + { + private readonly string _root = Path.Combine(Path.GetTempPath(), "archunit-consumer-" + Guid.NewGuid().ToString("N")); + + public SourceProject() => Write("Fixture.csproj", "net10.0"); + + public ProjectLocation Location => ProjectLocator.Locate(_root); + + public void Write(string relativePath, string content) + { + var path = Path.Combine(_root, relativePath); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content); + // These tests edit source within one process, unlike separate dotnet test runs. + GraphCache.Clear(); + } + + public void Dispose() => Directory.Delete(_root, recursive: true); + } +} diff --git a/eng/package-consumer/PackageConsumer.csproj b/eng/package-consumer/PackageConsumer.csproj new file mode 100644 index 0000000..cf4bf23 --- /dev/null +++ b/eng/package-consumer/PackageConsumer.csproj @@ -0,0 +1,17 @@ + + + net10.0 + enable + enable + false + true + true + + + + + + + + + diff --git a/eng/verify-packages.py b/eng/verify-packages.py new file mode 100644 index 0000000..6119bce --- /dev/null +++ b/eng/verify-packages.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Inspect the entire package graph and test it from outside the source checkout.""" + +import argparse +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import xml.etree.ElementTree as ET +import zipfile + + +def require(condition, message): + if not condition: + raise SystemExit(message) + + +def inspect_packages(repository, feed, version, require_license): + projects = sorted((repository / "src").glob("*/*.csproj")) + identities = {p.stem: "ArchUnit" if p.stem == "ArchUnitSharp" else p.stem for p in projects} + require(len(projects) == 11, "Update package inspection when the shipping graph changes.") + expected = {f"{identity}.{version}.nupkg" for identity in identities.values()} + actual = {p.name for p in feed.glob("*.nupkg")} + require(actual == expected, f"Package set mismatch. Missing: {expected - actual}; unexpected: {actual - expected}") + namespace = {"n": "http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd"} + for project in projects: + identity = identities[project.stem] + with zipfile.ZipFile(feed / f"{identity}.{version}.nupkg") as package: + nuspecs = [n for n in package.namelist() if n.endswith(".nuspec")] + require(len(nuspecs) == 1, f"{identity}: expected one manifest") + document = ET.fromstring(package.read(nuspecs[0])) + # NuGet's schema namespace varies with the metadata features in use. + namespace["n"] = document.tag.partition("}")[0].removeprefix("{") + metadata = document.find("n:metadata", namespace) + require(metadata is not None, f"{identity}: missing metadata") + text = lambda name: metadata.findtext(f"n:{name}", namespaces=namespace) + require(text("id") == identity and text("version") == version, f"{identity}: wrong identity/version") + require("Robey Beswick" in (text("authors") or ""), f"{identity}: missing original-author attribution") + require(text("readme") == "README.md" and "README.md" in package.namelist(), f"{identity}: missing README") + repository_metadata = metadata.find("n:repository", namespace) + require(repository_metadata is not None and repository_metadata.get("url") == "https://github.com/dragonsec-ai/ArchUnitNET", f"{identity}: incorrect repository") + require(f"lib/net10.0/{project.stem}.dll" in package.namelist(), f"{identity}: missing net10.0 assembly") + require(f"lib/net10.0/{project.stem}.xml" in package.namelist(), f"{identity}: missing XML documentation") + require(not any(".Tests" in name for name in package.namelist()), f"{identity}: test artifacts leaked") + if require_license: + license_node = metadata.find("n:license", namespace) + require(license_node is not None and license_node.get("type") == "file" and license_node.text == "LICENSE", f"{identity}: publication requires the reviewed LICENSE metadata (#53)") + require("LICENSE" in package.namelist() and package.read("LICENSE").strip(), f"{identity}: missing license text") + references = ET.parse(project).getroot().findall(".//ProjectReference") + expected_dependencies = { + identities[Path(item.attrib["Include"].replace("\\", "/")).stem] + for item in references + } + groups = metadata.findall("n:dependencies/n:group", namespace) + require(len(groups) == 1 and groups[0].get("targetFramework") == "net10.0", f"{identity}: unexpected framework groups") + dependencies = {d.get("id"): d.get("version") for d in groups[0].findall("n:dependency", namespace)} + internal = {name for name in dependencies if name in identities.values()} + require(internal == expected_dependencies, f"{identity}: incorrect internal dependencies: {internal}") + for dependency in internal: + require(dependencies[dependency] in (version, f"[{version}, )", f"[{version},)"), f"{identity}: incorrect dependency version for {dependency}") + print(f"Inspected all {len(expected)} packages at {version}.", flush=True) + return set(identities.values()) + + +def test_consumer(repository, feed, version, identities, public): + with tempfile.TemporaryDirectory(prefix="archunit-package-consumer-") as temporary: + root = Path(temporary).resolve() + require(not root.is_relative_to(repository), "Consumer must be outside the repository.") + consumer = root / "consumer" + shutil.copytree(repository / "eng/package-consumer", consumer, ignore=shutil.ignore_patterns("bin", "obj")) + configuration = ET.Element("configuration") + sources = ET.SubElement(configuration, "packageSources") + ET.SubElement(sources, "clear") + if not public: + ET.SubElement(sources, "add", key="local", value=str(feed)) + ET.SubElement(sources, "add", key="nuget", value="https://api.nuget.org/v3/index.json") + mapping = ET.SubElement(configuration, "packageSourceMapping") + if not public: + local = ET.SubElement(mapping, "packageSource", key="local") + ET.SubElement(local, "package", pattern="ArchUnit") + ET.SubElement(local, "package", pattern="ArchUnitSharp.*") + remote = ET.SubElement(mapping, "packageSource", key="nuget") + ET.SubElement(remote, "package", pattern="*") + fallback = ET.SubElement(configuration, "fallbackPackageFolders") + ET.SubElement(fallback, "clear") + config_path = root / "NuGet.config" + ET.ElementTree(configuration).write(config_path, encoding="unicode") + environment = dict(os.environ, NUGET_PACKAGES=str(root / "packages")) + common = [f"-p:ArchUnitPackageVersion={version}"] + dotnet = os.environ.get("DOTNET", "dotnet") + subprocess.run([dotnet, "restore", "PackageConsumer.csproj", "--configfile", str(config_path), "--no-cache", "-p:RestoreFallbackFolders=", *common], cwd=consumer, env=environment, check=True) + assets = json.loads((consumer / "obj/project.assets.json").read_text()) + require(all(library["type"] == "package" for library in assets["libraries"].values()), "Consumer restored a project reference.") + for identity in identities: + require(f"{identity}/{version}" in assets["libraries"], f"Consumer is missing {identity}/{version}") + subprocess.run([dotnet, "test", "PackageConsumer.csproj", "-c", "Release", "--no-restore", *common], cwd=consumer, env=environment, check=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--packages", type=Path, default=Path("artifacts/packages")) + parser.add_argument("--version", required=True) + parser.add_argument("--require-license", action="store_true") + parser.add_argument("--inspect-only", action="store_true") + parser.add_argument("--public", action="store_true", help="Restore from public NuGet after publication instead of the local feed.") + args = parser.parse_args() + require(re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?", args.version), "Expected a plain SemVer release version.") + repository = Path(__file__).resolve().parent.parent + feed = args.packages.resolve() + identities = inspect_packages(repository, feed, args.version, args.require_license) + if not args.inspect_only: + test_consumer(repository, feed, args.version, identities, args.public) + + +if __name__ == "__main__": + main() diff --git a/src/ArchUnitSharp.Common/Extraction/RegexFactory.cs b/src/ArchUnitSharp.Common/Extraction/RegexFactory.cs index 4e384e2..c89faf0 100644 --- a/src/ArchUnitSharp.Common/Extraction/RegexFactory.cs +++ b/src/ArchUnitSharp.Common/Extraction/RegexFactory.cs @@ -14,7 +14,8 @@ namespace ArchUnitSharp.Common.Extraction; /// character within a segment, [...] is a character class ([!...] negates it), and /// (**) is the capturing form of ** — it matches the same text and captures it, which /// is how the library's slices are named. Matching is case-sensitive. The whole glob is anchored, so -/// a glob matches a whole candidate, not a substring of one. +/// a glob matches a whole candidate, not a substring of one. A trailing /** includes the +/// base path itself as well as its descendants, so src/Models/** also matches src/Models. /// /// /// Separators are normalised before the glob is compiled: a backslash is treated as the same @@ -120,8 +121,17 @@ public static Regex CompileGlob(string glob) break; case '/': - pattern.Append('/'); - i += 1; + if (i + 3 == glob.Length && glob[i + 1] == '*' && glob[i + 2] == '*') + { + pattern.Append("(?:/.*)?"); + i += 3; + } + else + { + pattern.Append('/'); + i += 1; + } + break; default: diff --git a/src/ArchUnitSharp.Testing/ArchUnitSharp.Testing.csproj b/src/ArchUnitSharp.Testing/ArchUnitSharp.Testing.csproj index a5ceeb0..564f861 100644 --- a/src/ArchUnitSharp.Testing/ArchUnitSharp.Testing.csproj +++ b/src/ArchUnitSharp.Testing/ArchUnitSharp.Testing.csproj @@ -13,7 +13,8 @@ + - \ No newline at end of file + diff --git a/src/ArchUnitSharp.Testing/ViolationFactory.cs b/src/ArchUnitSharp.Testing/ViolationFactory.cs index edfc9c1..259030b 100644 --- a/src/ArchUnitSharp.Testing/ViolationFactory.cs +++ b/src/ArchUnitSharp.Testing/ViolationFactory.cs @@ -1,8 +1,10 @@ namespace ArchUnitSharp.Testing; +using System.Globalization; using ArchUnitSharp.Common.Extraction; using ArchUnitSharp.Files; using ArchUnitSharp.Layers; +using ArchUnitSharp.Metrics; using ArchUnitSharp.Slices; /// @@ -21,7 +23,8 @@ namespace ArchUnitSharp.Testing; /// , , /// , , /// , and -/// — and a violation subtype this factory does not know is a +/// , together with the count, custom, cohesion and distance +/// metric violations — and a violation subtype this factory does not know is a /// defect, so it throws rather than fabricate a message. /// /// @@ -56,10 +59,92 @@ public static string Format(Violation violation) $"Slice '{v.Slice}' must contain a dependency from a file matching '{v.From}' to a file matching '{v.To}'.", DiagramAdherenceViolation v => $"Slice '{v.SourceSlice}' must not depend on '{v.TargetSlice}' (not in the diagram).", + MetricViolation v => FormatMetric( + v.File, v.Class, CountMetricName(v.MetricKind), v.Value, v.Comparison, v.Threshold, v.Message), + CustomMetricViolation v => FormatMetric( + v.File, v.Class, $"custom metric '{v.MetricName}' ({v.Description})", + v.Value, v.Comparison, v.Threshold, v.Message), + LcomMetricViolation v => FormatMetric( + v.File, v.Class, LcomMetricName(v.MetricKind), v.Value, v.Comparison, v.Threshold, v.Message), + DistanceMetricViolation v => FormatMetric( + v.File, null, DistanceMetricName(v.MetricKind), v.Value, v.Comparison, v.Threshold, v.Message), + DistanceZoneViolation v => + $"File '{v.File}': abstractness is {Number(v.Abstractness)} and instability is {Number(v.Instability)}; " + + $"must not be in zone of {ZoneName(v.Zone)}.", _ => throw new ArgumentOutOfRangeException( nameof(violation), violation, "Violation is not a defined Violation subtype."), }; } + + private static string FormatMetric( + string file, + string? className, + string metric, + IFormattable value, + MetricComparison? comparison, + IFormattable? threshold, + string? message) + { + string subject = className is null ? $"File '{file}'" : $"Class '{className}' in file '{file}'"; + string requirement = comparison is { } kind && threshold is { } limit + ? $"{ComparisonWords(kind)} {Number(limit)}" + : $"satisfy '{message}'"; + return $"{subject}: {metric} is {Number(value)}; should {requirement}."; + } + + private static string Number(IFormattable value) => value.ToString(null, CultureInfo.InvariantCulture); + + private static string ComparisonWords(MetricComparison comparison) => comparison switch + { + MetricComparison.Below => "be below", + MetricComparison.Above => "be above", + MetricComparison.Equal => "be", + MetricComparison.BelowOrEqual => "be below or equal to", + MetricComparison.AboveOrEqual => "be above or equal to", + _ => throw new ArgumentOutOfRangeException(nameof(comparison), comparison, "Unknown metric comparison."), + }; + + private static string CountMetricName(CountMetricKind kind) => kind switch + { + CountMetricKind.MethodCount => "method count", + CountMetricKind.FieldCount => "field count", + CountMetricKind.LinesOfCode => "lines of code", + CountMetricKind.Statements => "statements", + CountMetricKind.Imports => "imports", + CountMetricKind.Classes => "classes", + CountMetricKind.Interfaces => "interfaces", + _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "Unknown count metric."), + }; + + private static string LcomMetricName(LcomMetricKind kind) => kind switch + { + LcomMetricKind.Lcom96a => "lcom96a", + LcomMetricKind.Lcom96b => "lcom96b", + LcomMetricKind.Lcom1 => "lcom1", + LcomMetricKind.Lcom2 => "lcom2", + LcomMetricKind.Lcom3 => "lcom3", + LcomMetricKind.Lcom4 => "lcom4", + LcomMetricKind.Lcom5 => "lcom5", + LcomMetricKind.LcomStar => "lcom*", + _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "Unknown cohesion metric."), + }; + + private static string DistanceMetricName(DistanceMetricKind kind) => kind switch + { + DistanceMetricKind.Abstractness => "abstractness", + DistanceMetricKind.Instability => "instability", + DistanceMetricKind.DistanceFromMainSequence => "distance from main sequence", + DistanceMetricKind.CouplingFactor => "coupling factor", + DistanceMetricKind.NormalisedDistance => "normalised distance", + _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "Unknown distance metric."), + }; + + private static string ZoneName(DistanceZone zone) => zone switch + { + DistanceZone.Pain => "pain", + DistanceZone.Uselessness => "uselessness", + _ => throw new ArgumentOutOfRangeException(nameof(zone), zone, "Unknown distance zone."), + }; } diff --git a/src/ArchUnitSharp/ArchUnitSharp.csproj b/src/ArchUnitSharp/ArchUnitSharp.csproj index 5c2cda0..f4ee372 100644 --- a/src/ArchUnitSharp/ArchUnitSharp.csproj +++ b/src/ArchUnitSharp/ArchUnitSharp.csproj @@ -1,6 +1,7 @@ + ArchUnit net10.0 enable enable @@ -23,4 +24,4 @@ - \ No newline at end of file + diff --git a/src/Directory.Build.props b/src/Directory.Build.props new file mode 100644 index 0000000..8afb272 --- /dev/null +++ b/src/Directory.Build.props @@ -0,0 +1,23 @@ + + + 3.0.0-beta.1 + $(MSBuildProjectName) + true + Robey Beswick;ArchUnit.NET contributors + Architecture tests for C# source: file dependencies, layers, slices, graphs, and metrics. + https://github.com/dragonsec-ai/ArchUnitNET + https://github.com/dragonsec-ai/ArchUnitNET + git + true + README.md + architecture;testing;csharp;archunit + + LICENSE + + + + + + diff --git a/tests/ArchUnitSharp.Common.Tests/Extraction/MatcherFactoryTests.cs b/tests/ArchUnitSharp.Common.Tests/Extraction/MatcherFactoryTests.cs index f4b08c8..78c3f04 100644 --- a/tests/ArchUnitSharp.Common.Tests/Extraction/MatcherFactoryTests.cs +++ b/tests/ArchUnitSharp.Common.Tests/Extraction/MatcherFactoryTests.cs @@ -28,6 +28,20 @@ public void Folder_binds_the_directory_target() Assert.True(any.Matches("src/Models/Car.cs")); } + [Theory] + [InlineData("src/Models/**")] + [InlineData(@"src\Models\**")] + public void Recursive_folder_includes_direct_and_nested_children_but_not_sibling_folders(string glob) + { + var filter = MatcherFactory.Folder(glob); + + Assert.True(filter.Matches("src/Models/Car.cs")); + Assert.True(filter.Matches("src/Models/Nested/Car.cs")); + Assert.True(filter.Matches(@"src\Models\Car.cs")); + Assert.False(filter.Matches("src/ModelsExtra/Car.cs")); + Assert.False(filter.Matches("src/Car.cs")); + } + [Fact] public void Path_binds_the_whole_identifier_target() { diff --git a/tests/ArchUnitSharp.Common.Tests/Extraction/RegexFactoryTests.cs b/tests/ArchUnitSharp.Common.Tests/Extraction/RegexFactoryTests.cs index 925b69e..79d9c17 100644 --- a/tests/ArchUnitSharp.Common.Tests/Extraction/RegexFactoryTests.cs +++ b/tests/ArchUnitSharp.Common.Tests/Extraction/RegexFactoryTests.cs @@ -39,6 +39,23 @@ public void Double_star_after_a_leading_path_matches_zero_or_more_segments() Assert.DoesNotMatch(regex, "src/ACar.cs"); } + [Theory] + [InlineData("src/Models/**")] + [InlineData(@"src\Models\**")] + public void Trailing_double_star_includes_the_base_path_and_descendants(string glob) + { + var regex = RegexFactory.CompileGlob(glob); + + Assert.Matches(regex, "src/Models"); + Assert.Matches(regex, "src/Models/"); + Assert.Matches(regex, "src/Models/Car.cs"); + Assert.Matches(regex, "src/Models/Nested/Car.cs"); + Assert.DoesNotMatch(regex, "src"); + Assert.DoesNotMatch(regex, "src/ModelsExtra"); + Assert.DoesNotMatch(regex, "src/ModelsExtra/Car.cs"); + Assert.DoesNotMatch(regex, "src/models"); + } + [Fact] public void Parenthesized_double_star_captures_the_segments_between_the_literals() { diff --git a/tests/ArchUnitSharp.Dogfood.Tests/DogfoodArchitectureTests.cs b/tests/ArchUnitSharp.Dogfood.Tests/DogfoodArchitectureTests.cs index 2b91be7..dec9792 100644 --- a/tests/ArchUnitSharp.Dogfood.Tests/DogfoodArchitectureTests.cs +++ b/tests/ArchUnitSharp.Dogfood.Tests/DogfoodArchitectureTests.cs @@ -127,7 +127,7 @@ public void The_module_dependency_graph_is_cycle_free() .WhereLayer("Layers").MayOnlyDependOnLayers("Common") .WhereLayer("Metrics").MayOnlyDependOnLayers("Common") .WhereLayer("Slices").MayOnlyDependOnLayers("Common", "Projection") - .WhereLayer("Testing").MayOnlyDependOnLayers("Common", "Files", "Layers", "Slices") + .WhereLayer("Testing").MayOnlyDependOnLayers("Common", "Files", "Layers", "Metrics", "Slices") .WhereLayer("Testing.Xunit").MayOnlyDependOnLayers("Common", "Testing") .WhereLayer("Surface").MayOnlyDependOnLayers( "Common", "Projection", "Extraction", "Files", "Graph", "Layers", "Metrics", "Slices", "Testing", "Testing.Xunit") diff --git a/tests/ArchUnitSharp.Files.Tests/FilesTests.cs b/tests/ArchUnitSharp.Files.Tests/FilesTests.cs index 5ffc537..b5bb22c 100644 --- a/tests/ArchUnitSharp.Files.Tests/FilesTests.cs +++ b/tests/ArchUnitSharp.Files.Tests/FilesTests.cs @@ -36,6 +36,25 @@ public void InFolder_selects_by_the_folder_not_the_file_name() Assert.Equal(new[] { "src/Models/Car.cs", "src/Models/Truck.cs" }, files.Select()); } + [Fact] + public void Recursive_folder_rules_check_a_direct_child_even_when_a_nested_child_keeps_the_selection_non_empty() + { + var domain = new Files(Graph( + Self("src/Domain/Order.cs"), + Self("src/Domain/Nested/Value.cs"), + Self("src/Infrastructure/Repository.cs"), + Self("src/Infrastructure/Nested/Cache.cs"), + new Edge("src/Domain/Order.cs", "src/Infrastructure/Repository.cs", external: false, ImportKind.Using))) + .InFolder("src/Domain/**"); + + IReadOnlyList violations = domain.ShouldNot().DependOn().InFolder("src/Infrastructure/**").Check(); + + Assert.Equal( + new Violation[] { new DependencyViolation("src/Domain/Order.cs", "src/Infrastructure/Repository.cs") }, + violations); + Assert.Equal(new[] { "src/Domain/Nested/Value.cs", "src/Domain/Order.cs" }, domain.Select()); + } + [Fact] public void InPath_selects_by_the_whole_path() { diff --git a/tests/ArchUnitSharp.Testing.Tests/MetricViolationFormattingTests.cs b/tests/ArchUnitSharp.Testing.Tests/MetricViolationFormattingTests.cs new file mode 100644 index 0000000..20fe224 --- /dev/null +++ b/tests/ArchUnitSharp.Testing.Tests/MetricViolationFormattingTests.cs @@ -0,0 +1,145 @@ +using System.Globalization; +using ArchUnitSharp.Common.Extraction; +using ArchUnitSharp.Files; +using ArchUnitSharp.Metrics; + +namespace ArchUnitSharp.Testing.Tests; + +public class MetricViolationFormattingTests +{ + [Theory] + [InlineData(MetricComparison.Below, "be below")] + [InlineData(MetricComparison.Above, "be above")] + [InlineData(MetricComparison.Equal, "be")] + [InlineData(MetricComparison.BelowOrEqual, "be below or equal to")] + [InlineData(MetricComparison.AboveOrEqual, "be above or equal to")] + public void A_file_metric_preserves_the_measured_value_and_comparison(MetricComparison comparison, string words) + { + var violation = new MetricViolation("src/App.cs", null, CountMetricKind.LinesOfCode, 42, comparison, 40); + + Assert.Equal( + $"File 'src/App.cs': lines of code is 42; should {words} 40.", + ViolationFactory.Format(violation)); + } + + [Fact] + public void A_class_metric_names_the_class_and_preserves_the_predicate_message() + { + var violation = new MetricViolation( + "src/App.cs", "App.Service", CountMetricKind.MethodCount, 3, "have an even number of methods"); + + Assert.Equal( + "Class 'App.Service' in file 'src/App.cs': method count is 3; should satisfy 'have an even number of methods'.", + ViolationFactory.Format(violation)); + } + + [Fact] + public void A_custom_metric_preserves_its_name_description_and_threshold() + { + var violation = new CustomMetricViolation( + "src/App.cs", "App.Service", "member count", "methods plus fields", 6, MetricComparison.Below, 5); + + Assert.Equal( + "Class 'App.Service' in file 'src/App.cs': custom metric 'member count' (methods plus fields) is 6; should be below 5.", + ViolationFactory.Format(violation)); + } + + [Fact] + public void A_custom_metric_preserves_its_predicate_message() + { + var violation = new CustomMetricViolation( + "src/App.cs", "App.Service", "member count", "methods plus fields", 3, "keep members paired"); + + Assert.Equal( + "Class 'App.Service' in file 'src/App.cs': custom metric 'member count' (methods plus fields) is 3; should satisfy 'keep members paired'.", + ViolationFactory.Format(violation)); + } + + [Theory] + [InlineData("en-US")] + [InlineData("de-DE")] + public void A_cohesion_metric_formats_fractional_values_independently_of_culture(string culture) + { + CultureInfo original = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); + var violation = new LcomMetricViolation( + "src/App.cs", "App.Service", LcomMetricKind.LcomStar, 0.75, MetricComparison.BelowOrEqual, 0.5); + + Assert.Equal( + "Class 'App.Service' in file 'src/App.cs': lcom* is 0.75; should be below or equal to 0.5.", + ViolationFactory.Format(violation)); + } + finally + { + CultureInfo.CurrentCulture = original; + } + } + + [Fact] + public void A_cohesion_metric_preserves_its_predicate_message() + { + var violation = new LcomMetricViolation( + "src/App.cs", "App.Service", LcomMetricKind.Lcom4, 2, "form one component"); + + Assert.Equal( + "Class 'App.Service' in file 'src/App.cs': lcom4 is 2; should satisfy 'form one component'.", + ViolationFactory.Format(violation)); + } + + [Fact] + public void A_distance_metric_preserves_its_file_value_and_threshold() + { + var violation = new DistanceMetricViolation( + "src/App.cs", DistanceMetricKind.DistanceFromMainSequence, 0.75, MetricComparison.Below, 0.5); + + Assert.Equal( + "File 'src/App.cs': distance from main sequence is 0.75; should be below 0.5.", + ViolationFactory.Format(violation)); + } + + [Fact] + public void A_distance_metric_preserves_its_predicate_message() + { + var violation = new DistanceMetricViolation( + "src/App.cs", DistanceMetricKind.Instability, 0.75, "remain stable"); + + Assert.Equal( + "File 'src/App.cs': instability is 0.75; should satisfy 'remain stable'.", + ViolationFactory.Format(violation)); + } + + [Theory] + [InlineData(DistanceZone.Pain, 0.1, 0.2, "pain")] + [InlineData(DistanceZone.Uselessness, 0.8, 0.9, "uselessness")] + public void A_zone_violation_names_the_zone_and_both_coordinates( + DistanceZone zone, double abstractness, double instability, string name) + { + var violation = new DistanceZoneViolation("src/App.cs", zone, abstractness, instability); + + string message = ViolationFactory.Format(violation); + + Assert.Equal( + FormattableString.Invariant($"File 'src/App.cs': abstractness is {abstractness} and instability is {instability}; must not be in zone of {name}."), + message); + } + + [Fact] + public void A_metric_result_keeps_all_diagnostics_in_order() + { + Violation[] violations = + { + new MetricViolation("src/App.cs", null, CountMetricKind.LinesOfCode, 42, MetricComparison.Below, 40), + new DependencyViolation("src/App.cs", "src/Legacy.cs"), + }; + + CheckResult result = ResultFactory.Create(violations); + + Assert.False(result.Passed); + Assert.Equal( + "File 'src/App.cs': lines of code is 42; should be below 40.\n" + + "File 'src/App.cs' must not depend on 'src/Legacy.cs'.", + result.Message); + } +} diff --git a/tests/ArchUnitSharp.Tests/ArchUnitSharp.Tests.csproj b/tests/ArchUnitSharp.Tests/ArchUnitSharp.Tests.csproj index dea309c..8da28be 100644 --- a/tests/ArchUnitSharp.Tests/ArchUnitSharp.Tests.csproj +++ b/tests/ArchUnitSharp.Tests/ArchUnitSharp.Tests.csproj @@ -18,6 +18,7 @@ + - \ No newline at end of file + diff --git a/tests/ArchUnitSharp.Tests/MetricAssertionIntegrationTests.cs b/tests/ArchUnitSharp.Tests/MetricAssertionIntegrationTests.cs new file mode 100644 index 0000000..d0d8825 --- /dev/null +++ b/tests/ArchUnitSharp.Tests/MetricAssertionIntegrationTests.cs @@ -0,0 +1,84 @@ +using ArchUnitSharp.Common.Extraction; +using ArchUnitSharp.Extraction; +using ArchUnitSharp.Metrics; +using ArchUnitSharp.Testing; +using ArchUnitSharp.Testing.Xunit; +using Xunit.Sdk; + +namespace ArchUnitSharp.Tests; + +public class MetricAssertionIntegrationTests +{ + [Theory] + [InlineData("lines", typeof(MetricViolation), "lines of code is 8; should be below 8.")] + [InlineData("count predicate", typeof(MetricViolation), "method count is 2; should satisfy 'declare one method'.")] + [InlineData("custom", typeof(CustomMetricViolation), "custom metric 'methods' (declared methods) is 2; should be below 2.")] + [InlineData("custom predicate", typeof(CustomMetricViolation), "custom metric 'methods' (declared methods) is 2; should satisfy 'declare one method'.")] + [InlineData("cohesion", typeof(LcomMetricViolation), "lcom4 is 2; should be 1.")] + [InlineData("cohesion predicate", typeof(LcomMetricViolation), "lcom4 is 2; should satisfy 'form one component'.")] + [InlineData("distance", typeof(DistanceMetricViolation), "abstractness is 0; should be above 0.")] + [InlineData("distance predicate", typeof(DistanceMetricViolation), "abstractness is 0; should satisfy 'contain an abstraction'.")] + [InlineData("zone", typeof(DistanceZoneViolation), "abstractness is 0 and instability is 0; must not be in zone of pain.")] + public void Source_based_metrics_report_assertion_failures_and_support_both_asserted_outcomes( + string family, Type violationType, string diagnostic) + { + using var project = new TempProject(); + project.WriteFile("App.sln", ""); + project.WriteFile("Sample.cs", """ + namespace Demo; + public class Sample + { + private int _left; + private int _right; + public void Left() { _left = 1; } + public void Right() { _right = 2; } + } + """); + var location = ProjectLocator.Locate(project.Root); + var metrics = Project.Metrics(location).WithName("Sample.cs"); + ICheckable failing = Rule(metrics, family, passing: false); + + Violation violation = Assert.Single(failing.Check()); + Assert.IsType(violationType, violation); + RuleAssert.Fails(failing); + failing.AssertFails(); + var generic = Assert.Throws(() => RuleAssert.Passes(failing)); + var native = Assert.Throws(() => failing.AssertPasses()); + + Assert.Contains("Sample.cs", generic.Message); + Assert.Contains(diagnostic, generic.Message); + Assert.Equal(generic.Message, native.Message); + if (family is "count predicate" or "custom" or "custom predicate" or "cohesion" or "cohesion predicate") + { + Assert.Contains("Demo.Sample", generic.Message); + } + + ICheckable passing = Rule(metrics, family, passing: true); + Assert.Empty(passing.Check()); + RuleAssert.Passes(passing); + passing.AssertPasses(); + Assert.Throws(() => RuleAssert.Fails(passing)); + Assert.Throws(() => passing.AssertFails()); + } + + private static ICheckable Rule(ArchUnitSharp.Metrics.Metrics metrics, string family, bool passing) => family switch + { + "lines" => metrics.Count().LinesOfCode().ShouldBeBelow(passing ? 9 : 8), + "count predicate" => metrics.Count().MethodCount() + .ShouldSatisfy(value => value == (passing ? 2 : 1), "declare one method"), + "custom" => metrics.CustomMetric("methods", "declared methods", info => info.Methods.Count) + .ShouldBeBelow(passing ? 3 : 2), + "custom predicate" => metrics.CustomMetric("methods", "declared methods", info => info.Methods.Count) + .ShouldSatisfy((value, _) => value == (passing ? 2 : 1), "declare one method"), + "cohesion" => metrics.Lcom().Lcom4().ShouldBe(passing ? 2 : 1), + "cohesion predicate" => metrics.Lcom().Lcom4() + .ShouldSatisfy(value => value == (passing ? 2 : 1), "form one component"), + "distance" => passing + ? metrics.Distance().Abstractness().ShouldBe(0) + : metrics.Distance().Abstractness().ShouldBeAbove(0), + "distance predicate" => metrics.Distance().Abstractness() + .ShouldSatisfy(value => passing ? value == 0 : value > 0, "contain an abstraction"), + "zone" => passing ? metrics.Distance().NotInZoneOfUselessness() : metrics.Distance().NotInZoneOfPain(), + _ => throw new ArgumentOutOfRangeException(nameof(family), family, "Unknown metric fixture."), + }; +}