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
21 changes: 21 additions & 0 deletions Docs/pages/docs/04-time-system/02-auto-advance.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,27 @@ Both methods throw a `TimeoutException` that describes the busy timers when they

Idle refers to the timers only, including those of the `TimeProvider` from `ToTimeProvider()`. `Task.Delay`, `Thread.Sleep` and `PeriodicTimer` of the `MockTimeSystem` move or wait for the clock on the calling thread and are not tracked. Neither is a callback that continues after it waited for the clock, nor the work that the callbacks start elsewhere, e.g. the continuations of a completed delay on the thread pool.

## Strict timer order

By default, the clock moves on when a callback blocked for one second of real time, as the callback might wait for something that only a later timer delivers, and it waits at most one second for the creator of a timer to finish setting it up, e.g. for `Task.Delay` on the `TimeProvider` to register its cancellation. On a loaded machine, both can let a later timer fire before an earlier one completed. When your tests depend on the order of the timers, e.g. a timeout that must cancel a delay before the delay completes, enable a strict timer order via `MockTimeSystemOptions.EnableStrictTimerOrder()`:

```csharp
MockTimeSystem timeSystem = new(o => o.EnableStrictTimerOrder());
TimeProvider timeProvider = timeSystem.ToTimeProvider();
DateTime start = timeSystem.DateTime.UtcNow;
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(10), timeProvider);

await That(() => Task.Delay(TimeSpan.FromSeconds(30), timeProvider, cts.Token))
.Throws<TaskCanceledException>();
await That(timeSystem.DateTime.UtcNow - start).IsEqualTo(TimeSpan.FromSeconds(10));
```

With a strict timer order, the thread that moves the clock waits for each callback until it completes or waits for the clock through the `MockTimeSystem`, e.g. with `ITimerMock.Wait`. The timers that move the clock on their own and `AdvanceToNextTimer` also wait up to the timeout, instead of one second, for the creator of a timer to set it up, and then move on like the real clock, e.g. for a `Task.Delay` on the `TimeProvider` with the token of a disposed `CancellationTokenSource`, which never registers. Another thread that moves the clock at the same time, e.g. `AdvanceBy` in the test while the timers advance the clock on their own, can still move it past a running callback. A time change callback (`On.TimeChanged`) that moves the clock again holds the clock while it does, so a timer callback that reads the clock in the meantime cannot complete and fails the strict timer order.

:::warning[A callback that waits for another timer]
A callback that blocks on something that only the clock can deliver, e.g. an event that another timer of the same `MockTimeSystem` sets, can never complete with a strict timer order. After the timeout (5 seconds by default, `EnableStrictTimerOrder(callbackTimeout)`), the scheduler fails with a `TimeoutException` that names the due time of the timer: the code that moves the clock throws it, and so does every later move of the clock and every `WaitUntilIdle`. When the timers move the clock on their own, nothing else reports the failure, and awaiting a timer, e.g. a delay on the `TimeProvider`, never completes, so wait with `WaitUntilIdle` to see it. Let such a callback wait through the `MockTimeSystem` instead, e.g. with `ITimerMock.Wait`.
:::

## Multi-threaded scenarios

All threads share one simulated clock, so two parallel `Sleep(5s)` calls move it by **10 seconds total**, which can be surprising. If your test exercises real parallelism, swap in the [thread-aware provider](./07-thread-aware-provider.mdx) so each async context has its own clock.
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,10 @@ internal static ArgumentOutOfRangeException TimerArgumentOutOfRange(
internal static TimeoutException TimerCallbackTimeout(int timeout)
=> new($"The callback of the next timer did not complete in {timeout}ms.");

internal static TimeoutException StrictTimerCallbackTimeout(string dueTime, TimeSpan timeout)
=> new(
$"The callback of the timer due at {dueTime} did not complete in {timeout} while the clock waited for it with a strict timer order. It probably waits for something that only the clock can deliver, e.g. another timer of the same MockTimeSystem, which cannot happen while the clock waits for the callback.");

internal static TimeoutException TimersNotIdle(int timeout, string busyTimers)
=> new($"The timers did not become idle in {timeout}ms: {busyTimers}.");

Expand Down
64 changes: 63 additions & 1 deletion Source/Testably.Abstractions.Testing/MockTimeSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public MockTimeSystem(ITimeProviderFactory timeProvider, Func<MockTimeSystemOpti
scheduler?.OnTimeChanged();
_callbackHandler.InvokeTimeChanged(now);
});
scheduler = new TimerScheduler(TimeProvider);
scheduler = new TimerScheduler(TimeProvider, initialization.StrictCallbackTimeout);
(TimeProvider as TimeProviderMock)?.UseScheduler(scheduler);
Scheduler = scheduler;
_dateTimeMock = new DateTimeMock(this, _callbackHandler);
Expand Down Expand Up @@ -182,6 +182,12 @@ public class MockTimeSystemOptions
/// </summary>
internal bool AutoAdvance { get; private set; } = true;

/// <summary>
/// How long the clock waits for a blocked timer callback with a strict timer order, or <see langword="null" />
/// without it.
/// </summary>
internal TimeSpan? StrictCallbackTimeout { get; private set; }

/// <summary>
/// Disables automatic advancement of the time when waiting for timers, tasks or threads to complete.
/// </summary>
Expand All @@ -190,5 +196,61 @@ public MockTimeSystemOptions DisableAutoAdvance()
AutoAdvance = false;
return this;
}

/// <summary>
/// Lets the thread that moves the clock wait for each timer callback until it completes, so that the timers
/// fire in the order of their due time also on a loaded machine. The clock waits for a blocked callback at most
/// 5 seconds.
/// </summary>
/// <remarks>
/// Enable it when your tests depend on the order of the timers, e.g. a timeout that must cancel a delay before
/// the delay completes, and fail only on a loaded machine, like a busy CI runner.
/// <para />
/// By default, the clock moves on when a callback blocked for one second of real time, as it may wait for the
/// clock. With a strict timer order, the clock waits until the callback completes or waits for the clock
/// through the <see cref="MockTimeSystem" />. When that takes longer than the timeout, the scheduler fails: the
/// code that moves the clock throws a <see cref="TimeoutException" />, and so does every later move of the clock
/// and every wait for idle timers. Another thread that moves the clock at the same time can still move it past
/// a running callback. The timers that move the clock on their own also wait up to the timeout, instead of one
/// second, for the creator of a timer to set it up, e.g. for a delay to register its cancellation, and then
/// move on, like the real clock does.
/// </remarks>
public MockTimeSystemOptions EnableStrictTimerOrder()
=> EnableStrictTimerOrder(TimeSpan.FromSeconds(5));

/// <summary>
/// Lets the thread that moves the clock wait for each timer callback until it completes, so that the timers
/// fire in the order of their due time also on a loaded machine. The clock waits for a blocked callback at most
/// the <paramref name="callbackTimeout" />.
/// </summary>
/// <remarks>
/// Enable it when your tests depend on the order of the timers, e.g. a timeout that must cancel a delay before
/// the delay completes, and fail only on a loaded machine, like a busy CI runner.
/// <para />
/// By default, the clock moves on when a callback blocked for one second of real time, as it may wait for the
/// clock. With a strict timer order, the clock waits until the callback completes or waits for the clock
/// through the <see cref="MockTimeSystem" />. When that takes longer than the
/// <paramref name="callbackTimeout" />, the scheduler fails: the code that moves the clock throws a
/// <see cref="TimeoutException" />, and so does every later move of the clock and every wait for idle timers.
/// Another thread that moves the clock at the same time can still move it past a running callback. The timers
/// that move the clock on their own also wait up to the <paramref name="callbackTimeout" />, instead of one
/// second, for the creator of a timer to set it up, e.g. for a delay to register its cancellation, and then
/// move on, like the real clock does.
/// </remarks>
/// <param name="callbackTimeout">
/// How long the clock waits for a blocked callback, or <see cref="System.Threading.Timeout.InfiniteTimeSpan" />
/// to wait forever.
/// </param>
public MockTimeSystemOptions EnableStrictTimerOrder(TimeSpan callbackTimeout)
{
if ((callbackTimeout <= TimeSpan.Zero && callbackTimeout != System.Threading.Timeout.InfiniteTimeSpan) ||
callbackTimeout.TotalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(callbackTimeout));
}

StrictCallbackTimeout = callbackTimeout;
return this;
}
}
}
10 changes: 7 additions & 3 deletions Source/Testably.Abstractions.Testing/TimeSystem/ITimerHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ public interface ITimerHandler
/// Throws a <see cref="TimeoutException" /> when the timeout is expired.
/// </param>
/// <returns><see langword="false" />, when no timer is scheduled, otherwise <see langword="true" />.</returns>
/// <exception cref="TimeoutException">When the callback does not complete within the <paramref name="timeout" />.</exception>
/// <exception cref="TimeoutException">
/// When the callback does not complete within the <paramref name="timeout" />, or when the scheduler failed with a
/// strict timer order. With a strict timer order, an expired <paramref name="timeout" /> fails the scheduler, so
/// that every later move of the clock throws as well.
/// </exception>
bool AdvanceToNextTimer(int timeout = 10000);

/// <summary>
Expand All @@ -51,7 +55,7 @@ public interface ITimerHandler
/// </param>
/// <exception cref="TimeoutException">
/// When the timers do not become idle within the <paramref name="timeout" />. The message describes what keeps
/// them busy.
/// them busy. Also when the scheduler failed with a strict timer order.
/// </exception>
void WaitUntilIdle(int timeout = 10000);

Expand All @@ -75,7 +79,7 @@ public interface ITimerHandler
/// <param name="cancellationToken">A token to cancel the wait.</param>
/// <exception cref="TimeoutException">
/// When the timers do not become idle within the <paramref name="timeout" />. The message describes what keeps
/// them busy.
/// them busy. Also when the scheduler failed with a strict timer order.
/// </exception>
Task WaitUntilIdleAsync(int timeout = 10000, CancellationToken cancellationToken = default);
}
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,9 @@ public bool AdvanceToNextTimer(int timeout = 10000)
public void WaitUntilIdle(int timeout = 10000)
{
ThrowIfTimeoutIsInvalid(timeout);
if (!_mockTimeSystem.Scheduler.WhenIdle().Wait(timeout))
bool isIdle = _mockTimeSystem.Scheduler.WhenIdle().Wait(timeout);
_mockTimeSystem.Scheduler.ThrowIfFailed();
if (!isIdle)
{
throw ExceptionFactory.TimersNotIdle(timeout, _mockTimeSystem.Scheduler.DescribeBusyTimers());
}
Expand All @@ -123,6 +125,7 @@ private async Task WaitUntilIdleCoreAsync(int timeout, CancellationToken cancell
Task idle = _mockTimeSystem.Scheduler.WhenIdle();
if (idle.IsCompleted)
{
_mockTimeSystem.Scheduler.ThrowIfFailed();
return;
}

Expand All @@ -134,6 +137,7 @@ private async Task WaitUntilIdleCoreAsync(int timeout, CancellationToken cancell
Task finished = await Task.WhenAny(idleOnThreadPool, Task.Delay(timeout, delayCancellation.Token))
.ConfigureAwait(false);
delayCancellation.Cancel();
_mockTimeSystem.Scheduler.ThrowIfFailed();
if (finished != idleOnThreadPool)
{
cancellationToken.ThrowIfCancellationRequested();
Expand Down
Loading
Loading