using System.Net; using Febe.App; using Febe.Core.Collection.Requests; using Febe.Tests.Desktop.Support; using Febe.Web.Connection; namespace Febe.Tests.Desktop; /// /// 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. /// [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 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"); } private async Task 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); } /// «Accedi» or «Usa il browser», the site's home with the session, «Ho finito». Returns the message. private static async Task 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()!; } }