Repository navigation
v0.14.0
·
43 commits
to main
since this release
Immutable
release. Only release title and notes can be modified.
[0.14.0] - 2026-11-06: one log capture, a wait with diagnostics, failure dumps, and a tee that respects the test's lifetime
Minor release with breaking changes. LogCollectorBuilder.Create() returns a LogCapture; WillLog(...) waits for background work and fails with the standard diagnostics; an opt-in assembly attribute lets the package see each test's end, which enables a dump of the captured records when a test does not pass and keeps the test-output tee out of finished tests. Also: a rate-limit terminator, a log contract renderer, a teed factory that keeps nothing, and a fix for records with custom state.
BREAKING
LogCollectorBuilder.Create(LogLevel)andTestOutputLogCollectorBuilder.CreateTeed(LogLevel)return aLogCaptureinstead of a(Factory, Collector)tuple, sovar (factory, collector) = LogCollectorBuilder.Create();and.Factorymember access no longer compile (.Collectorstill does), and code compiled against 0.13 must be recompiled. The deconstruction fails with a build error that names the new form. Migration:using var logs = LogCollectorBuilder.Create();, then uselogsas theILoggerFactoryandlogs.Collectorfor assertions.LogCaptureis alsoIAsyncDisposable, so in async code writeawait using var logs = ...; analyzers such as Roslynator RCS1261 and Meziantou MA0042 report a plainusingor an explicitDispose()call there.FakeLoggingBuilderExtensions.AddTeedFakeLogginglost itsILoggerProvider? teeProviderparameter, including calls that pass it by name. Passing a new provider there raised CA2000 at every call site, and the logging factory never disposed it. Migration: chain the provider,.AddTeedFakeLogging(collector, level).AddProvider(provider); for TUnit's correlated console output,.AddFakeLogging(collector, level).AddCorrelatedTUnit(level)fromTUnit.Logging.Microsoft.HasLogged()counts that admit zero (Never(),AtMost(n),Exactly(0),Between(0, n), and theHasLoggedAtMost(n)/HasLoggedExactly(0)/HasLoggedBetween(0, n)shorthands) fail as vacuous when every level the chain targets sits below the collector's capture floor, asHasNotLogged()already did. Such an assertion used to pass because nothing at those levels was captured. Migration: assert at a captured level, or lower the floor (LogCollectorBuilder.Create(minimumLevel)).- The built-in test-output tee (
CreateTeed,AddTeedFakeLogging) no longer writes a record that no running test claims into a test that has ended; the record is skipped and counted (see Changed). This changes test output only, not assertion outcomes.
Added
LogCapture(core): the logger factory and itsFakeLogCollectorin one disposable object. It implementsILoggerFactory(pass it wherever a factory is expected) andIAsyncDisposable; disposing it disposes the factory and its providers, including one added withAddProvider, and the collector keeps its records. Disposal does not stop capture: a logger created before keeps writing into the collector.- Its
Deconstructexists only to turn the 0.13 tuple form into a build error that names the new form; it is hidden from IntelliSense, cannot be called, and is removed in a later minor version.
- Its
LogCollectorBuilder.Create(TimeProvider timeProvider, LogLevel minimumLevel = LogLevel.Trace)andTestOutputLogCollectorBuilder.CreateTeed(TimeProvider timeProvider, LogLevel minimumLevel = LogLevel.Trace): the collector stamps each record withtimeProvider's time, soAtMostOncePerand the times in a failure dump follow a fake clock. Without a clock, timestamps come from the system clock, as before. A project that runs Meziantou MA0166 / MA0167 now gets a diagnostic at each call without a clock: pass the fake clock in scope, elseTimeProvider.System.[assembly: LogAssertions.TUnit.LogAssertionsTestLifetime]: an opt-in attribute, applied once per test project, that receives TUnit's start (before the[Before(Test)]hooks) and end (after the[After(Test)]hooks) of every test, once per attempt of a retried test. TUnit offers no public way for code inside a test to observe its end. The attribute enablesDumpToTestOutputOnFailure()and makes the tee's routing exact. All its state is static and keyed weakly by the test'sTestContext. Without it, the first built-in tee built in a test run writes one note to that test's output, naming the line to add.Assert.That(collector).WillLog(TimeSpan timeout, CancellationToken cancellationToken = default)(WillLogAssertion): the event-driven form ofHasLogged(), built onWaitForLogsAsync.- It waits on the collector's stream of records, with no polling and no real-time delay. The count is read from the collector right after the minimum number of matching records has been captured; records captured by then count, including ones logged before the assertion ran, and a record that arrives after the assertion has passed isn't checked.
- It fails when that count exceeds the maximum, and at once when the chain's levels all sit below the capture floor.
- When the
timeoutor the token ends the wait, it fails with the expectation, the count, and the captured records, not a bare cancellation. Thetimeoutis required and real time, whatever the collector's clock, and starts when the assertion runs, not when the chain is built. - Terminators:
Once(),Exactly(n),AtLeast(n),Between(min, max)with counts of at least 1, plusGetMatch()andGetMatches(), which run the assertion; insideAssert.Multiple(), after a failed wait they throwInvalidOperationExceptionnaming the failure. There is noNever()orAtMost(n), since a wait cannot prove absence.
HasLogged()...AtMostOncePer(TimeSpan interval): every gap between consecutive matching records, ordered byFakeLogRecord.Timestamp(the collector's clock), must be at leastinterval: two records exactlyintervalapart pass, one tick less fails. The failure names the first pair that was too close, with timestamps, the gap, and the number of short gaps. It constrains spacing only:HasLogged()still needs at least one match unless a count that admits zero is set, in either order.FakeLogCollector.DumpToTestOutputOnFailure()andDumpToTestOutputOnFailure(DumpVerbosity), called in a test or a[Before(Test)]hook (needs the lifetime attribute):- When the test ends without passing (failed, timed out, or canceled; not skipped), every record captured since the call is written to its output, with its timestamp (UTC, from the collector's clock). A test that passes writes nothing.
- The start point is the collector's latest record at the call, not a clock reading, so it is right with a fake clock; if the collector is cleared, every record is written.
- A retried test arms again in each attempt, and the heading names the attempt.
- Without the attribute it throws
InvalidOperationExceptionwith the line to add.
TestOutputLogCollectorBuilder.CreateTeedDiscarding(LogLevel minimumLevel = LogLevel.Trace): an enabledILoggerFactorythat keeps no records and tees every record to the test report, for fixtures and long-lived hosts whose logs nobody asserts on.LogContractRenderer.Render(IEnumerable<LogDefinition>)(core,LogAssertions.Render): one deterministic line per definition, for example1201 OrderProcessed Information "Order {OrderId} processed in {DurationMs} ms" OrderId,DurationMs.- Placeholder names are in template order. Lines are ordered by event ID, then name, template, and level, and end in LF, with no header.
- Templates are escaped to stay on one line.
- Composed with
MatchesSnapshot(), the log contract becomes a reviewed baseline.
Changed
- The built-in test-output tee picks the test for each record when it is logged:
- the test current at the log call;
- otherwise the test current when the tee was built, while that test runs;
- otherwise no test.
With the lifetime attribute a test counts as running until its[After(Test)]hooks finish, and a record on the flow of a test that has ended is not teed either. Without the attribute the fallback ends when the owning test has a result. Records that reach no test are counted, and disposing the factory writes the count to the test current then. The tee is now registered so that the logging container disposes it.
- Failure messages of every assertion (
HasLogged(),HasNotLogged(),HasLoggedSequence(),HasLoggedOnly(),WillLog()) show the last 50 captured records, after one line(N earlier record(s) not shown)when there are more. A long run's collector can hold thousands of records. The explicit dumps (DumpTo,DumpToTestOutput,DumpToTestOutputOnFailure) still write every record. TUnit.AssertionsandTUnit.Coreminimum versions raised from 1.77.0 to 1.80.0.- README and XML docs (all three READMEs):
- Setup and upgrade: a Setup section for the lifetime attribute and an upgrade table for 0.14.0.
- Background work: uses
WillLoginstead of polling withEventually, with a recipe for background work on a fake clock (start the assertion, advance the clock, then await it). - Clocks: each member that reads time says which clock: record timestamps come from the collector's clock, and
WillLog's timeout is real time. - Shared hosts: a table of where each record goes. A background loop keeps the context of the test that started it, so build and start a shared host inside
ExecutionContext.SuppressFlow(): TUnit runs hooks such as[Before(Class)]and shared-fixture initialization on the flow of the first test that needs them. - Private
[LoggerMessage]methods: matched byWithEventId/WithEventName, without making theminternal. - Corrected claims:
- disposing the factory does not stop capture;
AssertAllAsyncneedsusing LogAssertions.TUnit;, and with exactly one failure rethrows that exception as is;- an empty sequence step is a no-op;
WithScopePropertiestakes anIReadOnlyDictionary;WithProperty(key, null)also matches a record without that key;- the failure-message sample now shows the real format;
- the
AddTeedFakeLoggingremarks describe per-call routing, not a binding at configuration time.
- Other test frameworks: adapters for them are not planned.
Fixed
WithProperty,WithProperty<T>, andWithMessageTemplate(on the chains and onLogFilter),Matching(LogDefinition)/MatchingCall, andLogDefinition.CapturethrewInvalidCastExceptionon a record whose state is not a key/value list (a customTStatepassed toILogger.Log). A single such record made every property assertion on the collector throw. Such a record now has no properties and no template, and a custom-state call can be captured as a definition.HasLogged().GetMatch()andGetMatches()insideAssert.Multiple()after a failed assertion:GetMatches()returned an empty list andGetMatch()threwArgumentOutOfRangeException. Both now throwInvalidOperationException, whose message names the failure, and the scope still reports the original failure.