using System.Diagnostics;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Tests.Support;
namespace Febe.Tests.Server;
///
/// The clock of the end-to-end tests (): waits that overlap must not add up. With a clock that
/// adds them up, the background loops of the server used up the time limits of the real browser and the few minutes of
/// the first session in a moment, and the files of the end-to-end test came only after the next one («Tempo scaduto: tre
/// file di marta.prova scaricati»). The bounds follow the real time measured around, so a loaded runner does not fail them.
///
[TestClass]
public sealed class ScaledClockTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task OverlappingWaitsPassTheSameTime()
{
const double factor = 100;
var clock = new ScaledClock(factor);
var real = Stopwatch.StartNew();
var before = clock.Now;
await Task.WhenAll(Enumerable.Range(0, 10).Select(_ => clock.Delay(TimeSpan.FromSeconds(30), TestContext.CancellationToken)));
var passed = clock.Now - before;
Assert.IsGreaterThanOrEqualTo(TimeSpan.FromSeconds(30), passed, "every wait lasted its whole time");
Assert.IsLessThanOrEqualTo(real.Elapsed * factor, passed, "ten waits together pass the time of one, not of ten");
}
[TestMethod]
public async Task AWaitForThePageIsNotCutShortByTheLongWaitOfAnotherLoop()
{
// The wait of the recipes for the data of a page, as they do it, while another loop's long wait ends in the middle.
const double factor = 20;
var clock = new ScaledClock(factor);
var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), clock);
var other = clock.Delay(TimeSpan.FromSeconds(60), TestContext.CancellationToken);
await clock.Delay(TimeSpan.FromSeconds(50), TestContext.CancellationToken);
var real = Stopwatch.StartNew();
await capture.WaitAsync(capture.Mark(), _ => false, TimeSpan.FromSeconds(20), TimeSpan.FromMilliseconds(100), TestContext.CancellationToken);
Assert.IsGreaterThanOrEqualTo(TimeSpan.FromSeconds(20 / factor) - TimeSpan.FromMilliseconds(50), real.Elapsed, "the page had its whole time");
await other;
}
[TestMethod]
public async Task AWaitEndsWhenItIsCancelled()
{
var clock = new ScaledClock(10);
using var cancel = new CancellationTokenSource();
var wait = clock.Delay(TimeSpan.FromHours(1), cancel.Token);
await cancel.CancelAsync();
await Assert.ThrowsAsync(() => wait);
await Assert.ThrowsAsync(() => clock.Delay(TimeSpan.Zero, cancel.Token));
}
}