using System.Diagnostics;
using Febe.Core.Export;
using Febe.Tests.Desktop.Support;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Febe.Tests.Desktop;
///
/// The automatic export in the composition (tappa E5, D8): the worker runs only in a normal start (never with a
/// configuration problem; the demo never starts it), runs its start-up round at once, and the stop ends it first.
///
[TestClass]
public sealed class AutoExportCompositionTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheWorkerRunsInANormalStartAndTheStopEndsIt()
{
var ct = TestContext.CancellationToken;
AutoExportWorker worker;
bool? runningWhenTheInterfaceStops = null;
await using (var bed = await DesktopTestBed.StartAsync())
{
Assert.IsEmpty(bed.App.Problems);
Assert.IsTrue(bed.App.AutoExportStarted);
worker = bed.App.Web.Services.GetRequiredService();
var seen = worker;
bed.App.Web.Services.GetRequiredService().ApplicationStopping.Register(() => runningWhenTheInterfaceStops = seen.Running);
var watch = Stopwatch.StartNew();
while ((await worker.StatusAsync(ct)).LastRound is null)
{
Assert.IsLessThan(TimeSpan.FromSeconds(30), watch.Elapsed, "the start-up round did not run");
await Task.Delay(20, ct);
}
var status = await worker.StatusAsync(ct);
Assert.IsTrue(status.Running);
Assert.IsFalse(status.AnyAutomatic, "«Automatica» is off by default");
Assert.AreEqual(status.LastRound + TimeSpan.FromHours(1), status.NextRound);
}
Assert.IsFalse(worker.Running, "the stop ends the worker");
Assert.IsFalse(runningWhenTheInterfaceStops ?? true, "the worker is stopped first, before the interface and the engine");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task WithAStartupProblemTheWorkerDoesNotRun()
{
await using var bed = await DesktopTestBed.StartAsync(shell: new FakeDesktopShell { RuntimeVersion = null });
Assert.IsNotEmpty(bed.App.Problems);
Assert.IsFalse(bed.App.AutoExportStarted, "the composition does not start it");
var worker = bed.App.Web.Services.GetRequiredService();
Assert.IsFalse(worker.Running);
Assert.IsNull((await worker.StatusAsync(TestContext.CancellationToken)).LastRound);
}
}