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
2 changes: 1 addition & 1 deletion Docs/pages/docs/04-time-system/01-configuring-time.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ ITimeProviderFactory factory = new GalleryClockFactory(...);
MockTimeSystem timeSystem = new(factory);
```

`ITimeProviderFactory` receives a callback that your provider must invoke whenever the simulated time changes; the [notifications](./06-notifications.mdx) and waiting timers depend on it.
`ITimeProviderFactory` receives a callback that your provider must invoke whenever the simulated time changes; the [notifications](./06-notifications.mdx) and waiting timers depend on it. `timeSystem.TimeProvider` returns your provider itself. When you move its clock directly, the timers that became due fire afterward, as the clock is already past them. The waits of the `MockTimeSystem`, e.g. `Task.Delay` or `Thread.Sleep`, still fire them in [order](./02-auto-advance.mdx).

## Sharing the time system

Expand Down
22 changes: 22 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 @@ -15,6 +15,27 @@ await That(timeSystem.DateTime.UtcNow)
.IsEqualTo(new DateTime(2026, 1, 1, 0, 10, 0, DateTimeKind.Utc));
```

## Timers and timeouts

A timer moves the clock to its due time as well. The timers that are due on the way fire in the order of their due time, and each callback sees the clock at its own due time, not at the end of the wait. Like a real timer, a callback runs on another thread with the execution context of the code that created the timer, while the thread that moves the clock waits until it completes. When the callback waits for the clock, i.e. for `Task.Delay`, `PeriodicTimer.WaitForNextTickAsync` or `ITimerMock.Wait` of the `MockTimeSystem`, the clock moves on at once, just like the real clock keeps running. When it blocks on anything else, e.g. on another timer through an event or on a lock that the waiting code holds, the clock moves on after one second of real time. All timers move the clock on one shared background thread. Another thread that moves the clock at the same time, e.g. a `Task.Delay` or `AdvanceBy` in the test, can move it further while a callback runs.

A timer without a period whose state is a `CancellationTokenSource` is a timeout. This includes the timer of `new CancellationTokenSource(TimeSpan, TimeProvider)` on the [`TimeProvider`](./01-configuring-time.mdx) from `ToTimeProvider()`, a `Timer.New` that cancels the `CancellationTokenSource` it gets as state, and the timer of `Task.WaitAsync(TimeSpan, TimeProvider)`. A timeout never moves the clock on its own: it fires when a wait or `AdvanceBy` moves the clock past its due time, so that an operation with a timeout is not canceled before it starts. A one-shot timer that does other work should therefore not get a `CancellationTokenSource` as state.

```csharp
MockTimeSystem timeSystem = new();
TimeProvider timeProvider = timeSystem.ToTimeProvider();
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(1), timeProvider);

// Throws an OperationCanceledException, with the clock one second later
await Task.Delay(TimeSpan.FromSeconds(5), timeProvider, cts.Token);
```

A wait that its timeout cancels on the way stops the clock at the timeout. This applies to `Task.Delay` and `PeriodicTimer.WaitForNextTickAsync` of the `MockTimeSystem` and to `Task.Delay` on the `TimeProvider`.

:::warning[Waiting only for a timeout]
As a timeout never moves the clock, code that waits for nothing but a timeout, e.g. `Task.Delay(Timeout.InfiniteTimeSpan, timeProvider, cts.Token)`, waits until something else moves the clock. Only `Task.Delay(Timeout.InfiniteTimeSpan)` of the `MockTimeSystem` itself returns immediately with auto-advance.
:::

## Disabling auto-advance

When you need to assert *that* code waited (instead of just letting it through), turn auto-advance off via `MockTimeSystemOptions.DisableAutoAdvance()` and move the clock yourself with `TimeProvider.AdvanceBy(...)` or `TimeProvider.SetTo(...)`:
Expand All @@ -37,6 +58,7 @@ With auto-advance off:
| `Task.Delay` | Stays pending until the clock reaches the end of the delay |
| `PeriodicTimer.WaitForNextTickAsync` | Stays pending until the clock reaches the next tick |
| `Thread.Sleep` | Returns immediately without moving the clock |
| `Timer` | Fires when `AdvanceBy` reaches its due time; `AdvanceBy` waits for it |

:::warning[Awaiting a delay with auto-advance off]
Awaiting `Task.Delay` before anything advances the clock waits forever. Start the delay, advance the clock (or let another task do it), then await it.
Expand Down
15 changes: 14 additions & 1 deletion Source/Testably.Abstractions.Testing/MockTimeSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ public INotificationHandler On
/// </summary>
public ITimerHandler TimerHandler => _timerFactoryMock;

/// <summary>
/// The schedule of the timers, which moves the <see cref="TimeProvider" /> from one due time to the next.
/// </summary>
internal TimerScheduler Scheduler { get; }

private readonly NotificationHandler _callbackHandler;
private readonly DateTimeMock _dateTimeMock;
private readonly DateTimeOffsetMock _dateTimeOffsetMock;
Expand Down Expand Up @@ -94,7 +99,15 @@ public MockTimeSystem(ITimeProviderFactory timeProvider, Func<MockTimeSystemOpti
initialization = options(initialization);

_callbackHandler = new NotificationHandler(this);
TimeProvider = timeProvider.Create(_callbackHandler.InvokeTimeChanged);
TimerScheduler? scheduler = null;
TimeProvider = timeProvider.Create(now =>
{
scheduler?.OnTimeChanged();
_callbackHandler.InvokeTimeChanged(now);
});
scheduler = new TimerScheduler(TimeProvider);
(TimeProvider as TimeProviderMock)?.UseScheduler(scheduler);
Scheduler = scheduler;
_dateTimeMock = new DateTimeMock(this, _callbackHandler);
_dateTimeOffsetMock = new DateTimeOffsetMock(this, _callbackHandler);
_timeZoneInfoMock = new TimeZoneInfoMock(this);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,12 @@ public void Dispose()
{
if (_autoAdvance)
{
_timeSystem.TimeProvider.AdvanceBy(TimeSpan.FromTicks(nextTime - now));
if (!_timeSystem.Scheduler.AdvanceTo(nextTime,
_ => cancellationToken.IsCancellationRequested))
{
throw ExceptionFactory.TaskWasCanceled();
}

_lastTime = nextTime;
}
else
Expand All @@ -84,6 +89,7 @@ public void Dispose()
.TimeChanged(predicate: _ => _timeSystem.TimeProvider.ElapsedTicks >= nextTime);
if (_timeSystem.TimeProvider.ElapsedTicks < nextTime)
{
TimerScheduler.ReleaseClock();
await onTimeChanged.WaitAsync(
timeout: Timeout.InfiniteTimeSpan,
cancellationToken: cancellationToken).ConfigureAwait(false);
Expand Down
10 changes: 7 additions & 3 deletions Source/Testably.Abstractions.Testing/TimeSystem/TaskMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,17 @@ public Task Delay(TimeSpan delay, CancellationToken cancellationToken)

if (cancellationToken.IsCancellationRequested)
{
throw ExceptionFactory.TaskWasCanceled();
return Task.FromCanceled(cancellationToken);
}

if (_autoAdvance)
{
_mockTimeSystem.TimeProvider.AdvanceBy(delay);
bool isCompleted = delay < TimeSpan.Zero ||
_mockTimeSystem.Scheduler.AdvanceBy(delay,
_ => cancellationToken.IsCancellationRequested);

_callbackHandler.InvokeTaskDelayCallbacks(delay);
return Task.CompletedTask;
return isCompleted ? Task.CompletedTask : Task.FromCanceled(cancellationToken);
}

_callbackHandler.InvokeTaskDelayCallbacks(delay);
Expand Down Expand Up @@ -88,6 +91,7 @@ private async Task DelayUntilAdvanced(TimeSpan delay, CancellationToken cancella
{
bool isInfinite = delay.TotalMilliseconds < 0;
long targetTicks = _mockTimeSystem.TimeProvider.ElapsedTicks + delay.Ticks;
TimerScheduler.ReleaseClock();

while (true)
{
Expand Down
4 changes: 2 additions & 2 deletions Source/Testably.Abstractions.Testing/TimeSystem/ThreadMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ public void Sleep(TimeSpan timeout)
throw ExceptionFactory.ThreadSleepOutOfRange(nameof(timeout));
}

if (_autoAdvance)
if (_autoAdvance && timeout >= TimeSpan.Zero)
{
_mockTimeSystem.TimeProvider.AdvanceBy(timeout);
_mockTimeSystem.Scheduler.AdvanceBy(timeout, null);
}

Thread.Yield();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ internal sealed class TimeProviderMock : ITimeProvider
private long _elapsedTicks;
private readonly Action<DateTime> _onTimeChanged;
private readonly string _description;
private TimerScheduler? _scheduler;
private Dictionary<string, TimeZoneInfo>? _timeZones;
private bool _systemTimeZonesSeeded;
private TimeZoneInfo _localTimeZone;
Expand Down Expand Up @@ -106,6 +107,12 @@ public long ElapsedTicks
/// <inheritdoc cref="ITimeProvider.AdvanceBy(TimeSpan)" />
public void AdvanceBy(TimeSpan interval)
{
if (_scheduler is { IsMovingClock: false, } scheduler)
{
scheduler.AdvanceBy(interval);
return;
}

lock (_lock)
{
_now = _now.Add(interval);
Expand Down Expand Up @@ -162,6 +169,12 @@ public void RegisterTimeZone(TimeZoneInfo timeZone)
/// <inheritdoc cref="ITimeProvider.SetTo(DateTime)" />
public void SetTo(DateTime value)
{
if (_scheduler is { IsMovingClock: false, } scheduler)
{
scheduler.SetTo(value);
return;
}

lock (_lock)
{
_now = NormalizeToUtc(value, _localTimeZone);
Expand All @@ -171,6 +184,13 @@ public void SetTo(DateTime value)

#endregion

/// <summary>
/// Moves the clock through the <paramref name="scheduler" />, so that the timers fire in the order of their due
/// time, while the clock is at their due time.
/// </summary>
internal void UseScheduler(TimerScheduler scheduler)
=> _scheduler = scheduler;

/// <summary>
/// Returns the time zone registry, allocating and seeding it on first use.
/// </summary>
Expand Down
36 changes: 18 additions & 18 deletions Source/Testably.Abstractions.Testing/TimeSystem/TimerFactoryMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,34 +38,34 @@ public ITimeSystem TimeSystem

/// <inheritdoc cref="ITimerFactory.New(TimerCallback)" />
public ITimer New(TimerCallback callback)
{
TimerMock timerMock = new(_mockTimeSystem, _timerStrategy,
callback, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan, _autoAdvance);
return RegisterTimerMock(timerMock);
}
=> New(callback, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);

/// <inheritdoc cref="ITimerFactory.New(TimerCallback, object?, int, int)" />
public ITimer New(TimerCallback callback, object? state, int dueTime, int period)
{
TimerMock timerMock = new(_mockTimeSystem, _timerStrategy,
callback, state, TimeSpan.FromMilliseconds(dueTime), TimeSpan.FromMilliseconds(period), _autoAdvance);
return RegisterTimerMock(timerMock);
}
=> New(callback, state, TimeSpan.FromMilliseconds(dueTime), TimeSpan.FromMilliseconds(period));

/// <inheritdoc cref="ITimerFactory.New(TimerCallback, object?, long, long)" />
public ITimer New(TimerCallback callback, object? state, long dueTime, long period)
{
TimerMock timerMock = new(_mockTimeSystem, _timerStrategy,
callback, state, TimeSpan.FromMilliseconds(dueTime), TimeSpan.FromMilliseconds(period), _autoAdvance);
return RegisterTimerMock(timerMock);
}
=> New(callback, state, TimeSpan.FromMilliseconds(dueTime), TimeSpan.FromMilliseconds(period));

/// <inheritdoc cref="ITimerFactory.New(TimerCallback, object?, TimeSpan, TimeSpan)" />
/// <remarks>
/// The clock does not move on its own while the timer is created, so that its creator can finish setting it up,
/// e.g. store it to dispose it on a cancellation, before any timer fires.
/// </remarks>
public ITimer New(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
{
TimerMock timerMock = new(_mockTimeSystem, _timerStrategy,
callback, state, dueTime, period, _autoAdvance);
return RegisterTimerMock(timerMock);
_mockTimeSystem.Scheduler.BeginCreatingTimer();
try
{
TimerMock timerMock = new(_mockTimeSystem, _timerStrategy,
callback, state, dueTime, period, _autoAdvance);
return RegisterTimerMock(timerMock);
}
finally
{
_mockTimeSystem.Scheduler.EndCreatingTimer();
}
}

/// <inheritdoc cref="ITimerFactory.Wrap(Timer)" />
Expand Down
Loading
Loading