using System.Diagnostics; using Febe.Core.Abstractions; namespace Febe.Tests.Support; /// /// A clock that runs times faster than the real one: is a function of the real /// time alone, and waits that fraction of the requested time. For whole compositions, where many /// background loops wait at the same time: their waits overlap as they do in reality, so none of them moves the time /// of the others. (A clock that adds every wait to counts overlapping waits more than once: the time /// then jumps, and a 30-second limit on a real browser may end at once.) Measured with the monotonic timer, so a /// correction of the system time does not move it. /// internal sealed class ScaledClock(double factor, TimeZoneInfo? zone = null) : IClock { private readonly DateTimeOffset _start = DateTimeOffset.UtcNow; private readonly long _startStamp = Stopwatch.GetTimestamp(); public double Factor { get; } = factor >= 1 ? factor : throw new ArgumentOutOfRangeException(nameof(factor)); public TimeZoneInfo LocalZone { get; } = zone ?? TimeZoneInfo.Utc; public DateTimeOffset Now => _start + (Stopwatch.GetElapsedTime(_startStamp) * Factor); public async Task Delay(TimeSpan time, CancellationToken ct) { ct.ThrowIfCancellationRequested(); var target = Now + time; for (var left = time; left > TimeSpan.Zero; left = target - Now) { // Task.Delay counts whole milliseconds and may end a moment early: never less than one, then look again. var real = left / Factor; await Task.Delay(real > TimeSpan.FromMilliseconds(1) ? real : TimeSpan.FromMilliseconds(1), ct).ConfigureAwait(false); } } }