From 5e6db53b2cb9353a8391909201473ae9a880f7e7 Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Wed, 11 Nov 2026 21:13:55 -0500 Subject: [PATCH] feat(metrics,logging): address #161 1.4 dogfood follow-up findings Resolves the seven usability findings from the #161 dogfood follow-up (RESEARCH-0040 / PLAN-0075, beads compono-gec): - Compono.Metrics owns IMeterFactory: a new ComponoMetricsOwnsMeterFactory property (defaulted true by Compono.Metrics' packed props) excludes IMeterFactory from Compono.TestDoubles generation, so registration order against UseGeneratedTestDoubles() no longer matters (ADR-0072 Amendment 5, superseding "No generator exclusion is added"). Stage-6 first-registration-wins is unchanged; UseMetrics() remarks and the misuse message now name UseGeneratedTestDoubles() and catch-all providers. - Compono.Logging: LogVerificationBuilder.InCategoryPrefix and NotInCategoryPrefix (ordinal, literal prefix; ADR-0055 Amendment 7). - Docs only: ComposeData leading-positional binding and reading TConfig via a profile registration; per-engine disposal (xUnit v3 JIT disposes test arguments, XunitV3.Aot does not; ADR-0072 Amendment 6); ClearMeasurements() multi-pass pattern; wrapper-profile pattern for profile constructor arguments; new migration guide from Microsoft.Extensions.Diagnostics.Testing. - Recipes proven by JIT and Native AOT tests; skill references and evals updated; API reference regenerated. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/inspect-packed-nupkgs.sh | 5 + ...compono-logging-testing-support-package.md | 34 ++ ...compono-metrics-testing-support-package.md | 94 +++++ ...y-composed-configuration-per-theory-row.md | 6 + ...t-nothing-logged-at-error-across-a-host.md | 19 +- docs/how-to/use-profiles.md | 64 ++++ ...icrosoft-extensions-diagnostics-testing.md | 224 +++++++++++ docs/packages/compono-logging.md | 30 +- docs/packages/compono-metrics.md | 86 ++++- docs/packages/compono-xunitv3-aot.md | 11 +- docs/packages/compono-xunitv3.md | 55 +++ ...sue-161-1-4-dogfood-follow-up-impl-plan.md | 192 ++++++++++ docs/plans/README.md | 1 + ...gVerificationBuilder.InCategory(string).md | 4 +- ...icationBuilder.InCategoryPrefix(string).md | 27 ++ ...tionBuilder.NotInCategoryPrefix(string).md | 26 ++ .../Compono.Logging.LogVerificationBuilder.md | 4 +- ...Metrics(thisCompono.CompositionBuilder).md | 21 +- .../0040-issue-161-1-4-dogfood-follow-up.md | 359 ++++++++++++++++++ docs/troubleshooting/common-errors.md | 39 +- mkdocs.yml | 1 + .../MetricsTests.cs | 4 +- .../MigrationGuideMetricsTests.cs | 42 ++ skills/compono/evals/evals.json | 91 ++++- skills/compono/references/logging.md | 16 +- skills/compono/references/metrics.md | 45 ++- .../registrations-profiles-and-scopes.md | 10 + skills/compono/references/xunit-v3.md | 22 +- .../ComponoIncrementalGenerator.cs | 7 +- .../Discovery/TransitiveClosureWalker.cs | 19 + .../Models/GeneratorFeatureFlags.cs | 5 +- src/Compono.Logging/LogVerificationBuilder.cs | 33 +- src/Compono.Metrics/Compono.Metrics.csproj | 10 + .../CompositionBuilderExtensions.cs | 15 +- .../MeterFactoryTestingExtensions.cs | 7 +- .../build/Compono.Metrics.props | 21 + src/Compono/build/Compono.props | 10 + .../MetricsTestDoubleOwnershipTests.cs | 112 ++++++ test/Compono.Logging.AotSmokeTest/Program.cs | 3 + .../CategoryPrefixFilterTests.cs | 154 ++++++++ .../MigrationGuideExamplesTests.cs | 76 ++++ .../pack-compono.sh | 3 + .../verify-packaging.sh | 71 +++- .../Compono.Metrics.Tests.csproj | 17 + .../MeterFactoryOwnershipTests.cs | 101 +++++ .../MigrationGuideExamplesTests.cs | 86 +++++ test/Compono.Metrics.Tests/MisuseTests.cs | 13 + .../DocumentedRecipeTests.cs | 147 +++++++ .../DocumentedRecipeTests.cs | 123 ++++++ 49 files changed, 2502 insertions(+), 63 deletions(-) create mode 100644 docs/migrating-from-microsoft-extensions-diagnostics-testing.md create mode 100644 docs/plans/0075-issue-161-1-4-dogfood-follow-up-impl-plan.md create mode 100644 docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.InCategoryPrefix(string).md create mode 100644 docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.NotInCategoryPrefix(string).md create mode 100644 docs/research/0040-issue-161-1-4-dogfood-follow-up.md create mode 100644 samples/Compono.Samples.BasicUsage/MigrationGuideMetricsTests.cs create mode 100644 src/Compono.Metrics/build/Compono.Metrics.props create mode 100644 test/Compono.Generators.Tests/MetricsTestDoubleOwnershipTests.cs create mode 100644 test/Compono.Logging.Tests/CategoryPrefixFilterTests.cs create mode 100644 test/Compono.Logging.Tests/MigrationGuideExamplesTests.cs create mode 100644 test/Compono.Metrics.Tests/MeterFactoryOwnershipTests.cs create mode 100644 test/Compono.Metrics.Tests/MigrationGuideExamplesTests.cs create mode 100644 test/Compono.XunitV3.Aot.Tests/DocumentedRecipeTests.cs create mode 100644 test/Compono.XunitV3.Tests/DocumentedRecipeTests.cs diff --git a/.github/scripts/inspect-packed-nupkgs.sh b/.github/scripts/inspect-packed-nupkgs.sh index a4eeebef..ee02e2ee 100755 --- a/.github/scripts/inspect-packed-nupkgs.sh +++ b/.github/scripts/inspect-packed-nupkgs.sh @@ -268,6 +268,11 @@ main() { # generation lives inside the existing Compono.Generators (packed only into Compono.nupkg), # reached transitively through this package's Compono dependency, not a second analyzer DLL. extra_paths=$'build/Compono.Logging.props\nbuildTransitive/Compono.Logging.props' + elif [ "$pkg" = "Compono.Metrics" ]; then + # build/ + buildTransitive/ Compono.Metrics.props: defaults ComponoMetricsOwnsMeterFactory to + # true (ADR-0072 Amendment 5), so Compono.Generators never emits a TestDoubles double for + # IMeterFactory - same shape as Compono.Logging above, no analyzer DLL of its own. + extra_paths=$'build/Compono.Metrics.props\nbuildTransitive/Compono.Metrics.props' fi if [ "$pkg" = "Compono.XunitV3.Aot" ]; then # net9.0+ only - matches xUnit v3's own Native AOT floor (ADR-0066/RESEARCH-0032); no diff --git a/docs/adr/0055-compono-logging-testing-support-package.md b/docs/adr/0055-compono-logging-testing-support-package.md index d7bf77dc..bdbdb572 100644 --- a/docs/adr/0055-compono-logging-testing-support-package.md +++ b/docs/adr/0055-compono-logging-testing-support-package.md @@ -1686,3 +1686,37 @@ dependency) is unchanged. `UseLogging()`, `CapturingLogger`/`CapturingLogger` and their per-logger capture are unchanged apart from carrying `Category`. Implementation is tracked in [PLAN-0072](../plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md). + +## Amendment 7 (2026-11-11): category-prefix filters `InCategoryPrefix` / `NotInCategoryPrefix` + +**Status:** Accepted (maintainer decision, 2026-11-11). + +The #161 follow-up ([RESEARCH-0040](../research/0040-issue-161-1-4-dogfood-follow-up.md) +finding 5) reported that host-level guards filter by category prefix, +typically negated ("no `Error` outside `MyApp.Jobs.*`"). Today that needs +`Matching(e => !e.Category.StartsWith(...))`, because `InCategory` is an +exact match. + +**Decision.** `LogVerificationBuilder` gains two named filters: + +```csharp +public LogVerificationBuilder InCategoryPrefix(string prefix); // Category starts with prefix +public LogVerificationBuilder NotInCategoryPrefix(string prefix); // Category does not start with prefix +``` + +- `StringComparison.Ordinal` (case-sensitive), matching `InCategory`. +- The prefix is literal, with no implicit `.` separator. + `InCategoryPrefix("MyApp.Jobs")` also matches `MyApp.JobsLegacy`. The + docs show a trailing dot (`"MyApp.Jobs."`) for namespace-boundary intent. +- `null` throws `ArgumentNullException`, like `InCategory`. An empty prefix + isn't special-cased: `InCategoryPrefix("")` matches every entry and + `NotInCategoryPrefix("")` matches none. +- Both compose with the existing AND-only chain and appear in failure + descriptions (`category starting with "..."`, + `category not starting with "..."`). +- `InCategory` is unchanged. There's no general negation combinator. + `Matching` stays the escape hatch. + +Both work on `CapturingLogger` verification and on `LogCollector` +verification, because they share the builder. Plain string comparison, so +AOT-safe. diff --git a/docs/adr/0072-compono-metrics-testing-support-package.md b/docs/adr/0072-compono-metrics-testing-support-package.md index 5a37aad0..e0ae8db0 100644 --- a/docs/adr/0072-compono-metrics-testing-support-package.md +++ b/docs/adr/0072-compono-metrics-testing-support-package.md @@ -722,3 +722,97 @@ where it reads naturally). Example: `Expected exactly 1 call(s) to instrument "shop.orders.placed" (long) with tag region = "eu" and value 1, but received 0.` No public API changed, and core `CallVerifier` is untouched. + +## Amendment 5 (2026-11-11): Compono.Metrics owns `IMeterFactory` — excluded from `Compono.TestDoubles` generation + +**Status:** Accepted (maintainer decision, 2026-11-11). **This amendment +explicitly supersedes the "Precedence and misuse" sentence *"No generator +exclusion is added."*** Everything else in that section stands, including +first-registered-wins against `UseNSubstitute()`. + +### What dogfooding found + +The #161 follow-up ([RESEARCH-0040](../research/0040-issue-161-1-4-dogfood-follow-up.md) +finding 1) migrated a 231-test suite with `ComponoGeneratedTestDoubles=true`. +A shared base profile called `UseGeneratedTestDoubles()` before +`UseMetrics()`. `Compono.Generators` emits a double for every interface it +reaches, so it had generated one for the SUT's `IMeterFactory`, and +`GeneratedTestDoubleProvider` won stage 6. 28 tests failed on measurement +assertions. Separately, `UseMetrics()`'s remarks and the misuse exception +named only `UseNSubstitute()`, never `UseGeneratedTestDoubles()`. + +### Decision + +Follow [ADR-0055](0055-compono-logging-testing-support-package.md) +Amendment 4's ownership precedent. When `Compono.Metrics` is referenced, +`System.Diagnostics.Metrics.IMeterFactory` is a **Metrics-owned +abstraction**, and `Compono.Generators` never generates a +`Compono.TestDoubles` double for it. + +- **Signal:** a new MSBuild property, `ComponoMetricsOwnsMeterFactory`. + `Compono.Metrics`'s packed `build/` and `buildTransitive/` props default + it to `true` when it's unset, and core `Compono.props` declares it + `CompilerVisibleProperty`. That's the same split `ComponoGeneratedLogging` + uses (ADR-0055 Amendment 3). Package or type presence isn't the signal, + per Amendment 3's rejection of symbol-presence gating. A consumer can set + it to `false` to get a generated `IMeterFactory` double back. +- **Mechanism:** the existing `TransitiveClosureWalker.TryRecordTestDouble` + exclusion check that already skips Logging-owned types. When the flag is + on, it also skips the type `IMeterFactory` resolves to. Nothing else in + discovery changes. If the type can't be resolved, the flag has no effect. +- **Unchanged:** stage-6 first-registered-wins (ADR-0024/ADR-0043), core + composition, and provider precedence. `UseMetrics()` must still come + before `UseNSubstitute()` or any other catch-all stage-6 provider. That + guidance stays in the remarks, the misuse message, and the docs, which + now also name `UseGeneratedTestDoubles()` and explain that, with + `Compono.Metrics` referenced, order against it doesn't matter. + +### Tradeoff (accepted) + +With `Compono.Metrics` referenced, a composer that calls +`UseGeneratedTestDoubles()` but **not** `UseMetrics()` gets no +`IMeterFactory` double. The request falls through to any later stage-6 +provider, or composition fails with the standard "no provider could +satisfy" `CompositionException`. Referencing a metrics-testing package +without calling `UseMetrics()` is almost always a mistake, and a loud +failure beats a silently uncapturing double. Opting out is one property. + +### Verification + +Generator tests cover flag on, flag off, a sibling interface still being +doubled, and the flag having no effect when the type can't be resolved. +`Compono.Metrics.Tests` runtime tests (real generated doubles enabled) +cover both registration orders with `UseGeneratedTestDoubles()` and the +referenced-without-`UseMetrics()` case. Tracked in +[PLAN-0075](../plans/0075-issue-161-1-4-dogfood-follow-up-impl-plan.md). + +## Amendment 6 (2026-11-11): disposal patterns clarified per test engine — no ownership change + +**Status:** Accepted (maintainer decision, 2026-11-11). This is a +clarification only. "Composition stays non-owning", "No new ownership API +is added", and the "Automatic disposal by composition" non-goal are +unchanged, and [ADR-0022](0022-compono-xunit-package-design.md) +Amendment 4 stands. + +"Disposal patterns" pattern 1 prescribes `using var _ = meters;` in every +`[Compose]`-family test and says Compono doesn't rely on framework disposal +"either way". RESEARCH-0040 finding 3 checked this empirically on xUnit +v3 4.0.1 (JIT): xUnit itself disposes every `IDisposable`/`IAsyncDisposable` +test-method argument after the test case, once per argument slot +(RESEARCH-0038 §2.4, ADR-0070 contract item 12). A `[Shared] IMeterFactory` +parameter is the SUT's instance, so on `Compono.XunitV3` xUnit already +disposes it and the `using` line is redundant (harmless, because +`Dispose()` is idempotent). xUnit's AOT core doesn't dispose arguments. TUnit, +NUnit, and MSTest weren't re-tested here. TUnit's root-argument disposal is +already documented separately in +[ADR-0040](0040-compono-tunit-package-design.md) ("Diagnostics, disposal, +and seed observability") and in the `Compono.TUnit` package guide. This +amendment relies on that documented contract and doesn't re-verify it. + +The documented guidance is now per engine: on `Compono.XunitV3` the +`using` line is optional. It's also optional on `Compono.TUnit`, per ADR-0040's +documented root-argument disposal. Keep it on `Compono.XunitV3.Aot`, +`Compono.NUnit`, `Compono.MSTest`, and `Composer.Create` tests. Compono still registers +nothing for disposal (`ComposeAttributeDisposalTests` still guards that), +and xUnit's argument disposal remains xUnit's behavior, not a Compono +contract. diff --git a/docs/cookbook/vary-composed-configuration-per-theory-row.md b/docs/cookbook/vary-composed-configuration-per-theory-row.md index 7f0220bf..cc956a4e 100644 --- a/docs/cookbook/vary-composed-configuration-per-theory-row.md +++ b/docs/cookbook/vary-composed-configuration-per-theory-row.md @@ -86,6 +86,12 @@ parameter) and no xUnit `TypeHelper` conversion. Null is allowed only for a nullable value type or a `?`-annotated reference. Put the row values first in the parameter list; composed parameters follow. +**Need the row's `TConfig` in the test body?** Don't repeat its values as +extra row elements. Have the profile register the config it already +receives, `builder.Register(() => config)`, and add a composed `TConfig` +parameter after the row values. It resolves to that row's own instance. +See [Reading the row's `TConfig`](../packages/compono-xunitv3.md#per-row-configuration). + **`[Shared]` still works.** Mark a parameter `[Shared]` and, when a row supplies a value at that position, that value becomes the single instance every other parameter in the row resolving that type receives; otherwise diff --git a/docs/how-to/assert-nothing-logged-at-error-across-a-host.md b/docs/how-to/assert-nothing-logged-at-error-across-a-host.md index caa4ce95..2e68a312 100644 --- a/docs/how-to/assert-nothing-logged-at-error-across-a-host.md +++ b/docs/how-to/assert-nothing-logged-at-error-across-a-host.md @@ -65,15 +65,30 @@ or a short name. `InCategory` never matches by prefix, unlike the host's own `AddFilter` and `Logging:LogLevel:*` rules. A category string that matches nothing makes `Never()` pass without checking anything. To cover a whole -namespace, match the prefix explicitly: +namespace, use `InCategoryPrefix`, or `NotInCategoryPrefix` to check +everything *outside* it: ```csharp logs.Verify() .AtLevelOrAbove(LogLevel.Error) - .Matching(entry => entry.Category.StartsWith("MyApp.Payments.", StringComparison.Ordinal)) + .InCategoryPrefix("MyApp.Payments.") + .Never(); + +// The common host guard: nothing at Error or above outside your own code. +logs.Verify() + .AtLevelOrAbove(LogLevel.Error) + .NotInCategoryPrefix("MyApp.Jobs.") .Never(); ``` +`InCategoryPrefix`/`NotInCategoryPrefix` are ordinal and case-sensitive like +`InCategory`, and the prefix is **literal**: no namespace separator is +added. `InCategoryPrefix("MyApp.Jobs")` also matches `MyApp.JobsLegacy`, so +end the prefix with `.` to mean "beneath this namespace". `"MyApp.Jobs."` +doesn't match the bare `MyApp.Jobs` category itself. Use `.Matching(...)` for +anything else, such as several namespaces at once +([ADR-0055 Amendment 7](../adr/0055-compono-logging-testing-support-package.md)). + ## What the host may not capture Compono never changes the host's own filter rules. The default host diff --git a/docs/how-to/use-profiles.md b/docs/how-to/use-profiles.md index ca9ba320..ce4a2611 100644 --- a/docs/how-to/use-profiles.md +++ b/docs/how-to/use-profiles.md @@ -43,6 +43,70 @@ for the full shape and [Migrating from AutoFixture](../migrating-from-autofixture.md#migrate-a-parameterized-custom-autodataattribute) for the AutoFixture pattern this replaces. +## A profile whose constructor takes runtime objects + +`[Compose]` arguments must be attribute constants. A +profile that needs runtime objects, such as interceptors, a configured +client, or an in-memory log, can't get them from an attribute. There are +two patterns, and both work on `Compono.XunitV3` and `Compono.XunitV3.Aot`. + +**1. A parameterless wrapper profile per variant.** Name each variant once, +then use it like any other profile. The wrapper builds the arguments and +applies the real profile with `AddProfile(instance)`: + +```csharp +public sealed class DbProfile(AuditInterceptor? interceptor) : ICompositionProfile +{ + public void Configure(CompositionBuilder builder) => + builder.Register(() => new OrderRepository(interceptor)); +} + +public sealed class AuditedDbProfile : ICompositionProfile +{ + public void Configure(CompositionBuilder builder) + { + var log = new AuditLog(); + builder.Register(() => log); // so the test can assert on it + builder.AddProfile(new DbProfile(new AuditInterceptor(log))); + } +} + +[Theory, Compose] +public void SavingIsAudited(OrderRepository sut, AuditLog log) +{ + sut.Save("42"); + Assert.Equal(["saved 42"], log.Entries); +} +``` + +Prefer this over adding a parameterless constructor to `DbProfile` itself. +The variant gets its own name, and `DbProfile` keeps one constructor. + +**2. A single-row `[ComposeData]`.** When the arguments +are data (built in a static member rather than per variant), put them in a +`TConfig` and supply one row: + +```csharp +public sealed record AuditConfig(AuditInterceptor Interceptor); + +public static TheoryData Audited => + new() { new AuditConfig(new AuditInterceptor(new AuditLog())) }; + +[Theory] +[ComposeData(nameof(Audited))] +public void SavingIsAudited(OrderRepository sut, AuditLog log) { /* ... */ } +``` + +The test is a one-row theory. Both patterns are exercised by +`DocumentedRecipeTests` in `test/Compono.XunitV3.Tests` and +`test/Compono.XunitV3.Aot.Tests`. A dedicated "profile factory member" +attribute property isn't offered. It's deferred until these patterns prove +inadequate +([RESEARCH-0040](../research/0040-issue-161-1-4-dogfood-follow-up.md) +finding 6). Runtime values from an xUnit fixture can also be read inside a +profile with `TestContext.Current.RequireFixture()`; see the +[`Compono.XunitV3` Package Guide](../packages/compono-xunitv3.md). + ## Combining more than one profile ```csharp diff --git a/docs/migrating-from-microsoft-extensions-diagnostics-testing.md b/docs/migrating-from-microsoft-extensions-diagnostics-testing.md new file mode 100644 index 00000000..c059196f --- /dev/null +++ b/docs/migrating-from-microsoft-extensions-diagnostics-testing.md @@ -0,0 +1,224 @@ +--- +title: Migrating from Microsoft.Extensions.Diagnostics.Testing +description: Map AddFakeLogging, FakeLogCollector, FakeLogger, and MetricCollector onto Compono.Logging's LogCollector/AddComponoCapture and Compono.Metrics' CapturingMeterFactory/UseMetrics. +--- + +# Migrating from Microsoft.Extensions.Diagnostics.Testing + +`Microsoft.Extensions.Diagnostics.Testing` provides fake logging +(`AddFakeLogging`, `FakeLogCollector`, `FakeLogger`) and metric +collection (`MetricCollector`). [`Compono.Logging`](packages/compono-logging.md) +and [`Compono.Metrics`](packages/compono-metrics.md) cover the same ground +with composition built in, and neither depends on that package. You don't +have to migrate: if you prefer it, keep it. + +Every Compono ("After") example below comes from a compiled, running test: + +- Logging: `MigrationGuideExamplesTests` in `test/Compono.Logging.Tests`. + The short category-filter lines are covered by `CategoryPrefixFilterTests` + in the same project. +- Metrics `[Compose]` example: `MigrationGuideMetricsTests` in + `samples/Compono.Samples.BasicUsage`. +- Metrics host and `ClearMeasurements()` examples: `MigrationGuideExamplesTests` + in `test/Compono.Metrics.Tests`. + +The "Before" snippets show the `Microsoft.Extensions.Diagnostics.Testing` +code being replaced. They're for comparison and aren't compiled in this +repository. + +## At a glance + +| `Microsoft.Extensions.Diagnostics.Testing` | Compono | +|---|---| +| `builder.Logging.AddFakeLogging()` | `builder.Logging.AddComponoCapture(logs)` with a test-owned `var logs = new LogCollector();` | +| `host.Services.GetFakeLogCollector()` | The `LogCollector` instance you created. Nothing to resolve | +| `collector.GetSnapshot()` / `LatestRecord` / `Count` | `logs.GetCapturedEntries()` / `GetLastCapturedEntry()` / `GetCapturedEntries().Count` | +| `collector.Clear()` | `logs.ClearCapturedEntries()` | +| `FakeLogRecord.Level` / `Id` / `Category` / `Message` / `Exception` / `Scopes` | `CapturedLogEntry.LogLevel` / `EventId` / `Category` / `Message` / `Exception` / `Scopes` | +| LINQ over the snapshot, then assert | `logs.Verify().AtLevelOrAbove(...).InCategory(...).Never()` (or `.Once()`, `.Exactly(n)`, …) | +| `new FakeLogger()` | A composed `ILogger` under `UseLogging()`, or `new CapturingLogger()` | +| A hand-written test `IMeterFactory` | `UseMetrics()` (composed), or `new CapturingMeterFactory()` | +| `new MetricCollector(meterFactory, meterName, instrumentName)` | Nothing. The factory captures every instrument it creates | +| `collector.GetMeasurementSnapshot()` | `meters.GetMeasurements(meterName, instrumentName)` | +| `collector.LastMeasurement.Value` / `.Tags["k"]` | `meters.Verify(...).WithValue(v).WithTag("k", value).Once()` | +| `collector.RecordObservableInstruments()` | `meters.RecordObservableInstruments()` | +| `collector.Clear()` | `meters.ClearMeasurements()` | +| `collector.WaitForMeasurementsAsync(n)` | No equivalent. Synchronize on the SUT's own completion first | + +## Logging + +### Host-wide capture (`AddFakeLogging` → `AddComponoCapture`) + +```csharp +// Before +builder.Logging.AddFakeLogging(); +var logs = host.Services.GetFakeLogCollector(); +Assert.DoesNotContain(logs.GetSnapshot(), r => r.Level >= LogLevel.Error); + +// After +var logs = new LogCollector(); +var builder = Host.CreateApplicationBuilder(); +builder.Logging.ClearProviders(); +builder.Logging.AddComponoCapture(logs); +builder.Services.AddHostedService(); +using var host = builder.Build(); + +await host.StartAsync(cancellationToken); +await host.StopAsync(cancellationToken); + +logs.Verify().AtLevelOrAbove(LogLevel.Error).Never(); +logs.Verify() + .InCategory("Compono.Logging.Tests.CheckoutWorker") + .WithMessageContaining("Checkout started for 42") + .Once(); +``` + +The collector is test-owned. You create it before the host and pass it in, +so there's nothing to resolve from the container afterwards. Assert only after +the code under test has actually logged. `CheckoutWorker` here is an +`IHostedService` that logs in `StartAsync`. A `BackgroundService` runs +`ExecuteAsync` on a background task (since .NET 10), so stopping the host +straight after `StartAsync` can cancel it before it logs. Await the worker's +own completion signal first. Host filter +rules still apply exactly as they do for any other provider. See +[Assert Nothing Was Logged at Error Across a Host](how-to/assert-nothing-logged-at-error-across-a-host.md). + +### Category filters + +`Category` is the exact string the logging pipeline passes to +`ILoggerProvider.CreateLogger`. For an `ILogger` that's `T`'s full name, +with nested types joined by `.`. Matching is ordinal and case-sensitive: + +```csharp +logs.Verify().InCategory("MyApp.Jobs.Scheduler").Once(); // exact +logs.Verify().AtLevelOrAbove(LogLevel.Error).InCategoryPrefix("MyApp.Jobs.").Never(); +logs.Verify().AtLevelOrAbove(LogLevel.Error).NotInCategoryPrefix("MyApp.Jobs.").Never(); // "nothing outside my code" +``` + +Prefixes are literal. End one with `.` so `MyApp.Jobs.` doesn't also match +`MyApp.JobsLegacy`. + +### Inspecting and resetting + +```csharp +var entries = logs.GetCapturedEntries(); // GetSnapshot() +var last = logs.GetLastCapturedEntry(); // LatestRecord +logs.ClearCapturedEntries(); // Clear() +``` + +### A single logger (`FakeLogger` → composed `ILogger`) + +```csharp +var composer = Composer.Create(builder => builder.UseLogging()); +var logger = composer.Create>(); + +logger.LogWarning("Payment retry {Attempt}", 2); + +logger.Verify().AtLevel(LogLevel.Warning).WithMessageContaining("Payment retry 2").Once(); +``` + +In a `[Compose]` theory, take `[Shared] ILogger` alongside the SUT to get +the SUT's own logger. + +## Metrics + +### Composed factory (`MetricCollector` → `UseMetrics()`) + +```csharp +// Before +using var meterFactory = new TestMeterFactory(); // hand-written +using var collector = new MetricCollector(meterFactory, "Shop.Orders", "shop.orders.placed"); +var sut = new OrderService(meterFactory); +sut.PlaceOrder("eu", 2); +Assert.Equal(1, collector.LastMeasurement!.Value); +Assert.Equal("eu", collector.LastMeasurement.Tags["region"]); + +// After +[Theory, Compose] // MetricsProfile: builder.UseMetrics() +public void PlacingAnOrderCountsIt([Shared] IMeterFactory meters, OrderService sut) +{ + sut.PlaceOrder("eu", 2); + + meters.Verify("Shop.Orders", "shop.orders.placed").WithTag("region", "eu").WithValue(1).Once(); + var placed = meters.GetMeasurements("Shop.Orders", "shop.orders.placed"); // GetMeasurementSnapshot() + Assert.Single(placed); +} +``` + +You don't create a collector per instrument. The factory captures every +instrument its meters publish. `[Shared]` makes the parameter the same +factory the SUT received. `CapturedMeasurement.Tags` is an ordered list +of key/value pairs, not a dictionary, so use `WithTag`/`WithoutTag` to +filter. + +### Generic Host + +```csharp +using var meters = new CapturingMeterFactory(); +var builder = Host.CreateApplicationBuilder(); +builder.Services.AddSingleton(meters); // after the host's default: the last registration wins +builder.Services.AddSingleton(); +using var host = builder.Build(); + +await host.StartAsync(cancellationToken); +host.Services.GetRequiredService().RunOnce(); +await host.StopAsync(cancellationToken); + +meters.Verify("outbox.published").WithTag("queue", "orders").Once(); +``` + +Don't use `TryAddSingleton`. It keeps the host's default factory. See +[Verify Metrics Across a Host](how-to/verify-metrics-across-a-host.md). + +### Asserting on one pass (`collector.Clear()` → `ClearMeasurements()`) + +```csharp +sut.RunOnce(); +sut.RunOnce(); + +meters.ClearMeasurements(); // only the pass under test counts from here +sut.RunOnce(); + +meters.Verify("outbox.published").WithValue(1).Once(); +``` + +## Registration order + +- **Stage-6 composition order.** `UseMetrics()` and `UseLogging()` are + test-double providers, so they must come **before** `UseNSubstitute()` or + any other catch-all provider. Otherwise a substitute takes + `IMeterFactory`/`ILogger`. Put them first in a shared base profile. + Order against `UseGeneratedTestDoubles()` doesn't matter: both packages own + their abstractions by default (`ComponoMetricsOwnsMeterFactory`, + `ComponoGeneratedLogging`), so no generated double competes for them. +- **Host DI order.** A test `IMeterFactory` registered with + `AddSingleton` must come after anything else that registers one. The + container resolves a single service to its last registration. + `AddComponoCapture` adds a logging provider alongside the others. + `ClearProviders()` first if you want only Compono's capture. + +## Disposal + +- `LogCollector` holds no unmanaged state, so there's nothing to dispose. +- `IMeterFactory` is `IDisposable`. A factory you construct + (`new CapturingMeterFactory()`, host recipe) is yours: `using var meters`. + Dispose it after the host has stopped. +- A composed `[Shared] IMeterFactory` parameter: on `Compono.XunitV3`, xUnit + disposes test-method arguments itself, so `using var _ = meters;` is + optional. On `Compono.XunitV3.Aot` it's required. TUnit disposes composed + root arguments according to + [`Compono.TUnit` — Disposal](packages/compono-tunit.md#disposal) + (ADR-0040; documented, not re-tested for this guide). NUnit and MSTest + aren't verified, so keep it there. + Compono never disposes composed values. See + [Compono.Metrics — Disposal patterns](packages/compono-metrics.md#disposal-patterns). + +## What has no direct equivalent + +- **Waiting for measurements** (`WaitForMeasurementsAsync`) isn't provided. + Await the SUT's own completion signal before asserting. +- **`FakeLogCollectorOptions` filtering** (by category or level at capture + time). Capture everything the host's filters let through, and filter in + `Verify()` instead. +- **Redaction and enrichment fakes** from the same package are out of scope + for Compono. Keep using them if you need them. diff --git a/docs/packages/compono-logging.md b/docs/packages/compono-logging.md index ddaa00a9..b32f9e22 100644 --- a/docs/packages/compono-logging.md +++ b/docs/packages/compono-logging.md @@ -84,6 +84,7 @@ Console.WriteLine(failure.Properties?.First().Key); // "OrderId", e.g. required. - **`logger.Verify()`** — the fluent entry point: `.AtLevel(level)`, `.AtLevelOrAbove(level)`, `.InCategory(category)`, + `.InCategoryPrefix(prefix)`, `.NotInCategoryPrefix(prefix)`, `.WithEventId(id)`, `.WithException()`, `.WithMessageContaining(text)`, `.Matching(predicate)`, ending in `.Once()` / `.Never()` / `.Exactly(n)` / `.AtLeast(n)` / `.AtMost(n)` @@ -166,15 +167,29 @@ rules — `AddFilter("MyApp.Payments", ...)` and `Logging:LogLevel:MyApp.Payment configuration match every category that *starts with* that prefix. Combined with `Never()`, a category string that matches nothing passes without checking anything, so use the full category name, or assert by prefix -explicitly: +with `InCategoryPrefix`: ```csharp logs.Verify() .AtLevelOrAbove(LogLevel.Error) - .Matching(entry => entry.Category.StartsWith("MyApp.Payments.", StringComparison.Ordinal)) + .InCategoryPrefix("MyApp.Payments.") + .Never(); + +// The common host guard: nothing at Error or above outside your own code. +logs.Verify() + .AtLevelOrAbove(LogLevel.Error) + .NotInCategoryPrefix("MyApp.Jobs.") .Never(); ``` +`InCategoryPrefix`/`NotInCategoryPrefix` are ordinal and case-sensitive like +`InCategory`, and the prefix is **literal**: no namespace separator is +added. `InCategoryPrefix("MyApp.Jobs")` also matches `MyApp.JobsLegacy`, so +end the prefix with `.` to mean "beneath this namespace". `"MyApp.Jobs."` +doesn't match the bare `MyApp.Jobs` category itself. Use `.Matching(...)` for +anything else, such as several namespaces at once +([ADR-0055 Amendment 7](../adr/0055-compono-logging-testing-support-package.md)). + > **Behavioral compatibility note.** `Category` is part of > `CapturedLogEntry`'s record value equality: two entries identical in > every other field but produced by different categories are **not** equal @@ -184,15 +199,19 @@ logs.Verify() ### Filters -Two filters exist for the host-wide scenario and behave identically on a +These filters exist for the host-wide scenario and behave identically on a composed `logger.Verify()` and a `LogCollector.Verify()`: - `.AtLevelOrAbove(level)` — `Error` matches `Error` and `Critical`. `AtLevelOrAbove(LogLevel.None)` matches nothing. - `.InCategory(category)` — exact ordinal match; `null` throws `ArgumentNullException`. +- `.InCategoryPrefix(prefix)` / `.NotInCategoryPrefix(prefix)` — the + category does / doesn't start with the literal `prefix` (ordinal); `null` + throws `ArgumentNullException`. An empty prefix matches every entry / + no entry. -Both contribute to the failure text, e.g. `Expected exactly 0 call(s) to a +All of them contribute to the failure text, e.g. `Expected exactly 0 call(s) to a log entry matching level Error or above, but received 1.` The message names the filters and the match count only — it does not list the matching entries. Read them with `GetCapturedEntries()` when diagnosing a failure. @@ -495,6 +514,9 @@ the rationale behind each: ## Next +- [Migrating from Microsoft.Extensions.Diagnostics.Testing](../migrating-from-microsoft-extensions-diagnostics-testing.md) + — `AddFakeLogging`/`FakeLogCollector`/`MetricCollector` mapped onto + Compono, with registration order and disposal. - [Basic Usage sample](../samples/basic-usage.md) (`LoggingTests`) — a concise `UseLogging()`/`Verify()` scenario in this repo's single clearest reference project. diff --git a/docs/packages/compono-metrics.md b/docs/packages/compono-metrics.md index a6890088..6a9c2740 100644 --- a/docs/packages/compono-metrics.md +++ b/docs/packages/compono-metrics.md @@ -62,7 +62,7 @@ public sealed class MetricsProfile : ICompositionProfile [Compose] public void PlacingAnOrderCountsIt([Shared] IMeterFactory meters, OrderService sut) { - using var _ = meters; // the test owns disposal; see "Disposal patterns" + using var _ = meters; // optional on Compono.XunitV3 (JIT); see "Disposal patterns" sut.PlaceOrder(new Order("eu", 3)); @@ -96,7 +96,8 @@ Assert.Equal(1, placed.Sum(m => m.Value)); // value - **`meters.RecordObservableInstruments()`** — polls this factory's observable instruments. Reads never poll; see "Observable instruments." - **`meters.ClearMeasurements()`** — empties the capture buffer. Order is - otherwise capture order; see "Capture order." + otherwise capture order; see "Capture order." It's also the supported way + to assert on one pass of a multi-pass test; see "Asserting on one pass." - **`CapturingMeterFactory`** — hand-written and publicly, directly constructible with no composition involved at all: ```csharp @@ -243,7 +244,21 @@ thread-safe, so a test framework that also disposes the argument is harmless. The documented patterns: 1. **`[Compose]`-family tests: dispose the `[Shared]` parameter in the test - body.** + body, unless the test framework already does.** + + | Adapter | Disposes `IDisposable` test-method arguments? | `using var _ = meters;` | + |---|---|---| + | `Compono.XunitV3` (xUnit v3, JIT) | **Yes.** xUnit disposes every `IDisposable`/`IAsyncDisposable` argument after the test case, once per argument slot | Optional (harmless) | + | `Compono.XunitV3.Aot` (xUnit v3 Native AOT) | No | Required | + | `Compono.TUnit` | **Documented, not re-tested here:** TUnit disposes a composed **root** method argument itself ([`Compono.TUnit` — Disposal](compono-tunit.md#disposal), [ADR-0040](../adr/0040-compono-tunit-package-design.md)). ADR-0072 Amendment 6 didn't re-run that check | Optional by that documented behavior; keeping it is harmless | +| `Compono.NUnit`, `Compono.MSTest` | Not verified | Keep it (harmless; `Dispose()` is idempotent) | + + That disposal is xUnit's own behavior, not a Compono contract. Compono + registers nothing for disposal. With `[Shared]`, the parameter *is* the + SUT's factory, so xUnit disposing the argument disposes the SUT's meters + too. Without `[Shared]`, the SUT's factory is a different instance, and + nothing disposes it. See + [ADR-0072 Amendment 6](../adr/0072-compono-metrics-testing-support-package.md). ```csharp [Theory, Compose] @@ -262,6 +277,8 @@ harmless. The documented patterns: captured data stays readable after disposal. In an `async` test, `using var` works the same way and runs after the last `await`. `IMeterFactory` isn't `IAsyncDisposable`, so `await using` doesn't apply. + On `Compono.XunitV3`, you can drop the line. xUnit disposes the argument + after the test case, which is after every assertion has run. 2. **`Composer.Create` tests: construct the factory, then register it.** @@ -307,6 +324,37 @@ that created meters stays referenced by the BCL's static meter list for the process lifetime — the same cost as an undisposed `DefaultMeterFactory`. A factory that never created a meter costs nothing. +## Asserting on one pass + +A test that drives several passes over the same SUT (an outbox processor +run three times against one database, say) and asserts only on the last +pass calls `ClearMeasurements()` immediately before the step under test. +Everything recorded before that point is discarded, so the verification +reads as "measurements from this pass": + +```csharp +[Theory, Compose] +public async Task ThirdPassPublishesTheRemainingMessage([Shared] IMeterFactory meters, OutboxProcessor sut) +{ + await sut.RunOnceAsync(); // pass 1: arrange + await sut.RunOnceAsync(); // pass 2: arrange + + meters.ClearMeasurements(); // act boundary: only the pass under test counts from here + await sut.RunOnceAsync(); // pass 3: the step under test + + meters.Verify("outbox.published").WithValue(1).Once(); +} +``` + +This is the same reset idiom as `Compono.TestDoubles` `ClearCalls()` and +`Compono.Logging` `ClearCapturedEntries()`. `ClearMeasurements()` doesn't +change a snapshot list already returned by `GetMeasurements`, so to +assert on an earlier pass too, take that snapshot before clearing. +Checkpoint or scoped-capture APIs are deferred until a test needs +measurements from several phases kept and asserted independently +([RESEARCH-0040](../research/0040-issue-161-1-4-dogfood-follow-up.md) +finding 4). + ## Snapshot lifetime - `GetMeasurements` returns a new list each call. Later captures, @@ -345,19 +393,38 @@ factory that never created a meter costs nothing. - `UseMetrics()` registers a stage-6 provider that handles exactly `typeof(IMeterFactory)` and returns `NotHandled` for everything else. - Precedence against `UseNSubstitute()`/`UseGeneratedTestDoubles()` follows - the existing first-registered-wins rule + Precedence against `UseNSubstitute()` (or any other catch-all stage-6 + provider) follows the existing first-registered-wins rule ([ADR-0024](../adr/0024-public-provider-extensibility-model.md)). - Register `UseMetrics()` first: + Register `UseMetrics()` first, especially in a shared base profile: ```csharp builder.UseMetrics().UseNSubstitute(); // IMeterFactory -> CapturingMeterFactory builder.UseNSubstitute().UseMetrics(); // IMeterFactory -> a substitute instead ``` +- **`Compono.Metrics` owns `IMeterFactory`, so order against + `UseGeneratedTestDoubles()` doesn't matter.** Referencing the package sets + the MSBuild property `ComponoMetricsOwnsMeterFactory` to `true` by default. + `Compono.TestDoubles` then never generates a double for `IMeterFactory`, + even with `ComponoGeneratedTestDoubles=true`, and both + `UseGeneratedTestDoubles().UseMetrics()` and + `UseMetrics().UseGeneratedTestDoubles()` compose a `CapturingMeterFactory`. + Other interfaces still get their generated doubles + ([ADR-0072 Amendment 5](../adr/0072-compono-metrics-testing-support-package.md)). + - **Tradeoff:** with the package referenced, a composer that calls + `UseGeneratedTestDoubles()` but not `UseMetrics()` gets no + `IMeterFactory` double. The request falls through to a later stage-6 + provider (such as NSubstitute), or composition fails with a + `CompositionException` naming `IMeterFactory`. Add `UseMetrics()`. + - **Opt out:** to get a generated `IMeterFactory` double back, set + `false` + in the test project. Order against `UseGeneratedTestDoubles()` then + matters again. - Every `MeterFactoryTestingExtensions` method throws `InvalidOperationException` when the `IMeterFactory` isn't a `CapturingMeterFactory`. The message names `UseMetrics()`, the - registration-order requirement, and the host recipe. It's detected by a - type check, not reflection. + registration-order requirement for catch-all providers, the + `ComponoMetricsOwnsMeterFactory` ownership rule, and the host recipe. It's + detected by a type check, not reflection. - `Meter` constructor parameters are not composed by this package. Consumers that want a specific `Meter` register it from the shared factory in a profile. @@ -391,6 +458,9 @@ rationale behind each: ## Next +- [Migrating from Microsoft.Extensions.Diagnostics.Testing](../migrating-from-microsoft-extensions-diagnostics-testing.md) + — `AddFakeLogging`/`FakeLogCollector`/`MetricCollector` mapped onto + Compono, with registration order and disposal. - [Basic Usage sample](../samples/basic-usage.md) (`MetricsTests`) — a concise `UseMetrics()`/`Verify()` scenario in this repo's single clearest reference project. diff --git a/docs/packages/compono-xunitv3-aot.md b/docs/packages/compono-xunitv3-aot.md index 11d853c5..d4bc2cee 100644 --- a/docs/packages/compono-xunitv3-aot.md +++ b/docs/packages/compono-xunitv3-aot.md @@ -234,7 +234,16 @@ a shape is unreachable from generated code. The differences: - **Disposal.** xUnit's JIT runner disposes `IDisposable` theory arguments; its Native AOT core does not. Don't pass a fixture-owned disposable as a theory parameter on either engine — see [`Compono.XunitV3`'s - disposal note](compono-xunitv3.md#disposal). + disposal note](compono-xunitv3.md#disposal). A composed disposable you + *do* own, such as a `[Shared] IMeterFactory`, must be disposed in the test + body here (`using var _ = meters;`), because nothing else disposes it on + AOT. + +The register-the-row-config recipe for reading a row's `TConfig` in the test +body, and the wrapper-profile pattern for profile constructor arguments, work +unchanged on this package. See [`Compono.XunitV3`'s per-row +configuration](compono-xunitv3.md#per-row-configuration) and +[Use Profiles](../how-to/use-profiles.md#a-profile-whose-constructor-takes-runtime-objects). ## Not yet supported diff --git a/docs/packages/compono-xunitv3.md b/docs/packages/compono-xunitv3.md index 8e10eada..b4e999f6 100644 --- a/docs/packages/compono-xunitv3.md +++ b/docs/packages/compono-xunitv3.md @@ -301,6 +301,17 @@ values use — see [ADR-0022](../adr/0022-compono-xunit-package-design.md)): row value `i` binds to test parameter `i`, left to right, and any parameters after the row values are composed. To put a composed collaborator before a row value, reorder the method's parameters so the row values come first. +Write the signature as **row values first, then `[Shared]` and composed +parameters**: + +```csharp +// row: [config, "first", 1] -> label = "first", count = 1, then window and sut are composed +public void Ordered(string label, int count, [Shared] RetentionWindow window, RetentionPolicy sut) +``` + +Binding by parameter name, or binding a parameter to the row's `TConfig` +element, isn't supported. Either would make a row ambiguous whenever a later +element is also assignable to the same type. For `[ComposeData]`, element 0 is consumed as the row's configuration and is **not** a row value; elements 1..n bind to parameters @@ -327,6 +338,41 @@ it (`new TProfile(rowConfig)`). This is the multi-row counterpart to whole method, every row carries its own. The profile (and everything it registers) is never shared across rows. +**Reading the row's `TConfig` in the test body.** Element 0 goes to the +profile constructor and doesn't bind to a parameter. The profile already +holds it, so have the profile register it. A composed `TConfig` parameter +then receives that row's own instance (an exact registration), with no +need to repeat the same values as row elements: + +```csharp +public sealed record RetentionWindow(int DaysBefore, int DaysAfter); + +public sealed class RetentionProfile(RetentionWindow window) : ICompositionProfile +{ + public void Configure(CompositionBuilder builder) => builder.Register(() => window); +} + +public static TheoryData RetentionCases => new() +{ + { new RetentionWindow(DaysBefore: 7, DaysAfter: 30), 30, true }, + { new RetentionWindow(DaysBefore: 7, DaysAfter: 30), 31, false }, +}; + +[Theory] +[ComposeData(nameof(RetentionCases))] +public void Keeps(int ageInDays, bool expected, RetentionWindow window, RetentionPolicy sut) +{ + Assert.Equal(expected, sut.Keeps(ageInDays)); + Assert.Equal(expected, ageInDays <= window.DaysAfter); // the row's own config +} +``` + +This works the same on `Compono.XunitV3.Aot`. Both engines are proven by +`DocumentedRecipeTests` in `test/Compono.XunitV3.Tests` and +`test/Compono.XunitV3.Aot.Tests` +([RESEARCH-0040](../research/0040-issue-161-1-4-dogfood-follow-up.md) +finding 2). + ### Shared dependencies and `[Shared]` A `[Shared]` parameter works the same as under `[Compose]`: it names the one @@ -394,6 +440,15 @@ disposes every `IDisposable` theory argument, a `[Shared]` parameter included, so a fixture-owned instance would be disposed by JIT but not by AOT. Dispose what you create; let the fixture own anything longer lived. +The same xUnit behavior applies to `[Compose]` theories. It was confirmed on +xUnit v3 4.0.1: the argument is disposed after the test case, once per +argument slot, so a `[Shared]` value bound to two parameters is disposed +twice. Disposable composed types must therefore tolerate repeated +`Dispose()`, as .NET guidance already requires. A `using var _ = meters;` +line for a `[Shared] IMeterFactory` is optional on this package (xUnit +disposes the argument anyway) but still needed on `Compono.XunitV3.Aot`. +See [Compono.Metrics — Disposal patterns](compono-metrics.md#disposal-patterns). + ### Failures, seeds, and row labels Every failure — reading the member, building one row's profile, or composing a diff --git a/docs/plans/0075-issue-161-1-4-dogfood-follow-up-impl-plan.md b/docs/plans/0075-issue-161-1-4-dogfood-follow-up-impl-plan.md new file mode 100644 index 00000000..62ade6e2 --- /dev/null +++ b/docs/plans/0075-issue-161-1-4-dogfood-follow-up-impl-plan.md @@ -0,0 +1,192 @@ +# [PLAN-0075] Issue #161 1.4 Dogfood Follow-Up + +**Status:** Done (local; awaiting maintainer review before any PR) + +**Implements:** [ADR-0072](../adr/0072-compono-metrics-testing-support-package.md) +Amendments 5–6 and [ADR-0055](../adr/0055-compono-logging-testing-support-package.md) +Amendment 7. Triage and decisions: +[RESEARCH-0040](../research/0040-issue-161-1-4-dogfood-follow-up.md). +Beads epic: `compono-gec`. + +## Goal + +The seven #161 follow-up findings are resolved as RESEARCH-0040 decided. +`IMeterFactory` never gets a generated double when `Compono.Metrics` is +referenced. `LogVerificationBuilder` has `InCategoryPrefix` and +`NotInCategoryPrefix`. The documentation-only items (ComposeData binding +and `TConfig` access, per-engine disposal, the `ClearMeasurements()` +multi-pass pattern, profile constructor-argument patterns, and a +migration guide from `Microsoft.Extensions.Diagnostics.Testing`) ship +with tested examples. Build and tests are green on every TFM, and the +relevant AOT smoke tests and pack-consume checks pass. + +## Scope + +In scope: findings 1, 2, 3, 4 (docs only), 5, 6 (docs only), and 7, +per RESEARCH-0040's summary table. One PR, because the changes are small, +all trace back to one dogfood report, and every behavioral change is +additive or pre-stable. + +Explicitly deferred or rejected (RESEARCH-0040): metrics checkpoint, +`Since`, or scoped-capture APIs; `ProfileMember`/profile-factory +activation; implicit or named `ComposeData` binding of `TConfig`; +Compono-owned automatic disposal on any engine; provider-precedence +changes; a general log-filter negation combinator. + +## Tasks + +### C0: Research and decision records (`compono-gec.1`) + +- [x] RESEARCH-0040, covering all seven findings, with the empirical xUnit + disposal probe. +- [x] ADR-0072 Amendment 5 (generator exclusion, superseding "No generator + exclusion is added") and Amendment 6 (per-engine disposal + clarification). +- [x] ADR-0055 Amendment 7 (`InCategoryPrefix`/`NotInCategoryPrefix`). +- [x] This plan and its `docs/plans/README.md` row (`docs/research/` has no index). + +### C1: Metrics owns `IMeterFactory` (`compono-gec.2`) + +- [x] `GeneratorFeatureFlags` gains `MetricsOwnsMeterFactory`, read from + `build_property.ComponoMetricsOwnsMeterFactory`. +- [x] `TransitiveClosureWalker` skips `IMeterFactory` in + `TryRecordTestDouble` when the flag is on. The symbol is resolved + once per walk context, only when the flag is on. +- [x] Core `src/Compono/build/Compono.props` declares the + `CompilerVisibleProperty`. +- [x] New `src/Compono.Metrics/build/Compono.Metrics.props` defaults the + flag to `true`, packed to `build/` and `buildTransitive/`. +- [x] `UseMetrics()` remarks and the `RequireCapturing` misuse message name + `UseGeneratedTestDoubles()` and the ownership rule. +- [x] Generator tests: flag on, flag off, unset, unparseable, flag on + with TestDoubles disabled, and a sibling interface still doubled + (`MetricsTestDoubleOwnershipTests`). The "type unresolvable" case was + dropped: the in-memory harness always references the BCL, and the code + path is a `null` check on the resolved symbol. +- [x] `Compono.Metrics.Tests` runtime tests (TestDoubles generation + enabled): both orders with `UseGeneratedTestDoubles()`; + `UseGeneratedTestDoubles()` without `UseMetrics()`. +- [x] Pack-consume check: the packed `Compono.Metrics` props set the flag in + a consumer. + +### C2: Logging prefix filters (`compono-gec.3`) + +- [x] `LogVerificationBuilder.InCategoryPrefix` / `NotInCategoryPrefix`. +- [x] Tests: positive, negative, the literal boundary (`MyApp.Jobs` vs + `MyApp.JobsLegacy`, trailing dot), case sensitivity, `null`, empty + prefix, a failure description, `LogCollector` host path. +- [x] API reference regenerated (`docs/reference/api`). + +### C3: Documentation-only findings (`compono-gec.4`) + +- [x] Finding 2: `ComposeData` leading-positional ordering and the + register-the-config recipe, in the xUnit v3 package guides and the + cookbook. A JIT test and an AOT test prove the recipe. +- [x] Finding 3: per-engine disposal guidance in the Metrics package guide + (pattern 1) and the xUnit v3 guide. +- [x] Finding 4: `ClearMeasurements()` multi-pass example in the Metrics + guide. +- [x] Finding 6: wrapper-profile and single-row `ComposeData` patterns in + `how-to/use-profiles.md`, backed by a JIT test and an AOT test + (`DocumentedRecipeTests` in both xUnit test projects; the AOT one also + runs as a Native AOT-published binary). + +### C4: Migration guide (`compono-gec.5`) + +- [x] `docs/migrating-from-microsoft-extensions-diagnostics-testing.md`, + linked from the `mkdocs.yml` nav, the Logging/Metrics package guides' + "Next" sections, and the troubleshooting page. +- [x] Compiled examples in `Compono.Logging.Tests` and + `Compono.Metrics.Tests`. + +### C5: Skill (`compono-gec.6`) + +- [x] `skills/compono/references/metrics.md`, `logging.md`, `xunit-v3.md`, + and `registrations-profiles-and-scopes.md` updated. +- [x] `skills/compono/evals/evals.json` gets evals for the new guidance. + +### C6: Validation (`compono-gec.7`) + +- [x] `dotnet build`: 0 warnings, 0 errors. +- [x] `dotnet test`: full solution, every TFM. +- [x] Metrics/Logging/XunitV3.Aot AOT smoke tests, and pack-consume for + the generator and props change. +- [x] Plan status, Beads, and the Notes section updated. + +## Critical Files + +- `src/Compono.Generators/Models/GeneratorFeatureFlags.cs`, + `ComponoIncrementalGenerator.cs`, `Discovery/TransitiveClosureWalker.cs`: + the exclusion. +- `src/Compono/build/Compono.props`, `src/Compono.Metrics/build/Compono.Metrics.props`, + `src/Compono.Metrics/Compono.Metrics.csproj`: the flag wiring. +- `src/Compono.Metrics/CompositionBuilderExtensions.cs`, + `MeterFactoryTestingExtensions.cs`: remarks and the message. +- `src/Compono.Logging/LogVerificationBuilder.cs`: the new filters. +- `test/Compono.Generators.Tests`, `test/Compono.Metrics.Tests`, + `test/Compono.Logging.Tests`, `test/Compono.XunitV3.Tests`, + `test/Compono.XunitV3.Aot.*`: tests. +- `docs/packages/compono-{metrics,logging,xunitv3,xunitv3-aot}.md`, + `docs/how-to/use-profiles.md`, `docs/cookbook/vary-composed-configuration-per-theory-row.md`, + the new migration guide, and `skills/compono/**`. + +## Test Plan + +Generator unit tests use the in-memory harness, the same pattern as +`LoggingTestDoubleOwnershipTests`. Runtime regressions use real generated +output in `Compono.Metrics.Tests`, the same pattern as +`LoggingTestDoubleOwnershipCompileRegressionTests`. Builder tests cover +the logging filters. Documentation recipes get compiled, running tests on +JIT, plus an AOT test or sample where the recipe touches AOT. + +## Notes + +- 2026-11-11: xUnit v3 4.0.1 JIT was confirmed empirically to dispose + `IDisposable`/`IAsyncDisposable` method arguments once per argument slot + (RESEARCH-0040 finding 3). The probe was a temporary test, deleted after + the run. +- 2026-11-11: the `Compono.Metrics.Tests` ownership regressions were + confirmed to bite. Rebuilding with `-p:ComponoMetricsOwnsMeterFactory=false` + fails 3 of the 6 `MeterFactoryOwnershipTests`. +- 2026-11-11 validation (macOS arm64): + - `dotnet build`: 0 warnings, 0 errors. + - `dotnet test` (full solution, every TFM): 7,625 total, 0 failed, 501 + skipped. + - `mkdocs build --strict`: clean. + - `test/Compono.Metrics.AotSmokeTest/verify-packaging.sh`: PASS, including + the new packed-consumer ownership check + (`UseGeneratedTestDoubles().UseMetrics()` gives a `CapturingMeterFactory`, + and the sibling interface is doubled). + - Metrics and Logging AOT smoke publish-and-run (net10.0, osx-arm64): PASS. + - `Compono.XunitV3.Aot.Tests` Native AOT publish-and-run: 281 total, 0 + failed; `DocumentedRecipeTests` 6/6. +- Scope note: `test/Compono.Metrics.AotSmokeTest/pack-compono.sh` now also + packs `Compono.TestDoubles`, for the ownership consumer check. + `.github/scripts/inspect-packed-nupkgs.sh` expects the new props files in + `Compono.Metrics.nupkg`. +- 2026-11-12 review follow-up: + - The migration-guide `[Compose]` example now has a real + test (`samples/Compono.Samples.BasicUsage/MigrationGuideMetricsTests.cs`). + - Disposal wording is engine-specific in the troubleshooting page and evals + 39, 66, and 70. + - TUnit root-argument disposal now cross-references ADR-0040 (documented + behavior, not re-tested by Amendment 6). +- 2026-11-12 intermittent failure, root-caused: + `Compono.Logging.Tests.MigrationGuideExamplesTests.HostWideCapture_*` + failed once during the earlier review round (unidentified at the time). + It failed again on net10.0 in the first TRX-captured full run: + "Expected exactly 1 call(s) ... category Compono.Logging.Tests.CheckoutWorker + ..., but received 0". + - Cause: a race in the new test's own fixture. The example worker was a + `BackgroundService`, and since .NET 10 `ExecuteAsync` runs on a background + task, so `StopAsync` could cancel it before it logged. + - Fix: the worker is now an `IHostedService` that logs in `StartAsync`, and + the guide notes the `BackgroundService` caveat. + - After the fix: 15 targeted runs (all 4 TFMs) had 0 failures. A full xUnit + TRX run had 7,062 total, 0 failed, 47 TRX files, and no Failed outcomes. + A plain full suite had 7,626 total, 0 failed, 501 skipped. TUnit/MSTest + TRX runs passed. + - NUnit's runner has no TRX extension here, so it's covered by the plain run. +- Not done: external dogfood (`scripts/dogfood-validate.sh`, optional per + AGENTS.md) and xUnit 3.2.2 lower-bound reruns. Nothing was pushed, and no + PR was opened. diff --git a/docs/plans/README.md b/docs/plans/README.md index 0944d242..f7962fd1 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -89,3 +89,4 @@ one. This file is just the mechanics: numbering, status, and the index. | [0072](0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md) | `Compono.Logging` Host-Wide Log Capture (Issue #164) + .NET 11 GA Migration | Done | | [0073](0073-compono-nunit-classic-vstest-discovery-impl-plan.md) | Compono.NUnit: classic-VSTest discovery-time module initialization (Issue #171) | Done | | [0074](0074-compono-metrics-testing-support-impl-plan.md) | `Compono.Metrics`: `System.Diagnostics.Metrics` Testing Support (Issue #165) | In Progress | +| [0075](0075-issue-161-1-4-dogfood-follow-up-impl-plan.md) | Issue #161 1.4 Dogfood Follow-Up (Metrics `IMeterFactory` ownership, Logging prefix filters, docs) | Done | diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.InCategory(string).md b/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.InCategory(string).md index bbbb25e6..51c43635 100644 --- a/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.InCategory(string).md +++ b/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.InCategory(string).md @@ -4,8 +4,8 @@ ## LogVerificationBuilder\.InCategory\(string\) Method Restricts matches to entries whose [Category](Compono.Logging.CapturedLogEntry.Category.md 'Compono\.Logging\.CapturedLogEntry\.Category') is exactly -[category](Compono.Logging.LogVerificationBuilder.InCategory(string).md#Compono.Logging.LogVerificationBuilder.InCategory(string).category 'Compono\.Logging\.LogVerificationBuilder\.InCategory\(string\)\.category') \(ordinal, case\-sensitive \- use [Matching\(Func<CapturedLogEntry,bool>\)](Compono.Logging.LogVerificationBuilder.Matching(System.Func_Compono.Logging.CapturedLogEntry,bool_).md 'Compono\.Logging\.LogVerificationBuilder\.Matching\(System\.Func\\)') for a prefix -or wildcard match\)\. +[category](Compono.Logging.LogVerificationBuilder.InCategory(string).md#Compono.Logging.LogVerificationBuilder.InCategory(string).category 'Compono\.Logging\.LogVerificationBuilder\.InCategory\(string\)\.category') \(ordinal, case\-sensitive \- use [InCategoryPrefix\(string\)](Compono.Logging.LogVerificationBuilder.InCategoryPrefix(string).md 'Compono\.Logging\.LogVerificationBuilder\.InCategoryPrefix\(string\)') for a +prefix match, or [Matching\(Func<CapturedLogEntry,bool>\)](Compono.Logging.LogVerificationBuilder.Matching(System.Func_Compono.Logging.CapturedLogEntry,bool_).md 'Compono\.Logging\.LogVerificationBuilder\.Matching\(System\.Func\\)') for anything else\)\. ```csharp public Compono.Logging.LogVerificationBuilder InCategory(string category); diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.InCategoryPrefix(string).md b/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.InCategoryPrefix(string).md new file mode 100644 index 00000000..38dabe3b --- /dev/null +++ b/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.InCategoryPrefix(string).md @@ -0,0 +1,27 @@ +#### [Compono\.Logging](index.md 'index') +### [Compono\.Logging](Compono.Logging.md 'Compono\.Logging').[LogVerificationBuilder](Compono.Logging.LogVerificationBuilder.md 'Compono\.Logging\.LogVerificationBuilder') + +## LogVerificationBuilder\.InCategoryPrefix\(string\) Method + +Restricts matches to entries whose [Category](Compono.Logging.CapturedLogEntry.Category.md 'Compono\.Logging\.CapturedLogEntry\.Category') starts with +[prefix](Compono.Logging.LogVerificationBuilder.InCategoryPrefix(string).md#Compono.Logging.LogVerificationBuilder.InCategoryPrefix(string).prefix 'Compono\.Logging\.LogVerificationBuilder\.InCategoryPrefix\(string\)\.prefix') \(ordinal, case\-sensitive\)\. The prefix is literal \- no namespace +separator is implied \- so `InCategoryPrefix("MyApp.Jobs")` also matches +`MyApp.JobsLegacy`; pass a trailing dot \(`"MyApp.Jobs."`\) to match only categories +beneath that namespace\. An empty prefix matches every entry\. + +```csharp +public Compono.Logging.LogVerificationBuilder InCategoryPrefix(string prefix); +``` +#### Parameters + + + +`prefix` [System\.String](https://learn.microsoft.com/en-us/dotnet/api/system.string 'System\.String') + +#### Returns +[LogVerificationBuilder](Compono.Logging.LogVerificationBuilder.md 'Compono\.Logging\.LogVerificationBuilder') + +#### Exceptions + +[System\.ArgumentNullException](https://learn.microsoft.com/en-us/dotnet/api/system.argumentnullexception 'System\.ArgumentNullException') +[prefix](Compono.Logging.LogVerificationBuilder.InCategoryPrefix(string).md#Compono.Logging.LogVerificationBuilder.InCategoryPrefix(string).prefix 'Compono\.Logging\.LogVerificationBuilder\.InCategoryPrefix\(string\)\.prefix') is [null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null')\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.NotInCategoryPrefix(string).md b/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.NotInCategoryPrefix(string).md new file mode 100644 index 00000000..22f8b998 --- /dev/null +++ b/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.NotInCategoryPrefix(string).md @@ -0,0 +1,26 @@ +#### [Compono\.Logging](index.md 'index') +### [Compono\.Logging](Compono.Logging.md 'Compono\.Logging').[LogVerificationBuilder](Compono.Logging.LogVerificationBuilder.md 'Compono\.Logging\.LogVerificationBuilder') + +## LogVerificationBuilder\.NotInCategoryPrefix\(string\) Method + +Restricts matches to entries whose [Category](Compono.Logging.CapturedLogEntry.Category.md 'Compono\.Logging\.CapturedLogEntry\.Category') does \not\ start +with [prefix](Compono.Logging.LogVerificationBuilder.NotInCategoryPrefix(string).md#Compono.Logging.LogVerificationBuilder.NotInCategoryPrefix(string).prefix 'Compono\.Logging\.LogVerificationBuilder\.NotInCategoryPrefix\(string\)\.prefix') \(ordinal, case\-sensitive\) \- for host\-wide guards such as "nothing +at [Microsoft\.Extensions\.Logging\.LogLevel\.Error](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loglevel.error 'Microsoft\.Extensions\.Logging\.LogLevel\.Error') outside `MyApp.Jobs.`"\. The prefix is literal, exactly as for +[InCategoryPrefix\(string\)](Compono.Logging.LogVerificationBuilder.InCategoryPrefix(string).md 'Compono\.Logging\.LogVerificationBuilder\.InCategoryPrefix\(string\)'); an empty prefix matches no entry\. + +```csharp +public Compono.Logging.LogVerificationBuilder NotInCategoryPrefix(string prefix); +``` +#### Parameters + + + +`prefix` [System\.String](https://learn.microsoft.com/en-us/dotnet/api/system.string 'System\.String') + +#### Returns +[LogVerificationBuilder](Compono.Logging.LogVerificationBuilder.md 'Compono\.Logging\.LogVerificationBuilder') + +#### Exceptions + +[System\.ArgumentNullException](https://learn.microsoft.com/en-us/dotnet/api/system.argumentnullexception 'System\.ArgumentNullException') +[prefix](Compono.Logging.LogVerificationBuilder.NotInCategoryPrefix(string).md#Compono.Logging.LogVerificationBuilder.NotInCategoryPrefix(string).prefix 'Compono\.Logging\.LogVerificationBuilder\.NotInCategoryPrefix\(string\)\.prefix') is [null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null')\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.md b/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.md index afeb3782..e205853e 100644 --- a/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.md +++ b/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.md @@ -23,9 +23,11 @@ Inheritance [System\.Object](https://learn.microsoft.com/en-us/dotnet/api/system | [AtLevelOrAbove\(LogLevel\)](Compono.Logging.LogVerificationBuilder.AtLevelOrAbove(Microsoft.Extensions.Logging.LogLevel).md 'Compono\.Logging\.LogVerificationBuilder\.AtLevelOrAbove\(Microsoft\.Extensions\.Logging\.LogLevel\)') | Restricts matches to entries logged at [level](Compono.Logging.LogVerificationBuilder.AtLevelOrAbove(Microsoft.Extensions.Logging.LogLevel).md#Compono.Logging.LogVerificationBuilder.AtLevelOrAbove(Microsoft.Extensions.Logging.LogLevel).level 'Compono\.Logging\.LogVerificationBuilder\.AtLevelOrAbove\(Microsoft\.Extensions\.Logging\.LogLevel\)\.level') or any more severe level \(e\.g\. `AtLevelOrAbove(LogLevel.Error)` matches Error and Critical\)\. A captured entry is never [Microsoft\.Extensions\.Logging\.LogLevel\.None](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loglevel.none 'Microsoft\.Extensions\.Logging\.LogLevel\.None'), and neither is [Microsoft\.Extensions\.Logging\.LogLevel\.None](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loglevel.none 'Microsoft\.Extensions\.Logging\.LogLevel\.None') ever treated as "above" anything, so `AtLevelOrAbove(LogLevel.None)` matches nothing\. | | [AtMost\(int\)](Compono.Logging.LogVerificationBuilder.AtMost(int).md 'Compono\.Logging\.LogVerificationBuilder\.AtMost\(int\)') | Asserts the accumulated filters matched at most [times](Compono.Logging.LogVerificationBuilder.AtMost(int).md#Compono.Logging.LogVerificationBuilder.AtMost(int).times 'Compono\.Logging\.LogVerificationBuilder\.AtMost\(int\)\.times') times\. | | [Exactly\(int\)](Compono.Logging.LogVerificationBuilder.Exactly(int).md 'Compono\.Logging\.LogVerificationBuilder\.Exactly\(int\)') | Asserts the accumulated filters matched exactly [times](Compono.Logging.LogVerificationBuilder.Exactly(int).md#Compono.Logging.LogVerificationBuilder.Exactly(int).times 'Compono\.Logging\.LogVerificationBuilder\.Exactly\(int\)\.times') times\. | -| [InCategory\(string\)](Compono.Logging.LogVerificationBuilder.InCategory(string).md 'Compono\.Logging\.LogVerificationBuilder\.InCategory\(string\)') | Restricts matches to entries whose [Category](Compono.Logging.CapturedLogEntry.Category.md 'Compono\.Logging\.CapturedLogEntry\.Category') is exactly [category](Compono.Logging.LogVerificationBuilder.InCategory(string).md#Compono.Logging.LogVerificationBuilder.InCategory(string).category 'Compono\.Logging\.LogVerificationBuilder\.InCategory\(string\)\.category') \(ordinal, case\-sensitive \- use [Matching\(Func<CapturedLogEntry,bool>\)](Compono.Logging.LogVerificationBuilder.Matching(System.Func_Compono.Logging.CapturedLogEntry,bool_).md 'Compono\.Logging\.LogVerificationBuilder\.Matching\(System\.Func\\)') for a prefix or wildcard match\)\. | +| [InCategory\(string\)](Compono.Logging.LogVerificationBuilder.InCategory(string).md 'Compono\.Logging\.LogVerificationBuilder\.InCategory\(string\)') | Restricts matches to entries whose [Category](Compono.Logging.CapturedLogEntry.Category.md 'Compono\.Logging\.CapturedLogEntry\.Category') is exactly [category](Compono.Logging.LogVerificationBuilder.InCategory(string).md#Compono.Logging.LogVerificationBuilder.InCategory(string).category 'Compono\.Logging\.LogVerificationBuilder\.InCategory\(string\)\.category') \(ordinal, case\-sensitive \- use [InCategoryPrefix\(string\)](Compono.Logging.LogVerificationBuilder.InCategoryPrefix(string).md 'Compono\.Logging\.LogVerificationBuilder\.InCategoryPrefix\(string\)') for a prefix match, or [Matching\(Func<CapturedLogEntry,bool>\)](Compono.Logging.LogVerificationBuilder.Matching(System.Func_Compono.Logging.CapturedLogEntry,bool_).md 'Compono\.Logging\.LogVerificationBuilder\.Matching\(System\.Func\\)') for anything else\)\. | +| [InCategoryPrefix\(string\)](Compono.Logging.LogVerificationBuilder.InCategoryPrefix(string).md 'Compono\.Logging\.LogVerificationBuilder\.InCategoryPrefix\(string\)') | Restricts matches to entries whose [Category](Compono.Logging.CapturedLogEntry.Category.md 'Compono\.Logging\.CapturedLogEntry\.Category') starts with [prefix](Compono.Logging.LogVerificationBuilder.InCategoryPrefix(string).md#Compono.Logging.LogVerificationBuilder.InCategoryPrefix(string).prefix 'Compono\.Logging\.LogVerificationBuilder\.InCategoryPrefix\(string\)\.prefix') \(ordinal, case\-sensitive\)\. The prefix is literal \- no namespace separator is implied \- so `InCategoryPrefix("MyApp.Jobs")` also matches `MyApp.JobsLegacy`; pass a trailing dot \(`"MyApp.Jobs."`\) to match only categories beneath that namespace\. An empty prefix matches every entry\. | | [Matching\(Func<CapturedLogEntry,bool>\)](Compono.Logging.LogVerificationBuilder.Matching(System.Func_Compono.Logging.CapturedLogEntry,bool_).md 'Compono\.Logging\.LogVerificationBuilder\.Matching\(System\.Func\\)') | Restricts matches to entries satisfying an arbitrary [predicate](Compono.Logging.LogVerificationBuilder.Matching(System.Func_Compono.Logging.CapturedLogEntry,bool_).md#Compono.Logging.LogVerificationBuilder.Matching(System.Func_Compono.Logging.CapturedLogEntry,bool_).predicate 'Compono\.Logging\.LogVerificationBuilder\.Matching\(System\.Func\\)\.predicate') \- the escape hatch for anything the named filters above don't cover\. | | [Never\(\)](Compono.Logging.LogVerificationBuilder.Never().md 'Compono\.Logging\.LogVerificationBuilder\.Never\(\)') | Asserts the accumulated filters never matched\. | +| [NotInCategoryPrefix\(string\)](Compono.Logging.LogVerificationBuilder.NotInCategoryPrefix(string).md 'Compono\.Logging\.LogVerificationBuilder\.NotInCategoryPrefix\(string\)') | Restricts matches to entries whose [Category](Compono.Logging.CapturedLogEntry.Category.md 'Compono\.Logging\.CapturedLogEntry\.Category') does \not\ start with [prefix](Compono.Logging.LogVerificationBuilder.NotInCategoryPrefix(string).md#Compono.Logging.LogVerificationBuilder.NotInCategoryPrefix(string).prefix 'Compono\.Logging\.LogVerificationBuilder\.NotInCategoryPrefix\(string\)\.prefix') \(ordinal, case\-sensitive\) \- for host\-wide guards such as "nothing at [Microsoft\.Extensions\.Logging\.LogLevel\.Error](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loglevel.error 'Microsoft\.Extensions\.Logging\.LogLevel\.Error') outside `MyApp.Jobs.`"\. The prefix is literal, exactly as for [InCategoryPrefix\(string\)](Compono.Logging.LogVerificationBuilder.InCategoryPrefix(string).md 'Compono\.Logging\.LogVerificationBuilder\.InCategoryPrefix\(string\)'); an empty prefix matches no entry\. | | [Once\(\)](Compono.Logging.LogVerificationBuilder.Once().md 'Compono\.Logging\.LogVerificationBuilder\.Once\(\)') | Asserts the accumulated filters matched exactly once\. | | [WithEventId\(EventId\)](Compono.Logging.LogVerificationBuilder.WithEventId(Microsoft.Extensions.Logging.EventId).md 'Compono\.Logging\.LogVerificationBuilder\.WithEventId\(Microsoft\.Extensions\.Logging\.EventId\)') | Restricts matches to entries logged with exactly [eventId](Compono.Logging.LogVerificationBuilder.WithEventId(Microsoft.Extensions.Logging.EventId).md#Compono.Logging.LogVerificationBuilder.WithEventId(Microsoft.Extensions.Logging.EventId).eventId 'Compono\.Logging\.LogVerificationBuilder\.WithEventId\(Microsoft\.Extensions\.Logging\.EventId\)\.eventId')\. | | [WithException<TException>\(\)](Compono.Logging.LogVerificationBuilder.WithException_TException_().md 'Compono\.Logging\.LogVerificationBuilder\.WithException\\(\)') | Restricts matches to entries whose exception is a [TException](Compono.Logging.LogVerificationBuilder.WithException_TException_().md#Compono.Logging.LogVerificationBuilder.WithException_TException_().TException 'Compono\.Logging\.LogVerificationBuilder\.WithException\\(\)\.TException')\. | diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).md b/docs/reference/api/Compono.Metrics/Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).md index d67da9b2..df2904b6 100644 --- a/docs/reference/api/Compono.Metrics/Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).md +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).md @@ -28,9 +28,18 @@ The same [builder](Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisC [builder](Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).md#Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).builder 'Compono\.Metrics\.CompositionBuilderExtensions\.UseMetrics\(this Compono\.CompositionBuilder\)\.builder') is [null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null')\. ### Remarks -Register this \before\`UseNSubstitute()` if -[System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') should resolve through Compono\.Metrics rather -than an NSubstitute substitute \- Compono's stage\-6 providers resolve in registration order -\(first\-registered\-wins\), an existing, documented, `Accepted` pattern \(ADR\-0024\) this package -follows rather than replacing\. An exact `Register(...)` always wins over -`UseMetrics()` regardless of order\. \ No newline at end of file + +Register this before`UseNSubstitute()` or any other catch-all test-double provider if +[System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') should resolve through Compono.Metrics rather +than a substitute - Compono's stage-6 providers resolve in registration order +(first-registered-wins), an existing, documented, `Accepted` pattern (ADR-0024) this package +follows rather than replacing. An exact `Register(...)` always wins over +`UseMetrics()` regardless of order. + +Order against `UseGeneratedTestDoubles()` doesn't matter while +`ComponoMetricsOwnsMeterFactory` is enabled (the default whenever Compono.Metrics is +referenced): [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') is then Metrics-owned and +`Compono.TestDoubles` never generates a double for it. The same default means a composer that +calls `UseGeneratedTestDoubles()` without `UseMetrics()` gets no +[System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') double at all. See +docs/adr/0072-compono-metrics-testing-support-package.md Amendment 5. \ No newline at end of file diff --git a/docs/research/0040-issue-161-1-4-dogfood-follow-up.md b/docs/research/0040-issue-161-1-4-dogfood-follow-up.md new file mode 100644 index 00000000..d1b0384c --- /dev/null +++ b/docs/research/0040-issue-161-1-4-dogfood-follow-up.md @@ -0,0 +1,359 @@ +# RESEARCH-0040: Issue #161 1.4 Dogfood Follow-Up — Seven Usability Findings + +**Status:** Complete. Every finding is triaged below. The four material +design decisions (findings 1, 4, 5, 6) were confirmed by the maintainer on +2026-11-11. Execution is tracked by +[PLAN-0075](../plans/0075-issue-161-1-4-dogfood-follow-up-impl-plan.md). + +**Trigger:** the maintainer's follow-up comment on +[#161](https://github.com/LayeredCraft/compono/issues/161#issuecomment-6810922325) +(2026-11-12 UTC). It reports migrating a real .NET 11 / xUnit v3 worker +service (231 tests: unit, Testcontainers persistence, Generic Host) to +`1.4.0-preview.127` with all six packages. All four original #161 +workarounds were removed, with no defects and no `CMP` diagnostics. Seven +usability findings remain. None blocked the migration. + +**Release state when researched:** `main` at `9281cdc` (PR #179, +`Compono.Metrics`, merged). `v1.4.0` is a draft release, so +`Compono.Metrics` and the #162–#165 features haven't shipped stable yet. +Any change to their contracts in this follow-up is still pre-stable. + +## Summary + +| # | Finding | Kind | Outcome | +|---|---|---|---| +| 1 | `UseMetrics()` order vs `UseGeneratedTestDoubles()` | Defect (docs/message) + enhancement | **Implement**: generator exclusion for `IMeterFactory` (ADR-0072 Amendment 5), fix the docs and misuse message | +| 2 | `ComposeData` binding and `TConfig` access | Documentation | **Document**. No binding change | +| 3 | `[Shared]` disposables disposed by the test | Documentation (incorrect guidance) | **Document**. xUnit v3 JIT already disposes arguments. No ownership change (ADR-0072 Amendment 6) | +| 4 | Metrics checkpoints | Enhancement | **Defer**. Document the `ClearMeasurements()` multi-pass pattern | +| 5 | Logging category prefixes | Enhancement | **Implement** `InCategoryPrefix`/`NotInCategoryPrefix` (ADR-0055 Amendment 7) | +| 6 | Profile constructor arguments | Enhancement | **Document + defer**. Wrapper-profile pattern and single-row `ComposeData` | +| 7 | Migration guide from `Microsoft.Extensions.Diagnostics.Testing` | Documentation | **Document** | + +## Finding 1: `UseMetrics()` depends on order against `UseGeneratedTestDoubles()` + +**Consumer pain.** In a shared base profile, `UseGeneratedTestDoubles()` +came before `UseMetrics()`. A generated double took `IMeterFactory`, and +28 tests failed on measurement assertions. The misuse exception pointed at +the cause, but it's an easy trap. + +**Root cause (confirmed in source).** + +- `UseMetrics()` and `UseGeneratedTestDoubles()` both call + `CompositionBuilder.AddTestDoubleProvider`, which appends to one stage-6 + list. Stage-6 providers are tried in registration order, and the first + `Handled` wins (`CompositionBuilder.cs`, ADR-0024). +- With `ComponoGeneratedTestDoubles=true`, `Compono.Generators` emits a + double for **every** interface it reaches + (`LeafTypeClassifier.IsGeneratedTestDoubleEligible` is + `testDoublesEnabled && TypeKind.Interface`). A SUT constructor parameter + of `IMeterFactory` is reached, so a double is generated and registered + into `GeneratedTestDoubleRegistry`. `GeneratedTestDoubleProvider` then + claims `IMeterFactory` whenever it's ahead of `MetricsProvider`. +- **Documentation defect:** `UseMetrics()`'s XML remarks and the + `RequireCapturing` misuse message mention only `UseNSubstitute()`. The + trap the consumer actually hit (`UseGeneratedTestDoubles()`) isn't named + anywhere a developer would look first. + +**Existing behavior and ADRs.** ADR-0024 (first-registered-wins), ADR-0043 +("Runtime activation and precedence"), and ADR-0072 "Precedence and +misuse", which said: *"Register `UseMetrics()` first. No generator +exclusion is added."* The precedent for the opposite choice is ADR-0055 +Amendment 4: when `ComponoGeneratedLogging` is enabled, +`ILogger`/`ILogger` are **Logging-owned** and excluded from +`Compono.TestDoubles` generation. Logging made that call because of a +compile-time `Verify()` collision. Metrics has no compile-time collision +(`Verify(string)` and the generated `Verify()` have different +signatures), but it has the same ownership question at run time. + +**Options considered.** + +1. *Change provider precedence* (for example, specificity-based stage 6). + That's a core pipeline change for every integration. Rejected: it + reverses ADR-0024 for one package. +2. *Configuration-time detection.* `CompositionBuilder` doesn't expose its + provider list, and providers are opaque until probed. This needs new + core API. Rejected. +3. *Docs and message only.* Fix the omission. Ordering stays a trap. +4. *Generator exclusion* (ADR-0055 Amendment 4 pattern). Referencing + `Compono.Metrics` makes `IMeterFactory` Metrics-owned, so no generated + double exists, and order against `UseGeneratedTestDoubles()` stops + mattering. Order against `UseNSubstitute()` (a catch-all with no + generator involvement) still matters. + +**Decision (maintainer, 2026-11-11): option 4 plus option 3.** +Requirements recorded from that decision: exclude `IMeterFactory` from +generated doubles when `Compono.Metrics` is referenced, keep stage-6 +first-registration-wins, no core composition change, keep the ordering +guidance for `UseNSubstitute()` and other catch-all providers, verify and +document the "referenced but `UseMetrics()` not called" case, add +regression tests for both orders with `UseGeneratedTestDoubles()`, and +record the change as an ADR-0072 amendment that explicitly supersedes its +original no-exclusion sentence. + +**Public API impact.** No new C# API. One new MSBuild property, +`ComponoMetricsOwnsMeterFactory`, defaulted to `true` by +`Compono.Metrics`'s packed `build`/`buildTransitive` props and declared +`CompilerVisibleProperty` by core `Compono.props` (the same split +`ComponoGeneratedLogging` uses). A consumer can set it to `false` to get a +generated `IMeterFactory` double back. + +**Compatibility.** Only consumers who reference `Compono.Metrics` **and** +enable `ComponoGeneratedTestDoubles` see a change, and `Compono.Metrics` +hasn't shipped stable. The tradeoff: with `Compono.Metrics` referenced, a +composer that calls `UseGeneratedTestDoubles()` but not `UseMetrics()` no +longer gets a generated `IMeterFactory` double. The request falls through +to the next stage-6 provider (for example NSubstitute), or composition +fails with the usual "no provider" `CompositionException`. Referencing a +metrics-testing package and not calling `UseMetrics()` is almost always a +mistake, so the failure is a clearer signal than a silent double. + +**AOT / source generation.** A generator-only change on the existing +discovery path. One extra `GetTypeByMetadataName` per compilation, only +when the flag is on. No runtime reflection. Generated output for every +other interface is unchanged. + +**Tests.** Generator tests: flag on → no `IMeterFactory` double; flag off +→ double emitted; a sibling interface is still doubled; flag on without +the `System.Diagnostics.Metrics` type resolvable is inert. Runtime tests in +`Compono.Metrics.Tests` (with real generated doubles enabled): both +registration orders with `UseGeneratedTestDoubles()` produce a +`CapturingMeterFactory`; `UseGeneratedTestDoubles()` without `UseMetrics()` +fails clearly while a sibling interface still gets its double. + +**Complexity.** Small to medium (one flag, one exclusion check, props +wiring, tests, docs). + +## Finding 2: `ComposeData` row binding and `TConfig` access + +**Consumer pain.** (a) Row values bind to the leading parameters, so +signatures had to be reordered to put row data before `[Shared]` and +composed parameters. (b) There was no way to read the row's `TConfig` in +the test body, so one theory repeated `daysBefore`/`daysAfter` in both the +config record and the row values. + +**Root cause.** (a) is the contract, not a bug: ADR-0022's +leading-positional rule, reused by ADR-0070 behavior contract item 5. It's +the same rule `[Compose(42)]` uses. It's stated in the ADR and package +docs, but not prominently in the `ComposeData` usage material. (b) Element +0 of a `ComposeData` row is consumed by the profile +constructor and isn't bound to a parameter (ADR-0070 item 4). + +**Options considered.** + +- *Bind `TConfig` to row element 0 when parameter 0 is `TConfig`.* + Ambiguous: a row whose element 1 is also assignable to `TConfig` has two + readings. It also breaks the "element 0 is config, 1..n are values" + layout that ADR-0070 fixed for both engines. Rejected. +- *Named binding.* Rejected in ADR-0070 (Option 5) for conflicting with + ADR-0022, and it adds new vocabulary. Nothing new here changes that. +- *Explicit configuration injection, which already works.* The profile + already receives the config, so it can register it: + `builder.Register(() => config)`. A composed `TConfig` parameter then + resolves at stage 3 (exact registration) to the row's own instance. + That's explicit, needs no new API, uses no reflection, and is + AOT-compatible (it's an ordinary composed parameter). +- *Better docs.* Make the leading-positional rule and the recipe above + prominent. + +**Recommendation: Document.** The test needs no new API. Cover the +ordering rule and the register-the-config recipe in the package guides, +the cookbook, and the skill, with a real test on JIT and on AOT proving +the recipe. + +**Public API / compat / AOT.** None. + +**Complexity.** Small. + +## Finding 3: `[Shared]` disposables must be disposed by the test + +**Consumer pain.** Every test with `[Shared] IMeterFactory` carries +`using var _ = meters;`, because ADR-0072 and the package guide prescribe +it. + +**Finding (empirical, 2026-11-11, xUnit `xunit.v3.mtp-v2` 4.0.1, net11.0, +JIT `Compono.XunitV3`).** A probe theory with +`[Theory, Compose] Probe([Shared] D value, D again, +AsyncD a, Holder holder)`, where `D : IDisposable` and +`AsyncD : IAsyncDisposable`, was run with a file side-channel and no +`using` in the body: + +``` +body same=True holderSame=True +async disposed +sync disposed +sync disposed +``` + +xUnit itself disposes every `IDisposable`/`IAsyncDisposable` test-method +argument after the test case. It disposes once **per argument slot**, so a +`[Shared]` instance bound to two parameters is disposed twice. That +matches RESEARCH-0038 §2.4 (`DisposalTracker.AddRange(data)` per row on +3.2.2 and 4.0.1) and ADR-0070 contract item 12. **xUnit's AOT core +doesn't** (RESEARCH-0038 §2.4). Compono registers nothing with the +`DisposalTracker` (ADR-0022 Amendment 4, guarded by +`ComposeAttributeDisposalTests`). + +**So on `Compono.XunitV3` (JIT) the consumer's `using var _ = meters;` is +redundant.** It's harmless, because `CapturingMeterFactory.Dispose()` is +idempotent. ADR-0072's guidance to always write it was conservative, and it +didn't distinguish engines. + +**Ownership analysis.** + +- *Values Compono created vs externally supplied.* Compono still can't tell + them apart (RESEARCH-0015 §5 Model B, re-confirmed: no provenance between + construction and return). xUnit's disposal ignores provenance. That's + xUnit's existing behavior, already documented with a warning not to pass + fixture-owned disposables as parameters. +- *Shared values.* `[Shared]` makes the parameter the SUT's instance, so + xUnit's disposal of the parameter disposes the SUT's factory. Without + `[Shared]`, the SUT's factory isn't a parameter and nothing disposes it. +- *Other frameworks.* Not re-tested here. TUnit's composed root-argument + disposal is documented separately (ADR-0040, `Compono.TUnit` guide). It's not + established for NUnit, MSTest, or + xUnit AOT. Keep the explicit `using` guidance there. +- *Sync vs async.* xUnit prefers `DisposeAsync` when both are implemented. + `IMeterFactory` is sync-only. +- *Double disposal.* Already happens today whenever a test also writes + `using`, and whenever a `[Shared]` value appears in two parameter slots. + Disposable types passed as composed parameters must be idempotent, as + .NET guidance requires. + +**Options considered.** (a) Compono.XunitV3 registers `[Shared]` +disposables with the tracker: redundant on JIT (xUnit already does it) and +reintroduces the ADR-0022 Amendment 4 ownership hazard as Compono's own +contract. Rejected. (b) The AOT package registers disposal: the same +ownership hazard, plus a JIT/AOT difference Compono would then own. +Rejected without a disposal-ownership ADR (RESEARCH-0015 Outcome C). +(c) Document per engine. **Chosen.** + +**Recommendation: Document** (ADR-0072 Amendment 6 records the +clarification). On `Compono.XunitV3` the `using` line is optional. Keep it +on `Compono.XunitV3.Aot`, TUnit, NUnit, MSTest, and `Composer.Create` +tests. No automatic disposal, and no ownership-contract change. + +**Complexity.** Small. + +## Finding 4: asserting on one pass of a multi-pass test + +**Consumer pain.** Outbox tests run several passes and assert on the last. +`ClearMeasurements()` before the step under test works, but the consumer +felt it hides the intent. + +**Existing behavior.** `ClearMeasurements()` (ADR-0072) discards captured +measurements and keeps the sequence counter. Every captured measurement +carries an internal factory-wide sequence number (`StoredMeasurement`), so +a checkpoint would be cheap to build later. + +**Options.** (a) Keep `ClearMeasurements()`. (b) A checkpoint token plus +`Verify(...).Since(mark)`. (c) A scoped `BeginCapture()`. + +**Assessment.** (a) is the same idiom as `Compono.TestDoubles` +`ClearCalls()` (ADR-0060) and `Compono.Logging` `ClearCapturedEntries()` +(ADR-0071), so the ecosystem has one reset idiom. (b) is non-destructive +and cheap given the sequence numbers, but it's a new idiom that no other +package has, and the only evidence is readability. Nobody needs to assert +both before and after a point. (c) adds overlapping-scope concurrency +questions and the most surface. + +**Decision (maintainer, 2026-11-11): Defer, and document the +`ClearMeasurements()` multi-pass pattern.** No new public API. Revisit +checkpoints only when real consumer evidence needs measurements from +several phases kept and asserted independently. + +## Finding 5: `InCategory` is an exact match + +**Consumer pain.** Host-level guards filter by namespace prefix, for +example "no errors outside `MyApp.Jobs.*`", which is a **negated** prefix. +Today that needs `Matching(e => !e.Category.StartsWith(...))`. + +**Existing behavior.** `LogVerificationBuilder` has AND-only named filters. +`InCategory` is ordinal and exact, and `Matching` is the escape hatch. No +negated filter exists. Microsoft.Extensions.Logging's own filter rules use +case-insensitive prefix matching, but Compono's category filter is already +ordinal and case-sensitive, so consistency inside the builder wins. + +**Options.** `InCategoryPrefix` only, a boundary-aware `InNamespace`, a +prefix plus negated pair, or docs only. + +**Decision (maintainer, 2026-11-11): add `InCategoryPrefix(string prefix)` +and `NotInCategoryPrefix(string prefix)`.** `StringComparison.Ordinal`; +the prefix is literal, with no implicit `.` separator, and the docs show a +trailing `.` to avoid matching similarly named categories (`MyApp.Jobs.` +doesn't match `MyApp.JobsLegacy`); `ArgumentNullException` for `null`, +matching `InCategory`; existing `InCategory` unchanged; no general negation +framework. Recorded as ADR-0055 Amendment 7, because the builder's surface +is ADR-0055's. + +**Edge semantics.** An empty prefix is allowed and literal: +`InCategoryPrefix("")` matches every entry and `NotInCategoryPrefix("")` +matches none. That's consistent with `string.StartsWith("")`, and it isn't +special-cased. + +**AOT.** Plain string comparison. **Complexity.** Small. + +## Finding 6: profile constructor arguments in `[Compose]` + +**Consumer pain.** A profile that takes interceptors needed an extra +parameterless constructor so it could be named in `[Compose]`. +Variants that do need interceptors still use `Composer.Create(...)`. + +**Existing mechanisms.** `[Compose]` requires +`TProfile : new()`. `[Compose(args)]` builds `TConfig` +from attribute constants. `ComposeData` supplies +`TConfig` from a static member's rows, including non-constant objects. +`CompositionBuilder.AddProfile(ICompositionProfile)` composes profiles. + +**Patterns that already work with no new API.** + +1. **Wrapper profile:** a parameterless profile per variant that calls + `builder.AddProfile(new DbProfile(new AuditInterceptor()))`. It names + the variant, works with `[Compose]` on every framework + adapter, and works on AOT (`new()` constraint, no reflection). +2. **Single-row `ComposeData`:** a static member returns + one row whose `TConfig` carries the runtime objects. That's a + `[Theory]` with one row on `Compono.XunitV3` and `Compono.XunitV3.Aot`. + +**Options.** A `ProfileMember`/`ProfileFactory` static-member property on +the Compose-family attributes would touch JIT reflection, AOT generator +emission, new `CMP` diagnostics, and four framework adapters, and it would +create a second way to supply profile state next to `TConfig`. + +**Decision (maintainer, 2026-11-11): Document + defer.** Document both +patterns, with examples that compile and run on JIT and Native AOT. No +`ProfileMember` or other activation mechanism. Revisit only on evidence +that these patterns are materially inadequate. + +## Finding 7: migration guide from `Microsoft.Extensions.Diagnostics.Testing` + +**Recommendation: Document.** The new page is +`docs/migrating-from-microsoft-extensions-diagnostics-testing.md`. It maps +`AddFakeLogging`/`FakeLogCollector` to +`LogCollector`/`AddComponoCapture`, and `MetricCollector` to +`CapturingMeterFactory`/`UseMetrics()`/`Verify`/`GetMeasurements`. +It covers registration order (stage-6 order, plus host DI "last +registration wins" from ADR-0072 Amendment 3), explicit disposal, and +`ClearMeasurements()` for multi-pass tests. Its examples are backed by a +compiled test class in the logging and metrics test projects. + +## Bugs vs enhancements + +- **Bugs (documentation/diagnostic defects):** finding 1's omission of + `UseGeneratedTestDoubles()` from the `UseMetrics()` remarks and the + misuse message; finding 3's engine-agnostic "always dispose in the body" + guidance, which is redundant on xUnit JIT. +- **Enhancements:** finding 1's generator exclusion, finding 5's filters. +- **Documentation gaps:** findings 2, 4, 6, 7. +- **No runtime defect was found** in any #161 feature. + +## Links + +- [#161 follow-up comment](https://github.com/LayeredCraft/compono/issues/161#issuecomment-6810922325) +- [ADR-0022](../adr/0022-compono-xunit-package-design.md) Amendment 4 (no automatic disposal) +- [ADR-0024](../adr/0024-public-provider-extensibility-model.md) (stage-6 order) +- [ADR-0055](../adr/0055-compono-logging-testing-support-package.md) Amendments 4 and 7 +- [ADR-0070](../adr/0070-xunitv3-composedata-composed-theory-rows.md) (row layout, disposal item 12) +- [ADR-0072](../adr/0072-compono-metrics-testing-support-package.md) Amendments 5 and 6 +- [RESEARCH-0015](0015-disposal-ownership-research.md), [RESEARCH-0038](0038-issue-163-composed-theory-data-rows.md) +- [PLAN-0075](../plans/0075-issue-161-1-4-dogfood-follow-up-impl-plan.md) diff --git a/docs/troubleshooting/common-errors.md b/docs/troubleshooting/common-errors.md index 64b27900..6047d152 100644 --- a/docs/troubleshooting/common-errors.md +++ b/docs/troubleshooting/common-errors.md @@ -368,11 +368,17 @@ requires the `IMeterFactory` to be Compono's `CapturingMeterFactory`, and throws `InvalidOperationException` otherwise. This usually means one of: - **`UseMetrics()` isn't registered.** Add it to the profile or - `Composer.Create` call. -- **`UseMetrics()` is registered *after* `UseNSubstitute()`.** An interface - request resolves at whichever stage-6 provider is registered first, so - `NSubstituteProvider` wins and you get a substitute. Call `UseMetrics()` - first — see [Registration order and misuse](../packages/compono-metrics.md#registration-order-and-misuse). + `Composer.Create` call. (With `UseGeneratedTestDoubles()` and no + `UseMetrics()`, composition fails earlier with a `CompositionException` + naming `IMeterFactory`, because `Compono.Metrics` owns that type and no + generated double exists for it.) +- **`UseMetrics()` is registered *after* `UseNSubstitute()`** (or another + catch-all stage-6 provider). An interface request resolves at whichever + stage-6 provider is registered first, so `NSubstituteProvider` wins and + you get a substitute. Call `UseMetrics()` first, especially in a shared + base profile. See [Registration order and misuse](../packages/compono-metrics.md#registration-order-and-misuse). + Order against `UseGeneratedTestDoubles()` doesn't matter unless the + project sets `ComponoMetricsOwnsMeterFactory` to `false`. - **The Generic Host resolved its own default factory.** The builder already registers a default `IMeterFactory`. Register the test's factory with `builder.Services.AddSingleton(meters)`; the container @@ -423,9 +429,26 @@ unexpected meter name. A factory that created a meter stays referenced by the BCL's static meter list until it's disposed, keeping its meters, listener, and captured measurements alive — the same cost as an undisposed `DefaultMeterFactory`. -Dispose it at the end of the test with `using var _ = meters;` on the -`[Shared]` parameter, or one of the other two patterns in -[Disposal patterns](../packages/compono-metrics.md#disposal-patterns). A +Compono never disposes it. Who does depends on the test engine +([ADR-0072 Amendment 6](../adr/0072-compono-metrics-testing-support-package.md)): + +- **`Compono.XunitV3` (xUnit v3, JIT):** xUnit disposes every + `IDisposable` test-method argument after the test case, including a + `[Shared] IMeterFactory` parameter. `using var _ = meters;` is optional. +- **`Compono.XunitV3.Aot`:** xUnit's AOT core doesn't dispose arguments. + Dispose it in the test body with `using var _ = meters;`. +- **`Compono.TUnit`:** TUnit disposes a composed **root** method argument + itself, which is documented in + [`Compono.TUnit` — Disposal](../packages/compono-tunit.md#disposal) and + [ADR-0040](../adr/0040-compono-tunit-package-design.md). That's documented + behavior, not something ADR-0072 Amendment 6 re-tested. The `using` is + optional there, and keeping it is harmless. +- **`Compono.NUnit`, `Compono.MSTest`:** not verified. Keep + `using var _ = meters;`. It's harmless, because `Dispose()` is idempotent. +- **A factory you construct** (`Composer.Create` or host tests): you own it, + so use `using var meters = new CapturingMeterFactory();`. + +See [Disposal patterns](../packages/compono-metrics.md#disposal-patterns). A factory that never created a meter costs nothing. ## Next diff --git a/mkdocs.yml b/mkdocs.yml index 0f9a1de6..c3ecf71a 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -140,6 +140,7 @@ nav: - Basic Usage: samples/basic-usage.md - ASP.NET API: samples/aspnet-api.md - Migrating from AutoFixture: migrating-from-autofixture.md + - Migrating from Microsoft.Extensions.Diagnostics.Testing: migrating-from-microsoft-extensions-diagnostics-testing.md - Package Guides: - Overview: packages/index.md - Compono: packages/compono.md diff --git a/samples/Compono.Samples.BasicUsage/MetricsTests.cs b/samples/Compono.Samples.BasicUsage/MetricsTests.cs index 249afaad..19211880 100644 --- a/samples/Compono.Samples.BasicUsage/MetricsTests.cs +++ b/samples/Compono.Samples.BasicUsage/MetricsTests.cs @@ -7,7 +7,9 @@ namespace Compono.Samples.BasicUsage; // Compono.Metrics: UseMetrics() composes IMeterFactory as a CapturingMeterFactory - no substitute // needed to assert the measurements CheckoutService actually recorded. [Shared] reuses the exact // same composed factory the service's own constructor received, so the test asserts against the -// measurements the service produced. The test owns disposal via "using var _ = meters;". +// measurements the service produced. "using var _ = meters;" is optional here - xUnit v3 (JIT) +// disposes IDisposable test-method arguments itself - but is kept so the example stays correct on +// Compono.XunitV3.Aot, which doesn't (ADR-0072 Amendment 6). public sealed class MetricsTests { [Theory] diff --git a/samples/Compono.Samples.BasicUsage/MigrationGuideMetricsTests.cs b/samples/Compono.Samples.BasicUsage/MigrationGuideMetricsTests.cs new file mode 100644 index 00000000..782e827a --- /dev/null +++ b/samples/Compono.Samples.BasicUsage/MigrationGuideMetricsTests.cs @@ -0,0 +1,42 @@ +using System.Diagnostics.Metrics; +using Compono.Metrics; +using Compono.XunitV3; + +// A dedicated namespace so the guide's own type names (MetricsProfile, OrderService) compile verbatim +// without colliding with this sample's Domain.cs. +namespace Compono.Samples.BasicUsage.Migration; + +// The compiled, running source of the composed-factory example in +// docs/migrating-from-microsoft-extensions-diagnostics-testing.md ("Composed factory +// (MetricCollector -> UseMetrics())"). Keep the guide snippet and this test in step. +public sealed class MetricsProfile : ICompositionProfile +{ + public void Configure(CompositionBuilder builder) => builder.UseMetrics(); +} + +public sealed class OrderService +{ + private readonly Counter _placed; + + public OrderService(IMeterFactory meters) => + _placed = meters.Create(new MeterOptions("Shop.Orders")).CreateCounter("shop.orders.placed"); + + public void PlaceOrder(string region, int quantity) + { + _ = quantity; + _placed.Add(1, new KeyValuePair("region", region)); + } +} + +public sealed class MigrationGuideMetricsTests +{ + [Theory, Compose] + public void PlacingAnOrderCountsIt([Shared] IMeterFactory meters, OrderService sut) + { + sut.PlaceOrder("eu", 2); + + meters.Verify("Shop.Orders", "shop.orders.placed").WithTag("region", "eu").WithValue(1).Once(); + var placed = meters.GetMeasurements("Shop.Orders", "shop.orders.placed"); // GetMeasurementSnapshot() + Assert.Single(placed); + } +} diff --git a/skills/compono/evals/evals.json b/skills/compono/evals/evals.json index 946af420..d1f13386 100644 --- a/skills/compono/evals/evals.json +++ b/skills/compono/evals/evals.json @@ -29,7 +29,7 @@ "id": 3, "category": "routing", "prompt": "Convert this xUnit test that manually builds an Order and a fake IOrderRepository into an xUnit v3 test that uses Compono. The project references Compono, Compono.XunitV3, and Compono.NSubstitute.", - "expected_output": "Uses [Theory]/[Compose] or [Compose], composes Order directly, and uses [Shared] IOrderRepository with UseNSubstitute() from a profile rather than a hand-rolled fake \u2014 because Compono.NSubstitute is referenced.", + "expected_output": "Uses [Theory]/[Compose] or [Compose], composes Order directly, and uses [Shared] IOrderRepository with UseNSubstitute() from a profile rather than a hand-rolled fake — because Compono.NSubstitute is referenced.", "files": [], "expectations": [ "Uses [Compose] or [Compose] correctly, only one Compose-family attribute on the method", @@ -531,12 +531,13 @@ "id": 39, "category": "behavioral-correctness", "prompt": "We compose an IDisposable HTTP client wrapper as a Compose parameter. Does xUnit v3 dispose it like TUnit does?", - "expected_output": "Distinguishes integrations: Compono.XunitV3 does not automatically dispose composed values, while TUnit disposes composed root method arguments but not arbitrary nested dependencies. Caller must own cleanup where needed.", + "expected_output": "Distinguishes engine behavior from Compono behavior: Compono itself never registers or disposes composed values. On Compono.XunitV3 (xUnit v3 JIT), xUnit itself disposes every IDisposable/IAsyncDisposable test-method argument after the test case (once per argument slot) - that is xUnit's behavior, not a Compono contract - so the composed wrapper parameter is disposed by xUnit; xUnit's Native AOT core (Compono.XunitV3.Aot) does not, so dispose explicitly there. TUnit disposes composed root method arguments but not arbitrary nested dependencies (per Compono.TUnit's guide). Nested dependencies and anything not passed as a parameter need explicit caller-owned cleanup, and a fixture-owned disposable should not be passed as a test parameter.", "files": [], "expectations": [ - "States xUnit v3 does not automatically dispose composed values", + "States Compono itself does not own or dispose composed values", + "States xUnit v3 JIT disposes IDisposable test-method arguments itself, while Compono.XunitV3.Aot (xUnit AOT core) does not", "States TUnit root-only disposal boundary and nested-dependency limitation", - "Recommends explicit ownership/cleanup rather than assuming framework disposal" + "Recommends explicit ownership/cleanup for nested dependencies and AOT rather than assuming framework disposal" ] }, { @@ -828,11 +829,11 @@ "id": 66, "category": "routing", "prompt": "This class takes an IMeterFactory constructor dependency and records a counter and a histogram. The project references Compono, Compono.XunitV3, and Compono.Metrics. Write the test that asserts the recorded values.", - "expected_output": "Adds builder.UseMetrics() (typically in an ICompositionProfile), composes the SUT directly, and takes [Shared] IMeterFactory meters so the test sees the same factory the SUT used; the test disposes it with 'using var _ = meters;'. Asserts with meters.Verify(\"shop.orders.placed\").WithTag(\"region\", \"eu\").WithValue(1).Once() and meters.Verify(\"shop.orders.duration\").Once(), or reads via meters.GetMeasurements(...) and does value math with LINQ. Never hand-rolls an IMeterFactory, never reaches for Microsoft.Extensions.Diagnostics.Testing MetricCollector, and never adds an MSBuild opt-in property (none exists for Compono.Metrics).", + "expected_output": "Adds builder.UseMetrics() (typically in an ICompositionProfile), composes the SUT directly, and takes [Shared] IMeterFactory meters so the test sees the same factory the SUT used; disposal follows the engine: on Compono.XunitV3 (JIT) xUnit disposes the argument so 'using var _ = meters;' is optional, while on Compono.XunitV3.Aot (and on engines not verified for this guidance) the test disposes it with 'using var _ = meters;'. Asserts with meters.Verify(\"shop.orders.placed\").WithTag(\"region\", \"eu\").WithValue(1).Once() and meters.Verify(\"shop.orders.duration\").Once(), or reads via meters.GetMeasurements(...) and does value math with LINQ. Never hand-rolls an IMeterFactory, never reaches for Microsoft.Extensions.Diagnostics.Testing MetricCollector, and never needs to add an MSBuild property (Compono.Metrics' only one, ComponoMetricsOwnsMeterFactory, is defaulted on by the package).", "files": [], "expectations": [ "Registers UseMetrics() (or relies on it already being registered) rather than a hand-rolled IMeterFactory or MetricCollector", - "Uses [Shared] IMeterFactory so the SUT and the test share one factory, and disposes it in the test body (using var _ = meters;)", + "Uses [Shared] IMeterFactory so the SUT and the test share one factory, and gives engine-correct disposal guidance (optional using on Compono.XunitV3 JIT, explicit using var _ = meters; on Compono.XunitV3.Aot/unverified engines) without claiming Compono disposes it", "Verifies via meters.Verify(...) with WithTag/WithValue/Once (or GetMeasurements plus LINQ), not a two-verb VerifyMetrics shape", "Does not suggest adding a Microsoft.Extensions.Diagnostics.Testing dependency or an MSBuild opt-in property for Compono.Metrics" ] @@ -862,6 +863,84 @@ "States the poll runs only this factory's observable callbacks, synchronously", "Does not suggest an auto-poll-on-read option or a wait/timeout API (neither exists)" ] + }, + { + "id": 69, + "category": "behavioral-correctness", + "prompt": "Our shared base profile does builder.UseGeneratedTestDoubles().UseMetrics(), with ComponoGeneratedTestDoubles=true and Compono.Metrics + Compono.TestDoubles referenced from NuGet. Will a generated double steal IMeterFactory from UseMetrics() because it's registered first? What changes if I drop UseMetrics()?", + "expected_output": "No: referencing Compono.Metrics defaults ComponoMetricsOwnsMeterFactory=true, so Compono.TestDoubles never generates an IMeterFactory double and both registration orders compose a CapturingMeterFactory (other interfaces still get generated doubles). First-registered-wins still applies against UseNSubstitute()/other catch-all providers, so UseMetrics() must precede those. Dropping UseMetrics() makes IMeterFactory composition fail with a CompositionException naming IMeterFactory (or fall through to a later catch-all provider); the fix is to add UseMetrics(). Setting ComponoMetricsOwnsMeterFactory=false restores a generated double and order sensitivity.", + "files": [], + "expectations": [ + "States order against UseGeneratedTestDoubles() does not matter because Compono.Metrics owns IMeterFactory (ComponoMetricsOwnsMeterFactory)", + "Keeps the rule that UseMetrics() must come before UseNSubstitute() or other catch-all providers", + "Explains that without UseMetrics() IMeterFactory composition fails (or falls through) rather than getting a generated double", + "Mentions the ComponoMetricsOwnsMeterFactory=false opt-out without recommending it by default" + ] + }, + { + "id": 70, + "category": "behavioral-correctness", + "prompt": "Every one of my Compono.XunitV3 tests with [Shared] IMeterFactory meters has `using var _ = meters;`. Can Compono dispose [Shared] disposables for me at the end of the test? Should I delete the line?", + "expected_output": "Compono never disposes composed values (no ownership contract; ADR-0022 Amendment 4 / ADR-0072 Amendment 6). On Compono.XunitV3 (JIT) the line is optional because xUnit itself disposes every IDisposable/IAsyncDisposable test-method argument after the test case (once per argument slot, so disposal must be idempotent - CapturingMeterFactory's is). Keep the line on Compono.XunitV3.Aot (xUnit's AOT core doesn't dispose arguments), NUnit and MSTest (not verified), and for factories created in Composer.Create/host tests. On Compono.TUnit, TUnit disposes composed root method arguments per its documented contract (ADR-0040), so the line is optional there too.", + "files": [], + "expectations": [ + "Does not claim Compono disposes [Shared] or composed values", + "Explains xUnit v3 JIT already disposes IDisposable test-method arguments, making the line optional on Compono.XunitV3", + "Says to keep the explicit using on Compono.XunitV3.Aot and other framework adapters", + "Does not propose a new Compono auto-disposal setting or API", + "Distinguishes documented TUnit root-argument disposal (ADR-0040) from the unverified NUnit/MSTest engines" + ] + }, + { + "id": 71, + "category": "behavioral-correctness", + "prompt": "In a host-level test I want to assert nothing was logged at Error or above outside my own MyApp.Jobs namespace, using Compono.Logging's LogCollector. How?", + "expected_output": "logs.Verify().AtLevelOrAbove(LogLevel.Error).NotInCategoryPrefix(\"MyApp.Jobs.\").Never(); InCategoryPrefix/NotInCategoryPrefix are ordinal, case-sensitive and literal (no implied separator), so end the prefix with '.' to avoid matching e.g. MyApp.JobsLegacy (note \"MyApp.Jobs.\" also excludes the bare MyApp.Jobs category). InCategory remains an exact match; Matching(...) stays the escape hatch for multi-namespace conditions.", + "files": [], + "expectations": [ + "Uses NotInCategoryPrefix combined with AtLevelOrAbove(LogLevel.Error) and Never()", + "Explains the prefix is literal/ordinal and recommends a trailing dot", + "Does not claim InCategory performs prefix matching", + "Does not invent a general negation combinator or InNamespace API" + ] + }, + { + "id": 72, + "category": "behavioral-correctness", + "prompt": "I use [ComposeData(nameof(Cases))] and need daysBefore/daysAfter from the row's RetentionWindow inside the test body to compute the expected value. Can a TConfig parameter bind to row element 0, or can I bind rows by parameter name?", + "expected_output": "Neither exists: element 0 is consumed by the profile constructor and row values bind leading-positionally (row values first, then [Shared]/composed parameters). Recipe: have the profile register the config it already holds (builder.Register(() => window)) and add a composed RetentionWindow parameter after the row values - it resolves to that row's own instance. Works the same on Compono.XunitV3.Aot. Don't duplicate the config values as extra row elements.", + "files": [], + "expectations": [ + "States TConfig (element 0) does not bind to a parameter and named binding is unsupported", + "Recommends the profile register its config and the test take a composed TConfig parameter", + "Explains row values bind to the leading parameters before [Shared]/composed ones", + "Does not invent new ComposeData binding attributes or options" + ] + }, + { + "id": 73, + "category": "behavioral-correctness", + "prompt": "My DbProfile takes interceptor objects in its constructor, so I can't name it in [Compose]. I added a second parameterless constructor just for the attribute. Is there a better way, or can Compono call a static factory member for the profile?", + "expected_output": "Write a parameterless wrapper profile per variant (e.g. AuditedDbProfile) whose Configure calls builder.AddProfile(new DbProfile(new AuditInterceptor(log))) and registers anything the test asserts on; use [Compose]. Alternatively a single-row [ComposeData] whose TConfig carries the runtime objects. Both work on JIT and Native AOT. There is no profile-factory/ProfileMember attribute property (deferred).", + "files": [], + "expectations": [ + "Recommends a parameterless wrapper profile that calls AddProfile(new DbProfile(...))", + "Mentions the single-row ComposeData alternative", + "Does not invent a ProfileMember/static-factory attribute property", + "Does not use reflection-based profile activation" + ] + }, + { + "id": 74, + "category": "behavioral-correctness", + "prompt": "My outbox test runs the processor three times against one database and I only want to assert the measurements from the third run. MetricCollector had Clear(); what's the Compono.Metrics way - is there a checkpoint or Since() API?", + "expected_output": "Call meters.ClearMeasurements() immediately before the step under test, then Verify - the same reset idiom as TestDoubles ClearCalls()/Logging ClearCapturedEntries(). Snapshots already returned by GetMeasurements are unaffected, so take one before clearing if an earlier pass must also be asserted. There is no checkpoint/Since/scoped-capture API (deferred).", + "files": [], + "expectations": [ + "Recommends ClearMeasurements() right before the step under test", + "Notes earlier GetMeasurements snapshots are unaffected by clearing", + "Does not invent Checkpoint(), Since(...), or BeginCapture() APIs" + ] } ] } diff --git a/skills/compono/references/logging.md b/skills/compono/references/logging.md index c5707757..249f35b1 100644 --- a/skills/compono/references/logging.md +++ b/skills/compono/references/logging.md @@ -108,6 +108,7 @@ discovered. — never suggest a two-verb `VerifyLog()...Verify()` shape, that was explicitly considered and rejected): `.AtLevel(level)`, `.AtLevelOrAbove(level)`, `.InCategory(category)`, + `.InCategoryPrefix(prefix)`, `.NotInCategoryPrefix(prefix)`, `.WithEventId(id)`, `.WithException()`, `.WithMessageContaining(text)`, `.Matching(predicate)`, ending in `.Once()` / `.Never()` / `.Exactly(n)` / `.AtLeast(n)` / `.AtMost(n)` — @@ -134,9 +135,10 @@ using var host = builder.Build(); logs.Verify().AtLevelOrAbove(LogLevel.Error).Never(); // One category: the ILogger type's FULL name, matched exactly. logs.Verify().AtLevelOrAbove(LogLevel.Error).InCategory("MyApp.Payments.PaymentGateway").Never(); -// A namespace: match the prefix explicitly. -logs.Verify().AtLevelOrAbove(LogLevel.Error) - .Matching(e => e.Category.StartsWith("MyApp.Payments.", StringComparison.Ordinal)).Never(); +// A namespace: literal ordinal prefix - end it with "." for namespace-boundary intent. +logs.Verify().AtLevelOrAbove(LogLevel.Error).InCategoryPrefix("MyApp.Payments.").Never(); +// Host guard: nothing at Error or above OUTSIDE your own code. +logs.Verify().AtLevelOrAbove(LogLevel.Error).NotInCategoryPrefix("MyApp.Jobs.").Never(); ``` Key semantics to get right: @@ -148,8 +150,12 @@ Key semantics to get right: case-sensitive — **not** a prefix match, unlike the host's own `AddFilter`/`Logging:LogLevel:*` rules. Never write `InCategory("Payments")`/a namespace with `.Never()`: it matches nothing - and passes without checking anything. Use the full category name or - `.Matching(e => e.Category.StartsWith(...))`. + and passes without checking anything. Use the full category name, or + `.InCategoryPrefix(prefix)`/`.NotInCategoryPrefix(prefix)` (ordinal, + literal - `"MyApp.Jobs"` also matches `MyApp.JobsLegacy`, so recommend a + trailing `.`). Don't hand-write `.Matching(e => e.Category.StartsWith(...))` + for a single prefix any more; keep `.Matching` for multi-namespace or + other custom conditions. - `Never()`'s failure text names the filters and the match count only (`Expected exactly 0 call(s) to a log entry matching level Error or above, but received 1.`); it does not list entries — read them with diff --git a/skills/compono/references/metrics.md b/skills/compono/references/metrics.md index 74a34230..2e904910 100644 --- a/skills/compono/references/metrics.md +++ b/skills/compono/references/metrics.md @@ -25,7 +25,7 @@ public sealed class CheckoutProfile : ICompositionProfile [Theory, Compose] public void PlacingAnOrderCountsIt([Shared] IMeterFactory meters, CheckoutService service) { - using var _ = meters; // the test owns disposal + using var _ = meters; // optional on Compono.XunitV3 (xUnit disposes args); required on XunitV3.Aot; keep on NUnit/MSTest service.Place(new Order("eu", 3)); @@ -77,7 +77,11 @@ compile-time opt-in for it — there is none. observable instruments. Idempotent per call (twice records twice); a no-op before the first `Create` or after `Dispose`. - `meters.ClearMeasurements()` — clears captured measurements (doesn't reset - capture order's sequence). + capture order's sequence). This is **the** supported way to assert on one + pass of a multi-pass test: call it immediately before the step under test, + then `Verify`. Take a `GetMeasurements` snapshot first if an earlier + pass must also be asserted. Don't invent `Checkpoint()`/`Since(...)`/ + `BeginCapture()` APIs; they were considered and deferred (RESEARCH-0040). Never suggest a two-verb `VerifyMetrics()...Verify()` shape or an aggregate helper (`Sum`, `LastValue`) — both were considered and rejected (ADR-0072). @@ -157,6 +161,15 @@ measurements stay readable, `ClearMeasurements` works, meters' instruments isn't captured. Three documented patterns: 1. `[Compose]` tests — dispose the `[Shared]` parameter: `using var _ = meters;`. + On `Compono.XunitV3` (JIT) the line is optional: xUnit itself disposes every + `IDisposable`/`IAsyncDisposable` test-method argument after the test case + (once per argument slot), which is xUnit's behavior, not a Compono + contract. Keep it on `Compono.XunitV3.Aot` (xUnit's AOT core doesn't + dispose arguments), NUnit, and MSTest (not verified). TUnit disposes composed + *root* method arguments per `Compono.TUnit`'s documented contract (ADR-0040), + which ADR-0072 Amendment 6 didn't re-test; there the line is optional and + harmless. Never tell a user Compono + disposes composed values; it doesn't (ADR-0072 Amendment 6). 2. `Composer.Create` tests — construct the factory, then `Register(() => meters)` (which also beats `UseMetrics()`). 3. Generic Host/DI — `services.AddSingleton(meters)`. The @@ -183,19 +196,37 @@ readable; a disposed meter's instruments report `Enabled == false`. ## Registration order (stage-6 precedence) and misuse -`UseMetrics()` shares stage 6 with `UseNSubstitute()`/`UseGeneratedTestDoubles()` -— the existing first-registered-wins rule (ADR-0024) applies unchanged: +`UseMetrics()` shares stage 6 with `UseNSubstitute()` and any other catch-all +provider — the existing first-registered-wins rule (ADR-0024) applies +unchanged: ```csharp builder.UseMetrics().UseNSubstitute(); // IMeterFactory -> CapturingMeterFactory builder.UseNSubstitute().UseMetrics(); // IMeterFactory -> an NSubstitute substitute instead ``` -Register `UseMetrics()` first. Every `MeterFactoryTestingExtensions` method +Register `UseMetrics()` first, especially in a shared base profile. + +**Order against `UseGeneratedTestDoubles()` does not matter** (ADR-0072 +Amendment 5): referencing `Compono.Metrics` defaults the MSBuild property +`ComponoMetricsOwnsMeterFactory` to `true`, so `Compono.TestDoubles` never +generates an `IMeterFactory` double; both orders compose a +`CapturingMeterFactory`, and other interfaces still get generated doubles. +Consequences to explain when relevant: `UseGeneratedTestDoubles()` *without* +`UseMetrics()` now fails composition with a `CompositionException` naming +`IMeterFactory` (fix: add `UseMetrics()`), and a project that genuinely wants +a generated `IMeterFactory` double sets +`false`. +A `ProjectReference` (not `PackageReference`) to Compono.Metrics doesn't get +the packed default — set the property explicitly there. + +Every `MeterFactoryTestingExtensions` method throws `InvalidOperationException` when the `IMeterFactory` isn't a `CapturingMeterFactory` (detected by a type check, not reflection); the -message names `UseMetrics()`, the registration-order requirement, and the -host recipe. `Meter` constructor parameters are **not** composed by this +message names `UseMetrics()`, the catch-all registration-order requirement, +the `ComponoMetricsOwnsMeterFactory` ownership rule, and the host recipe. +Migrating from `MetricCollector`? See +docs/migrating-from-microsoft-extensions-diagnostics-testing.md. `Meter` constructor parameters are **not** composed by this package — register them from the shared factory in a profile. ## `Share()` and `[Shared]` diff --git a/skills/compono/references/registrations-profiles-and-scopes.md b/skills/compono/references/registrations-profiles-and-scopes.md index 31d79afc..44b612ea 100644 --- a/skills/compono/references/registrations-profiles-and-scopes.md +++ b/skills/compono/references/registrations-profiles-and-scopes.md @@ -111,6 +111,16 @@ var composer = Composer.Create(b => b.AddProfile()); - Pure configuration, applied synchronously exactly once. - `AddProfile()` requires a parameterless constructor; `AddProfile(instance)` for one that doesn't. +- **Profile constructor arguments with `[Compose]`** (runtime + objects such as interceptors, which can't be attribute constants): write a + parameterless *wrapper* profile per variant whose `Configure` calls + `builder.AddProfile(new DbProfile(new AuditInterceptor(log)))`. Register + anything the test must assert on, such as `log`. Alternatively, use a + single-row `[ComposeData]` whose `TConfig` carries the + objects. Both work on JIT and Native AOT. Don't suggest adding a second + parameterless constructor to the real profile, and don't invent a + `ProfileMember`/profile-factory attribute property. That was deferred + (RESEARCH-0040). - Multiple `AddProfile<...>()` calls all apply, in the order added. - A profile applying itself (directly or through nesting) is a `CompositionConfigurationException` (`ProfileCycle`), immediately — not diff --git a/skills/compono/references/xunit-v3.md b/skills/compono/references/xunit-v3.md index af6dd572..ebc1a8bf 100644 --- a/skills/compono/references/xunit-v3.md +++ b/skills/compono/references/xunit-v3.md @@ -184,7 +184,27 @@ own `TypeHelper` conversions, the same strictness as `[Compose(42)]`: The same leading-positional, compose-the-rest algorithm `[Compose]` uses (ADR-0022) applies to the composed parameters — `[Shared]` parameters -resolve first, then the rest. +resolve first, then the rest. So write signatures as **row values first, +then `[Shared]`/composed parameters**. Binding by parameter name doesn't +exist; never suggest it. + +**Reading the row's `TConfig` in the test body.** Element 0 is consumed by +the profile constructor and never binds to a parameter. Don't duplicate its +values as extra row elements, and don't invent a "bind `TConfig` to +parameter 0" feature. The supported recipe: the profile registers the config +it already holds, `builder.Register(() => config)`, and the test adds a +composed `TConfig` parameter after the row values. It resolves to that row's +own instance. Works identically on `Compono.XunitV3.Aot` (RESEARCH-0040). + +```csharp +public sealed class RetentionProfile(RetentionWindow window) : ICompositionProfile +{ + public void Configure(CompositionBuilder builder) => builder.Register(() => window); +} + +[Theory, ComposeData(nameof(Cases))] +public void Keeps(int ageInDays, bool expected, RetentionWindow window, RetentionPolicy sut) { } +``` ### Shared dependencies and `[Shared]` diff --git a/src/Compono.Generators/ComponoIncrementalGenerator.cs b/src/Compono.Generators/ComponoIncrementalGenerator.cs index 06712b61..5613654a 100644 --- a/src/Compono.Generators/ComponoIncrementalGenerator.cs +++ b/src/Compono.Generators/ComponoIncrementalGenerator.cs @@ -40,7 +40,12 @@ public void Initialize(IncrementalGeneratorInitializationContext context) && testDoublesEnabled, provider.GlobalOptions.TryGetValue("build_property.ComponoGeneratedLogging", out var loggingValue) && bool.TryParse(loggingValue, out var loggingEnabled) - && loggingEnabled)) + && loggingEnabled, + // ADR-0072 Amendment 5: Compono.Metrics owns IMeterFactory - read into the same + // flags value for the same reason as ComponoGeneratedLogging above. + provider.GlobalOptions.TryGetValue("build_property.ComponoMetricsOwnsMeterFactory", out var metricsValue) + && bool.TryParse(metricsValue, out var metricsOwnsMeterFactory) + && metricsOwnsMeterFactory)) .WithTrackingName(TrackingNames.TestDoublesEnabled); var callSiteResults = context.SyntaxProvider diff --git a/src/Compono.Generators/Discovery/TransitiveClosureWalker.cs b/src/Compono.Generators/Discovery/TransitiveClosureWalker.cs index d6d01a91..de6c1a97 100644 --- a/src/Compono.Generators/Discovery/TransitiveClosureWalker.cs +++ b/src/Compono.Generators/Discovery/TransitiveClosureWalker.cs @@ -209,6 +209,14 @@ private static void TryRecordTestDouble(ITypeSymbol type, WalkContext ctx) if (IsLoggingOwned(type, ctx)) return; + // ADR-0072 Amendment 5: Metrics owns IMeterFactory when ComponoMetricsOwnsMeterFactory is on + // (Compono.Metrics' packed default), so a generated double can never win stage 6 over + // UseMetrics()'s CapturingMeterFactory just because UseGeneratedTestDoubles() was registered + // first. Same ownership shape as IsLoggingOwned above; null (inert) when the flag is off or + // System.Diagnostics.Metrics.IMeterFactory doesn't resolve in this compilation. + if (ctx.MetricsOwnedMeterFactory is { } meterFactory && SymbolEqualityComparer.Default.Equals(type, meterFactory)) + return; + var interfaceType = (INamedTypeSymbol)type; if (!ctx.VisitedTestDoubleInterfaces.Add(interfaceType)) @@ -381,6 +389,8 @@ private static (DiscoveredTypeInfo Info, IMethodSymbol? Constructor, IReadOnlyLi // kind this walker learns to recognize. private sealed class WalkContext { + private static readonly WellKnownTypes.BoundedCacheWithFactory MeterFactoryCache = new(); + public WalkContext(Compilation compilation, LocationInfo? location, GeneratorFeatureFlags flags) { Compilation = compilation; @@ -395,6 +405,13 @@ public WalkContext(Compilation compilation, LocationInfo? location, GeneratorFea LoggingWellKnown = flags.LoggingEnabled ? Compono.Generators.WellKnownTypes.LoggingWellKnownTypes.TryCreate(compilation) : null; + // Resolved only when the flag is on (so a consumer without Compono.Metrics pays nothing), + // and cached per compilation like LoggingWellKnownTypes, since a context is built per root. + MetricsOwnedMeterFactory = flags.MetricsOwnsMeterFactory + ? MeterFactoryCache.GetOrCreateValue( + compilation, + static c => c.GetTypeByMetadataName("System.Diagnostics.Metrics.IMeterFactory")) + : null; } public Compilation Compilation { get; } @@ -409,6 +426,8 @@ public WalkContext(Compilation compilation, LocationInfo? location, GeneratorFea public WellKnownTypes.LoggingWellKnownTypes? LoggingWellKnown { get; } + public INamedTypeSymbol? MetricsOwnedMeterFactory { get; } + public CollectionWellKnownTypes CollectionTypes { get; } // IncludeNullability, not Default - Default treats Box and Box as the same diff --git a/src/Compono.Generators/Models/GeneratorFeatureFlags.cs b/src/Compono.Generators/Models/GeneratorFeatureFlags.cs index dba61f1f..266d6de6 100644 --- a/src/Compono.Generators/Models/GeneratorFeatureFlags.cs +++ b/src/Compono.Generators/Models/GeneratorFeatureFlags.cs @@ -8,5 +8,8 @@ namespace Compono.Generators.Models; /// when unset - 's own default-to- /// behavior for a consumer who references Compono.Logging comes from that package's own /// packed MSBuild props asset, not from this type or this generator. +/// ComponoMetricsOwnsMeterFactory (docs/adr/0072-compono-metrics-testing-support-package.md +/// Amendment 5) follows the same split: when unset here, defaulted to +/// by Compono.Metrics's own packed props. /// -internal readonly record struct GeneratorFeatureFlags(bool TestDoublesEnabled, bool LoggingEnabled); +internal readonly record struct GeneratorFeatureFlags(bool TestDoublesEnabled, bool LoggingEnabled, bool MetricsOwnsMeterFactory); diff --git a/src/Compono.Logging/LogVerificationBuilder.cs b/src/Compono.Logging/LogVerificationBuilder.cs index fa583e9d..3e97f031 100644 --- a/src/Compono.Logging/LogVerificationBuilder.cs +++ b/src/Compono.Logging/LogVerificationBuilder.cs @@ -36,8 +36,8 @@ public LogVerificationBuilder AtLevelOrAbove(LogLevel level) => /// /// Restricts matches to entries whose is exactly - /// (ordinal, case-sensitive - use for a prefix - /// or wildcard match). + /// (ordinal, case-sensitive - use for a + /// prefix match, or for anything else). /// /// is . public LogVerificationBuilder InCategory(string category) @@ -47,6 +47,35 @@ public LogVerificationBuilder InCategory(string category) return Add($"category \"{category}\"", entry => string.Equals(entry.Category, category, StringComparison.Ordinal)); } + /// + /// Restricts matches to entries whose starts with + /// (ordinal, case-sensitive). The prefix is literal - no namespace + /// separator is implied - so InCategoryPrefix("MyApp.Jobs") also matches + /// MyApp.JobsLegacy; pass a trailing dot ("MyApp.Jobs.") to match only categories + /// beneath that namespace. An empty prefix matches every entry. + /// + /// is . + public LogVerificationBuilder InCategoryPrefix(string prefix) + { + ArgumentNullException.ThrowIfNull(prefix); + + return Add($"category starting with \"{prefix}\"", entry => entry.Category.StartsWith(prefix, StringComparison.Ordinal)); + } + + /// + /// Restricts matches to entries whose does not start + /// with (ordinal, case-sensitive) - for host-wide guards such as "nothing + /// at outside MyApp.Jobs.". The prefix is literal, exactly as for + /// ; an empty prefix matches no entry. + /// + /// is . + public LogVerificationBuilder NotInCategoryPrefix(string prefix) + { + ArgumentNullException.ThrowIfNull(prefix); + + return Add($"category not starting with \"{prefix}\"", entry => !entry.Category.StartsWith(prefix, StringComparison.Ordinal)); + } + /// Restricts matches to entries logged with exactly . public LogVerificationBuilder WithEventId(EventId eventId) => Add($"event id {eventId}", entry => entry.EventId == eventId); diff --git a/src/Compono.Metrics/Compono.Metrics.csproj b/src/Compono.Metrics/Compono.Metrics.csproj index 731bd6cc..48a25e39 100644 --- a/src/Compono.Metrics/Compono.Metrics.csproj +++ b/src/Compono.Metrics/Compono.Metrics.csproj @@ -25,6 +25,16 @@ + + + + + + diff --git a/src/Compono.Metrics/CompositionBuilderExtensions.cs b/src/Compono.Metrics/CompositionBuilderExtensions.cs index b78db7de..7c78c54b 100644 --- a/src/Compono.Metrics/CompositionBuilderExtensions.cs +++ b/src/Compono.Metrics/CompositionBuilderExtensions.cs @@ -11,12 +11,23 @@ public static class CompositionBuilderExtensions /// per request. /// /// - /// Register this before UseNSubstitute() if + /// + /// Register this before UseNSubstitute() or any other catch-all test-double provider if /// should resolve through Compono.Metrics rather - /// than an NSubstitute substitute - Compono's stage-6 providers resolve in registration order + /// than a substitute - Compono's stage-6 providers resolve in registration order /// (first-registered-wins), an existing, documented, Accepted pattern (ADR-0024) this package /// follows rather than replacing. An exact Register<IMeterFactory>(...) always wins over /// UseMetrics() regardless of order. + /// + /// + /// Order against UseGeneratedTestDoubles() doesn't matter while + /// ComponoMetricsOwnsMeterFactory is enabled (the default whenever Compono.Metrics is + /// referenced): is then Metrics-owned and + /// Compono.TestDoubles never generates a double for it. The same default means a composer that + /// calls UseGeneratedTestDoubles() without UseMetrics() gets no + /// double at all. See + /// docs/adr/0072-compono-metrics-testing-support-package.md Amendment 5. + /// /// /// The builder to register into. /// The same , for chaining. diff --git a/src/Compono.Metrics/MeterFactoryTestingExtensions.cs b/src/Compono.Metrics/MeterFactoryTestingExtensions.cs index e65b4a7c..6c550ca2 100644 --- a/src/Compono.Metrics/MeterFactoryTestingExtensions.cs +++ b/src/Compono.Metrics/MeterFactoryTestingExtensions.cs @@ -131,8 +131,11 @@ private static CapturingMeterFactory RequireCapturing(IMeterFactory factory) $"'{factory.GetType()}' is not a Compono.Metrics capturing meter factory. This member is only usable " + "against an IMeterFactory produced by Compono.Metrics (UseMetrics(), or a directly constructed " + "CapturingMeterFactory). If this IMeterFactory was composed, confirm UseMetrics() is registered " + - "before UseNSubstitute() - Compono's stage-6 test-double providers resolve in registration order, " + - "and whichever provider is registered first wins for a given request. If this IMeterFactory came " + + "and comes before UseNSubstitute() or any other catch-all test-double provider - Compono's stage-6 " + + "test-double providers resolve in registration order, and whichever provider is registered first " + + "wins for a given request. A Compono.TestDoubles generated double only competes when " + + "ComponoMetricsOwnsMeterFactory has been set to false; by default Compono.Metrics owns " + + "IMeterFactory and UseGeneratedTestDoubles() never doubles it. If this IMeterFactory came " + "from a host's IServiceProvider (for example AddMetrics()'s DefaultMeterFactory), register a " + "CapturingMeterFactory instance with services.AddSingleton(meters) instead. The " + "container resolves a single IMeterFactory to its last registration, so add that call after anything " + diff --git a/src/Compono.Metrics/build/Compono.Metrics.props b/src/Compono.Metrics/build/Compono.Metrics.props new file mode 100644 index 00000000..e82154d5 --- /dev/null +++ b/src/Compono.Metrics/build/Compono.Metrics.props @@ -0,0 +1,21 @@ + + + + + true + + + diff --git a/src/Compono/build/Compono.props b/src/Compono/build/Compono.props index a313f4c8..43c5da58 100644 --- a/src/Compono/build/Compono.props +++ b/src/Compono/build/Compono.props @@ -24,4 +24,14 @@ + + + + + diff --git a/test/Compono.Generators.Tests/MetricsTestDoubleOwnershipTests.cs b/test/Compono.Generators.Tests/MetricsTestDoubleOwnershipTests.cs new file mode 100644 index 00000000..8291c38d --- /dev/null +++ b/test/Compono.Generators.Tests/MetricsTestDoubleOwnershipTests.cs @@ -0,0 +1,112 @@ +namespace Compono.Generators.Tests; + +/// +/// ADR-0072 Amendment 5: when ComponoMetricsOwnsMeterFactory is enabled (Compono.Metrics' packed +/// default), System.Diagnostics.Metrics.IMeterFactory is Metrics-owned and excluded from +/// Compono.TestDoubles generation, so UseGeneratedTestDoubles() can never take it ahead of +/// UseMetrics() (the #161 follow-up trap, RESEARCH-0040 finding 1). Mirrors +/// . +/// +public sealed class MetricsTestDoubleOwnershipTests +{ + private const string MeterFactoryRegistration = + "RegisterFactory"; + + private const string SiblingRegistration = + "RegisterFactory"; + + private const string Source = """ + namespace TestNamespace; + + public interface IJobClock + { + System.DateTimeOffset Now(); + } + + public sealed class MeteredJob + { + public MeteredJob(System.Diagnostics.Metrics.IMeterFactory meters, IJobClock clock) { } + } + + public static class EntryPoint + { + public static void Run() + { + var composer = Compono.Composer.Create(); + var job = composer.Create(); + } + } + """; + + private static string Generate(bool testDoublesEnabled, string? metricsOwnsMeterFactory) + { + var properties = new Dictionary + { + ["ComponoGeneratedTestDoubles"] = testDoublesEnabled ? "true" : "false", + }; + + if (metricsOwnsMeterFactory is not null) + properties["ComponoMetricsOwnsMeterFactory"] = metricsOwnsMeterFactory; + + var (driver, _) = GeneratorTestHelpers.GenerateFromSource( + new CodeGenerationOptions + { + SourceCode = Source, + MSBuildProperties = properties, + }, + TestContext.Current.CancellationToken); + + return string.Join("\n", driver.GetRunResult().GeneratedTrees.Select(t => t.GetText().ToString())); + } + + [Fact] + public void FlagUnset_TestDoublesEnabled_IMeterFactoryStillGetsADouble_PreExistingBehaviorPreserved() + { + var generated = Generate(testDoublesEnabled: true, metricsOwnsMeterFactory: null); + + generated.Should().Contain(MeterFactoryRegistration); + generated.Should().Contain(SiblingRegistration); + } + + [Fact] + public void FlagFalse_TestDoublesEnabled_IMeterFactoryGetsADouble_OptOutHonored() + { + var generated = Generate(testDoublesEnabled: true, metricsOwnsMeterFactory: "false"); + + generated.Should().Contain(MeterFactoryRegistration); + } + + [Fact] + public void FlagTrue_TestDoublesEnabled_MetricsOwnsIMeterFactory_NoGeneratedDouble() + { + var generated = Generate(testDoublesEnabled: true, metricsOwnsMeterFactory: "true"); + + generated.Should().NotContain(MeterFactoryRegistration); + generated.Should().NotContain("IMeterFactory_global__"); + } + + [Fact] + public void FlagTrue_ExclusionIsNarrow_SiblingInterfaceStillGetsADouble() + { + var generated = Generate(testDoublesEnabled: true, metricsOwnsMeterFactory: "true"); + + generated.Should().Contain(SiblingRegistration); + } + + [Fact] + public void FlagTrue_TestDoublesDisabled_NothingGenerated() + { + var generated = Generate(testDoublesEnabled: false, metricsOwnsMeterFactory: "true"); + + generated.Should().NotContain(MeterFactoryRegistration); + generated.Should().NotContain(SiblingRegistration); + } + + [Fact] + public void FlagUnparseable_TreatedAsDisabled() + { + var generated = Generate(testDoublesEnabled: true, metricsOwnsMeterFactory: "yes-please"); + + generated.Should().Contain(MeterFactoryRegistration); + } +} diff --git a/test/Compono.Logging.AotSmokeTest/Program.cs b/test/Compono.Logging.AotSmokeTest/Program.cs index 08077577..6fa72d76 100644 --- a/test/Compono.Logging.AotSmokeTest/Program.cs +++ b/test/Compono.Logging.AotSmokeTest/Program.cs @@ -98,6 +98,9 @@ private static void VerifyHostWideCapture() collector.Verify().InCategory("Host.Smoke").AtLevelOrAbove(LogLevel.Warning).Once(); collector.Verify().AtLevelOrAbove(LogLevel.Error).Never(); + // ADR-0055 Amendment 7: literal ordinal prefix filters under Native AOT. + collector.Verify().InCategoryPrefix("Host.").AtLevelOrAbove(LogLevel.Warning).Once(); + collector.Verify().NotInCategoryPrefix("Host.").AtLevelOrAbove(LogLevel.Warning).Never(); } private static void VerifyProviderAliasRuleUnderAot() diff --git a/test/Compono.Logging.Tests/CategoryPrefixFilterTests.cs b/test/Compono.Logging.Tests/CategoryPrefixFilterTests.cs new file mode 100644 index 00000000..024c4606 --- /dev/null +++ b/test/Compono.Logging.Tests/CategoryPrefixFilterTests.cs @@ -0,0 +1,154 @@ +using Microsoft.Extensions.Logging; + +namespace Compono.Logging.Tests; + +/// +/// ADR-0055 Amendment 7: and +/// - ordinal, case-sensitive, literal prefixes +/// (no implied namespace separator). +/// +public sealed class CategoryPrefixFilterTests +{ + private static readonly DateTimeOffset Timestamp = new(2026, 11, 11, 12, 0, 0, TimeSpan.Zero); + + private static LogCollector CollectorWith(params (string Category, LogLevel Level)[] entries) + { + var collector = new LogCollector(); + foreach (var (category, level) in entries) + collector.Add(new CapturedLogEntry(category, level, default, null, "message", null, null, null, [], Timestamp)); + + return collector; + } + + [Fact] + public void InCategoryPrefix_MatchesTheCategoryItselfAndEverythingBeneathIt() + { + var collector = CollectorWith( + ("MyApp.Jobs", LogLevel.Information), + ("MyApp.Jobs.Scheduler", LogLevel.Information), + ("MyApp.Api", LogLevel.Information)); + + collector.Verify().InCategoryPrefix("MyApp.Jobs").Exactly(2); + } + + [Fact] + public void InCategoryPrefix_IsLiteral_SoAPrefixWithoutTrailingDotMatchesSimilarlyNamedCategories() + { + var collector = CollectorWith( + ("MyApp.Jobs.Scheduler", LogLevel.Information), + ("MyApp.JobsLegacy.Runner", LogLevel.Information)); + + collector.Verify().InCategoryPrefix("MyApp.Jobs").Exactly(2); + } + + [Fact] + public void InCategoryPrefix_TrailingDot_ExcludesSimilarlyNamedCategoriesAndTheBareNamespace() + { + var collector = CollectorWith( + ("MyApp.Jobs", LogLevel.Information), + ("MyApp.Jobs.Scheduler", LogLevel.Information), + ("MyApp.JobsLegacy.Runner", LogLevel.Information)); + + collector.Verify().InCategoryPrefix("MyApp.Jobs.").Once(); + } + + [Fact] + public void InCategoryPrefix_IsCaseSensitive() + { + var collector = CollectorWith(("MyApp.Jobs.Scheduler", LogLevel.Information)); + + collector.Verify().InCategoryPrefix("myapp.jobs").Never(); + } + + [Fact] + public void InCategoryPrefix_Empty_MatchesEveryEntry() + { + var collector = CollectorWith(("A", LogLevel.Information), ("B", LogLevel.Information)); + + collector.Verify().InCategoryPrefix(string.Empty).Exactly(2); + } + + [Fact] + public void NotInCategoryPrefix_HostGuard_NoErrorsOutsideOwnNamespace() + { + var collector = CollectorWith( + ("MyApp.Jobs.Scheduler", LogLevel.Error), + ("Microsoft.Hosting.Lifetime", LogLevel.Information), + ("Quartz.Core.QuartzScheduler", LogLevel.Error)); + + collector.Verify().AtLevelOrAbove(LogLevel.Error).NotInCategoryPrefix("MyApp.Jobs.").Once(); + collector.Verify().AtLevelOrAbove(LogLevel.Error).InCategoryPrefix("MyApp.Jobs.").Once(); + } + + [Fact] + public void NotInCategoryPrefix_TrailingDot_TreatsSimilarlyNamedCategoryAsOutside() + { + var collector = CollectorWith( + ("MyApp.Jobs.Scheduler", LogLevel.Error), + ("MyApp.JobsLegacy.Runner", LogLevel.Error)); + + collector.Verify().NotInCategoryPrefix("MyApp.Jobs.").Once(); + collector.Verify().NotInCategoryPrefix("MyApp.Jobs").Never(); + } + + [Fact] + public void NotInCategoryPrefix_IsCaseSensitive() + { + var collector = CollectorWith(("MyApp.Jobs.Scheduler", LogLevel.Error)); + + collector.Verify().NotInCategoryPrefix("myapp.jobs.").Once(); + } + + [Fact] + public void NotInCategoryPrefix_Empty_MatchesNoEntry() + { + var collector = CollectorWith(("A", LogLevel.Error)); + + collector.Verify().NotInCategoryPrefix(string.Empty).Never(); + } + + [Fact] + public void PrefixFilters_Null_ThrowArgumentNullException() + { + var collector = new LogCollector(); + + var include = () => collector.Verify().InCategoryPrefix(null!); + var exclude = () => collector.Verify().NotInCategoryPrefix(null!); + + include.Should().Throw().WithParameterName("prefix"); + exclude.Should().Throw().WithParameterName("prefix"); + } + + [Fact] + public void InCategory_IsUnchanged_StillExactMatchOnly() + { + var collector = CollectorWith(("MyApp.Jobs.Scheduler", LogLevel.Information)); + + collector.Verify().InCategory("MyApp.Jobs").Never(); + } + + [Fact] + public void FailureMessage_DescribesBothPrefixFilters() + { + var collector = CollectorWith(("Quartz.Core", LogLevel.Error)); + + var act = () => collector.Verify() + .InCategoryPrefix("Quartz.") + .NotInCategoryPrefix("Quartz.Core") + .Once(); + + act.Should().Throw() + .WithMessage("Expected exactly 1 call(s) to a log entry matching category starting with \"Quartz.\" and category not starting with \"Quartz.Core\", but received 0."); + } + + [Fact] + public void PrefixFilters_WorkOnAComposedCapturingLogger() + { + var logger = new CapturingLogger(); + + logger.LogWarning("warning"); + + logger.Verify().InCategoryPrefix("Compono.Logging.").Once(); + logger.Verify().NotInCategoryPrefix("Compono.Logging.").Never(); + } +} diff --git a/test/Compono.Logging.Tests/MigrationGuideExamplesTests.cs b/test/Compono.Logging.Tests/MigrationGuideExamplesTests.cs new file mode 100644 index 00000000..598fa26d --- /dev/null +++ b/test/Compono.Logging.Tests/MigrationGuideExamplesTests.cs @@ -0,0 +1,76 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Compono.Logging.Tests; + +// Logs synchronously in StartAsync so the entry exists once host.StartAsync returns. A +// BackgroundService would race here: since .NET 10 its ExecuteAsync runs on a background task, so +// StopAsync can cancel it before it logs (observed as an intermittent net10.0 failure of this test). +public sealed class CheckoutWorker(ILogger logger) : IHostedService +{ + public Task StartAsync(CancellationToken cancellationToken) + { + logger.LogInformation("Checkout started for {OrderId}", 42); + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} + +/// +/// The compiled, running source of the logging examples in +/// docs/migrating-from-microsoft-extensions-diagnostics-testing.md (RESEARCH-0040 finding 7). Keep the +/// two in step: a change to one of these tests means the matching guide snippet changes too. +/// +public sealed class MigrationGuideExamplesTests +{ + + [Fact] + public async Task HostWideCapture_ReplacesAddFakeLoggingAndFakeLogCollector() + { + // Before: builder.Logging.AddFakeLogging(); var logs = host.Services.GetFakeLogCollector(); + var logs = new LogCollector(); + var builder = Host.CreateApplicationBuilder(); + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(logs); + builder.Services.AddHostedService(); + using var host = builder.Build(); + + await host.StartAsync(TestContext.Current.CancellationToken); + await host.StopAsync(TestContext.Current.CancellationToken); + + // Before: Assert.DoesNotContain(logs.GetSnapshot(), r => r.Level >= LogLevel.Error); + logs.Verify().AtLevelOrAbove(LogLevel.Error).Never(); + + // Before: logs.GetSnapshot().Where(r => r.Category == "Compono.Logging.Tests.CheckoutWorker") + logs.Verify() + .InCategory("Compono.Logging.Tests.CheckoutWorker") + .WithMessageContaining("Checkout started for 42") + .Once(); + + // Before: logs.GetSnapshot().Where(r => r.Level >= LogLevel.Error && !r.Category.StartsWith("Compono.Logging.Tests.")) + logs.Verify().AtLevelOrAbove(LogLevel.Error).NotInCategoryPrefix("Compono.Logging.Tests.").Never(); + + // Before: logs.LatestRecord / logs.GetSnapshot() / logs.Count + var entries = logs.GetCapturedEntries(); + entries.Should().Contain(entry => entry.Message == "Checkout started for 42"); + + // Before: logs.Clear(); + logs.ClearCapturedEntries(); + logs.GetCapturedEntries().Should().BeEmpty(); + } + + [Fact] + public void ComposedLogger_ReplacesFakeLoggerOfT() + { + // Before: var logger = new FakeLogger(); ... logger.Collector.GetSnapshot() + var composer = Composer.Create(builder => builder.UseLogging()); + var logger = composer.Create>(); + + logger.LogWarning("Payment retry {Attempt}", 2); + + logger.Verify().AtLevel(LogLevel.Warning).WithMessageContaining("Payment retry 2").Once(); + logger.GetLastCapturedEntry()!.Value.Category.Should().Be("Compono.Logging.Tests.CheckoutWorker"); + } +} diff --git a/test/Compono.Metrics.AotSmokeTest/pack-compono.sh b/test/Compono.Metrics.AotSmokeTest/pack-compono.sh index dc3e6870..6ebdcb48 100755 --- a/test/Compono.Metrics.AotSmokeTest/pack-compono.sh +++ b/test/Compono.Metrics.AotSmokeTest/pack-compono.sh @@ -26,3 +26,6 @@ rm -rf "$restore_packages_path" dotnet pack "$script_dir/../../src/Compono/Compono.csproj" -c Release -o "$feed_dir" -p:Version=1.0.0 --nologo dotnet pack "$script_dir/../../src/Compono.Metrics/Compono.Metrics.csproj" -c Release -o "$feed_dir" -p:Version=1.0.0 --nologo +# verify-packaging.sh's ownership check (ADR-0072 Amendment 5) consumes Compono.TestDoubles alongside +# Compono.Metrics; packing it here is harmless for the AOT smoke test, which never references it. +dotnet pack "$script_dir/../../src/Compono.TestDoubles/Compono.TestDoubles.csproj" -c Release -o "$feed_dir" -p:Version=1.0.0 --nologo diff --git a/test/Compono.Metrics.AotSmokeTest/verify-packaging.sh b/test/Compono.Metrics.AotSmokeTest/verify-packaging.sh index 2c704766..aba10bba 100755 --- a/test/Compono.Metrics.AotSmokeTest/verify-packaging.sh +++ b/test/Compono.Metrics.AotSmokeTest/verify-packaging.sh @@ -5,13 +5,17 @@ # loudly with the evidence" shape. # # Confirms, from a real packed .nupkg (not source, not a ProjectReference): -# 1. Compono.Metrics.nupkg ships no analyzer/props of its own. +# 1. Compono.Metrics.nupkg ships no analyzer of its own, and ships build/ + buildTransitive/ +# Compono.Metrics.props defaulting ComponoMetricsOwnsMeterFactory to true (ADR-0072 Amendment 5). # 2. Compono.Metrics.nupkg's .nuspec has exactly one dependency group per target TFM (4), each with # exactly one dependency - Compono - pinned to the exact version (ADR-0072: zero dependency # beyond core Compono; the exact-version pin target is the same one every other package uses). # 3. A scratch PackageReference consumer of Compono.Metrics ALONE (no explicit property, no # ProjectReference workaround) gets real generator-discovered IMeterFactory composition, capture, # tag matching, and Verify() - proving the whole chain flows transitively through Compono. +# 4. A scratch consumer that also references Compono.TestDoubles with ComponoGeneratedTestDoubles=true +# gets a CapturingMeterFactory even when UseGeneratedTestDoubles() is registered BEFORE +# UseMetrics() - the packed props' ownership default reaches the generator (ADR-0072 Amendment 5). set -euo pipefail script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -34,7 +38,9 @@ fail() { } [ -d "$metrics_inspect/analyzers" ] && fail "Compono.Metrics.nupkg unexpectedly contains an analyzers/ directory - it must ship no generator/analyzer DLL of its own" -[ -d "$metrics_inspect/build" ] && fail "Compono.Metrics.nupkg unexpectedly contains a build/ directory - it must ship no props of its own" +[ -f "$metrics_inspect/build/Compono.Metrics.props" ] || fail "Compono.Metrics.nupkg is missing build/Compono.Metrics.props" +[ -f "$metrics_inspect/buildTransitive/Compono.Metrics.props" ] || fail "Compono.Metrics.nupkg is missing buildTransitive/Compono.Metrics.props" +grep -q "ComponoMetricsOwnsMeterFactory" "$metrics_inspect/build/Compono.Metrics.props" || fail "build/Compono.Metrics.props does not default ComponoMetricsOwnsMeterFactory" nuspec=$(find "$metrics_inspect" -maxdepth 1 -name '*.nuspec' | head -n 1) [ -n "$nuspec" ] || fail "Compono.Metrics.nupkg is missing its .nuspec" @@ -50,7 +56,7 @@ non_compono_deps=$(grep -o ' "$owner_dir/OwnerConsumer.csproj" < + + Exe + net10.0 + enable + enable + false + $owner_dir/.nuget-packages + true + + + + + + +EOF +cat > "$owner_dir/Program.cs" <<'EOF' +using System.Diagnostics.Metrics; +using Compono; +using Compono.Metrics; + +var composer = Composer.Create(builder => builder.UseGeneratedTestDoubles().UseMetrics()); +var service = composer.Create(); +using var _ = service.Meters; + +Console.WriteLine(service.Meters is CapturingMeterFactory ? "METRICS-OWNERSHIP-OK" : "UNEXPECTED-FACTORY " + service.Meters.GetType()); +Console.WriteLine(service.Clock is not null ? "SIBLING-DOUBLE-OK" : "UNEXPECTED-SIBLING"); + +public interface IOwnerClock +{ + DateTimeOffset Now(); +} + +public sealed class OwnerService(IMeterFactory meters, IOwnerClock clock) +{ + public IMeterFactory Meters { get; } = meters; + + public IOwnerClock Clock { get; } = clock; +} +EOF + +owner_output=$(cd "$owner_dir" && dotnet run -c Release 2>&1) +echo "$owner_output" | grep -q "METRICS-OWNERSHIP-OK" || { + echo "verify-packaging.sh: FAIL - UseGeneratedTestDoubles() registered first took IMeterFactory despite Compono.Metrics' ownership props. Output:" >&2 + echo "$owner_output" >&2 + exit 1 +} +echo "$owner_output" | grep -q "SIBLING-DOUBLE-OK" || { + echo "verify-packaging.sh: FAIL - the exclusion was not narrow: a sibling interface did not get its generated double. Output:" >&2 + echo "$owner_output" >&2 + exit 1 +} +echo "verify-packaging.sh: confirmed - Compono.Metrics owns IMeterFactory regardless of UseGeneratedTestDoubles() order." + echo "verify-packaging.sh: PASS - all packaging/consumption behaviors confirmed against a real packed nupkg." diff --git a/test/Compono.Metrics.Tests/Compono.Metrics.Tests.csproj b/test/Compono.Metrics.Tests/Compono.Metrics.Tests.csproj index 8d653b35..4895283c 100644 --- a/test/Compono.Metrics.Tests/Compono.Metrics.Tests.csproj +++ b/test/Compono.Metrics.Tests/Compono.Metrics.Tests.csproj @@ -10,8 +10,22 @@ true true + + true + true + + + + + + @@ -26,6 +40,9 @@ + +