Files
Febe/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs
T
Alby96andClaude Opus 5.5 74e67adbab Sessione salvata: seconda revisione di S4b (#36)
La scelta per la copia incompleta si legge prima dell'ultimo controllo che la pagina sia ancora di Alberto, così fra quello sguardo e la scrittura non passa nessuna attesa (regola 7); se l'impostazione non si legge vale «Sostituisci comunque» e il registro scrive solo il tipo d'errore, invece di far fallire «Ho finito» lasciando il permesso di guida trattenuto. Ogni abbandono del browser senza «Ho finito» dimentica la copia di un abbandono precedente dello stesso uso prima di provare la sua: un «Ho finito» tardivo dopo una seconda chiusura rifiutata (pagina di accesso) non dice più che la sessione era già stata copiata. Tre prove nuove, che senza le correzioni non passano. Fine riga già conformi: indice LF come il resto del repository, nessuna conversione necessaria.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:03:59 +01:00

389 lines
21 KiB
C#

using System.Net;
using Febe.App;
using Febe.Core.Collection.Requests;
using Febe.Tests.Desktop.Support;
using Febe.Web.Connection;
namespace Febe.Tests.Desktop;
/// <summary>
/// Stage S4b of issue #36 (answers of Alberto of 18 November 2026) in the shared composition, with a fake browser and
/// the test site's catalog: the session is copied also when Alberto closes the browser window and when his driving
/// lease ends by itself — only from a page of the site, before the page goes back to the engine (rule 7) —; with the
/// raccolta «richieste» «Collegato» needs a readable saved session («Serve «Ho finito»» otherwise, the engine waits);
/// an incomplete copy can keep the complete one; the Collegamento page gets counts and names, never values. Never
/// Instagram.
/// </summary>
[TestClass]
public sealed class SessionCopyOnLetGoTests
{
private const string Site = "http://127.0.0.1:8481";
public TestContext TestContext { get; set; } = null!;
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ClosingTheWindowCopiesTheSessionBeforeThePageGoesBackToTheEngine()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
// «Apri il browser»: only the window holds the engine still (no lease of «Accedi»).
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
bool? drivingWhileCopying = null;
bool? sessionWhileCopying = null;
browser.FakeCdp.OnCapture = () =>
{
drivingWhileCopying = browser.UserIsDriving;
sessionWhileCopying = bed.App.Engine!.Services.Runtime.CurrentSession is not null;
};
await browser.CloseWindowAsync(ct);
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
Assert.IsTrue(drivingWhileCopying, "the page is still Alberto's while it is read");
Assert.IsFalse(sessionWhileCopying, "no engine session runs meanwhile");
Assert.IsFalse(browser.UserIsDriving, "then it goes back to the engine");
var saved = bed.App.SavedSession!.Read();
Assert.IsNotNull(saved);
Assert.AreEqual(Febe.SitoDiProva.TestSite.SpinBranch, saved.Fields["spin_b"]);
Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ClosingTheWindowOffTheSiteOrWithoutASessionCopiesNothing()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
// Another site's page: the copier refuses before reading the modules.
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated("https://altro.example.invalid/pagina");
await browser.CloseWindowAsync(ct);
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
Assert.IsNull(bed.App.SavedSession!.Read());
// A page of the site without the session cookie: nothing to copy.
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.LoggedIn = false;
browser.FakeCdp.Navigated(Site + "/");
await browser.CloseWindowAsync(ct);
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
Assert.IsNull(bed.App.SavedSession.Read());
Assert.IsFalse(browser.UserIsDriving);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheEndOfTheLeaseCopiesOnceAndNotAgainAfterTheWindowCopied()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.DrivingGrace = TimeSpan.FromMilliseconds(400);
// «Usa il browser», then the window is put away without «Ho finito»: the lease ends by itself after the copy.
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida");
Assert.AreEqual(1, browser.FakeCdp.CaptureReads, "copied when the lease ended");
Assert.IsNotNull(bed.App.SavedSession!.Read());
// «Usa il browser» again, the window closed (a copy), then the lease ends: no second copy for the same use.
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.Navigated(Site + "/profilo/marta.prova/");
await browser.CloseWindowAsync(ct);
Assert.AreEqual(2, browser.FakeCdp.CaptureReads, "the window's copy");
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo la finestra");
Assert.AreEqual(2, browser.FakeCdp.CaptureReads, "the end of the lease does not copy again");
// On the site's login page (a path of its stop rules) the end of the lease copies nothing: the copier refuses it.
var before = bed.App.SavedSession.Read();
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.Navigated(Site + "/accesso/");
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida sulla pagina di accesso");
Assert.AreSame(before, bed.App.SavedSession.Read());
Assert.AreEqual(2, browser.FakeCdp.CaptureReads, "refused before the modules are read");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ALateHoFinitoFollowsTheLastLettingGoNotAnEarlierOne()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.DrivingGrace = TimeSpan.FromMilliseconds(400);
// «Usa il browser», the window closed on the site's home: copied.
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
await browser.CloseWindowAsync(ct);
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
// Same use: the window back in front, then closed again on the login page (perhaps another account): refused.
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.Navigated(Site + "/accesso/");
await browser.CloseWindowAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida");
// A late «Ho finito» must not say that the session was already copied: the last letting go copied nothing.
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
var message = finish.GetProperty("message").GetString()!;
StringAssert.Contains(message, "non è stata copiata");
Assert.DoesNotContain("era già stata copiata", message);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task AnErrorDuringTheCopyWhenAlbertoLetsGoStillGivesThePageBackToTheEngine()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.DrivingGrace = TimeSpan.FromMilliseconds(300);
// An error nobody expects in the middle of the copy (the database busy, say): the end of the lease must still
// come, or the engine would stay in «Stai usando il browser» for ever.
browser.FakeCdp.OnCapture = () => throw new Microsoft.Data.Sqlite.SqliteException("prova: database occupato", 5);
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo un errore della copia");
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
Assert.IsNull(bed.App.SavedSession!.Read());
await DesktopTestBed.WaitUntilAsync(() => ReadLog(bed).Contains("il motore può riprendere", StringComparison.Ordinal), TimeSpan.FromSeconds(10), "la riga della fine della guida");
var log = ReadLog(bed);
StringAssert.Contains(log, "Fine della guida del browser: copia della sessione non riuscita per un errore (SqliteException).");
Assert.DoesNotContain("database occupato", log, "the kind of error only (rule 10)");
// The same error when the window is closed: the page goes back all the same.
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.Navigated(Site + "/");
await browser.CloseWindowAsync(ct);
Assert.AreEqual(2, browser.FakeCdp.CaptureReads);
Assert.IsFalse(browser.UserIsDriving);
StringAssert.Contains(ReadLog(bed), "Finestra del browser chiusa: copia della sessione non riuscita per un errore (SqliteException).");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheLogSaysWhetherTheWindowWasClosedOrLeftMinimisedTooLong()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
await browser.CloseWindowAsync(ct, Febe.App.BrowserWindowLetGo.MinimizedTooLong);
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
var log = ReadLog(bed);
StringAssert.Contains(log, "Finestra del browser ridotta a icona troppo a lungo: sessione copiata");
Assert.DoesNotContain("Finestra del browser chiusa", log, "it was not closed");
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.Navigated(Site + "/");
await browser.CloseWindowAsync(ct);
StringAssert.Contains(ReadLog(bed), "Finestra del browser chiusa: sessione copiata");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task WithRichiesteCollegatoNeedsTheSavedSessionAndTheEngineWaitsForIt()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
// The session in the browser, but «Annulla» instead of «Ho finito»: no copy.
await BeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel"))
{
Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode);
}
// As the background look would see it a moment later.
await connection.RefreshAsync(ct);
var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection");
Assert.AreEqual("copyMissing", status.GetProperty("state").GetString());
var saved = status.GetProperty("savedSession");
Assert.AreEqual("none", saved.GetProperty("state").GetString());
Assert.IsTrue(connection.IsConnected);
Assert.IsTrue(connection.SessionCopyMissing);
Assert.IsFalse(connection.IsReadyToCollect, "the engine waits");
Assert.IsFalse(bed.App.Engine!.Services.Runtime.IsConnected);
Assert.IsTrue(bed.App.Engine.Services.Runtime.SessionCopyMissing);
var engine = await bed.JsonAsync(HttpMethod.Get, "/api/engine");
Assert.AreEqual("copyMissing", engine.GetProperty("connection").GetProperty("state").GetString());
Assert.AreEqual("Serve «Ho finito»", engine.GetProperty("snapshot").GetProperty("headline").GetString());
// «Ho finito»: «Collegato», with counts and names of the copy and never a value.
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.Navigated(Site + "/");
await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
using (var answer = await bed.SendAsync(HttpMethod.Get, "/api/connection"))
{
var text = await answer.Content.ReadAsStringAsync(ct);
foreach (var secret in new[] { Febe.SitoDiProva.TestSite.Lsd, Febe.SitoDiProva.TestSite.Dtsg, Febe.SitoDiProva.TestSite.EntryNonce, Febe.SitoDiProva.TestSite.SpinBranch, "sessione-di-prova", "csrf-di-prova", "Finestra di prova" })
{
Assert.DoesNotContain(secret, text, "counts and names only");
}
}
status = await bed.JsonAsync(HttpMethod.Get, "/api/connection");
Assert.AreEqual("connected", status.GetProperty("state").GetString());
saved = status.GetProperty("savedSession");
Assert.AreEqual("present", saved.GetProperty("state").GetString());
Assert.IsTrue(saved.GetProperty("copiedAt").GetInt64() > 0);
Assert.AreEqual(saved.GetProperty("valuesExpected").GetInt32(), saved.GetProperty("valuesPresent").GetInt32());
Assert.AreEqual(0, saved.GetProperty("missingValues").GetArrayLength());
Assert.AreEqual(0, saved.GetProperty("neededMissing").GetInt32());
Assert.IsTrue(connection.IsReadyToCollect);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task WithPagineCollegatoIsTheCookieAloneAndNoSavedSessionIsShown()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site]);
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
await BeginAsync(bed);
bed.Browser!.FakeCdp.LoggedIn = true;
await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection");
Assert.AreEqual("connected", status.GetProperty("state").GetString());
Assert.IsTrue(status.TryGetProperty("savedSession", out var saved) is false || saved.ValueKind == System.Text.Json.JsonValueKind.Null);
Assert.IsFalse(bed.App.Connection!.SessionCopyMissing);
Assert.AreEqual(0, bed.Browser.FakeCdp.CaptureReads);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheIncompleteCopySettingIsStoredAndHeldByTheNextHoFinito()
{
await using var bed = await StartAsync();
var browser = bed.Browser!;
// The default: «sostituisci»; an unknown choice is refused.
Assert.AreEqual(SessionCopySettings.ReplaceText, (await bed.JsonAsync(HttpMethod.Get, "/api/connection/settings")).GetProperty("incompleteCopy").GetString());
using (var wrong = await bed.SendAsync(HttpMethod.Put, "/api/connection/settings", """{"incompleteCopy":"forse"}"""))
{
Assert.AreEqual(HttpStatusCode.BadRequest, wrong.StatusCode);
}
var keep = await bed.JsonAsync(HttpMethod.Put, "/api/connection/settings", """{"incompleteCopy":"tieni-completa"}""");
Assert.AreEqual(SessionCopySettings.KeepCompleteText, keep.GetProperty("incompleteCopy").GetString());
Assert.AreEqual(SessionCopySettings.KeepCompleteText, await bed.App.Database.Settings.GetAsync(SessionCopySettings.IncompleteCopyKey));
// A complete copy, then one from a page without the nonce: the complete one stays and «Ho finito» says so.
await FinishOnSiteAsync(bed, openLogin: true);
var complete = bed.App.SavedSession!.Read()!;
var page = FakeCdp.DefaultPageCapture();
((System.Text.Json.Nodes.JsonObject)page["values"]!).Remove("entry_nonce");
browser.FakeCdp.PageCapture = page;
var message = await FinishOnSiteAsync(bed, openLogin: false);
StringAssert.Contains(message, "Febe tiene la copia completa salvata prima");
StringAssert.Contains(message, "«Sostituisci comunque»");
Assert.AreSame(complete, bed.App.SavedSession.Read());
// «Sostituisci comunque»: the next incomplete copy replaces it, as in S4.
await bed.JsonAsync(HttpMethod.Put, "/api/connection/settings", """{"incompleteCopy":"sostituisci"}""");
message = await FinishOnSiteAsync(bed, openLogin: false);
StringAssert.Contains(message, "ha comunque sostituito quella salvata");
Assert.IsFalse(bed.App.SavedSession.Read()!.Fields.ContainsKey("entry_nonce"));
var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection");
Assert.AreEqual("connected", status.GetProperty("state").GetString(), "an incomplete copy is still a readable session");
var saved = status.GetProperty("savedSession");
Assert.AreEqual("entry_nonce", saved.GetProperty("missingValues")[0].GetString());
Assert.AreEqual(1, saved.GetProperty("neededMissing").GetInt32());
}
[TestMethod]
public void TheMessagesOfTheNewOutcomesSayWhatHappened()
{
var kept = BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, 3, 1, 0));
StringAssert.Contains(kept, "mancavano 1 valori");
StringAssert.Contains(kept, "tiene la copia completa salvata prima");
StringAssert.Contains(kept, "Riapri il browser dalla pagina Collegamento");
Assert.AreEqual("sessione copiata", BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 0, 0)));
StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 2, 0)), "mancano 2 valori");
StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, 3, 1, 0)), "resta quella completa");
StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Refused, Febe.Browser.Session.CaptureRefusal.CheckpointPage, 0, 0, 0)), "pagina di accesso o di verifica");
// A late «Ho finito» after the copy made when the browser went back to the engine.
var before = BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 0, 0), earlier: true);
StringAssert.Contains(before, "era già stata copiata quando il browser è tornato al motore");
StringAssert.Contains(before, "Non serve rifare l'accesso");
Assert.DoesNotContain("non è stata copiata", before);
var beforeIncomplete = BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 2, 0), earlier: true);
StringAssert.Contains(beforeIncomplete, "era già stata copiata");
StringAssert.Contains(beforeIncomplete, "mancavano 2 valori");
Assert.DoesNotContain("Non serve rifare l'accesso", beforeIncomplete);
StringAssert.Contains(BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.SavedInMemoryOnly, null, 3, 0, 0), earlier: true), "non ancora scritta su disco");
StringAssert.Contains(BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, 3, 1, 0), earlier: true), "Quando il browser è tornato al motore alla pagina mancavano 1 valori");
}
/// <summary>The log files of this start, read while Febe still writes them.</summary>
private static string ReadLog(DesktopTestBed bed)
{
var folder = bed.App.Log.Folder;
Assert.IsNotNull(folder, "the log has a folder");
var text = new System.Text.StringBuilder();
foreach (var file in Directory.GetFiles(folder))
{
using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var reader = new StreamReader(stream);
text.Append(reader.ReadToEnd());
}
return text.ToString();
}
private async Task<DesktopTestBed> StartAsync()
{
var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site, "--raccolta", "richieste"]);
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), TestContext.CancellationToken);
return bed;
}
private static async Task BeginAsync(DesktopTestBed bed, bool openLogin = true)
{
using var begin = await bed.SendAsync(HttpMethod.Post, "/api/connection/begin", openLogin ? """{"openLogin":true}""" : """{"openLogin":false}""");
Assert.AreEqual(HttpStatusCode.NoContent, begin.StatusCode);
}
/// <summary>«Accedi» or «Usa il browser», the site's home with the session, «Ho finito». Returns the message.</summary>
private static async Task<string> FinishOnSiteAsync(DesktopTestBed bed, bool openLogin)
{
await BeginAsync(bed, openLogin);
bed.Browser!.FakeCdp.LoggedIn = true;
bed.Browser.FakeCdp.Navigated(Site + "/");
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsTrue(finish.GetProperty("connected").GetBoolean(), finish.GetProperty("message").GetString());
return finish.GetProperty("message").GetString()!;
}
}