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
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.
8 changes: 7 additions & 1 deletion src/TUnit.Core/Interfaces/ITestEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public interface ITestEvents
/// <summary>
/// Gets the event that is raised when the test has been registered with the test runner.
/// </summary>
/// <remarks>Handler failures propagate and stop registration.</remarks>
AsyncEvent<TestContext>? OnTestRegistered { get; }

/// <summary>
Expand All @@ -39,20 +40,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; }
}
9 changes: 8 additions & 1 deletion src/TUnit.Core/TestContextEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
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
{
Expand Down Expand Up @@ -80,8 +81,14 @@ internal DataRowScopeCollection? DataRowScopes
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; }
}
45 changes: 36 additions & 9 deletions src/TUnit.Engine/Services/EventReceiverOrchestrator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ public ValueTask InvokeTestStartEventReceiversAsync(TestContext context, Cancell
}
#endif
// Fast path - no allocation if no receivers
if (!_registry.HasTestStartReceivers())
if (!_registry.HasTestStartReceivers() && (stage == EventReceiverStage.Early || context.InternalEventsIfCreated?.OnTestStart is null))
{
return ValueTask.CompletedTask;
}
Expand Down Expand Up @@ -196,6 +196,14 @@ private async ValueTask InvokeTestStartEventReceiversCore(TestContext context, C
await receiver.OnTestStart(context);
}
#endif
// Delegate events have no stage; dispatch once, with the default (late) receivers.
if (stage != EventReceiverStage.Early && context.InternalEventsIfCreated?.OnTestStart is { } onStart)
{
foreach (var handler in onStart.InvocationList)
{
await handler.InvokeAsync(context, context);
}
}
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
Expand All @@ -207,15 +215,15 @@ public ValueTask<IReadOnlyList<Exception>> InvokeTestEndEventReceiversAsync(Test
return new ValueTask<IReadOnlyList<Exception>>([]);
}
#endif
if (!_registry.HasTestEndReceivers())
if (!_registry.HasTestEndReceivers() && (stage == EventReceiverStage.Early || context.InternalEventsIfCreated?.OnTestEnd is null))
{
return new ValueTask<IReadOnlyList<Exception>>([]);
}
#if NET
if (stage.HasValue)
{
var receivers = context.GetTestEndReceivers(stage.Value);
if (receivers.Length == 0)
if (receivers.Length == 0 && (stage == EventReceiverStage.Early || context.InternalEventsIfCreated?.OnTestEnd is null))
{
return new ValueTask<IReadOnlyList<Exception>>([]);
}
Expand All @@ -225,7 +233,7 @@ public ValueTask<IReadOnlyList<Exception>> InvokeTestEndEventReceiversAsync(Test
var earlyReceivers = context.GetTestEndReceivers(EventReceiverStage.Early);
var lateReceivers = context.GetTestEndReceivers(EventReceiverStage.Late);

if (earlyReceivers.Length == 0 && lateReceivers.Length == 0)
if (earlyReceivers.Length == 0 && lateReceivers.Length == 0 && context.InternalEventsIfCreated?.OnTestEnd is null)
{
return new ValueTask<IReadOnlyList<Exception>>([]);
}
Expand Down Expand Up @@ -309,13 +317,29 @@ private async ValueTask<IReadOnlyList<Exception>> InvokeTestEndEventReceiversCor
}
#endif

if (stage != EventReceiverStage.Early && context.InternalEventsIfCreated?.OnTestEnd is { } onEnd)
{
foreach (var handler in onEnd.InvocationList)
{
try
{
await handler.InvokeAsync(context, context);
}
catch (Exception ex)
{
await _logger.LogErrorAsync($"Error in test end event handler: {ex.Message}");
(exceptions ??= []).Add(ex);
}
}
}

return exceptions == null ? Array.Empty<Exception>() : exceptions;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ValueTask InvokeTestSkippedEventReceiversAsync(TestContext context, CancellationToken cancellationToken)
{
if (!_registry.HasTestSkippedReceivers())
if (!_registry.HasTestSkippedReceivers() && context.InternalEventsIfCreated?.OnTestSkipped is null)
{
return ValueTask.CompletedTask;
}
Expand All @@ -328,14 +352,17 @@ private async ValueTask InvokeTestSkippedEventReceiversCore(TestContext context,
// Use pre-computed receivers (already filtered, sorted, and scoped-attribute filtered)
var receivers = context.GetTestSkippedReceivers();

if (receivers.Length == 0)
foreach (var receiver in receivers)
{
return;
await receiver.OnTestSkipped(context);
}

foreach (var receiver in receivers)
if (context.InternalEventsIfCreated?.OnTestSkipped is { } onSkipped)
{
await receiver.OnTestSkipped(context);
foreach (var handler in onSkipped.InvocationList)
{
await handler.InvokeAsync(context, context);
}
}
}

Expand Down
27 changes: 27 additions & 0 deletions src/TUnit.Engine/Services/TestExecution/RetryHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,33 @@ public static async Task ExecuteWithRetry(TestContext testContext, Func<ValueTas
return;
}

if (testContext.InternalEventsIfCreated?.OnTestRetry is { } onRetry)
{
try
{
foreach (var handler in onRetry.InvocationList)
{
await handler.InvokeAsync(testContext, (testContext, attempt + 1)).ConfigureAwait(false);
}
}
catch
{
if (testContext.CompleteTestCancellation())
{
SetCancelledResult(testContext);
return;
}

throw;
}
}
Comment thread
thomhurst marked this conversation as resolved.
Resolved
Comment thread
thomhurst marked this conversation as resolved.
Resolved

if (testContext.IsTestCancellationRequested)
{
SetCancelledResult(testContext);
return;
}

continue;
}

Expand Down
27 changes: 27 additions & 0 deletions src/TUnit.Engine/Services/TestFilterService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,28 @@ private async Task RegisterTest(AbstractExecutableTest test, bool isForExecution
await InvokeTestRegisteredReceivers(registeredReceivers, registeredContext, invokedReceivers).ConfigureAwait(false);
}

HashSet<AsyncEvent<TestContext>.Invocation>? invokedDelegates = null;
await InvokeRegistrationDelegatesAsync().ConfigureAwait(false);

async Task InvokeRegistrationDelegatesAsync()
{
if (test.Context.InternalEventsIfCreated?.OnTestRegistered is not { } onRegistered)
{
return;
}

// Snapshot because a handler can subscribe another handler while it runs.
// Invocation identity preserves duplicate subscriptions while skipping the earlier pass.
foreach (var handler in onRegistered.InvocationList)
{
invokedDelegates ??= [];
if (invokedDelegates.Add(handler))
{
await handler.InvokeAsync(test.Context, test.Context).ConfigureAwait(false);
}
}
}

// If the test was marked as skipped by an event receiver, skip argument registration entirely.
// This avoids initializing expensive shared data sources (e.g., WebApplicationFactory)
// for tests that will never execute.
Expand Down Expand Up @@ -191,6 +213,11 @@ private async Task RegisterTest(AbstractExecutableTest test, bool isForExecution

await InvokeTestRegisteredReceivers(test.Context.GetTestRegisteredReceivers(), registeredContext, invokedReceivers).ConfigureAwait(false);
}

if (argumentsRegistered)
{
await InvokeRegistrationDelegatesAsync().ConfigureAwait(false);
}
}

// Clear the cached display name after registration events
Expand Down
115 changes: 115 additions & 0 deletions tests/TUnit.TestProject/DelegateLifecycleEventTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
using TUnit.TestProject.Attributes;

namespace TUnit.TestProject;

public class DelegateLifecycleEventTests
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public sealed class SubscribeAttribute : DataSourceGeneratorAttribute<int>
{
public int Rows { get; set; } = 1;

protected override IEnumerable<Func<int>> GenerateDataSources(DataGeneratorMetadata metadata)
{
for (var i = 0; i < Rows; i++)
{
yield return () =>
{
metadata.TestBuilderContext.Current.StateBag["factoryState"] = "preserved";
var events = metadata.TestBuilderContext.Current.Events;
events.OnTestRegistered += Record("registered");
events.OnTestStart += Record("start");
events.OnTestEnd += Record("end");
events.OnTestSkipped += Record("skipped");
events.OnTestRetry += (_, args) =>
{
args.TestContext.StateBag.Items["retry"] = args.RetryAttempt;
return default;
};
return 1;
};
}
}

private static Func<object, TestContext, ValueTask> Record(string name) => (_, context) =>
{
context.StateBag.Items.TryGetValue(name, out var count);
context.StateBag.Items[name] = (count as int? ?? 0) + 1;
return default;
};
}

[Test, Subscribe, EngineTest(ExpectedResult.Pass)]
public async Task Passing(int value)
{
await Assert.That(TestContext.Current!.StateBag.Items["registered"]).IsEqualTo(1);
await Assert.That(TestContext.Current.StateBag.Items["start"]).IsEqualTo(1);
}

[Test, Subscribe, EngineTest(ExpectedResult.Pass)]
public async Task Generic<T>(T value)
{
await Assert.That(TestContext.Current!.StateBag.Items["registered"]).IsEqualTo(1);
await Assert.That(TestContext.Current.StateBag.Items["start"]).IsEqualTo(1);
}

[Test, Subscribe, Retry(1), EngineTest(ExpectedResult.Pass)]
public async Task Retried(int value)
{
var context = TestContext.Current!;
if (!context.StateBag.Items.ContainsKey("retry"))
{
throw new InvalidOperationException("Exercise retry notification");
}

await Assert.That(context.StateBag.Items["retry"]).IsEqualTo(1);
await Assert.That(context.StateBag.Items["start"]).IsEqualTo(2);
await Assert.That(context.StateBag.Items["end"]).IsEqualTo(1);
}

[Test, Subscribe, Skip("Exercise skipped notification")]
public void Skipped(int value) => throw new InvalidOperationException("Must not execute");

[After(Class)]
public static async Task Verify(ClassHookContext context)
{
foreach (var test in context.Tests)
{
await Assert.That(test.StateBag.Items["registered"]).IsEqualTo(1);
if (test.Metadata.TestDetails.MethodName == nameof(Skipped))
{
await Assert.That(test.StateBag.Items["skipped"]).IsEqualTo(1);
await Assert.That(test.StateBag.Items["end"]).IsEqualTo(1);
await Assert.That(test.StateBag.Items.ContainsKey("start")).IsFalse();
}
else
{
var expected = test.Metadata.TestDetails.MethodName == nameof(Retried) ? 2 : 1;
await Assert.That(test.StateBag.Items["end"]).IsEqualTo(expected);
}
}
}
}

[DelegateLifecycleEventTests.Subscribe(Rows = 2)]
public class ClassDelegateLifecycleEventTests(int value)
{
[Test, Repeat(1), EngineTest(ExpectedResult.Pass)]
public async Task FirstRow()
{
await Assert.That(value).IsEqualTo(1);
await Assert.That(TestContext.Current!.StateBag.Items["factoryState"]).IsEqualTo("preserved");
await Assert.That(TestContext.Current!.StateBag.Items["registered"]).IsEqualTo(1);
await Assert.That(TestContext.Current.StateBag.Items["start"]).IsEqualTo(1);
}

[After(Class)]
public static async Task Verify(ClassHookContext context)
{
foreach (var test in context.Tests)
{
await Assert.That(test.StateBag.Items["end"]).IsEqualTo(1);
}
}
}

Loading
Loading