Unione di funzione/sessione-s4b in funzione/codec-immagini (catena della 0.3.0)
Porta nel ramo dei codec le regole e le risposte del 25 novembre (ramo dei documenti) e la tappa S4b della sessione salvata, così che il ramo si unisca in main dopo i due precedenti senza conflitti da risolvere di nuovo. Conflitti risolti tenendo le due intenzioni: - Directory.Packages.props: il commento «Niente componenti esterni» dei documenti, senza le righe di SkiaSharp, che questo ramo ha già tolto (C1). - docs/decisioni.md: tutte le righe aggiunte dai due lati, prima le 39 della catena (documenti e S4b), poi le 23 dei codec. - docs/docker.md: ffmpeg «fino alla tappa C3» dei documenti più la riga dei codec «Nessuna libreria per le immagini». - docs/guida/Sviluppo.md: la regola «Niente componenti esterni» dei documenti, con SkiaSharp detto già uscito con la tappa C1 e i codec e il disegnatore di casa che lo sostituiscono. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
a0e7404297
62 files changed
+2944
-242
No files matched your search
@@ -279,7 +279,7 @@ public sealed class SessionCaptureTests
|
||||
.CopyAsync(() => true, CancellationToken.None);
|
||||
Assert.AreEqual(1, needed.MissingValues);
|
||||
Assert.AreEqual(0, needed.MissingDocIds);
|
||||
StringAssert.Contains(log[^1], "mancano app_id, che servono alle operazioni configurate");
|
||||
StringAssert.Contains(log[^1], "manca app_id, che serve alle operazioni configurate");
|
||||
|
||||
// With the shipped catalog the query is configured: its doc_id counts.
|
||||
var shipped = await new BrowserSessionCopier(Page($"http://{SiteHost}/", page: page), Plan, new InMemorySiteSession(null), new VirtualClock(), log.Add)
|
||||
@@ -289,6 +289,154 @@ 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], "manca lsd, che serve alle operazioni configurate");
|
||||
|
||||
// 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 AChoiceThatCannotBeReadIsTheDefaultAndTheCopyGoesOn()
|
||||
{
|
||||
// The setting lives in the database: a failure there must not make «Ho finito» fail (the lease would stay held).
|
||||
var log = new List<string>();
|
||||
var store = new InMemorySiteSession(null);
|
||||
await new BrowserSessionCopier(Page($"http://{SiteHost}/"), Plan, store, new VirtualClock(), log.Add).CopyAsync(() => true, CancellationToken.None);
|
||||
var complete = store.Read();
|
||||
Assert.IsNotNull(complete);
|
||||
var lacking = PageValues();
|
||||
((JsonObject)lacking["values"]!).Remove("lsd");
|
||||
var copier = new BrowserSessionCopier(Page($"http://{SiteHost}/", page: lacking), Plan, store, new VirtualClock(), log.Add)
|
||||
{
|
||||
IncompleteCopy = _ => throw new InvalidOperationException("prova: impostazione illeggibile"),
|
||||
};
|
||||
|
||||
var outcome = await copier.CopyAsync(() => true, CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(SessionCopyStatus.Saved, outcome.Status, "«Sostituisci comunque», the default");
|
||||
Assert.AreNotSame(complete, store.Read());
|
||||
var text = string.Join("\n", log);
|
||||
StringAssert.Contains(text, "Scelta per la copia incompleta non letta (InvalidOperationException)");
|
||||
Assert.DoesNotContain("impostazione illeggibile", text, "the kind of error only (rule 10)");
|
||||
AssertNoSecret(text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ThePageIsLookedAtLastAfterTheChoiceIsRead()
|
||||
{
|
||||
// Rule 7: nothing awaited between the last look at whose page it is and the decision on the saved session. Here
|
||||
// the page goes back to the engine while the choice is read: the copy is thrown away, not kept nor saved.
|
||||
var store = new InMemorySiteSession(null);
|
||||
await new BrowserSessionCopier(Page($"http://{SiteHost}/"), Plan, store, new VirtualClock(), _ => { }).CopyAsync(() => true, CancellationToken.None);
|
||||
var complete = store.Read();
|
||||
var lacking = PageValues();
|
||||
((JsonObject)lacking["values"]!).Remove("lsd");
|
||||
var lost = false;
|
||||
var copier = new BrowserSessionCopier(Page($"http://{SiteHost}/", page: lacking), Plan, store, new VirtualClock(), _ => { })
|
||||
{
|
||||
IncompleteCopy = _ =>
|
||||
{
|
||||
lost = true;
|
||||
return Task.FromResult(IncompleteCopyChoice.KeepComplete);
|
||||
},
|
||||
};
|
||||
|
||||
var outcome = await copier.CopyAsync(() => !lost, CancellationToken.None);
|
||||
|
||||
Assert.IsTrue(lost, "the choice was read");
|
||||
Assert.AreEqual(SessionCopyStatus.Discarded, outcome.Status);
|
||||
Assert.AreSame(complete, store.Read());
|
||||
}
|
||||
|
||||
[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 +530,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);
|
||||
}
|
||||
|
||||
@@ -109,7 +109,7 @@ public sealed class SavedSessionConnectionTests
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task ALateHoFinitoAfterTheLeaseEndedDoesNotCopy()
|
||||
public async Task ALateHoFinitoAfterTheLeaseEndedReadsNothingAndSaysTheSessionWasAlreadyCopied()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await StartAsync();
|
||||
@@ -118,17 +118,38 @@ public sealed class SavedSessionConnectionTests
|
||||
|
||||
await BeginAsync(bed);
|
||||
browser.FakeCdp.LoggedIn = true;
|
||||
|
||||
// He closes the window without «Ho finito»: the lease ends by itself, 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 + "/");
|
||||
|
||||
// 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");
|
||||
Assert.AreEqual(1, browser.FakeCdp.CaptureReads, "copied once, before the lease ended");
|
||||
var copied = bed.App.SavedSession!.Read();
|
||||
Assert.IsNotNull(copied);
|
||||
|
||||
// «Ho finito» pressed late: nothing is read from a page that is not his, and he is not asked to log in again
|
||||
// for a session copied a moment before.
|
||||
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
|
||||
Assert.IsTrue(finish.GetProperty("connected").GetBoolean());
|
||||
var message = finish.GetProperty("message").GetString()!;
|
||||
StringAssert.Contains(message, "era già stata copiata quando il browser è tornato al motore");
|
||||
StringAssert.Contains(message, "Non serve rifare l'accesso");
|
||||
Assert.DoesNotContain("non è stata copiata", message);
|
||||
Assert.DoesNotContain("Rifai l'accesso", message);
|
||||
Assert.AreEqual(1, browser.FakeCdp.CaptureReads, "nothing is read from a page that is not his");
|
||||
Assert.AreSame(copied, bed.App.SavedSession.Read());
|
||||
|
||||
// A new use of the browser whose end copies nothing (the login page): a late «Ho finito» now says that this time
|
||||
// the session was not copied, even if an earlier use had copied it.
|
||||
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");
|
||||
finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
|
||||
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);
|
||||
Assert.AreSame(copied, bed.App.SavedSession.Read());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -0,0 +1,601 @@
|
||||
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 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 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// «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).
|
||||
/// </summary>
|
||||
private async Task<IDisposable> DockerBeginAsync(DesktopTestBed bed)
|
||||
{
|
||||
await BeginAsync(bed, openLogin: false);
|
||||
await bed.Browser!.HideFromUserAsync(TestContext.CancellationToken);
|
||||
return bed.Browser.UserDriving.Begin();
|
||||
}
|
||||
|
||||
/// <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,34 @@ 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.
|
||||
/// <paramref name="how"/>: closed, or left minimised too long.
|
||||
/// </summary>
|
||||
public async Task CloseWindowAsync(CancellationToken ct, BrowserWindowLetGo how = BrowserWindowLetGo.Closed)
|
||||
{
|
||||
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(how, 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 +272,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 +298,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 +400,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();
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Febe.Tests.Docs;
|
||||
|
||||
/// <summary>
|
||||
/// The documents agree with each other where a review of the 18 November 2026 changes found them apart: the rule on
|
||||
/// external components allows only gitleaks, Trivy, Xvfb and the Debian packages Chromium needs, and every other
|
||||
/// component the project still uses says in which stage of 0.3.0 it leaves; no hypothesis of spec §6.6 is called
|
||||
/// verified without an outcome in docs/sonda/esito.md; the questions Alberto answered are not open any more; and the
|
||||
/// paragraphs of §2, §3, §4.10, §6.0, §6.1, §6.6, §13.2, §14.1 and §15 that were contradictory or unbounded say what
|
||||
/// settles them. Since 25 November 2026 also Alberto's answers of that day (the session copied when the browser page is
|
||||
/// left in Docker, the fonts of the Docker image, damaged images refused without a perceptual hash, HEVC RExt kept)
|
||||
/// and the features of issue #59 (download order, Dashboard, grouped or per-file mosaic, stage D1).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed partial class SpecificationConsistencyTests
|
||||
{
|
||||
/// <summary>Packages that rule 13 allows for good; any other one must say in which stage it leaves.</summary>
|
||||
private static readonly string[] AllowedPackages = ["Microsoft.Data.Sqlite", "Microsoft.Web.WebView2", "MSTest"];
|
||||
|
||||
/// <summary>The only exceptions the rule allows besides .NET, Microsoft.Data.Sqlite, the browser and MSTest.</summary>
|
||||
private static readonly string[] Exceptions = ["gitleaks e Trivy", "Xvfb", "pacchetti Debian che gli servono"];
|
||||
|
||||
/// <summary>
|
||||
/// Components still in use that the rule must name, each with the stage of 0.3.0 it leaves with: the first stage
|
||||
/// named after the last mention of the component.
|
||||
/// </summary>
|
||||
private static readonly (string Component, string Stage)[] Leaving =
|
||||
[
|
||||
("SkiaSharp", "C1"), ("ffmpeg", "C3"), ("NSIS", "C6"), ("Node", "C6"), ("Archivo", "C6"), ("Lucide", "C6"),
|
||||
];
|
||||
|
||||
/// <summary>Questions of spec §16 that Alberto answered, with the day of the answer: their row must say so.</summary>
|
||||
private static readonly (string Number, string Day)[] AnsweredQuestions =
|
||||
[
|
||||
("13", "18 novembre 2026"), ("14", "18 novembre 2026"), ("15", "18 novembre 2026"), ("16", "18 novembre 2026"),
|
||||
("17", "18 novembre 2026"), ("18", "25 novembre 2026"),
|
||||
];
|
||||
|
||||
/// <summary>Phrases that called those answers still open; none may be left in the specification.</summary>
|
||||
private static readonly string[] StaleProposals =
|
||||
[
|
||||
"da confermare con alberto (§16, domande 15 e 16)",
|
||||
"se alberto lo conferma",
|
||||
"proposta da confermare con alberto, §16 domanda 14",
|
||||
"oggi copia solo «ho finito»",
|
||||
"oggi una copia incompleta sostituisce sempre",
|
||||
"in docker ci sono solo il primo e l'ultimo",
|
||||
"proposta da confermare con alberto all'inizio di c4",
|
||||
"quattro voci (libreria, account, attività, importa)",
|
||||
"la pagina attività",
|
||||
"in attività",
|
||||
"da attività",
|
||||
"caratteri di sistema compresi quelli per le emoji",
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// (point, start of the line in docs/SPECIFICA.md, phrases that line must all contain). Phrases are compared like
|
||||
/// <see cref="GuideTests.Normalize"/>: no case, no emphasis.
|
||||
/// </summary>
|
||||
public static IEnumerable<object[]> SettledPoints =>
|
||||
[
|
||||
["«Collegato» vuole la sessione salvata solo quando si costruisce", "**«Collegato», con «richieste»**", new[] { "almeno un'operazione configurata", "tappa s4b", "serve «ho finito»", "mai i valori" }],
|
||||
["la sessione si copia anche lasciando il browser, prima che la pagina torni al motore", "**Quando si copia**", new[] { "tappa s4b", "prima che la pagina torni al motore", "chiude la finestra «browser di febe»", "il permesso di guida finisce da solo", "la presa del permesso di guida e il turno della pagina", "10 secondi" }],
|
||||
["il permesso e il turno si tengono per tutta la copia, in ogni momento", "La copia si fa solo da una pagina del sito", new[] { "tiene il permesso e il turno della pagina per tutta la copia", "alla chiusura della finestra e alla fine del permesso", "«quando si copia»" }],
|
||||
["la copia incompleta segue l'opzione", "**Copia incompleta**", new[] { "`sessione.copia-incompleta`", "tappa s4b", "«sostituisci comunque»", "le richieste continuano a usarla" }],
|
||||
["il comando CDP della copia dice i tre momenti", "| Copiare la sessione", new[] { "a «ho finito»", "alla chiusura della finestra «browser di febe»", "alla fine del permesso di guida", "prima che la pagina torni al motore" }],
|
||||
["spin_r, spin_b e spin_t hanno un posto nella tabella dei valori", "| `spin_r`, `spin_b`, `spin_t` |", new[] { "`sitedata.__spin_r`", "h23" }],
|
||||
["spin_r, spin_b e spin_t non sono più pending", "- `__spin_r`, `__spin_b`, `__spin_t`", new[] { "non sono più `pending`", "h23" }],
|
||||
["H23 sta fra le ipotesi", "| H23 |", new[] { "sitedata", "da verificare da alberto", "graphql/query" }],
|
||||
["la regola 11 lascia alla pagina Collegamento solo data, conteggi e nomi", "11. **Segreti fuori dai registri", new[] { "la pagina collegamento ne mostra solo la data della copia, i conteggi e i nomi dei valori che mancano, mai un valore" }],
|
||||
["§13.2 lascia alla pagina Collegamento solo data, conteggi e nomi", "- La sessione di Instagram vive nel profilo", new[] { "solo la data della copia, i conteggi", "i nomi di quelli che mancano, mai un valore" }],
|
||||
["browser e client mai nello stesso momento", "**Niente browser e client insieme", new[] { "nello stesso momento", "una alla volta" }],
|
||||
["H21 e H22 restano da verificare", "- H21 (`require()`", new[] { "restano da verificare", "docs/sonda/esito.md" }],
|
||||
["lo stesso post in due account: «Una copia per account» è il predefinito", "- **Lo stesso post in due account**", new[] { "«una copia per account»", "predefinito", "«una copia sola»" }],
|
||||
["una copia ha l'account effettivo nella sua identità", "- Una riga per copia (`export_copy`)", new[] { "account effettivo" }],
|
||||
["lo stesso SHA-256 due volte nella cartella generale", "- **Una storia entrata in una raccolta in evidenza**", new[] { "per lo stesso account effettivo", "due volte nella cartella generale" }],
|
||||
["l'adozione non si fida della sola dimensione", "- **Adozione per percorso**", new[] { "rifà la conversione", "la sola dimensione non basta mai", "nome libero" }],
|
||||
["le immagini animate si copiano come originali", "| Foto |", new[] { "immagini animate", "`acTL`", "`anim`/`anmf`" }],
|
||||
["il file di prova delle cartelle rifiutate è un .part nella sola candidata", "- Cartelle rifiutate", new[] { "`.febe-prova-*.part`", "solo nella cartella candidata", "mai in dati, libreria, cartelle degli account o `/importa`" }],
|
||||
["i decodificatori dicono il loro sottoinsieme", "- decodificatori di immagini:", new[] { "rfc 6386", "codifica aritmetica", "precisione a 12 bit" }],
|
||||
["il decodificatore H.264 copre tutto lo standard", "- decodificatore H.264", new[] { "tutto lo standard", "extended", "high 10", "high 4:4:4", "piani di colore separati", "senza perdita", "monocromatico", "paff", "mbaff", "svc", "mvc", "cabac" }],
|
||||
["il decodificatore H.265 è dentro la 0.3.0 e tiene RExt", "- decodificatore H.265/HEVC", new[] { "tappa c4", "main 10", "domanda 18", "risposta di alberto del 25 novembre 2026", "estensioni di formato (rext)", "che restano", "fino a 12 bit", "fotogramma non disponibile per questo video" }],
|
||||
["VP9 e AV1 hanno la tessera neutra", "- VP9, AV1", new[] { "tessera neutra", "fotogramma non disponibile per questo video" }],
|
||||
["i lettori dei contenitori comprendono ASF, FLV e MPEG-PS", "- lettori dei contenitori ASF", new[] { "flv", "mpeg-ps", "13818-1", "durata, dimensioni, codec e data", "tappa c5" }],
|
||||
["l'installatore si scrive in casa", "- l'installatore di Windows", new[] { "al posto di nsis", "tappa c6" }],
|
||||
["la CI non vuole Node", "- i passi della CI", new[] { "node", "git", "curl verso l'api di gitea", "tappa c6" }],
|
||||
["le serie di conformità stanno nel repository con la loro fonte", "- Le serie di conformità ITU-T", new[] { "h.264.1", "h.265.1", "solo i flussi e l'md5 dell'uscita di riferimento", "`leggimi.md` che dice la fonte" }],
|
||||
["SkiaSharp esce anche dal disegno", "- ridimensionamento", new[] { "brandicon", "demoimages", "importpreview", "mediafactory", "librarytestsupport", "importtestfiles" }],
|
||||
["le prove dei codec con perdita hanno una tolleranza", "- **Codec e video**", new[] { "psnr", "esattamente per png" }],
|
||||
["C1 comprende disegno e tolleranze", "| **C1 Codec delle immagini** |", new[] { "disegnatore 2d", "tolleranze di §14.1" }],
|
||||
["C3 copre tutto H.264 e tutti i flussi", "| **C3 Decodificatore H.264** |", new[] { "tutto lo standard", "tutti i flussi di itu-t h.264.1", "nessuno saltato", "permesso di alberto", "`leggimi.md`" }],
|
||||
["C4 porta HEVC con i flussi H.265.1, RExt compreso", "| **C4 Decodificatore H.265** |", new[] { "itu-t h.265.1", "nessuno saltato", "`leggimi.md`", "rext", "`hevc_v1`" }],
|
||||
["C5 porta i lettori ASF, FLV e MPEG-PS", "| **C5 Lettori ASF, FLV e MPEG-PS** |", new[] { "asf", "flv", "13818-1", "file costruiti dalle prove" }],
|
||||
["C6 toglie Node, NSIS, Archivo e Lucide", "| **C6 Niente terzi nella CI e nell'interfaccia** |", new[] { "senza node", "al posto di nsis", "al posto di archivo", "al posto di lucide", "gitleaks e trivy" }],
|
||||
["le tappe C4–C6 e D1 hanno le loro dipendenze", "Dipendenze: C1", new[] { "c3 → c4", "c5 dopo c2", "c6 indipendente", "d1 indipendente" }],
|
||||
["in Docker lasciare la pagina del browser copia la sessione", "**Quando si copia**", new[] { "lasciare la pagina del browser", "risposta di alberto del 25 novembre 2026", "pagina «browser»", "vista remota della pagina collegamento", "chiudere la scheda", "per 5 secondi", "ricaricare la pagina non è lasciarla", "lasciando la pagina in docker e alla fine del permesso la copia ha le stesse garanzie" }],
|
||||
["il comando CDP della copia comprende la pagina lasciata in Docker", "| Copiare la sessione", new[] { "25 novembre 2026", "in docker lasciando la pagina del browser o chiudendone la scheda" }],
|
||||
["l'immagine Docker tiene le emoji e non Liberation", "- **Immagine.**", new[] { "`fonts-noto-color-emoji`, che resta", "`fonts-liberation` esce", "25 novembre 2026" }],
|
||||
["un'immagine troncata non ha impronta e resta", "- **Immagini troncate o rovinate**", new[] { "«file danneggiato o incompleto»", "nessuna impronta visiva", "mai doppione probabile per impronta", "resta in libreria", "25 novembre 2026" }],
|
||||
["il visualizzatore dice «File danneggiato o incompleto»", "- **File danneggiato o incompleto**", new[] { "tessera neutra", "visualizzatore", "resta in libreria", "non lo riscarica" }],
|
||||
["l'importazione non fa doppioni per impronta di un'immagine troncata", "I doppioni si cercano anche dentro la sorgente stessa", new[] { "mai «doppione probabile» per impronta", "«file danneggiato o incompleto»" }],
|
||||
["«Cosa scaricare prima» pesa visite e coda senza cambiare il resto", "- **Cosa scaricare prima** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026). Un ordine", new[] { "storie, evidenza, post, reel, taggati", "dopo il giro dei seguiti, che resta sempre primo", "visite del motore nella sessione", "coda dei file", "«come le impostazioni generali», il predefinito", "il governatore e i tetti", "le frequenze", "composizione casuale delle sessioni", "non le rende fisse", "§16 domanda 19" }],
|
||||
["«Cosa scaricare prima» c'è anche per account", "- **Cosa scaricare prima** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026): «Come", new[] { "«come le impostazioni generali» (predefinito)", "trascinando", "§7.2, §6.5" }],
|
||||
["la coda dei file segue «Cosa scaricare prima»", "6. Coda dedicata", new[] { "«cosa scaricare prima»", "prima i file del tipo che viene primo", "le foto del profilo vanno con i post" }],
|
||||
["il peso di un tipo ha i suoi numeri", "| Peso di un tipo nella scelta", new[] { "16, 8, 4, 2, 1", "proposta" }],
|
||||
["la Dashboard è il cruscotto e la pagina iniziale", "La **Dashboard**", new[] { "cruscotto del motore", "pagina iniziale", "`/dashboard`", "`/attivita`", "la finestra di febe per windows si apre lì", "compatta" }],
|
||||
["la Dashboard mostra sempre l'anteprima del browser", "- **l'anteprima del browser, sempre visibile**", new[] { "che scorre", "mai nascosta dietro un clic" }],
|
||||
["la cronologia ha le miniature e l'anteprima ingrandita", "- la **cronologia dell'attività**", new[] { "miniature", "anteprima ingrandita", "«apri nella libreria»", "«apri l'account»" }],
|
||||
["la Dashboard è la prima voce della barra laterale", "Barra laterale fissa", new[] { "quattro voci (dashboard, libreria, account, importa)", "prima voce e la pagina iniziale" }],
|
||||
["«Raggruppa i post» o «Tutte le foto», ricordato per pagina", "- **«Raggruppa i post» o «Tutte le foto»**", new[] { "libreria e della vista dei contenuti della scheda account", "il predefinito", "una tessera per file", "una per la libreria e una per le viste degli account", "dentro un `try`", "vale «raggruppa i post»", "200.000 elementi" }],
|
||||
["la Dashboard è composta dai mockup", "- **Dashboard** (§7.9), dai mockup 06 e 11", new[] { "mockup 01", "dialogo leggero" }],
|
||||
["D1 ha le sue prove", "| **D1 Dashboard e ordine** |", new[] { "issue #59", "«cosa scaricare prima»", "`/dashboard`", "«raggruppa i post» / «tutte le foto»", "simulazione di 30 giorni", "il giro resta primo" }],
|
||||
["la domanda sulle raccolte in evidenza propone il loro posto", "| 19 |", new[] { "storie, evidenza, post, reel, taggati" }],
|
||||
["il glossario ha la Dashboard", "| Dashboard |", new[] { "`dashboard`", "attività" }],
|
||||
["il glossario ha «Cosa scaricare prima»", "| Cosa scaricare prima |", new[] { "`downloadorder`" }],
|
||||
["il glossario ha «Raggruppa i post»", "| Raggruppa i post |", new[] { "tessera per elemento" }],
|
||||
["il glossario ha «Tutte le foto»", "| Tutte le foto |", new[] { "tessera per file" }],
|
||||
];
|
||||
|
||||
private static string Root() => Directory.GetParent(GuideTests.GuideFolder())!.Parent!.FullName;
|
||||
|
||||
private static string Read(params string[] parts) => File.ReadAllText(Path.Combine([Root(), .. parts]));
|
||||
|
||||
[TestMethod]
|
||||
[DynamicData(nameof(SettledPoints))]
|
||||
public void TheSpecificationSettlesThePoint(string point, string start, string[] phrases)
|
||||
{
|
||||
var line = Read("docs", "SPECIFICA.md").Split('\n').FirstOrDefault(l => l.StartsWith(start, StringComparison.Ordinal));
|
||||
Assert.IsNotNull(line, $"«{point}»: nessuna riga di SPECIFICA.md comincia con «{start}»");
|
||||
var text = GuideTests.Normalize(line);
|
||||
var missing = phrases.Where(p => !text.Contains(GuideTests.Normalize(p), StringComparison.Ordinal)).ToList();
|
||||
Assert.IsEmpty(missing, $"«{point}»: mancano: {string.Join(" | ", missing)}");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheRuleOnExternalComponentsIsTheSameEverywhereAndSaysWhenEachComponentLeaves()
|
||||
{
|
||||
var claude = RuleLine(Read("CLAUDE.md"), "12. Niente componenti esterni");
|
||||
var appendix = RuleLine(Read("docs", "SPECIFICA.md")[Read("docs", "SPECIFICA.md").IndexOf("## Appendice A", StringComparison.Ordinal)..], "12. Niente componenti esterni");
|
||||
Assert.AreEqual(claude, appendix, "la regola 12 di CLAUDE.md e la sua copia nell'appendice A della specifica differiscono");
|
||||
|
||||
var spec = Read("docs", "SPECIFICA.md");
|
||||
var rule13 = RuleLine(spec, "13. **Niente componenti esterni**");
|
||||
var guide = Read("docs", "guida", "Sviluppo.md");
|
||||
var guideRule = guide[guide.IndexOf("- **Niente componenti esterni**", StringComparison.Ordinal)..];
|
||||
guideRule = guideRule[..guideRule.IndexOf("\n-", StringComparison.Ordinal)];
|
||||
var problems = new List<string>();
|
||||
foreach (var (name, raw) in new[] { ("CLAUDE.md, regola 12", claude), ("SPECIFICA §2, regola 13", rule13), ("guida/Sviluppo.md", guideRule) })
|
||||
{
|
||||
var text = GuideTests.Normalize(raw);
|
||||
problems.AddRange(Exceptions.Where(e => !text.Contains(GuideTests.Normalize(e), StringComparison.Ordinal)).Select(e => $"{name} non ammette per nome «{e}»"));
|
||||
if (text.Contains("da confermare", StringComparison.Ordinal))
|
||||
{
|
||||
problems.Add($"{name} lascia ancora qualcosa «da confermare»: Alberto ha risposto (§16, domanda 17)");
|
||||
}
|
||||
|
||||
foreach (var (component, stage) in Leaving)
|
||||
{
|
||||
var last = text.LastIndexOf(component.ToLowerInvariant(), StringComparison.Ordinal);
|
||||
if (last < 0)
|
||||
{
|
||||
problems.Add($"{name} non nomina {component}");
|
||||
continue;
|
||||
}
|
||||
|
||||
var next = Stage().Match(text, last);
|
||||
if (!next.Success || !string.Equals(next.Value, stage.ToLowerInvariant(), StringComparison.Ordinal))
|
||||
{
|
||||
problems.Add($"{name}: {component} esce con la tappa {stage}, il testo dice «{(next.Success ? next.Value : "nessuna tappa")}»");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsEmpty(problems, string.Join("\n", problems));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheAnsweredQuestionsAreNotOpenAnyMore()
|
||||
{
|
||||
var spec = Read("docs", "SPECIFICA.md");
|
||||
var start = spec.IndexOf("## 16. Domande aperte per Alberto", StringComparison.Ordinal);
|
||||
Assert.IsGreaterThanOrEqualTo(0, start, "la specifica non ha §16");
|
||||
var lines = spec[start..spec.IndexOf("## Appendice A", start, StringComparison.Ordinal)].Split('\n');
|
||||
var problems = new List<string>();
|
||||
foreach (var (number, day) in AnsweredQuestions)
|
||||
{
|
||||
var row = lines.FirstOrDefault(l => l.StartsWith($"| {number} |", StringComparison.Ordinal));
|
||||
if (row is null)
|
||||
{
|
||||
problems.Add($"§16 non ha la domanda {number}");
|
||||
continue;
|
||||
}
|
||||
|
||||
var text = GuideTests.Normalize(row);
|
||||
if (!text.Contains($"risposta di alberto del {day}", StringComparison.Ordinal) && !text.Contains($"risposte di alberto del {day}", StringComparison.Ordinal))
|
||||
{
|
||||
problems.Add($"la domanda {number} di §16 non dice la risposta di Alberto del {day}");
|
||||
}
|
||||
}
|
||||
|
||||
var normalized = GuideTests.Normalize(spec);
|
||||
problems.AddRange(StaleProposals.Where(p => normalized.Contains(p, StringComparison.Ordinal)).Select(p => $"la specifica dice ancora «{p}», ma Alberto ha risposto"));
|
||||
Assert.IsEmpty(problems, string.Join("\n", problems));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryMentionOfFfmpegSaysThatItLeavesWithStageC3()
|
||||
{
|
||||
var problems = new List<string>();
|
||||
foreach (var file in new[] { "CLAUDE.md", "docs/docker.md", "docs/processo.md", "docs/guida/Sviluppo.md" })
|
||||
{
|
||||
var lines = Read(file.Split('/')).Split('\n');
|
||||
for (var i = 0; i < lines.Length; i++)
|
||||
{
|
||||
var line = lines[i];
|
||||
if (!line.Contains("ffmpeg", StringComparison.OrdinalIgnoreCase) || line.Contains("niente ffmpeg", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!line.Contains("C3", StringComparison.Ordinal))
|
||||
{
|
||||
problems.Add($"{file}:{i + 1}: ffmpeg senza la tappa C3 in cui esce");
|
||||
}
|
||||
|
||||
if (line.Contains("C2–C3", StringComparison.Ordinal) || line.Contains("C2-C3", StringComparison.Ordinal))
|
||||
{
|
||||
problems.Add($"{file}:{i + 1}: ffmpeg esce con la tappa C3, non con C2–C3");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsEmpty(problems, string.Join("\n", problems));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryPackageIsAllowedOrSaysInWhichStageItLeaves()
|
||||
{
|
||||
var lines = Read("Directory.Packages.props").Split('\n');
|
||||
Assert.IsTrue(lines.Any(l => l.Contains("<!-- Niente componenti esterni", StringComparison.Ordinal)), "Directory.Packages.props non nomina la regola «Niente componenti esterni»");
|
||||
var lastComment = string.Empty;
|
||||
var problems = new List<string>();
|
||||
foreach (var line in lines)
|
||||
{
|
||||
if (line.Contains("<!--", StringComparison.Ordinal))
|
||||
{
|
||||
lastComment = line;
|
||||
}
|
||||
|
||||
var match = PackageVersion().Match(line);
|
||||
if (!match.Success)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var name = match.Groups["name"].Value;
|
||||
if (!AllowedPackages.Contains(name, StringComparer.Ordinal) && !StageComment().IsMatch(lastComment))
|
||||
{
|
||||
problems.Add($"{name}: non è ammesso dalla regola 13 e nessun commento dice in quale tappa esce");
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsEmpty(problems, string.Join("\n", problems));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NoHypothesisIsCalledVerifiedWithoutAnOutcome()
|
||||
{
|
||||
var outcomes = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (Match row in OutcomeRow().Matches(Read("docs", "sonda", "esito.md")))
|
||||
{
|
||||
outcomes.Add(row.Groups["id"].Value);
|
||||
}
|
||||
|
||||
var problems = new List<string>();
|
||||
foreach (var line in Read("docs", "SPECIFICA.md").Split('\n'))
|
||||
{
|
||||
foreach (Match claim in VerifiedClaim().Matches(line))
|
||||
{
|
||||
// The ids the claim is about are those of its own sentence or table cell.
|
||||
var start = line.LastIndexOfAny(['.', ';', '|'], Math.Max(0, claim.Index - 1)) + 1;
|
||||
var row = OutcomeRow().Match(line);
|
||||
var sentence = line[start..claim.Index];
|
||||
var ids = HypothesisId().Matches(sentence).Select(m => m.Value).ToList();
|
||||
if (row.Success && row.Index == 0)
|
||||
{
|
||||
ids.Add(row.Groups["id"].Value);
|
||||
}
|
||||
|
||||
problems.AddRange(ids.Where(id => !outcomes.Contains(id)).Select(id => $"{id} è detta verificata, ma docs/sonda/esito.md non ne ha l'esito"));
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsEmpty(problems, string.Join("\n", problems.Distinct()));
|
||||
}
|
||||
|
||||
private static string RuleLine(string text, string start)
|
||||
{
|
||||
var line = text.Split('\n').FirstOrDefault(l => l.StartsWith(start, StringComparison.Ordinal));
|
||||
Assert.IsNotNull(line, $"nessuna riga comincia con «{start}»");
|
||||
return line;
|
||||
}
|
||||
|
||||
[GeneratedRegex("<PackageVersion Include=\"(?<name>[^\"]+)\"")]
|
||||
private static partial Regex PackageVersion();
|
||||
|
||||
[GeneratedRegex(@"tappa C\d")]
|
||||
private static partial Regex StageComment();
|
||||
|
||||
/// <summary>A stage of 0.3.0 in normalized (lower-case) text.</summary>
|
||||
[GeneratedRegex(@"\bc\d\b")]
|
||||
private static partial Regex Stage();
|
||||
|
||||
[GeneratedRegex(@"^\| (?<id>[HS]\d+) \|", RegexOptions.Multiline)]
|
||||
private static partial Regex OutcomeRow();
|
||||
|
||||
[GeneratedRegex(@"(?i)verificat[ae] da alberto|le ha verificate")]
|
||||
private static partial Regex VerifiedClaim();
|
||||
|
||||
[GeneratedRegex(@"\b[HS]\d+\b")]
|
||||
private static partial Regex HypothesisId();
|
||||
}
|
||||
@@ -132,6 +132,33 @@ public sealed class RemoteViewStartTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task OnlyAViewClosedByItsPageIsToldToTheConnection()
|
||||
{
|
||||
// Docker (answer of 25 November 2026): a view closed by its page may be Alberto leaving the browser; one replaced
|
||||
// by another tab, one that did not start, or one closed because Febe stops is not.
|
||||
var ct = TestContext.CancellationToken;
|
||||
var told = 0;
|
||||
await using var bed = new Bed(attempt => attempt == 3 ? new CdpDisconnectedException("Il collegamento con il browser si è chiuso.") : null, viewClosed: () => Interlocked.Increment(ref told));
|
||||
|
||||
var older = await bed.Host.OpenAsync(ct);
|
||||
var newer = await bed.Host.OpenAsync(ct);
|
||||
Assert.AreEqual(RemoteViewEnd.Replaced, older.Ended);
|
||||
Assert.AreEqual(0, Volatile.Read(ref told), "replaced by another tab: Alberto is still at the browser");
|
||||
|
||||
await newer.DisposeAsync();
|
||||
Assert.AreEqual(1, Volatile.Read(ref told), "the page closed its view");
|
||||
|
||||
await Assert.ThrowsExactlyAsync<RemoteViewUnavailableException>(() => bed.Host.OpenAsync(ct));
|
||||
Assert.AreEqual(1, Volatile.Read(ref told), "a view that did not start was never the page's");
|
||||
|
||||
var last = await bed.Host.OpenAsync(ct);
|
||||
await bed.Host.ShutdownAsync();
|
||||
Assert.AreEqual(RemoteViewEnd.ShuttingDown, last.Ended);
|
||||
Assert.AreEqual(1, Volatile.Read(ref told), "Febe stopping is not Alberto leaving");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task PaginaInizialeOpensTheStartPageOfTheMoment()
|
||||
@@ -300,7 +327,8 @@ public sealed class RemoteViewStartTests
|
||||
/// tested in BrowserStartPageTests); null: nowhere.
|
||||
/// </param>
|
||||
/// <param name="open">What «Pagina iniziale» does instead (it wins over <paramref name="startPage"/>).</param>
|
||||
public Bed(Func<int, Exception?> startFailure, Func<string>? startPage = null, Func<CancellationToken, Task>? open = null)
|
||||
/// <param name="viewClosed">What the connection is told when a view is closed by its page.</param>
|
||||
public Bed(Func<int, Exception?> startFailure, Func<string>? startPage = null, Func<CancellationToken, Task>? open = null, Action? viewClosed = null)
|
||||
{
|
||||
Clock = new VirtualClock();
|
||||
_start = Clock.Now;
|
||||
@@ -326,7 +354,7 @@ public sealed class RemoteViewStartTests
|
||||
};
|
||||
Browser = new PageBrowser(Cdp);
|
||||
_log = new FebeLog(null, null, Clock);
|
||||
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, openStartPage: open ?? (startPage is null ? null : async ct => await Cdp.NavigateAsync(startPage(), ct)))
|
||||
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, openStartPage: open ?? (startPage is null ? null : async ct => await Cdp.NavigateAsync(startPage(), ct)), viewClosed: viewClosed)
|
||||
{
|
||||
// The virtual clock moves only in the pauses: a watchdog on it would never wait.
|
||||
Watchdog = null,
|
||||
|
||||
@@ -63,19 +63,21 @@ public sealed class ConnectionApiTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task LeavingThePageIsAnnullaInDockerAndOnlyTheEndOfTheHoldOnWindows()
|
||||
public async Task LeavingThePageLetsGoOfTheBrowserInDockerAndOnlyEndsTheHoldOnWindows()
|
||||
{
|
||||
// Docker: the remote view is the page, leaving it gives the browser back to rest.
|
||||
// Docker: the remote view is the page; leaving it lets go of the browser like closing the window on Windows (the
|
||||
// session is copied: answer of 25 November 2026), while the button «Annulla» still cancels.
|
||||
var docker = new RecordingConnection();
|
||||
await using (var server = await Part2.StartAsync(services: s => s.AddSingleton<IConnectionService>(docker)))
|
||||
{
|
||||
var (status, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel", new { pageLeft = true });
|
||||
Assert.AreEqual(HttpStatusCode.NoContent, status);
|
||||
await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel");
|
||||
var (showStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/browser/show");
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, showStatus, "in Docker the browser is the Browser page");
|
||||
}
|
||||
|
||||
CollectionAssert.AreEqual(new[] { "cancel" }, docker.Calls);
|
||||
CollectionAssert.AreEqual(new[] { "leave", "cancel" }, docker.Calls);
|
||||
|
||||
// Windows (issue #52): the window stays as it is; «Annulla» is still «Annulla»; «Apri il browser» says which page.
|
||||
var windows = new RecordingConnection();
|
||||
|
||||
@@ -61,6 +61,33 @@ public sealed class EngineConnectionStateTests
|
||||
Assert.AreEqual(JsonValueKind.Null, (await LinkAsync(EngineMode.NotConnected)).GetProperty("username").ValueKind, "Not connected: no name.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NotConnectedTakesCopyMissingFromTheSnapshotWithoutAskingTheBrowser()
|
||||
{
|
||||
// Issue #36, S4b: the engine already knows whether the copy for the requests is missing (its headline says
|
||||
// «Serve «Ho finito»»); every event of the stream must not cost a look at the browser for it.
|
||||
var connection = new RecordingConnection { Status = new ConnectionStatus(ConnectionState.SessionCopyMissing, null, null, false, null) };
|
||||
await using var server = await Part2.StartAsync(services: s =>
|
||||
{
|
||||
s.AddSingleton<IEngineMonitor>(sp => new FixedModeMonitor(sp.GetRequiredService<IClock>()) { Mode = EngineMode.NotConnected });
|
||||
s.AddSingleton<IConnectionService>(connection);
|
||||
});
|
||||
var monitor = (FixedModeMonitor)server.App.Services.GetRequiredService<IEngineMonitor>();
|
||||
var reads = connection.StatusReads;
|
||||
|
||||
Assert.AreEqual("notConnected", (await server.GetJsonAsync("/api/engine")).GetProperty("connection").Str("state"), "the engine's word, not the connection's");
|
||||
monitor.CopyMissing = true;
|
||||
var engine = await server.GetJsonAsync("/api/engine");
|
||||
Assert.AreEqual("copyMissing", engine.GetProperty("connection").Str("state"));
|
||||
Assert.IsTrue(engine.GetProperty("snapshot").GetProperty("sessionCopyMissing").GetBoolean());
|
||||
Assert.AreEqual(reads, connection.StatusReads, "no status asked while the engine runs");
|
||||
|
||||
// Only when the engine loop does not run is the connection asked.
|
||||
monitor.Mode = EngineMode.Off;
|
||||
Assert.AreEqual("copyMissing", (await server.GetJsonAsync("/api/engine")).GetProperty("connection").Str("state"));
|
||||
Assert.AreEqual(reads + 1, connection.StatusReads);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutEngineAndBrowserTheSidebarSaysNotConnectedEvenIfTuIsKnown()
|
||||
{
|
||||
@@ -76,8 +103,10 @@ public sealed class EngineConnectionStateTests
|
||||
{
|
||||
public EngineMode Mode { get; set; } = EngineMode.Resting;
|
||||
|
||||
public bool CopyMissing { get; set; }
|
||||
|
||||
public Task<EngineSnapshot> GetSnapshotAsync(CancellationToken ct = default) =>
|
||||
Task.FromResult(SnapshotParts.Build(clock, Mode, "Prova", [], "Prova", CautionProfile.Prudent));
|
||||
Task.FromResult(SnapshotParts.Build(clock, Mode, "Prova", [], "Prova", CautionProfile.Prudent) with { SessionCopyMissing = CopyMissing });
|
||||
|
||||
public async IAsyncEnumerable<EngineNotification> SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
|
||||
{
|
||||
|
||||
@@ -47,6 +47,13 @@ public sealed class HostingAndSecurityTests
|
||||
// The text resource is valid JSON with the Italian texts.
|
||||
using var texts = JsonDocument.Parse(files.ReadText("testi/it.json")!);
|
||||
Assert.AreEqual("Libreria", texts.RootElement.GetProperty("nav").GetProperty("libreria").GetString());
|
||||
|
||||
// A count of one has its singular (t() picks the part before «|» when n is 1): never «1 di questi servono».
|
||||
var needed = texts.RootElement.GetProperty("impostazioni").GetProperty("collegamento").GetProperty("salvata").GetProperty("servono").GetString()!;
|
||||
var forms = needed.Split('|');
|
||||
Assert.HasCount(2, forms, needed);
|
||||
StringAssert.StartsWith(forms[0], "{n} di questi serve ");
|
||||
StringAssert.StartsWith(forms[1], "{n} di questi servono ");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -90,12 +90,12 @@ public sealed class InterfaceTests
|
||||
await ui.OpenAsync(new Uri(server.Address, "/browser"));
|
||||
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False") && view.Opened.Count == 1, "il browser in uso con la vista aperta");
|
||||
|
||||
// Another page from the sidebar: the view closes and the lease of «begin» goes too (like «Annulla»).
|
||||
// Another page from the sidebar: the view closes and the page lets go of the browser (not «Annulla»: the session is copied).
|
||||
await ui.EvalAsync("document.querySelector('a[data-nav=libreria]').click()");
|
||||
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
|
||||
await ui.WaitForAsync(() => connection.Snapshot().Contains("cancel"), "il browser restituito lasciando la pagina");
|
||||
await ui.WaitForAsync(() => connection.Snapshot().Contains("leave"), "il browser restituito lasciando la pagina");
|
||||
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa");
|
||||
CollectionAssert.AreEqual(new[] { "begin:False", "cancel" }, connection.Snapshot());
|
||||
CollectionAssert.AreEqual(new[] { "begin:False", "leave" }, connection.Snapshot());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -111,7 +111,7 @@ public sealed class InterfaceTests
|
||||
|
||||
// The document goes away (tab closed, reload, another site): only the page-hide event is left to say so.
|
||||
await ui.SendAsync("Page.navigate", new JsonObject { ["url"] = "about:blank" });
|
||||
await ui.WaitForAsync(() => connection.Snapshot().Contains("cancel"), "il browser restituito chiudendo la scheda");
|
||||
await ui.WaitForAsync(() => connection.Snapshot().Contains("leave"), "il browser restituito chiudendo la scheda");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -180,6 +180,31 @@ public sealed class InterfaceTests
|
||||
Assert.IsFalse((await ui.EvalAsync("document.querySelector('.chi-collegato').textContent.includes('@')")).GetBoolean(), "no «@» without a name");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheIncompleteCopyChoiceIsShownOnlyOnceTheServerSaysWhichOneIsStored()
|
||||
{
|
||||
// «Tieni la copia completa» stored; the page must not show «Sostituisci comunque» meanwhile, nor let a choice be
|
||||
// made that the late answer would then undo.
|
||||
var saved = new SavedSessionStatus(SavedSessionStatus.Present, null, 3, 7, 7, [], 2, 2, [], 0);
|
||||
var connection = new RecordingConnection { Status = Connected with { SavedSession = saved } };
|
||||
await using var server = await DockerAsync(connection, new FakeRemoteViewHost());
|
||||
await server.Db.Settings.SetAsync(Febe.Core.Collection.Requests.SessionCopySettings.IncompleteCopyKey, Febe.Core.Collection.Requests.SessionCopySettings.KeepCompleteText);
|
||||
await using var ui = await UiBrowser.StartAsync();
|
||||
await ui.AddInitScriptAsync(UiBrowser.Requests);
|
||||
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
|
||||
await ui.EvalAsync("window.__hold('/api/connection/settings')");
|
||||
await ui.NavigateAsync("/impostazioni/collegamento");
|
||||
await ui.WaitAsync("document.querySelector('.sessione-salvata input[value=\"tieni-completa\"]') !== null", "riquadro della sessione salvata");
|
||||
await ui.WaitAsync("window.__started['/api/connection/settings'] >= 1", "scelta chiesta al server");
|
||||
Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.sessione-salvata input[type=radio]')].every((i) => !i.checked && i.disabled)")).GetBoolean(), "neither choice shown nor pickable before the answer " + ui.Report());
|
||||
|
||||
await ui.EvalAsync("window.__release('/api/connection/settings')");
|
||||
await ui.WaitAsync("document.querySelector('.sessione-salvata input[value=\"tieni-completa\"]').checked", "la scelta salvata mostrata");
|
||||
Assert.IsFalse((await ui.EvalAsync("document.querySelector('.sessione-salvata input[value=\"sostituisci\"]').checked")).GetBoolean());
|
||||
Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.sessione-salvata input[type=radio]')].every((i) => !i.disabled)")).GetBoolean(), "pickable once known");
|
||||
Assert.IsTrue((await ui.EvalAsync("document.querySelector('.scelta-ignota').hidden")).GetBoolean(), "no warning when the choice was read");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task HoFinitoOnCollegamentoClosesTheRemoteView()
|
||||
{
|
||||
@@ -233,7 +258,7 @@ public sealed class InterfaceTests
|
||||
await ui.NavigateAsync("/libreria");
|
||||
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
|
||||
await ui.WaitForQuietAsync("richieste della pagina finite");
|
||||
CollectionAssert.AreEqual(new[] { "begin:False", "finish", "begin:False", "cancel" }, connection.Snapshot(), "leaving the page gives the browser back");
|
||||
CollectionAssert.AreEqual(new[] { "begin:False", "finish", "begin:False", "leave" }, connection.Snapshot(), "leaving the page gives the browser back");
|
||||
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa");
|
||||
}
|
||||
|
||||
|
||||
@@ -69,6 +69,7 @@ internal sealed class FixedProblems(params ConfigurationProblem[] problems) : IC
|
||||
internal sealed class RecordingConnection : IConnectionService
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private int _statusReads;
|
||||
|
||||
public List<string> Calls { get; } = [];
|
||||
|
||||
@@ -86,7 +87,14 @@ internal sealed class RecordingConnection : IConnectionService
|
||||
}
|
||||
}
|
||||
|
||||
public Task<ConnectionStatus> GetStatusAsync(CancellationToken ct) => Task.FromResult(Status);
|
||||
/// <summary>How many times the status was asked (each one costs the real connection a look at the browser).</summary>
|
||||
public int StatusReads => Volatile.Read(ref _statusReads);
|
||||
|
||||
public Task<ConnectionStatus> GetStatusAsync(CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _statusReads);
|
||||
return Task.FromResult(Status);
|
||||
}
|
||||
|
||||
public Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct)
|
||||
{
|
||||
@@ -116,6 +124,14 @@ internal sealed class RecordingConnection : IConnectionService
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Docker: the page of the browser left without «Ho finito» or «Annulla» (not «Annulla»: it copies).</summary>
|
||||
public Task LeavePageAsync(CancellationToken ct)
|
||||
{
|
||||
Record("leave");
|
||||
Status = Status with { UserIsDriving = false };
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task ReleaseAsync(CancellationToken ct)
|
||||
{
|
||||
Record("release");
|
||||
|
||||
Reference in new issue
Block a user