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 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 ALeaseThatCameBackDuringTheCopyIsNotEndedAfterIt()
{
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 put away: the end of the lease copies. While it copies, the remote view (or the
// window) comes back.
IDisposable? back = null;
browser.FakeCdp.OnCapture = () => back ??= browser.UserDriving.Begin();
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => ReadLog(bed).Contains("Fine della guida del browser: sessione copiata", StringComparison.Ordinal), TimeSpan.FromSeconds(10), "la copia alla fine della guida");
Assert.IsNotNull(back);
// Time enough for the look after the copy: the lease of «Usa il browser» must still be there, beside the view's.
await Task.Delay(TimeSpan.FromMilliseconds(300), ct);
Assert.AreEqual(2, browser.UserDriving.Leases, "the lease of «Usa il browser» goes on while the view is back");
// The view goes away again: a new letting go, a new copy, and only then the lease ends.
browser.FakeCdp.OnCapture = null;
back.Dispose();
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo la vista");
Assert.AreEqual(2, browser.FakeCdp.CaptureReads, "the second letting go copies again");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task AHoFinitoAfterARefusedHoFinitoDoesNotReportTheCopyOfAnEarlierLettingGo()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
// «Usa il browser», the window closed on the site's home: copied, while the lease of «Usa il browser» holds.
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
await browser.CloseWindowAsync(ct);
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
Assert.IsTrue(browser.UserIsDriving, "the lease of «Usa il browser» is still there");
// The window back, another login ending on the login page: «Ho finito» copies again and is refused.
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.Navigated(Site + "/accesso/");
var first = (await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish")).GetProperty("message").GetString()!;
StringAssert.Contains(first, "non è stata copiata");
// A second «Ho finito» (a double click, another tab) must not say the session was already copied.
var second = (await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish")).GetProperty("message").GetString()!;
Assert.DoesNotContain("era già stata copiata", second);
Assert.DoesNotContain("Non serve rifare l'accesso", second);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task WhenTheTimeRunsOutWaitingForThePageTheLogSaysThePageWasBusy()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.LetGoWait = TimeSpan.FromMilliseconds(500);
connection.PageTurnWait = TimeSpan.FromSeconds(30);
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
// A step of the profile search holds the page for longer than the window may wait.
using (await bed.App.Engine!.Services.PageTurns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct))
{
await browser.CloseWindowAsync(ct);
}
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
Assert.IsFalse(browser.UserIsDriving);
var log = ReadLog(bed);
StringAssert.Contains(log, "Finestra del browser chiusa: sessione non copiata, la pagina era occupata dalla ricerca dei profili.");
Assert.DoesNotContain("il browser non ha risposto in tempo", log, "the browser was not the cause");
}
[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 LeavingTheBrowserPageInDockerCopiesTheSessionOnceNoViewOpensAgain()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageLeaveGrace = TimeSpan.FromMilliseconds(400);
// «Usa il browser» from the Browser page of Docker: no window, the remote view holds the engine still.
var view = await DockerBeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
bool? drivingWhileCopying = null;
browser.FakeCdp.OnCapture = () => drivingWhileCopying = browser.UserIsDriving;
// The page says it is left; while its view (or another tab's) is still open nothing happens.
await connection.LeavePageAsync(ct);
await Task.Delay(TimeSpan.FromMilliseconds(900), ct);
Assert.IsTrue(browser.UserIsDriving, "a view is still open");
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
// Its view closes with it and no other opens: the copy while the page is still his, then it goes back to the engine.
view.Dispose();
connection.RemoteViewClosed();
await DesktopTestBed.WaitUntilAsync(() => ReadLog(bed).Contains("Pagina del browser lasciata: nessuna vista del browser riaperta, il motore può riprendere.", StringComparison.Ordinal), TimeSpan.FromSeconds(10), "la fine della guida lasciando la pagina");
Assert.IsFalse(browser.UserIsDriving);
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
Assert.IsTrue(drivingWhileCopying, "the page is still Alberto's while it is read");
Assert.IsNotNull(bed.App.SavedSession!.Read());
StringAssert.Contains(ReadLog(bed), "Pagina del browser lasciata: sessione copiata");
// A late «Ho finito» from another tab reads nothing and says that the session was already copied.
var finish = (await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish")).GetProperty("message").GetString()!;
StringAssert.Contains(finish, "era già stata copiata");
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task AReloadOfTheBrowserPageIsNotLeavingItAndAnnullaStillCopiesNothing()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageLeaveGrace = TimeSpan.FromSeconds(1);
var view = await DockerBeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
// A reload: the old page says it left and its view closes, the new page takes the browser and opens its view.
await connection.LeavePageAsync(ct);
view.Dispose();
connection.RemoteViewClosed();
view = await DockerBeginAsync(bed);
await Task.Delay(TimeSpan.FromSeconds(2), ct);
Assert.IsTrue(browser.UserIsDriving, "a reload is not leaving the browser");
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
// «Annulla» on the reloaded page: the browser goes back to rest, nothing is copied.
view.Dispose();
using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel"))
{
Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode);
}
Assert.IsFalse(browser.UserIsDriving);
await Task.Delay(TimeSpan.FromSeconds(1.5), ct);
Assert.AreEqual(0, browser.FakeCdp.CaptureReads, "«Annulla» never copies");
Assert.IsNull(bed.App.SavedSession!.Read());
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ABeginOfAReloadedPageCancelsTheLeaveEvenBeforeItsViewOpens()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageLeaveGrace = TimeSpan.FromSeconds(1);
var view = await DockerBeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
// A reload where the new page's «begin» arrives but its view does not open within the moment: «begin» alone says
// Alberto is back. Waited past PageLeaveGrace and well below DrivingGrace.
await connection.LeavePageAsync(ct);
view.Dispose();
connection.RemoteViewClosed();
await BeginAsync(bed, openLogin: false);
await browser.HideFromUserAsync(ct);
await Task.Delay(TimeSpan.FromSeconds(2.5), ct);
Assert.IsTrue(browser.UserIsDriving, "begin cancels the leave");
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
Assert.DoesNotContain("Pagina del browser lasciata: nessuna vista", ReadLog(bed));
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
[DataRow(false, DisplayName = "«pageLeft» tardivo della pagina ricaricata")]
[DataRow(true, DisplayName = "vecchia vista chiusa da «Riprova»")]
public async Task ALeaveFollowedByAViewOpenAgainIsForgottenWhenThatViewEndsFromTheServer(bool oldViewClosed)
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageLeaveGrace = TimeSpan.FromSeconds(1);
var view = await DockerBeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
// The leave arrives while a view is open: the keepalive «pageLeft» of a reloaded page after the new page's
// «begin», or the old socket closed by «Riprova» while the new view opens without «begin».
if (oldViewClosed)
{
connection.RemoteViewClosed();
}
else
{
await connection.LeavePageAsync(ct);
}
await Task.Delay(TimeSpan.FromMilliseconds(600), ct);
// That view then ends from the server (the browser stopped): it is not told to the connection. A browser that is
// down is not leaving it, so the lease waits for DrivingGrace, not for PageLeaveGrace.
view.Dispose();
await Task.Delay(TimeSpan.FromSeconds(2.5), ct);
Assert.IsTrue(browser.UserIsDriving, "the earlier leave was forgotten once a view was open again");
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
Assert.DoesNotContain("Pagina del browser lasciata: nessuna vista", ReadLog(bed));
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task LeavingTheBrowserPageWaitsForAnotherCommandOnlyForLetGoWait()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageLeaveGrace = TimeSpan.FromMilliseconds(300);
connection.LetGoWait = TimeSpan.FromMilliseconds(500);
connection.PageTurnWait = TimeSpan.FromSeconds(30);
var view = await DockerBeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
// «Pagina iniziale» holds the commands of the connection while it waits for the page's turn, which a step of the
// profile search keeps for longer than leaving the page may wait.
using var press = CancellationTokenSource.CreateLinkedTokenSource(ct);
Task startPage;
using (await bed.App.Engine!.Services.PageTurns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct))
{
startPage = connection.OpenStartPageAsync(press.Token);
await Task.Delay(TimeSpan.FromMilliseconds(200), ct);
view.Dispose();
connection.RemoteViewClosed();
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo l'attesa massima");
press.Cancel();
}
await startPage;
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
StringAssert.Contains(ReadLog(bed), "Pagina del browser lasciata: sessione non copiata, un altro comando del collegamento era ancora in corso.");
Assert.IsNull(bed.App.SavedSession!.Read());
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task LeavingTheBrowserPageOnTheLoginPageCopiesNothingButGivesThePageBack()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageLeaveGrace = TimeSpan.FromMilliseconds(300);
var view = await DockerBeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/accesso/");
// The tab closed on the site's login page (a path of its stop rules): the copier refuses it.
view.Dispose();
connection.RemoteViewClosed();
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida lasciando la pagina di accesso");
Assert.AreEqual(0, browser.FakeCdp.CaptureReads, "refused before the modules are read");
Assert.IsNull(bed.App.SavedSession!.Read());
await DesktopTestBed.WaitUntilAsync(() => ReadLog(bed).Contains("Pagina del browser lasciata: sessione non copiata", StringComparison.Ordinal), TimeSpan.FromSeconds(10), "la riga della copia rifiutata");
}
[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);
StringAssert.Contains(ReadLog(bed), "Motore avviato: aspetta il collegamento", "at start-up nothing was connected");
StringAssert.Contains(FebeApp.StartedMessage(connection), "aspetta la copia della sessione", "the start-up line says what the engine waits for");
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);
Assert.AreEqual("Motore avviato: il browser è collegato.", FebeApp.StartedMessage(connection));
}
[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, "Alla pagina mancava 1 valore che serve alle richieste");
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)), "(1 valore mancante), resta quella completa");
StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, 3, 2, 1)), "(3 valori mancanti)");
StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 0, 1)), ", ma manca 1 valore che serve alle richieste");
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 mancava 1 valore che serve");
// Italian singular and plural (never «1 valori»).
var one = BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 1, 0));
StringAssert.Contains(one, "Alla pagina però mancava 1 valore che serve alle richieste");
StringAssert.Contains(one, "le richieste che lo usano non partono");
var two = BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 1, 1));
StringAssert.Contains(two, "Alla pagina però mancavano 2 valori che servono alle richieste");
StringAssert.Contains(two, "le richieste che li usano non partono");
foreach (var text in new[] { kept, one, two, before, beforeIncomplete, BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 1, 0)) })
{
Assert.DoesNotContain("1 valori", text);
}
}
/// The log files of this start, read while Febe still writes them.
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 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);
}
///
/// «Usa il browser» as the Browser page of Docker takes it: the lease of the connection and the lease of its remote
/// view (returned), without the window of this composition (put away at once).
///
private async Task DockerBeginAsync(DesktopTestBed bed)
{
await BeginAsync(bed, openLogin: false);
await bed.Browser!.HideFromUserAsync(TestContext.CancellationToken);
return bed.Browser.UserDriving.Begin();
}
/// «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()!;
}
}