Rapporto di diagnostica della raccolta (#39)
verifica / controlli (push) Successful in 18s
verifica / prove (push) Successful in 13m5s
verifica / installatore (push) Successful in 4m11s
verifica / immagine (push) Successful in 14m4s

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-13 14:41:34 +01:00
1 parent bf03cb45a5
commit badd1681a0
55 files changed
+5395 -134

No files matched your search

+56
View File
@@ -1,7 +1,12 @@
using System.Net;
using System.Text.Json;
using Febe.Core.Collection;
using Febe.Core.Engine;
using Febe.Sonda;
using Febe.Tests.Collection;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web.Api;
using Febe.Web.Demo;
namespace Febe.Tests.Web;
@@ -129,6 +134,57 @@ public sealed class DemoPart2Tests
Assert.IsTrue(normal.All(i => !i.Bool("open")));
}
[TestMethod]
public async Task TheDiagnosticReportFollowsTheSceneAndNamesNobody()
{
var finished = s_demo!.World.Today.Count;
Assert.IsGreaterThan(0, finished, "the demo day has sessions");
var names = (await s_demo.Storage.Accounts.ListAsync()).Select(a => a.Username).ToList();
names.AddRange(["marta.demo", "giulia.corre.demo", "tuo.profilo"]);
var vocabulary = ReportLeaks.Vocabulary(SiteMap.LoadInstagram());
var sensitive = names.SelectMany(SensitiveTokens.Tokenize).Where(t => !vocabulary.Contains(t)).ToHashSet(StringComparer.Ordinal);
Assert.IsGreaterThan(20, sensitive.Count);
async Task<JsonElement> ReportAsync(string scene)
{
using var response = await Client.GetAsync($"{ActivityApi.DiagnosticsPath}?scena={scene}");
var text = await response.Content.ReadAsStringAsync();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{scene}: {text}");
Assert.AreEqual("attachment", response.Content.Headers.ContentDisposition?.DispositionType);
Assert.AreEqual("no-store", response.Headers.CacheControl?.ToString());
ReportLeaks.AssertClean(text, names, sensitive, ReportLeaks.FieldKeys([]));
return JsonDocument.Parse(text).RootElement.Clone();
}
var normal = await ReportAsync("normale");
Assert.AreEqual("windows", normal.Str("edizione"), "the demo looks like the desktop by default");
var sessions = normal.Items("sessioni").ToList();
Assert.HasCount(finished, sessions);
Assert.IsTrue(sessions.All(s => s.Str("outcome") == nameof(Febe.Core.Domain.SessionOutcome.Completed) && !s.Bool("inProgress")));
Assert.IsTrue(sessions.All(s => s.Items("responses").Any() && s.Items("recipes").Any()));
Assert.AreEqual(0, sessions.Sum(s => s.Items("signals").Count()));
Assert.HasCount(1, normal.Items("fuoriSessione").ToList());
var running = (await ReportAsync("sessione")).Items("sessioni").ToList();
Assert.HasCount(finished + 1, running);
Assert.IsTrue(running[^1].Bool("inProgress"), "the session in progress comes last");
var stopped = (await ReportAsync("fermo")).Items("sessioni").ToList();
Assert.HasCount(finished, stopped);
Assert.AreEqual(nameof(SessionStopCause.BreakerOpen), stopped[^1].Str("stopCause"));
Assert.AreEqual(DemoDiagnosticSource.ChallengeCode, stopped[^1].Items("signals").Single().Str("code"));
Assert.IsTrue(stopped.Take(stopped.Count - 1).All(s => s.Str("stopCause") != nameof(SessionStopCause.BreakerOpen)));
foreach (var scene in new[] { "scollegato", "errore" })
{
var empty = await ReportAsync(scene);
Assert.AreEqual(0, empty.GetProperty("sessioni").GetArrayLength(), scene);
Assert.AreEqual(0, empty.GetProperty("fuoriSessione").GetArrayLength(), scene);
}
Assert.AreEqual("docker", (await ReportAsync("normale&veste=docker")).Str("edizione"));
}
[TestMethod]
public async Task EverySettingsPageHasItsData()
{
@@ -0,0 +1,139 @@
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));
}
}
}