Skip to content

[Feature]: Test-composition gaps: cross-category log capture, metrics testing, multi-attribute theories and runtime values in profiles #161

Closed
4 of 4 issues completed

Description

@ncipollina

Motivation

While migrating an xUnit v3 test suite (.NET 11) from NSubstitute and Microsoft.Extensions.Diagnostics.Testing to full Compono alignment (Compono, Compono.XunitV3, Compono.TestDoubles, Compono.Logging, Compono.Options, all 1.3.2), four scenarios could not be expressed with Compono alone. Each one was hit by a real test, checked against the 1.3.2 documentation, and needed a workaround. No CMP diagnostics were raised, and several other candidate gaps turned out to be supported, so they are not listed.

1. No catch-all log capture across categories

  • Need: a Generic Host test asserts that nothing was logged at Error level or above in any category, including framework and library categories (a scheduler, the hosting layer) that the test does not compose.
  • Today: Compono.Logging composes ILogger and ILogger<T> instances. There is no ILoggerProvider, ILoggerFactory or ILoggingBuilder integration, which the documentation describes as a v1 boundary.
  • Workaround: keep AddFakeLogging() and FakeLogCollector for that one guard.

2. No metrics support

  • Need: compose an IMeterFactory and assert counter, gauge and histogram measurements.
  • Today: there is no Compono package for metrics.
  • Workaround: a hand-written test IMeterFactory registered in a profile, plus MetricCollector<T> from Microsoft.Extensions.Diagnostics.Testing.

3. One Compose-family attribute per method, so no data rows

  • Need: a table-driven theory whose rows vary composed configuration (option values, a clock instant) together with expected values.
  • Today: only one Compose-family attribute is allowed per method. It cannot be combined with [InlineData] or [MemberData], and [Compose<TProfile, TConfig>(...)] arguments must be attribute constants.
  • Cost: a 6-row table became 6 methods plus a shared assertion helper. Types that are not valid attribute arguments (such as DateTimeOffset) need a string stand-in in the config record.

4. Runtime fixture values cannot reach a profile

  • Need: compose a SUT whose dependencies depend on values created by an xUnit class or collection fixture, such as the connection string of a container-backed database or a broker address.
  • Today: those values exist only at runtime and cannot be attribute constants. Profiles cannot receive fixture instances.
  • Workaround: build the composer in the test body with Composer.Create(...), register only the fixture-derived values, then call composer.Create<TSut>().

Together these force a mix of Compono and non-Compono test infrastructure and extra boilerplate in an otherwise fully composed suite.

Proposed solution

Each item is independent and can be delivered separately. The API names below are suggestions, not requirements.

1. Provider-backed log capture across categories

Add an extension to Compono.Logging that registers a capturing ILoggerProvider on the host's ILoggingBuilder, for example builder.Logging.AddComponoCapture().

  • All categories write to one shared collector, including categories the test never composes.
  • The collector exposes the recorded entries (level, category, message, exception, scope state) and simple filters, such as "any entry at or above LogLevel.Error".
  • The existing composed ILogger<T> capture keeps working, and both can read from the same collector.

2. A Compono.Metrics package

  • Register a composed test IMeterFactory through UseMetrics() (or similar), so meters created by the SUT are observable.
  • Provide collector helpers to read counter, gauge and histogram measurements by instrument name and tags. These can wrap MetricCollector<T>.
  • Follow the same lifetime rules as the other integration packages, so the factory and its meters are disposed with the composition scope.

3. Data rows for composed theories

Either of these would remove the one-method-per-row split:

  • Preferred: allow several [Compose<TProfile, TConfig>(...)] attributes on one method, with one theory row per attribute.
  • Alternative: allow [InlineData] or [MemberData] values to fill the non-composed parameters, with [Compose] filling the rest.

Also consider accepting non-constant config through a static member reference (like [MemberData]), so types such as DateTimeOffset need no string stand-in.

4. Fixture values available to profiles

Let a profile receive the xUnit class or collection fixture instances of the running test, for example through a profile constructor parameter or a context.Fixture<T>() call inside Configure.

  • Fixture-derived values (connection strings, broker addresses) can then be registered in the profile.
  • Tests can use [Compose<TProfile>] for those SUTs and no longer need to call Composer.Create(...) in the test body.
  • Resolution should fail with a clear diagnostic when the requested fixture is not declared on the test class.

Priority

If these have to be prioritized, items 4 and 3 remove the most test boilerplate. Item 1 is a small, contained addition. Item 2 is the largest, since it is a new package.

Sub-issues

Sub-issues

4 of 4 Issues completed
Loading 4 sub-issues

Activity

  1. added
    💡 idea
    on Nov 3, 2026
  2. ncipollina commented on Nov 4, 2026

    @ncipollina
    ContributorAuthor

    Feature intake complete. This issue stays open as the umbrella tracker. Each item is now its own sub-issue:

    #161 item Sub-issue Intake classification
    4. Runtime fixture values in profiles #162 Mostly a docs/discoverability gap. A throwaway spike showed that TestContext.Current.GetFixture<T>() inside a profile Register<T> factory already reaches class and collection fixtures (friction: ValueTask sync-over-async, ambient xUnit coupling, untyped failure). Whether a Compono-native API is needed is still open.
    3. Composed theory data rows #163 Confirmed missing capability. Reopens the restriction that ADR-0022 Amendment 7 deferred for lack of a real call site. Highest architectural risk.
    1. Cross-category log capture #164 Confirmed missing capability (ADR-0055 deferred ILoggerFactory until evidence). Looks feasible inside Compono.Logging with no new dependency.
    2. Metrics testing #165 Confirmed no support. Gate A ("meaningful abstraction" versus a cookbook recipe) and the ownership model are genuinely open. Needs admission research first.

    The API names in #161 and in the sub-issues are illustrative, not approved designs. The intake summary is in docs/research/0036-issue-161-test-composition-gaps-intake.md (pending review).

  3. ncipollina commented on Nov 12, 2026

    @ncipollina
    ContributorAuthor

    Follow-up: adopted 1.4.0-preview.127, and all four workarounds are gone

    I've migrated the suite that prompted this issue to 1.4.0-preview.127: all six packages, now including Compono.Metrics. It's an xUnit v3 / .NET 11 GA worker service with 231 tests (unit, Testcontainers persistence and Generic Host). All four workarounds from the original report are removed, and the case count and assertions are unchanged. I checked every migrated test family by deliberately breaking the production code it covers and confirming the tests fail. I found no defects and no CMP diagnostics.

    #161 item Sub-issue What we use now Result
    1. Cross-category log capture #164 LogCollector + builder.Logging.AddComponoCapture(collector) on a Generic Host AddFakeLogging and Microsoft.Extensions.Diagnostics.Testing removed entirely
    2. Metrics #165 UseMetrics(), CapturingMeterFactory, Verify<long>(meter, instrument).WithValue(1).Once(), GetMeasurements<T> Hand-written IMeterFactory and MetricCollector<T> deleted
    3. Composed theory rows #163 [ComposeData<TProfile, TConfig>(nameof(Rows))] over TheoryDataRow[] with Label Four 2- to 6-method families collapsed into single theories; DateTimeOffset config with no string stand-in
    4. Fixture values in profiles #162 TestContext.Current.RequireFixture<T>() inside profile Register factories Database profiles lost their connection-string constructor parameter; single-read tests moved to [Compose<TProfile>]

    Remaining friction

    None of these blocked us. They're ordered roughly by how much they cost us.

    1. UseMetrics() depends on call order relative to UseGeneratedTestDoubles() ([Feature]: Metrics testing: observe IMeterFactory-created instruments in composed tests #165).

      • The first test double provider wins. When UseMetrics() came second, a generated double took IMeterFactory, and 28 tests failed on the measurement assertions. The package's error message pointed us to the cause, but it's an easy trap in a shared base profile.
      • Suggestion: have the metrics provider always win for IMeterFactory regardless of order, or raise an error at configuration time when it's registered after a catch-all double provider.
    2. ComposeData row binding and access to the config ([Feature]: Composed theory data rows: vary profile configuration and expected values per row in one method #163).

      • Row values bind to the method's leading parameters, so we reordered several signatures to put the row data before the [Shared] and composed parameters. That's workable, but not obvious from the docs.
      • We found no way to get the row's TConfig back in the test body. One theory had to repeat daysBefore and daysAfter in both the config record and the row values, so it could assert on them.
      • Suggestion: allow a TConfig parameter to bind to row element 0, or bind row values by parameter name.
    3. [Shared] disposables must be disposed by the test ([Feature]: Metrics testing: observe IMeterFactory-created instruments in composed tests #165).

      • Every test that takes a [Shared] IMeterFactory needs using var _ = meters;.
      • Suggestion: have Compono.XunitV3 dispose shared disposables when the test ends, which would remove that line throughout the suite.
    4. Asserting on one pass of a multi-pass test ([Feature]: Metrics testing: observe IMeterFactory-created instruments in composed tests #165).

      • Our outbox tests run several passes against the same database and assert only on the last one, so we call ClearMeasurements() before the step under test. That works but hides the intent.
      • Suggestion: a checkpoint or scoped verify, for example using (meters.BeginCapture()) { ... } or Verify(...).Since(mark), would read better.
    5. InCategory is an exact match ([Feature]: Host-wide log capture across all categories via Compono.Logging #164).

      • Filtering by namespace prefix ("anything outside MyApp.Jobs.*") is common in host-level guards, and today it needs a Matching(e => e.Category.StartsWith(...)) predicate.
      • Suggestion: add an InCategoryPrefix or InNamespace helper.
    6. Profiles with constructor arguments in attributes ([Feature]: Runtime fixture values in composition profiles (xUnit class/collection fixtures) #162).

      • RequireFixture removed the connection-string parameter, but a profile that also takes interceptors needs an extra parameterless constructor to be named in [Compose<TProfile>]. The variants that do need interceptors must still be created in code with Composer.Create(...).
      • Suggestion: a way to supply profile constructor arguments from a static member, similar to how ComposeData supplies TConfig, would close that gap.
    7. Documentation: a short "migrating from Microsoft.Extensions.Diagnostics.Testing" page would have shortened this work. It should map AddFakeLogging/FakeLogCollector to LogCollector/AddComponoCapture, and MetricCollector<T> to CapturingMeterFactory/Verify, and it should call out the UseMetrics() ordering.

    We're pinned to the preview until stable 1.4.0 ships. Thanks for turning this around so quickly.

  4. added a commit that references this issue on Nov 12, 2026
  5. ncipollina commented on Nov 12, 2026

    @ncipollina
    ContributorAuthor

    Thanks for the quick turnaround on #181. We adopted 1.4.0-preview.128 in our service's test suite (xUnit v3 JIT, Compono + Logging + Metrics + Options + TestDoubles + XunitV3). Everything from #181 behaved as documented:

    Item Result
    ComponoMetricsOwnsMeterFactory ✅ Evaluates true in every test project, including one that only gets Compono transitively via ProjectReference. Order of UseMetrics() vs UseGeneratedTestDoubles() no longer matters.
    Composed TConfig via builder.Register(() => config) ✅ Removed duplicated row values from our window theory; the composed parameter resolves to the row's own instance.
    xUnit v3 disposes test arguments ✅ Removed all seven using var _ = meterFactory; lines.
    Wrapper profile instead of parameterless ctor ✅ Removed the parameterless constructor (our profile isn't named in an attribute, so no wrapper needed).
    ClearMeasurements() ✅ No change needed.

    Build: 0 warnings, no CMP diagnostics. 231/231 tests passing.

    Remaining findings (preview.128)

    1. Missing UseMetrics() error isn't actionable. Leaving out UseMetrics() produces:

      Compono.CompositionException : No registration, configuration rule, semantic provider, test-double provider, built-in provider, or generated plan could satisfy 'IMeterFactory'.
      

      It's accurate, but since Compono already knows Compono.Metrics owns IMeterFactory (that's what ComponoMetricsOwnsMeterFactory drives), a hint like "IMeterFactory is provided by Compono.Metrics; call UseMetrics()" would save a lookup. The same idea could apply to ILogger → UseLogging().

    2. Reading the row's TConfig back still needs boilerplate. Each profile has to add builder.Register(() => config) by hand, and the test has to declare an extra parameter. An opt-in that exposes the row's TConfig automatically would remove that. This is minor.

    3. Is Share<IMeterFactory>() still required alongside UseMetrics()? We still call both. If UseMetrics() already shares the factory per graph, a note in the docs (or making it do so) would let us drop the extra line.

    4. Failed ComposeData rows collapse the theory count. When composition fails for a row (e.g. the missing UseMetrics() case above), the theory is reported once instead of once per row. Our Application test count went from 49 to 42 in that run. This is harmless but surprising when you compare counts.

    No mismatches between the docs and the behavior beyond the above.

  6. added a commit that references this issue on Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    💡 idea

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions