using System.Globalization;
using System.Net;
using System.Text;
using System.Text.Json;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Tests.Web.Part2Support;
using Febe.Tests.Web.Support;
using Febe.Web;
using Febe.Web.Api;
using Febe.Web.Connection;
using Febe.Web.Engine;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
///
/// «Esporta il rapporto di diagnostica» in Attività (issue #39, spec §7.9): a JSON attachment named after the local day,
/// never cached, with the traces of the recorder and what is missing from them; empty without one; answered also when
/// a configuration problem keeps the engine off (empty: nothing ran).
///
[TestClass]
public sealed class DiagnosticReportApiTests
{
[TestMethod]
public async Task TheReportIsAJsonAttachmentOfTheLocalDayNeverCached()
{
var source = new FixedDiagnostics();
await using var server = await Part2.StartAsync(services: s => s.AddSingleton(source));
source.Traces = Traces(server.Clock.Now);
source.DamagedLines = 2;
source.Faults = 1;
using var response = await server.Client.GetAsync(ActivityApi.DiagnosticsPath);
var bytes = await response.Content.ReadAsByteArrayAsync();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, Encoding.UTF8.GetString(bytes));
Assert.AreEqual("application/json", response.Content.Headers.ContentType?.MediaType);
Assert.AreEqual("utf-8", response.Content.Headers.ContentType?.CharSet);
Assert.AreEqual("no-store", response.Headers.CacheControl?.ToString());
var disposition = response.Content.Headers.ContentDisposition;
Assert.IsNotNull(disposition);
Assert.AreEqual("attachment", disposition.DispositionType);
var day = LocalCalendar.Today(server.Clock.Now, server.Clock.LocalZone).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
Assert.AreEqual($"febe-diagnostica-{day}.json", disposition.FileName?.Trim('"'));
Assert.AreEqual((byte)'{', bytes[0], "UTF-8 without BOM");
using var report = JsonDocument.Parse(bytes);
var root = report.RootElement;
Assert.AreEqual(DiagnosticReport.Title, root.GetProperty("rapporto").GetString());
Assert.AreEqual(server.App.Services.GetRequiredService().Version, root.GetProperty("versione").GetString());
Assert.AreEqual("docker", root.GetProperty("edizione").GetString());
Assert.AreEqual(DiagnosticReport.ZoneName(server.Clock.LocalZone), root.GetProperty("fuso").GetString());
Assert.AreEqual(14, root.GetProperty("giorni").GetInt32());
Assert.AreEqual(2, root.GetProperty("righeRovinate").GetInt32(), "The report says what it misses.");
Assert.AreEqual(1, root.GetProperty("erroriRegistratore").GetInt32());
var session = root.GetProperty("sessioni").EnumerateArray().Single();
Assert.AreEqual(7, session.GetProperty("session").GetInt64());
Assert.AreEqual(nameof(SessionStopCause.BreakerOpen), session.GetProperty("stopCause").GetString());
Assert.AreEqual(1, root.GetProperty("fuoriSessione").GetArrayLength());
Assert.AreEqual(1, source.Calls);
}
[TestMethod]
public async Task TheWindowsLookSaysWindows()
{
await using var server = await Part2.StartAsync(FebeEdition.Desktop);
using var response = await server.Client.GetAsync(ActivityApi.DiagnosticsPath);
using var report = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.AreEqual("windows", report.RootElement.GetProperty("edizione").GetString());
}
[TestMethod]
public async Task WithoutARecorderTheReportIsThereAndEmpty()
{
await using var server = await Part2.StartAsync();
using var response = await server.Client.GetAsync(ActivityApi.DiagnosticsPath);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
using var report = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.AreEqual(0, report.RootElement.GetProperty("sessioni").GetArrayLength());
Assert.AreEqual(0, report.RootElement.GetProperty("fuoriSessione").GetArrayLength());
}
[TestMethod]
public async Task TheReportIsAnsweredEvenWithAConfigurationProblem()
{
CollectionAssert.Contains(ConfigurationGateMiddleware.AllowedApi.ToList(), ActivityApi.DiagnosticsPath);
var problem = new ConfigurationProblem("password-mancante", "Manca la password dell'interfaccia", "Spiegazione.", "Rimedio.");
await using var server = await Part2.StartAsync(services: s => s.AddSingleton(new FixedProblems(problem)));
var (blocked, _, _) = await server.GetAsync("/api/duplicates/count");
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, blocked, "the gate is closed for the rest");
var (status, text, _) = await server.GetAsync(ActivityApi.DiagnosticsPath);
Assert.AreEqual(HttpStatusCode.OK, status, text);
using var report = JsonDocument.Parse(text);
Assert.AreEqual(DiagnosticReport.Title, report.RootElement.GetProperty("rapporto").GetString());
Assert.AreEqual(0, report.RootElement.GetProperty("sessioni").GetArrayLength(), "The engine never started.");
}
private static List Traces(DateTimeOffset now) =>
[
new SessionTrace
{
Session = 7,
Start = now - TimeSpan.FromMinutes(40),
End = now - TimeSpan.FromMinutes(30),
Outcome = SessionOutcome.Stopped,
StopCause = SessionStopCause.BreakerOpen,
Mood = 0.9,
Pages = [new PageVisit(now - TimeSpan.FromMinutes(39), SitePages.Home, "/", true)],
Signals = [new SignalLine(now - TimeSpan.FromMinutes(30), SignalLevel.Challenge, "challenge-url")],
},
new SessionTrace { Session = null, Start = now - TimeSpan.FromMinutes(20), InProgress = true },
];
private sealed class FixedDiagnostics : IDiagnosticSource
{
public IReadOnlyList Traces { get; set; } = [];
public int Calls { get; private set; }
public int DamagedLines { get; set; }
public int Faults { get; set; }
public Task> ListAsync(CancellationToken ct)
{
Calls++;
return Task.FromResult(Traces);
}
public Task GatherAsync(CancellationToken ct)
{
Calls++;
return Task.FromResult(new DiagnosticCollection(Traces, DamagedLines, Faults));
}
}
}