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
28 changes: 12 additions & 16 deletions docs/docs/assertions/tasks-and-async.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@ public async Task Task_Completes_Within_Timeout()
}
```

For a `Task<T>`, or a function that returns one, `CompletesWithin` returns the task's result (see [Task Result Assertions](#task-result-assertions)).

Fails if timeout exceeded:

```csharp
Expand Down Expand Up @@ -182,10 +184,10 @@ public async Task API_Call_Completes_In_Time()
{
var apiTask = _httpClient.GetAsync("https://api.example.com/data");

await Assert.That((Func<Task>)(async () => { await apiTask; })).CompletesWithin(TimeSpan.FromSeconds(5));
// For a Task<T>, CompletesWithin returns the task's result
var response = await Assert.That(apiTask).CompletesWithin(TimeSpan.FromSeconds(5));

var response = await apiTask;
await Assert.That(response.IsSuccessStatusCode).IsTrue();
await Assert.That(response!.IsSuccessStatusCode).IsTrue();
}
```

Expand Down Expand Up @@ -241,19 +243,16 @@ public async Task Async_Method_Throws_Exception()

### Task Result Assertions

For `Task<T>`, await the task first, then assert on the result:
For `Task<T>`, `CompletesWithin` returns the task's result, so you can assert on it next:

```csharp
[Test]
public async Task Task_Returns_Expected_Result()
{
var task = GetValueAsync();

// Ensure it completes in time
await Assert.That((Func<Task>)(async () => { await task; })).CompletesWithin(TimeSpan.FromSeconds(1));

// Get the result
var result = await task;
// Ensure it completes in time, and get the result
var result = await Assert.That(task).CompletesWithin(TimeSpan.FromSeconds(1));

// Assert on the result
await Assert.That(result).IsEqualTo(42);
Expand Down Expand Up @@ -362,7 +361,7 @@ public async Task Any_Task_Completes()

var firstCompleted = Task.WhenAny(fastTask, slowTask);

await Assert.That((Func<Task>)(async () => { await firstCompleted; })).CompletesWithin(TimeSpan.FromMilliseconds(500));
await Assert.That(firstCompleted).CompletesWithin(TimeSpan.FromMilliseconds(500));

var completed = await firstCompleted;
await Assert.That(completed).IsSameReferenceAs(fastTask);
Expand Down Expand Up @@ -398,8 +397,7 @@ public async Task Chained_Task_Assertions()
{
var task = GetDataAsync();

await Assert.That((Func<Task>)(async () => { await task; }))
.CompletesWithin(TimeSpan.FromSeconds(5));
await Assert.That(task).CompletesWithin(TimeSpan.FromSeconds(5));

await Assert.That(task)
.IsCompleted()
Expand Down Expand Up @@ -427,8 +425,7 @@ public async Task Retry_Eventually_Succeeds()
return "Success";
}, maxRetries: 5);

await Assert.That((Func<Task>)(async () => { await task; })).CompletesWithin(TimeSpan.FromSeconds(10));
var result = await task;
var result = await Assert.That(task).CompletesWithin(TimeSpan.FromSeconds(10));
await Assert.That(result).IsEqualTo("Success");
}
```
Expand All @@ -447,8 +444,7 @@ public async Task Debounced_Operation()

trigger.OnNext("value");

await Assert.That((Func<Task>)(async () => { await debouncedTask; }))
.CompletesWithin(TimeSpan.FromSeconds(1));
await Assert.That(debouncedTask).CompletesWithin(TimeSpan.FromSeconds(1));
}
```

Expand Down
127 changes: 100 additions & 27 deletions src/TUnit.Assertions/Conditions/CompletesWithinAssertion.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
using System.Diagnostics;
using System.Text;
using TUnit.Assertions.Core;

namespace TUnit.Assertions.Conditions;

/// <summary>
/// Asserts that an action completes execution within the specified time limit.
/// Supports cancellation to avoid waiting for slow operations.
/// Stops waiting at the limit; the action itself is not canceled.
/// </summary>
public class CompletesWithinActionAssertion : Assertion<object?>
{
Expand All @@ -27,35 +26,31 @@ public CompletesWithinActionAssertion(

protected override async Task<AssertionResult> CheckAsync(EvaluationMetadata<object?> metadata)
{
var value = metadata.Value;
var exception = metadata.Exception;

var stopwatch = Stopwatch.StartNew();
using var cts = new CancellationTokenSource(_timeout);
using var cts = new CancellationTokenSource();
var delay = Task.Delay(_timeout, cts.Token); // before the action, so an invalid timeout does not start it

try
{
var task = Task.Run(() => _action());
var completedTask = await Task.WhenAny(task, Task.Delay(_timeout, cts.Token));
var completedTask = await Task.WhenAny(task, delay);

if (completedTask != task)
{
return AssertionResult.Failed("it took too long to complete");
}

await task; // Await to get any exceptions
stopwatch.Stop();

return AssertionResult.Passed;
}
catch (OperationCanceledException)
{
return AssertionResult.Failed("it took too long to complete");
}
catch (Exception ex)
{
return AssertionResult.Failed($"threw {ex.GetType().FullName}: {ex.Message}", ex);
}
finally
{
cts.Cancel(); // stops the delay's timer when the work finished first or threw
}
}

protected override string GetExpectation() =>
Expand All @@ -64,7 +59,7 @@ protected override string GetExpectation() =>

/// <summary>
/// Asserts that an async function completes execution within the specified time limit.
/// Supports cancellation to avoid waiting for slow operations.
/// Stops waiting at the limit; the function's task is not canceled.
/// </summary>
public class CompletesWithinAsyncAssertion : Assertion<object?>
{
Expand All @@ -85,37 +80,115 @@ public CompletesWithinAsyncAssertion(

protected override async Task<AssertionResult> CheckAsync(EvaluationMetadata<object?> metadata)
{
var value = metadata.Value;
var exception = metadata.Exception;

var stopwatch = Stopwatch.StartNew();
using var cts = new CancellationTokenSource(_timeout);
using var cts = new CancellationTokenSource();
var delay = Task.Delay(_timeout, cts.Token); // before the task, so an invalid timeout does not start it

try
{
var task = _asyncAction();
var completedTask = await Task.WhenAny(task, Task.Delay(_timeout, cts.Token));

if (completedTask != task)
if (await CompletesWithinTimeout.HasTimedOutAsync(task, delay, _timeout))
{
return AssertionResult.Failed("it took too long to complete");
// A task that faulted while it ran past the limit gives its exception, so it is not left unobserved
return AssertionResult.Failed("it took too long to complete", task.Exception?.InnerException);
}

await task; // Await to get any exceptions
stopwatch.Stop();

return AssertionResult.Passed;
}
catch (OperationCanceledException)
{
return AssertionResult.Failed("it took too long to complete");
}
catch (Exception ex)
{
return AssertionResult.Failed($"threw {ex.GetType().FullName}: {ex.Message}", ex);
}
finally
{
cts.Cancel(); // stops the delay's timer when the work finished first or threw
}
}

protected override string GetExpectation() =>
$"action to complete within {_timeout.TotalMilliseconds:F0} milliseconds";
}

/// <summary>
/// Asserts that an async function or a task completes within the specified time limit,
/// and returns its result when awaited.
/// </summary>
/// <typeparam name="TValue">The type of the result</typeparam>
public class CompletesWithinAsyncAssertion<TValue> : Assertion<TValue>
{
private readonly TimeSpan _timeout;

internal CompletesWithinAsyncAssertion(
Func<Task<TValue?>> asyncFunc,
TimeSpan timeout,
StringBuilder expressionBuilder)
: base(CreateContext(asyncFunc ?? throw new ArgumentNullException(nameof(asyncFunc)), timeout, expressionBuilder))
{
_timeout = timeout;
}

protected override Task<AssertionResult> CheckAsync(EvaluationMetadata<TValue> metadata) =>
Task.FromResult(metadata.Exception switch
{
null => AssertionResult.Passed,
CompletesWithinTimeoutException timedOut => AssertionResult.Failed("it took too long to complete", timedOut.InnerException),
var ex => AssertionResult.Failed($"threw {ex.GetType().FullName}: {ex.Message}", ex),
});

protected override string GetExpectation() =>
$"action to complete within {_timeout.TotalMilliseconds:F0} milliseconds";

private static AssertionContext<TValue> CreateContext(
Func<Task<TValue?>> asyncFunc,
TimeSpan timeout,
StringBuilder expressionBuilder) =>
new(new EvaluationContext<TValue>(() => EvaluateWithinAsync(asyncFunc, timeout)), expressionBuilder);

private static async Task<(TValue?, Exception?)> EvaluateWithinAsync(Func<Task<TValue?>> asyncFunc, TimeSpan timeout)
{
using var cts = new CancellationTokenSource();
var delay = Task.Delay(timeout, cts.Token); // before the task, so an invalid timeout does not start it

try
{
var task = asyncFunc();

return await CompletesWithinTimeout.HasTimedOutAsync(task, delay, timeout)
? (default, new CompletesWithinTimeoutException(timeout, task.Exception?.InnerException))
: (await task, null);
}
catch (Exception ex)
{
return (default, ex);
}
finally
{
cts.Cancel(); // stops the delay's timer when the task finished first or threw
}
}
}

internal static class CompletesWithinTimeout
{
/// <summary>
/// Whether <paramref name="task"/> missed the limit that <paramref name="delay"/> measures.
/// A function that blocks past the limit before it returns its task has timed out too.
/// <see cref="Task.Delay(TimeSpan, CancellationToken)"/> truncates the limit to whole milliseconds,
/// so a limit under a millisecond (zero included) is over at once: it still passes a task that is
/// already complete when the function returns it, and fails a pending one.
/// </summary>
internal static async Task<bool> HasTimedOutAsync(Task task, Task delay, TimeSpan timeout)
{
var limitIsUnderAMillisecond = (long)timeout.TotalMilliseconds == 0;
return (!limitIsUnderAMillisecond && delay.IsCompleted) || (await Task.WhenAny(task, delay)) != task;
}
}

/// <summary>
/// Marks a timeout in the evaluation of <see cref="CompletesWithinAsyncAssertion{TValue}"/>, with the exception
/// of a task that faulted while it ran past the limit. Internal, so no awaited task can throw it.
/// </summary>
internal sealed class CompletesWithinTimeoutException(TimeSpan timeout, Exception? innerException)
: TimeoutException($"did not complete within {timeout.TotalMilliseconds:F0} milliseconds", innerException);
50 changes: 48 additions & 2 deletions src/TUnit.Assertions/Extensions/AssertionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1679,7 +1679,8 @@ public static CompletesWithinActionAssertion CompletesWithin(
var action = GetActionFromDelegate(source);
var assertionSource = (IAssertionSource<object?>)source;
assertionSource.Context.ExpressionBuilder.Append($".CompletesWithin({expression})");
return new CompletesWithinActionAssertion(action, timeout);
return new CompletesWithinActionAssertion(action, timeout,
new AssertionContext<object?>((object?)null, assertionSource.Context.ExpressionBuilder));
}

/// <summary>
Expand All @@ -1694,7 +1695,52 @@ public static CompletesWithinAsyncAssertion CompletesWithin(
var asyncAction = GetFuncFromAsyncDelegate(source);
var assertionSource = (IAssertionSource<object?>)source;
assertionSource.Context.ExpressionBuilder.Append($".CompletesWithin({expression})");
return new CompletesWithinAsyncAssertion(asyncAction, timeout);
return new CompletesWithinAsyncAssertion(asyncAction, timeout,
new AssertionContext<object?>((object?)null, assertionSource.Context.ExpressionBuilder));
}

/// <summary>
/// Asserts that an asynchronous function completes execution within the specified timeout, and returns its result.
/// If the function takes longer than the timeout, the assertion fails.
/// Example: var reply = await Assert.That(() => GetReplyAsync()).CompletesWithin(TimeSpan.FromSeconds(5));
/// </summary>
public static CompletesWithinAsyncAssertion<TValue> CompletesWithin<TValue>(
this AsyncFuncAssertion<TValue> source,
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
Comment thread
JohnVerheij marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
TimeSpan timeout,
[CallerArgumentExpression(nameof(timeout))] string? expression = null)
{
source.Context.ExpressionBuilder.Append($".CompletesWithin({expression})");
return new CompletesWithinAsyncAssertion<TValue>(source.AsyncFunc, timeout, source.Context.ExpressionBuilder);
}

/// <summary>
/// Asserts that an asynchronous function returning a collection completes execution within the specified timeout,
/// and returns the collection.
/// If the function takes longer than the timeout, the assertion fails.
/// Example: var items = await Assert.That(async () => await GetItemsAsync()).CompletesWithin(TimeSpan.FromSeconds(5));
/// </summary>
public static CompletesWithinAsyncAssertion<IEnumerable<TItem>> CompletesWithin<TItem>(
this AsyncFuncCollectionAssertion<TItem> source,
TimeSpan timeout,
[CallerArgumentExpression(nameof(timeout))] string? expression = null)
{
source.Context.ExpressionBuilder.Append($".CompletesWithin({expression})");
return new CompletesWithinAsyncAssertion<IEnumerable<TItem>>(source.AsyncFunc, timeout, source.Context.ExpressionBuilder);
}

/// <summary>
/// Asserts that a task completes within the specified timeout, and returns its result.
/// If the task takes longer than the timeout, the assertion fails.
/// Example: var reply = await Assert.That(replyTask).CompletesWithin(TimeSpan.FromSeconds(5));
/// </summary>
public static CompletesWithinAsyncAssertion<TValue> CompletesWithin<TValue>(
this TaskAssertion<TValue> source,
TimeSpan timeout,
[CallerArgumentExpression(nameof(timeout))] string? expression = null)
{
source.Context.ExpressionBuilder.Append($".CompletesWithin({expression})");
var task = source.SourceTask;
return new CompletesWithinAsyncAssertion<TValue>(() => task, timeout, source.Context.ExpressionBuilder);
}

/// <summary>
Expand Down
2 changes: 2 additions & 0 deletions src/TUnit.Assertions/Sources/AsyncFuncAssertion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@ namespace TUnit.Assertions.Sources;
public class AsyncFuncAssertion<TValue> : IAssertionSource<TValue>, IDelegateAssertionSource<TValue>
{
public AssertionContext<TValue> Context { get; }
internal Func<Task<TValue?>> AsyncFunc { get; }

public AsyncFuncAssertion(Func<Task<TValue?>> func, string? expression)
{
AsyncFunc = func;
var expressionBuilder = AssertionExpressionBuilder.Create(expression);
var evaluationContext = new EvaluationContext<TValue>(async () =>
{
Expand Down
3 changes: 3 additions & 0 deletions src/TUnit.Assertions/Sources/AsyncFuncCollectionAssertion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@ namespace TUnit.Assertions.Sources;
/// </summary>
public class AsyncFuncCollectionAssertion<TItem> : CollectionAssertionBase<IEnumerable<TItem>, TItem>, IDelegateAssertionSource<IEnumerable<TItem>>
{
internal Func<Task<IEnumerable<TItem>?>> AsyncFunc { get; }

public AsyncFuncCollectionAssertion(Func<Task<IEnumerable<TItem>?>> func, string? expression)
: base(CreateContext(func, expression))
{
AsyncFunc = func;
}

private static AssertionContext<IEnumerable<TItem>> CreateContext(Func<Task<IEnumerable<TItem>?>> func, string? expression)
Expand Down
2 changes: 2 additions & 0 deletions src/TUnit.Assertions/Sources/TaskAssertion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ public class TaskAssertion<TValue> : IAssertionSource<TValue>, IDelegateAssertio
AssertionContext<Task<TValue?>> IAssertionSource<Task<TValue?>>.Context => TaskContext;

private AssertionContext<Task<TValue?>> TaskContext { get; }
internal Task<TValue?> SourceTask { get; }

public TaskAssertion(Task<TValue?> task, string? expression)
{
SourceTask = task;
var expressionBuilder = AssertionExpressionBuilder.Create(expression);

// Context for result assertions (e.g., IsEqualTo on the TValue result)
Expand Down
Loading
Loading