Sessione salvata: copia alla chiusura della finestra e alla fine della guida, «Serve «Ho finito»», scelta per la copia incompleta e stato in Collegamento (#36, S4b)

Risposte 1, 5, 6, 9 e 10 di Alberto a S4. I valori __spin_r, __spin_b e __spin_t si copiano dalla pagina come gli altri (su Instagram da SiteData, ipotesi H23, operazioni ancora non configurate; nel sito di prova dal modulo GiroProva). La sessione si copia anche quando si chiude la finestra del browser su Windows e quando il permesso di guida finisce, sempre prima che la pagina torni al motore e con le garanzie di «Ho finito». Con «richieste» «Collegato» vuole una sessione salvata leggibile, altrimenti lo stato è «Serve «Ho finito»» e il motore aspetta. Nuova impostazione sessione.copia-incompleta (sostituisci, predefinita, o tieni-completa) e riquadro della sessione salvata nella pagina Collegamento, con soli conteggi e nomi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 11:41:35 +01:00
1 parent 9958745e53
commit 883ea4683c
41 files changed
+1349 -101

No files matched your search

@@ -58,7 +58,9 @@ internal sealed class DesktopBed : IAsyncDisposable
/// <param name="name">Prefix of the temporary folder.</param>
/// <param name="autoLogin"><c>--accesso-di-prova</c>: the composition opens the test site once at start-up.</param>
public static async Task<DesktopBed> StartAsync(string name, bool autoLogin, CancellationToken ct)
/// <param name="ct">Cancels the start.</param>
/// <param name="extra">More options of Febe.exe (<c>--raccolta richieste</c>).</param>
public static async Task<DesktopBed> StartAsync(string name, bool autoLogin, CancellationToken ct, string[]? extra = null)
{
var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
var folder = new TestFolder(name);
@@ -77,6 +79,8 @@ internal sealed class DesktopBed : IAsyncDisposable
arguments.Add("--accesso-di-prova");
}
arguments.AddRange(extra ?? []);
if (!DesktopCommandLine.TryParse([.. arguments], out var options, out var problem))
{
throw new ArgumentException(problem);
@@ -1,3 +1,4 @@
using Febe.Browser.Cdp;
using Febe.Core.Storage;
using Febe.Tests.Windows.Support;
using Febe.Web.Connection;
@@ -64,4 +65,42 @@ public sealed class WebView2ConnectionTests
Assert.IsFalse(bed.Lines.Any("non parte"), bed.Lines.Text);
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
}
[TestMethod]
[Timeout(240_000, CooperativeCancellation = true)]
public async Task WithRichiesteClosingTheWindowCopiesTheSessionBeforeThePageGoesBack()
{
// Issue #36, S4b (answer 5 of 18 November 2026): the window «Browser di Febe» closed with its X, without
// «Ho finito», copies the session from the site's page into the saved session, under Alberto's lease.
var ct = TestContext.CancellationToken;
await using var bed = await DesktopBed.StartAsync("finestra-copia", autoLogin: false, ct, ["--raccolta", "richieste"]);
var app = bed.App;
await app.Running.WaitAsync(TimeSpan.FromSeconds(120), ct);
var connection = app.Connection!;
var browser = bed.Browser;
var savedSession = app.SavedSession ?? throw new AssertFailedException("the test site's catalog has configured operations");
var window = await bed.Ui.InvokeAsync(() => browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
// «Accedi» (the welcome page starts the test site's session), then Alberto goes to the home of the site.
await connection.BeginUserDrivingAsync(openLogin: true, ct);
await browser.Cdp.NavigateAsync(bed.Site.Url("/"), ct);
await connection.RefreshAsync(ct);
Assert.AreEqual(ConnectionState.SessionCopyMissing, (await connection.GetStatusAsync(ct)).State, "the cookie alone is not «Collegato» with «richieste»");
await bed.Ui.InvokeAsync(() =>
{
window.Close();
return true;
});
await bed.WaitUntilAsync(() => Task.FromResult(savedSession.Read() is not null), TimeSpan.FromSeconds(30), "la copia alla chiusura della finestra", ct);
var saved = savedSession.Read()!;
Assert.AreEqual(Febe.SitoDiProva.TestSite.SpinBranch, saved.Fields["spin_b"]);
Assert.AreEqual(Febe.SitoDiProva.TestSite.EntryNonce, saved.Fields["entry_nonce"]);
Assert.IsFalse(await bed.Ui.InvokeAsync(() => window.IsOnScreen));
Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State);
Assert.IsTrue(bed.Lines.Any("Finestra del browser chiusa: sessione copiata"), bed.Lines.Text);
Assert.IsFalse(bed.Lines.Any(Febe.SitoDiProva.TestSite.Lsd), "no value in the log");
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
await connection.CancelAsync(ct);
}
}
@@ -289,6 +289,101 @@ public sealed class SessionCaptureTests
AssertNoSecret(string.Join("\n", log));
}
[TestMethod]
public async Task KeepTheCompleteCopyKeepsTheSavedOneOnlyWhenItIsCompleteAndTheNewOneLacksWhatTheRequestsNeed()
{
// Answer 9 of 18 November 2026: «tieni la completa» is a choice; «sostituisci» stays the default.
var log = new List<string>();
var store = new InMemorySiteSession(null);
var choice = IncompleteCopyChoice.KeepComplete;
BrowserSessionCopier Copier(JsonObject page) =>
new(Page($"http://{SiteHost}/", page: page), Plan, store, new VirtualClock(), log.Add) { IncompleteCopy = _ => Task.FromResult(choice) };
var lacking = PageValues();
((JsonObject)lacking["values"]!).Remove("lsd");
// Nothing saved yet: the incomplete copy is saved all the same (there is no complete one to keep).
Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(lacking).CopyAsync(() => true, CancellationToken.None)).Status);
var incomplete = store.Read()!;
// An incomplete saved copy is not one to keep: the next incomplete copy replaces it.
Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(lacking).CopyAsync(() => true, CancellationToken.None)).Status);
Assert.AreNotEqual(incomplete.Capture, store.Read()!.Capture);
// A complete copy, then an incomplete one: the complete one stays, and the outcome says so.
Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(PageValues()).CopyAsync(() => true, CancellationToken.None)).Status);
var complete = store.Read();
var kept = await Copier(lacking).CopyAsync(() => true, CancellationToken.None);
Assert.AreEqual(SessionCopyStatus.KeptComplete, kept.Status);
Assert.IsFalse(kept.Saved);
Assert.AreEqual(1, kept.MissingValues);
Assert.AreSame(complete, store.Read(), "the saved session stays as it was");
StringAssert.Contains(log[^1], "resta la copia completa salvata prima");
StringAssert.Contains(log[^1], "mancano lsd");
// A complete new copy always replaces it.
Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(PageValues()).CopyAsync(() => true, CancellationToken.None)).Status);
Assert.AreNotSame(complete, store.Read());
complete = store.Read();
// With «sostituisci» the incomplete copy replaces the complete one, as in S4.
choice = IncompleteCopyChoice.Replace;
Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(lacking).CopyAsync(() => true, CancellationToken.None)).Status);
Assert.AreNotSame(complete, store.Read());
Assert.IsFalse(store.Read()!.Fields.ContainsKey("lsd"), "missing, never guessed");
AssertNoSecret(string.Join("\n", log));
}
[TestMethod]
public async Task TheReportCountsAndNamesWhatTheSavedSessionHoldsAndNeverAValue()
{
var store = new InMemorySiteSession(null);
var clock = new VirtualClock();
var page = PageValues();
((JsonObject)page["values"]!).Remove("hsi");
((JsonObject)page["docIds"]!).Remove("ProvaProfiloQuery");
var copier = new BrowserSessionCopier(Page($"http://{SiteHost}/", page: page), Plan, store, clock, _ => { });
var none = copier.Report();
Assert.AreEqual(SavedSessionState.None, none.State);
Assert.AreEqual(SavedSessionState.None, copier.SavedState);
Assert.IsFalse(none.Complete);
Assert.IsNull(none.CopiedAt);
Assert.AreEqual(Plan.Values.Count, none.ValuesExpected);
Assert.AreEqual(0, none.ValuesPresent);
await copier.CopyAsync(() => true, CancellationToken.None);
var report = copier.Report();
Assert.AreEqual(SavedSessionState.Present, report.State);
Assert.AreEqual(SavedSessionState.Present, copier.SavedState);
Assert.AreEqual(clock.Now, report.CopiedAt);
Assert.AreEqual(3, report.Cookies);
Assert.AreEqual(Plan.Values.Count - 1, report.ValuesPresent);
Assert.AreEqual(14, report.ValuesExpected, "the page values of the test catalog, spin_r, spin_b and spin_t among them");
CollectionAssert.AreEqual(new[] { "hsi" }, report.MissingValues.ToArray());
Assert.AreEqual(0, report.DocIdsPresent);
CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery" }, report.MissingDocIds.ToArray());
Assert.AreEqual(2, report.NeededMissing, "the configured GraphQL query sends both");
Assert.IsFalse(report.Complete);
AssertNoSecret(report.ToString());
AssertNoSecret(string.Join(",", report.MissingValues.Concat(report.MissingDocIds)));
}
[TestMethod]
public async Task TheSpinValuesAreCopiedFromTheirModuleLikeTheOtherValuesOfThePage()
{
// Decision of 18 November 2026: __spin_r, __spin_b, __spin_t are a snapshot of the page at «Ho finito».
var store = new InMemorySiteSession(null);
await new BrowserSessionCopier(Page($"http://{SiteHost}/"), Plan, store, new VirtualClock(), _ => { }).CopyAsync(() => true, CancellationToken.None);
var saved = store.Read()!;
Assert.AreEqual("1001", saved.Fields["spin_r"]);
Assert.AreEqual("ramo", saved.Fields["spin_b"]);
Assert.AreEqual("1700000000", saved.Fields["spin_t"]);
var script = SessionCaptureScript.Build(Plan);
StringAssert.Contains(script, "read(\"GiroProva\", \"revisione\")");
StringAssert.Contains(script, "read(\"GiroProva\", \"tempo\")");
Assert.DoesNotContain("SiteData", script, "the test site's own module names, never Instagram's");
}
[TestMethod]
[Timeout(20_000, CooperativeCancellation = true)]
public async Task ABrowserThatDoesNotAnswerIsABrowserErrorAfterTheTimeout()
@@ -382,6 +477,9 @@ public sealed class SessionCaptureTests
["comet_req"] = "7",
["ccg"] = "BUONA",
["entry_nonce"] = "nonce-segreto",
["spin_r"] = "1001",
["spin_b"] = "ramo",
["spin_t"] = "1700000000",
["estraneo"] = "non chiesto",
},
["docIds"] = new JsonObject { ["ProvaProfiloQuery"] = "9000000000000009", ["AltraQuery"] = "1" },
@@ -65,7 +65,8 @@ public sealed class HttpSiteRequesterShapeTests
Assert.AreEqual(TestSite.ProfileQuery, request.Header("x-fb-friendly-name"));
Assert.AreEqual("0", request.Header("x-ig-www-claim"));
Assert.AreEqual(
"av=17841400000000077&__a=1&__ccg=BUONA&__comet_req=7&__hs=hs-di-prova&__hsi=hsi-di-prova&__rev=revisione-di-prova&dpr=1"
"av=17841400000000077&__a=1&__ccg=BUONA&__comet_req=7&__hs=hs-di-prova&__hsi=hsi-di-prova&__rev=revisione-di-prova"
+ "&__spin_r=1001&__spin_b=ramo-di-prova&__spin_t=1700000000&dpr=1"
+ "&fb_dtsg=dtsg-di-prova&lsd=lsd-di-prova&fb_api_req_friendly_name=ProvaProfiloQuery"
+ "&variables=%7B%22username%22%3A%22marta.prova%22%2C%22scheda%22%3A%22post%22%2C%22primi%22%3A12%2C%22raccolte%22%3Atrue%7D"
+ "&doc_id=8000000000000001",
@@ -360,6 +361,9 @@ public sealed class HttpSiteRequesterShapeTests
[DataRow("ccg", "__ccg")]
[DataRow("comet_req", "__comet_req")]
[DataRow("entry_nonce", "x-fb-entry-nonce")]
[DataRow("spin_r", "__spin_r")]
[DataRow("spin_b", "__spin_b")]
[DataRow("spin_t", "__spin_t")]
public async Task AVersionFieldTheSessionLacksStopsTheQueryBeforeItLeaves(string field, string missing)
{
using var listener = new OneShotListener("""{"profilo":{}}""");
@@ -452,7 +452,7 @@ public sealed class HttpSiteRequesterTests
var secrets = new List<string>
{
Csrf, OtherCookie, SiteControl.InitialSession, "rinnovata-1", "claim-prova-1", TestSite.AppId, TestSite.Lsd, TestSite.Dtsg, AccountId,
TestSite.Revision, TestSite.HasteSession, TestSite.HasteSessionId, TestSite.ConnectionClass, TestSite.EntryNonce,
TestSite.Revision, TestSite.HasteSession, TestSite.HasteSessionId, TestSite.ConnectionClass, TestSite.EntryNonce, TestSite.SpinBranch,
TestSite.DocIds[TestSite.ProfileQuery], UserAgent, "Mozilla", "marta.prova", "luca.prova", "c12", "127.0.0.1", "scheda", "primi", "accesso", "next",
};
secrets.AddRange(cases.Values.SelectMany(c => c.Values.Values));
@@ -574,6 +574,9 @@ public sealed class HttpSiteRequesterTests
["comet_req"] = TestSite.CometReq,
["ccg"] = TestSite.ConnectionClass,
["entry_nonce"] = TestSite.EntryNonce,
["spin_r"] = TestSite.SpinRevision,
["spin_b"] = TestSite.SpinBranch,
["spin_t"] = TestSite.SpinTime,
};
/// <summary>A site client for the test site with its session, clock and log.</summary>
@@ -345,6 +345,9 @@ public sealed partial class RequestCatalogTests
Assert.AreEqual(new PageValueSource("SiteData", "comet_env"), instagram.Values["comet_req"]);
Assert.AreEqual(new PageValueSource("WebConnectionClassServerGuess", "connectionClass"), instagram.Values["ccg"]);
Assert.AreEqual(new PageValueSource("BootloaderConfig", "nonce"), instagram.Values["entry_nonce"]);
Assert.AreEqual(new PageValueSource("SiteData", "__spin_r"), instagram.Values["spin_r"]);
Assert.AreEqual(new PageValueSource("SiteData", "__spin_b"), instagram.Values["spin_b"]);
Assert.AreEqual(new PageValueSource("SiteData", "__spin_t"), instagram.Values["spin_t"]);
CollectionAssert.AreEquivalent(SiteSessionValues.PageFields.ToArray(), instagram.Values.Keys.ToArray(), "A place for every page value.");
// The test site has its own module names, never Instagram's.
@@ -376,9 +379,10 @@ public sealed partial class RequestCatalogTests
Assert.AreEqual(new ValueSource(ValueSourceKind.Session, "entry_nonce"), operation.Headers["x-fb-entry-nonce"], operation.Name);
Assert.AreEqual(new ValueSource(ValueSourceKind.Constant, "359341"), operation.Headers["x-asbd-id"], "The BDHeaderConfig property is not established.");
foreach (var spin in new[] { "__spin_r", "__spin_b", "__spin_t" })
// A snapshot of the page at «Ho finito» (decision of 18 November 2026); the operations stay not configured anyway.
foreach (var spin in new[] { "spin_r", "spin_b", "spin_t" })
{
Assert.AreEqual(ValueSourceKind.Pending, operation.Body[spin].Kind, $"{operation.Name} {spin}: who adds it to the request is not shown.");
Assert.AreEqual(new ValueSource(ValueSourceKind.Session, spin), operation.Body["__" + spin], $"{operation.Name} __{spin}");
}
}
}
@@ -387,17 +391,18 @@ public sealed partial class RequestCatalogTests
public void EveryPendingLeftIsARuntimeValueABrowserHeaderOrARemovedName()
{
// A closed list: what the page computes while it runs (__req, __s, __dyn, __csr, __hblp, __hsdp, __sjsp, __crn,
// __d, __spin_*, x-web-session-id), headers of the browser (referer, priority, sec-ch-ua*, x-ig-max-touch-points)
// __d, x-web-session-id), headers of the browser (referer, priority, sec-ch-ua*, x-ig-max-touch-points)
// and the names the probe removed. Nothing else may stay pending without a decision.
var allowed = new HashSet<string>(StringComparer.Ordinal)
{
"__req", "__s", "__dyn", "__csr", "__hblp", "__hsdp", "__sjsp", "__crn", "__d", "__spin_r", "__spin_b", "__spin_t",
"__req", "__s", "__dyn", "__csr", "__hblp", "__hsdp", "__sjsp", "__crn", "__d",
"x-web-session-id", "referer", "priority", "sec-ch-ua", "sec-ch-ua-mobile", "sec-ch-ua-platform", "x-ig-max-touch-points",
"fb_api_analytics_tags", "qpl_active_flow_ids", RequestCatalog.RemovedName,
};
var pending = RequestCatalog.LoadInstagram().Operations.SelectMany(o => o.PendingValues).Distinct(StringComparer.Ordinal).ToList();
CollectionAssert.AreEqual(Array.Empty<string>(), pending.Where(p => !allowed.Contains(p)).ToArray());
Assert.IsFalse(pending.Contains("__rev") || pending.Contains("x-fb-entry-nonce"), "Settled in S4.");
Assert.IsFalse(pending.Contains("__spin_r") || pending.Contains("__spin_b") || pending.Contains("__spin_t"), "Settled in S4b.");
Assert.AreEqual(0, RequestCatalog.LoadTestSite().Operations.Sum(o => o.PendingValues.Count));
}
@@ -471,7 +476,7 @@ public sealed partial class RequestCatalogTests
[TestMethod]
public void TheNewSessionFieldsAreAcceptedAndUnknownOnesStillRefused()
{
foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce" })
foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t" })
{
var operation = Rest("post2", "/dati/post/{code}");
operation["headers"] = new JsonObject { ["user-agent"] = "session:user_agent", ["x-prova"] = "session:" + field };
@@ -480,7 +485,7 @@ public sealed partial class RequestCatalogTests
Assert.AreEqual(new ValueSource(ValueSourceKind.Session, field), Get(RequestCatalog.Parse(Alone(operation), "richieste.prova.json"), "post2").Headers["x-prova"]);
}
foreach (var field in new[] { "password", "spin_r", "cookie", "sessionid" })
foreach (var field in new[] { "password", "spin", "cookie", "sessionid" })
{
var operation = Rest("post2", "/dati/post/{code}");
operation["headers"] = new JsonObject { ["x-prova"] = "session:" + field };
@@ -91,6 +91,9 @@ public sealed class SessionCaptureIntegrationTests
Assert.IsTrue(apiCookie.HostOnly);
Assert.AreEqual(TestSite.Lsd, values.Fields["lsd"]);
Assert.AreEqual(TestSite.Dpr, values.Fields["dpr"], "a number of the page as text");
Assert.AreEqual(TestSite.SpinRevision, values.Fields["spin_r"], "S4b: __spin_r from the page, a number as text");
Assert.AreEqual(TestSite.SpinBranch, values.Fields["spin_b"]);
Assert.AreEqual(TestSite.SpinTime, values.Fields["spin_t"]);
Assert.AreEqual(TestSite.DocIds[TestSite.ProfileQuery], values.DocIds[TestSite.ProfileQuery]);
lock (site.World.Gate)
{
@@ -405,14 +405,14 @@ public sealed class SiteSessionTests
[TestMethod]
public void TheNewPageFieldsAreSessionFieldsAndTheVocabularyIsClosed()
{
foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "lsd", "fb_dtsg", "app_id", "account_id" })
foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t", "lsd", "fb_dtsg", "app_id", "account_id" })
{
Assert.IsTrue(SiteSessionValues.PageFields.Contains(field), field);
Assert.IsTrue(ValueSource.SessionFields.Contains(field), field);
}
CollectionAssert.AreEquivalent(new[] { "user_agent", "claim", "doc_id" }, ValueSource.SessionFields.Except(SiteSessionValues.PageFields).ToArray());
Assert.IsFalse(ValueSource.SessionFields.Contains("spin_r"), "__spin_* stay pending: who adds them to the request is not shown.");
Assert.IsFalse(ValueSource.SessionFields.Contains("spin"), "The vocabulary is closed.");
}
private static SiteCookie Cookie(string name, string value, DateTimeOffset? expires = null) =>
@@ -111,7 +111,7 @@ public sealed class TestSiteSessionTests
}
Assert.AreEqual(200, await StatusWith("rev", TestSite.Revision), "the right values pass");
foreach (var field in new[] { "rev", "hs", "hsi", "ccg", "dpr", "comet_req", "entry_nonce" })
foreach (var field in new[] { "rev", "hs", "hsi", "ccg", "dpr", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t" })
{
Assert.AreEqual(400, await StatusWith(field, "altro-valore"), field);
}
@@ -118,17 +118,21 @@ public sealed class SavedSessionConnectionTests
await BeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
// He closes the window without «Ho finito»: the lease ends by itself, the page is the engine's again.
// He puts the window away without «Ho finito»: the lease ends by itself, after the copy of S4b (its page is still
// his until then), and the page is the engine's again.
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida");
browser.FakeCdp.Navigated(Site + "/");
Assert.AreEqual(1, browser.FakeCdp.CaptureReads, "copied once, before the lease ended");
var copied = bed.App.SavedSession!.Read();
Assert.IsNotNull(copied);
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsTrue(finish.GetProperty("connected").GetBoolean());
StringAssert.Contains(finish.GetProperty("message").GetString(), "non è stata copiata");
Assert.AreEqual(0, browser.FakeCdp.CaptureReads, "nothing is read from a page that is not his");
Assert.IsNull(bed.App.SavedSession!.Read());
Assert.AreEqual(1, browser.FakeCdp.CaptureReads, "nothing is read from a page that is not his");
Assert.AreSame(copied, bed.App.SavedSession.Read());
}
[TestMethod]
@@ -0,0 +1,272 @@
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 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<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()!;
}
}
@@ -196,6 +196,33 @@ internal sealed class FakeBrowser : IFebeBrowser
return Task.CompletedTask;
}
/// <summary>
/// Like Alberto closing the real window «Browser di Febe» (WebView2Host.Done, issue #36, S4b): out of view at once,
/// the copy of the session before the page goes back to the engine (a hold keeps it his meanwhile), then the lease ends.
/// </summary>
public async Task CloseWindowAsync(CancellationToken ct)
{
Hidden++;
if (_lease is null || _context.CopyOnWindowClosed is not { } copy)
{
_lease?.Dispose();
_lease = null;
return;
}
var hold = UserDriving.Begin();
_lease.Dispose();
_lease = null;
try
{
await copy(ct);
}
finally
{
hold.Dispose();
}
}
/// <summary>The next «Scollega» finds a file held by another process (Windows) and cannot delete the profile.</summary>
public bool ProfileLocked { get; set; }
@@ -244,6 +271,9 @@ internal sealed class FakeCdp : ICdpSession
/// </summary>
public JsonObject? PageCapture { get; set; } = DefaultPageCapture();
/// <summary>Called when the copy's evaluation is asked, before it answers (what the test wants to look at then).</summary>
public Action? OnCapture { get; set; }
/// <summary>How many times the copy's evaluation (the one that reads <c>navigator.userAgent</c>) was asked.</summary>
public int CaptureReads => Volatile.Read(ref _captureReads);
@@ -267,6 +297,9 @@ internal sealed class FakeCdp : ICdpSession
["comet_req"] = Febe.SitoDiProva.TestSite.CometReq,
["ccg"] = Febe.SitoDiProva.TestSite.ConnectionClass,
["entry_nonce"] = Febe.SitoDiProva.TestSite.EntryNonce,
["spin_r"] = Febe.SitoDiProva.TestSite.SpinRevision,
["spin_b"] = Febe.SitoDiProva.TestSite.SpinBranch,
["spin_t"] = Febe.SitoDiProva.TestSite.SpinTime,
},
["docIds"] = new JsonObject { [Febe.SitoDiProva.TestSite.ProfileQuery] = Febe.SitoDiProva.TestSite.DocIds[Febe.SitoDiProva.TestSite.ProfileQuery] },
};
@@ -366,6 +399,7 @@ internal sealed class FakeCdp : ICdpSession
private JsonObject Capture()
{
Interlocked.Increment(ref _captureReads);
OnCapture?.Invoke();
return PageCapture is { } page
? new JsonObject { ["result"] = new JsonObject { ["type"] = "object", ["value"] = JsonNode.Parse(page.ToJsonString()) } }
: new JsonObject();