Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
1b6c09f
fix: dispatch test context lifecycle delegates (#7308)
thomhurst Nov 2, 2026
2ba3c66
fix: preserve class row callbacks and retry scope lifetime (#7308)
thomhurst Nov 2, 2026
daf26b3
fix: preserve row state and isolate class callbacks (#7308)
thomhurst Nov 2, 2026
a0e3e58
fix: isolate factory state between data rows (#7308)
thomhurst Nov 3, 2026
b5f51b3
fix(core): leave scope-owned arguments to their DI scope (#7308)
thomhurst Nov 3, 2026
0139166
fix: balance scope references and preserve cleanup order (#7308)
thomhurst Nov 3, 2026
d8d8af7
fix: dispose DI scopes in dependency graph order (#7308)
thomhurst Nov 3, 2026
993e845
fix: retain DI cleanup for skipped and failed rows (#7308)
thomhurst Nov 3, 2026
c9d5e82
fix: preserve row cleanup ownership and retry cancellation (#7308)
thomhurst Nov 3, 2026
02d1090
fix: keep claimed scope cleanup off enumeration failures (#7308)
thomhurst Nov 3, 2026
0c27ce0
fix: guard class iterator failure cleanup ownership (#7308)
thomhurst Nov 3, 2026
4d8ad3d
fix: isolate class source and constructor factory contexts (#7308)
thomhurst Nov 3, 2026
44e3b81
fix: preserve enumeration state across class factories (#7308)
thomhurst Nov 3, 2026
d7b2518
fix: retain constructor updates and unclaimed cleanup (#7308)
thomhurst Nov 3, 2026
a85e4ba
fix: compare saved class state against immutable baseline (#7308)
thomhurst Nov 3, 2026
b2da25e
fix: replay saved constructor state removals (#7308)
thomhurst Nov 3, 2026
45e85ce
fix: preserve method-enumeration state removals (#7308)
thomhurst Nov 3, 2026
95e05fd
fix: complete property data-source lifecycle dispatch (#7308)
thomhurst Nov 3, 2026
5b38538
Merge main and preserve lifecycle scope cleanup across scheduler path…
thomhurst Nov 3, 2026
f9136c5
fix: preserve row callbacks and synchronize session cleanup (#7308)
thomhurst Nov 3, 2026
009efea
fix: model data-row scope ownership explicitly (#7308)
thomhurst Nov 3, 2026
0017885
fix: retain lazy constructor event sharing for #7308
thomhurst Nov 3, 2026
08df302
fix: retain rejected row cleanup and encapsulate contexts (#7308)
thomhurst Nov 3, 2026
b3435e8
fix: snapshot lifecycle delegate dispatch for #7308
thomhurst Nov 3, 2026
91a17f7
fix: retain rejected method-row cleanup state for #7308
thomhurst Nov 3, 2026
101f074
Merge remote-tracking branch 'origin/main' into issue-7308-events
thomhurst Nov 3, 2026
eafd1f3
fix: allow registration-hold cleanup without a test context (#7308)
thomhurst Nov 3, 2026
2f39ed7
fix: refresh constructor state baseline for refetched rows (#7308)
thomhurst Nov 3, 2026
a454169
fix: isolate empty constructor state snapshots (#7308)
thomhurst Nov 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/docs/execution/retrying.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,7 @@ So the order of precedence is:
1. Method
1. Class
1. Assembly

## Retry event handlers

Handlers subscribed through `TestBuilderContext.Events.OnTestRetry` receive the upcoming, one-based retry number after backoff and cancellation checks. If a handler throws, retry processing stops and the failure propagates. If cancellation was already accepted, the test remains cancelled instead.
14 changes: 14 additions & 0 deletions src/TUnit.Core/AsyncEvent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,20 @@ public class AsyncEvent<TEventArgs>
{
private List<Invocation>? _handlers;

internal AsyncEvent<TEventArgs> Clone() => new()
{
_handlers = _handlers is null ? null : [.. _handlers]
};

internal void AddMissingFrom(AsyncEvent<TEventArgs> source)
{
foreach (var invocation in source.InvocationList)
{
if (_handlers?.Contains(invocation) != true)
(_handlers ??= []).Insert(FindInsertionIndex(invocation.Order), invocation);
}
}

/// <summary>
/// Represents a single invocation of an async event handler.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,9 @@ public abstract class DependencyInjectionDataSourceAttribute<TScope> : UntypedDa
// disposing the returned objects, as it does for any other data source.
var scopeOwnsCreatedObjects = scope is IDisposable or IAsyncDisposable;

// Set up disposal for this specific scope in the current test context
dataGeneratorMetadata.TestBuilderContext.Current.Events.OnDispose += async (_, _) =>
{
if (scope is IAsyncDisposable asyncDisposable)
{
await asyncDisposable.DisposeAsync().ConfigureAwait(false);
}
else if (scope is IDisposable disposable)
{
disposable.Dispose();
}
};
// Register before resolving so a failed factory still releases its scope.
var cleanup = dataGeneratorMetadata.TestBuilderContext.Current.Events.DataRowScopes ??= new();
var owner = cleanup.Register(scope);
Comment thread
thomhurst marked this conversation as resolved.
Resolved

return dataGeneratorMetadata.MembersToGenerate
.Select(m => m switch
Expand All @@ -41,6 +32,7 @@ public abstract class DependencyInjectionDataSourceAttribute<TScope> : UntypedDa
.Select(x =>
{
var created = Create(scope, x);
cleanup.RegisterObject(owner, created);

if (scopeOwnsCreatedObjects)
{
Expand Down
103 changes: 103 additions & 0 deletions src/TUnit.Core/DataRowScopeCollection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
namespace TUnit.Core;

/// <summary>
/// Owns a row's scopes. Object lookup releases each scope at its first resolved object's graph
/// depth; completion releases scopes left by failed factories or untracked values.
/// </summary>
internal sealed class DataRowScopeCollection
{
private readonly List<ScopeOwner> _owners = [];
private readonly Dictionary<object, List<ScopeOwner>> _objects = new(Helpers.ReferenceEqualityComparer.Instance);

internal ScopeOwner Register(object? scope)
{
var owner = new ScopeOwner(scope);
_owners.Add(owner);
return owner;
}

internal void RegisterObject(ScopeOwner owner, object? instance)
{
if (instance is null)
{
return;
}

if (!_objects.TryGetValue(instance, out var owners))
{
_objects.Add(instance, owners = []);
}

if (!owners.Contains(owner))
{
owners.Add(owner);
}
}

internal DataRowScopeCollection Clone()
{
var clone = new DataRowScopeCollection();
clone.AddRange(this);
return clone;
}

internal void AddRange(DataRowScopeCollection scopes)
{
_owners.AddRange(scopes._owners);
foreach (var pair in scopes._objects)
{
foreach (var owner in pair.Value)
{
RegisterObject(owner, pair.Key);
}
}
}

internal ValueTask<List<Exception>?> ReleaseAsync(object instance, List<Exception>? exceptions = null)
=> _objects.TryGetValue(instance, out var owners)
? DisposeAsync(owners, exceptions)
: new(exceptions);

internal ValueTask<List<Exception>?> CompleteAsync(List<Exception>? exceptions = null)
=> DisposeAsync(_owners, exceptions);

private static async ValueTask<List<Exception>?> DisposeAsync(List<ScopeOwner> owners, List<Exception>? exceptions)
{
foreach (var owner in owners)
{
try
{
await owner.DisposeAsync().ConfigureAwait(false);
}
catch (Exception exception)
{
(exceptions ??= []).Add(exception);
}
}

return exceptions;
}

/// <summary>Shared by cloned rows; scope disposal is attempted once, including when it throws.</summary>
internal sealed class ScopeOwner(object? scope)
{
private int _disposed;

internal async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return;
}

if (scope is IAsyncDisposable asyncDisposable)
{
await asyncDisposable.DisposeAsync().ConfigureAwait(false);
}
else if (scope is IDisposable disposable)
{
disposable.Dispose();
}
}
}
}
7 changes: 6 additions & 1 deletion src/TUnit.Core/Interfaces/ITestEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,25 @@ public interface ITestEvents
/// <summary>
/// Gets the event that is raised before the test method is invoked.
/// </summary>
/// <remarks>Handler failures propagate and prevent the test method from running.</remarks>
AsyncEvent<TestContext>? OnTestStart { get; }

/// <summary>
/// Gets the event that is raised after the test method has completed.
/// </summary>
/// <remarks>Handler failures join the teardown exception collection, alongside receiver failures.</remarks>
AsyncEvent<TestContext>? OnTestEnd { get; }

/// <summary>
/// Gets the event that is raised if the test was skipped.
/// </summary>
/// <remarks>Handler failures propagate.</remarks>
AsyncEvent<TestContext>? OnTestSkipped { get; }

/// <summary>
/// Gets the event that is raised before a test is retried.
/// Gets the event raised before a retry, after backoff and cancellation checks.
/// The retry attempt is one-based. A handler failure aborts retry processing;
/// an accepted cancellation is preserved as a cancelled result.
/// </summary>
AsyncEvent<(TestContext TestContext, int RetryAttempt)>? OnTestRetry { get; }
}
24 changes: 24 additions & 0 deletions src/TUnit.Core/TestBuilderContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,30 @@ internal void ShareEventsWith(TestBuilderContext source)
/// </summary>
internal Attribute[]? InitializedAttributes { get; set; }

// Child rows start with isolated state and no event subscriptions. Callers that build an
// executable view can explicitly share the state/events with their factory context instead.
internal TestBuilderContext CreateChild(IDataSourceAttribute? classDataSource, IDataSourceAttribute? dataSource = null, bool shareFactoryContext = false)
{
var child = new TestBuilderContext
{
TestMetadata = TestMetadata,
InitializedAttributes = InitializedAttributes,
ClassConstructor = ClassConstructor,
ClassDataSourceAttribute = classDataSource,
DataSourceAttribute = dataSource
};
if (shareFactoryContext)
{
child.ShareStateBagWith(this);
child.ShareEventsWith(this);
}
else
{
CopyStateBagTo(child);
}
return child;
}

public void RegisterForInitialization(object? obj)
{
Events.OnInitialize += async (sender, args) =>
Expand Down
52 changes: 51 additions & 1 deletion src/TUnit.Core/TestContextEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,65 @@
namespace TUnit.Core;

/// <summary>
/// Test context events container
/// Test context events container. Registration, start and skipped handler failures propagate
/// and stop the remaining handlers. End handler failures are collected with teardown failures.
/// </summary>
public class TestContextEvents : ITestEvents
{
internal TestContextEvents Clone() => new()
{
DataRowScopes = DataRowScopes?.Clone(),
OnDispose = OnDispose?.Clone(),
OnTestRegistered = OnTestRegistered?.Clone(),
OnInitialize = OnInitialize?.Clone(),
OnTestStart = OnTestStart?.Clone(),
OnTestEnd = OnTestEnd?.Clone(),
OnTestSkipped = OnTestSkipped?.Clone(),
OnTestRetry = OnTestRetry?.Clone()
};

private object? _scopeLock;

internal void AddDataRowScopes(DataRowScopeCollection scopes)
{
lock (LazyInitializer.EnsureInitialized(ref _scopeLock)!)
{
(DataRowScopes ??= new()).AddRange(scopes);
}
}

internal DataRowScopeCollection? DetachDataRowScopes()
{
lock (LazyInitializer.EnsureInitialized(ref _scopeLock)!)
{
var scopes = DataRowScopes;
DataRowScopes = null;
return scopes;
}
}

internal void AddCleanupFrom(TestContextEvents source)
{
if (source.DataRowScopes is { } scopes)
AddDataRowScopes(scopes);
if (source.OnDispose is { } onDispose)
(OnDispose ??= new()).AddMissingFrom(onDispose);
}

// Clones share once-only scope owners while keeping row ownership collections isolated.
internal DataRowScopeCollection? DataRowScopes { get; set; }

public AsyncEvent<TestContext>? OnDispose { get; set; }
public AsyncEvent<TestContext>? OnTestRegistered { get; set; }
public AsyncEvent<TestContext>? OnInitialize { get; set; }
// Delegate subscribers run once in the late stage, after early-stage receivers.
public AsyncEvent<TestContext>? OnTestStart { get; set; }
public AsyncEvent<TestContext>? OnTestEnd { get; set; }
public AsyncEvent<TestContext>? OnTestSkipped { get; set; }
/// <summary>
/// Gets or sets handlers invoked before a retry, after backoff and cancellation checks.
/// The retry attempt is one-based. A handler failure aborts retry processing;
/// an accepted cancellation is preserved as a cancelled result.
/// </summary>
public AsyncEvent<(TestContext TestContext, int RetryAttempt)>? OnTestRetry { get; set; }
}
19 changes: 13 additions & 6 deletions src/TUnit.Core/Tracking/ObjectTracker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ internal class ObjectTracker(TrackableObjectGraphProvider trackableObjectGraphPr
// TryRemove guards against racing disposals (e.g. a late UntrackObject call)
if (!s_trackedObjects.TryRemove(kvp.Key, out _) || IsExternallyOwned(kvp.Key))
{
// An object marked after it was counted belongs to its external owner, which disposes it.
continue;
}

Expand Down Expand Up @@ -264,6 +263,11 @@ private static void RemoveObjectsNotIn(SortedList<int, HashSet<object>>? tracked

foreach (var obj in bucket)
{
if (testContext?.InternalEventsIfCreated?.DataRowScopes is { } scopes)
{
cleanupExceptions = await scopes.ReleaseAsync(obj, cleanupExceptions).ConfigureAwait(false);
}

try
{
var task = UntrackObject(obj, testContext);
Expand Down Expand Up @@ -337,8 +341,7 @@ private void TrackObject(object? obj)

private async ValueTask UntrackObject(object? obj, TestContext? testContext)
{
// Every disposable is counted, including externally owned objects. Ownership changes only
// who disposes it, so each test always releases exactly the reference it took.
// Release any count acquired before another source marked the object externally owned.
if (obj is not IDisposable and not IAsyncDisposable)
Comment thread
thomhurst marked this conversation as resolved.
Resolved
Comment thread
thomhurst marked this conversation as resolved.
Resolved
{
return;
Expand Down Expand Up @@ -629,7 +632,7 @@ private static bool Contains(SortedList<int, HashSet<object>>? trackedObjects, o
/// </summary>
private static bool ShouldSkipTracking(object? obj)
{
return obj is not IDisposable and not IAsyncDisposable;
return obj is null || obj is not IDisposable and not IAsyncDisposable;
}

/// <summary>
Expand All @@ -639,15 +642,19 @@ internal static bool IsExternallyOwned(object obj)
=> s_hasExternallyOwned && s_externallyOwned.TryGetValue(obj, out _);

// Objects whose lifetime another owner controls (a dependency injection scope, for example).
// The tracker counts references but leaves disposal to their owner.
// The tracker balances references but never disposes them; their owner controls disposal.
private static readonly ConditionalWeakTable<object, object> s_externallyOwned = new();
private static readonly object s_externallyOwnedMarker = new();

// Ownership cannot live only on a row or counted entry: a container singleton can be
// supplied by another source before or after its DI row, including after its count reaches zero.
// A weak identity mark preserves that ownership without retaining the singleton.
// The flag deliberately stays set: live marks can outlast any individual row or test session.
// Skips the table lookup for every tracked object until something is marked.
private static volatile bool s_hasExternallyOwned;

/// <summary>
/// Marks <paramref name="obj"/> as disposed by another owner, so the tracker counts references without disposing it.
/// Marks <paramref name="obj"/> as disposed by another owner, so the tracker never disposes it.
/// Dependency injection data sources mark the services they resolve, because the scope that created
/// them disposes them when the test ends (#7205). Existing tracker references are released
/// without disposing the object, regardless of which data source supplied it first.
Expand Down
Loading
Loading