Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
56 changes: 41 additions & 15 deletions src/TUnit.Core/AsyncEvent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,31 @@ namespace TUnit.Core;
/// </example>
public class AsyncEvent<TEventArgs>
{
// Published lists are immutable snapshots; readers and clones need no monitor.
private List<Invocation>? _handlers;
private object? _handlerLock;

internal AsyncEvent<TEventArgs> Clone() => new()
{
_handlers = Volatile.Read(ref _handlers)
};

internal void AddMissingFrom(AsyncEvent<TEventArgs> source)
{
var sourceHandlers = source.InvocationList;
lock (LazyInitializer.EnsureInitialized(ref _handlerLock)!)
{
var handlers = _handlers is null ? [] : new List<Invocation>(_handlers);
foreach (var invocation in sourceHandlers)
{
// Clones share Invocation identities. Separate subscriptions, even of the same
// delegate, remain distinct and must both run.
if (!handlers.Contains(invocation))
handlers.Insert(FindInsertionIndex(handlers, invocation.Order), invocation);
}
Volatile.Write(ref _handlers, handlers);
}
}

/// <summary>
/// Represents a single invocation of an async event handler.
Expand Down Expand Up @@ -92,8 +116,12 @@ public void Add(Func<object, TEventArgs, ValueTask> callback, int order = int.Ma
}

var invocation = new Invocation(callback, order);
var insertIndex = FindInsertionIndex(order);
(_handlers ??= []).Insert(insertIndex, invocation);
lock (LazyInitializer.EnsureInitialized(ref _handlerLock)!)
{
var handlers = _handlers is null ? [] : new List<Invocation>(_handlers);
handlers.Insert(FindInsertionIndex(handlers, order), invocation);
Volatile.Write(ref _handlers, handlers);
}
}

/// <summary>
Expand All @@ -115,9 +143,13 @@ public void AddAt(Func<object, TEventArgs, ValueTask> callback, int index, int o
}

var invocation = new Invocation(callback, order);
var handlers = _handlers ??= [];
var clampedIndex = index < 0 ? 0 : (index > handlers.Count ? handlers.Count : index);
handlers.Insert(clampedIndex, invocation);
lock (LazyInitializer.EnsureInitialized(ref _handlerLock)!)
{
var handlers = _handlers is null ? [] : new List<Invocation>(_handlers);
var clampedIndex = index < 0 ? 0 : (index > handlers.Count ? handlers.Count : index);
handlers.Insert(clampedIndex, invocation);
Volatile.Write(ref _handlers, handlers);
}
}

/// <summary>
Expand All @@ -131,13 +163,7 @@ public IReadOnlyList<Invocation> InvocationList
{
get
{
if (_handlers == null)
{
return [];
}

return _handlers;

return Volatile.Read(ref _handlers) is { } handlers ? handlers : [];
}
}

Expand Down Expand Up @@ -180,13 +206,13 @@ public AsyncEvent<TEventArgs> InsertAtFront(Func<object, TEventArgs, ValueTask>
return e;
}

private int FindInsertionIndex(int order)
private static int FindInsertionIndex(List<Invocation> handlers, int order)
{
int left = 0, right = (_handlers ??= []).Count;
int left = 0, right = handlers.Count;
while (left < right)
{
var mid = left + (right - left) / 2;
if (_handlers[mid].Order <= order)
if (handlers[mid].Order <= order)
left = mid + 1;
else
right = mid;
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.GetOrCreateDataRowScopes();
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
121 changes: 121 additions & 0 deletions src/TUnit.Core/DataRowScopeCollection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
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 object _lock = new();
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);
lock (_lock)
_owners.Add(owner);
return owner;
}

// A scope resolving several objects is released at the first object's graph depth;
// subsequent releases share the same once-only owner.
internal void RegisterObject(ScopeOwner owner, object? instance)
{
if (instance is null)
{
return;
}

lock (_lock)
{
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)
{
// Snapshot the source before locking the destination to avoid lock-order inversions.
ScopeOwner[] owners;
KeyValuePair<object, ScopeOwner[]>[] objects;
lock (scopes._lock)
{
owners = scopes._owners.ToArray();
objects = scopes._objects.Select(pair =>
new KeyValuePair<object, ScopeOwner[]>(pair.Key, pair.Value.ToArray())).ToArray();
}
lock (_lock)
{
_owners.AddRange(owners);
foreach (var pair in objects)
foreach (var owner in pair.Value)
RegisterObject(owner, pair.Key);
}
}

internal ValueTask<List<Exception>?> ReleaseAsync(object instance, List<Exception>? exceptions = null)
{
ScopeOwner[] owners;
lock (_lock)
owners = _objects.TryGetValue(instance, out var registered) ? registered.ToArray() : [];
return DisposeAsync(owners, exceptions);
}

internal ValueTask<List<Exception>?> CompleteAsync(List<Exception>? exceptions = null)
{
ScopeOwner[] owners;
lock (_lock)
owners = _owners.ToArray();
return DisposeAsync(owners, exceptions);
}

private static async ValueTask<List<Exception>?> DisposeAsync(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();
}
}
}
}
12 changes: 12 additions & 0 deletions src/TUnit.Core/Models/TestSessionContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,18 @@ internal static void DeferOnDisposeToSessionEnd(TestContextEvents? events)
{
lock (s_deferredOnDisposeLock)
{
// Preserve session ownership for discovery rows now that DI cleanup is stored separately.
if (events?.DetachDataRowScopes() is { } scopes)
{
events.OnDispose += async (_, _) =>
{
if (await scopes.CompleteAsync().ConfigureAwait(false) is { Count: > 0 } errors)
{
throw new AggregateException("Errors occurred while disposing discovery scopes", errors);
}
};
}

if (events is not { OnDispose: { } onDispose })
{
return;
Expand Down
14 changes: 8 additions & 6 deletions src/TUnit.Core/StaticPropertyReflectionInitializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,13 +99,8 @@ private async ValueTask ReleaseAsync()
var onDispose = TestSessionContext.TakeStaticOnDispose(context);
_context = null;
_error = null;
if (onDispose is null)
{
return;
}

var exceptions = new List<Exception>();
foreach (var invocation in onDispose.InvocationList)
foreach (var invocation in onDispose?.InvocationList ?? [])
{
try
{
Expand All @@ -117,6 +112,13 @@ private async ValueTask ReleaseAsync()
}
}

// The private initialization context owns DI scopes independently of OnDispose.
// Drain even after failed initialization or a throwing callback.
if (context.EventsIfCreated?.DetachDataRowScopes() is { } scopes)
{
await scopes.CompleteAsync(exceptions).ConfigureAwait(false);
}

if (exceptions.Count > 0)
{
throw new AggregateException("Errors occurred while disposing reflection static properties", exceptions);
Expand Down
26 changes: 25 additions & 1 deletion src/TUnit.Core/TestBuilderContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public TestContextEvents Events
{
// A sharing context resolves the source's container on every read rather than caching it, so a
// later assignment to the source's Events reaches this context too.
get => _events ?? _eventsSource?.Events ?? (_events = new TestContextEvents());
get => _events ?? _eventsSource?.Events ?? LazyInitializer.EnsureInitialized(ref _events)!;
set
{
_eventsSource = null;
Expand Down 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
Loading
Loading