Files
Febe/tests/Febe.Tests/Web/DiagnosticReportApiTests.cs
T
Alby96andClaude Opus 5.5 badd1681a0
verifica / controlli (push) Successful in 18s
verifica / prove (push) Successful in 13m5s
verifica / installatore (push) Successful in 4m11s
verifica / immagine (push) Successful in 14m4s
Rapporto di diagnostica della raccolta (#39)
Dopo una prova dal vivo andata male, Alberto deve poter mandare un solo file che
spieghi perché, senza che nessuno veda dati di altre persone. Attività ha ora il
pulsante «Diagnostica», che scarica il rapporto delle sessioni degli ultimi 14 giorni:
pagine aperte e forma degli indirizzi, risposte per tipo, stato e dimensione con ciò
che i lettori ne hanno fatto, struttura stretta delle forme sconosciute, ricette,
segnali, permessi negati, file in coda e scaricati, e il motivo di ogni arresto.

Nel rapporto entrano solo valori da elenchi chiusi, numeri, orari e forme: mai nomi,
indirizzi completi, codici, cursori, cookie o pezzi di risposte. Le forme degli
indirizzi e la regola delle chiavi-dato passano dalla sonda a Core, e la sonda le
richiama. Il registratore non lancia mai eccezioni verso la raccolta e tiene i file in
Dati/diagnostica per 14 giorni.

Prova che il rapporto non contiene valori, con controlli di mutazione; tre giri di
revisione avversaria (25 difetti confermati, tutti corretti).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 14:41:34 +01:00

140 lines
6.7 KiB
C#

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;
/// <summary>
/// «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).
/// </summary>
[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<IDiagnosticSource>(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<FebeWebOptions>().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<IConfigurationProblems>(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<SessionTrace> 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<SessionTrace> Traces { get; set; } = [];
public int Calls { get; private set; }
public int DamagedLines { get; set; }
public int Faults { get; set; }
public Task<IReadOnlyList<SessionTrace>> ListAsync(CancellationToken ct)
{
Calls++;
return Task.FromResult(Traces);
}
public Task<DiagnosticCollection> GatherAsync(CancellationToken ct)
{
Calls++;
return Task.FromResult(new DiagnosticCollection(Traces, DamagedLines, Faults));
}
}
}