From cf618d898627f315b52556d79653e6cfdaa55aa8 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 10:30:51 +0200 Subject: [PATCH] Una sessione di raccolta vera della composizione condivisa su WebView2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit L'equivalente per Windows della prova d'insieme del server su Chromium: FebeApp composto come lo compone Febe.exe (DesktopPlatform, DesktopShell, la finestra «Browser di Febe» su un thread di WPF), contro il sito di prova con accesso automatico, un orologio dieci volte più veloce e un fuso in cui è mezzogiorno. Il browser parte da un thread della composizione (il percorso che falliva sul PC di Alberto), si aggiungono marta.prova e luca.prova dall'interfaccia con il gettone di questo avvio, «Controlla ora» su marta.prova, e una sessione del motore agisce sul sito attraverso WebView2 con i permessi del Governatore: i file arrivano interi nella libreria temporanea, scaricati dal CDN del sito di prova attraverso il browser. Nel registro nessun avvio fallito e nessun indirizzo firmato. Co-Authored-By: Claude Opus 5.5 --- .../Support/CompositionSupport.cs | 78 ++++++++ .../WebView2CollectionTests.cs | 168 ++++++++++++++++++ 2 files changed, 246 insertions(+) create mode 100644 tests/Febe.Tests.Windows/Support/CompositionSupport.cs create mode 100644 tests/Febe.Tests.Windows/WebView2CollectionTests.cs diff --git a/tests/Febe.Tests.Windows/Support/CompositionSupport.cs b/tests/Febe.Tests.Windows/Support/CompositionSupport.cs new file mode 100644 index 0000000..54f2c73 --- /dev/null +++ b/tests/Febe.Tests.Windows/Support/CompositionSupport.cs @@ -0,0 +1,78 @@ +using Febe.Core.Abstractions; +using Febe.Desktop.Core; + +namespace Febe.Tests.Windows.Support; + +/// +/// A clock that compresses time, like the one of the Linux suite: waits for real only a fraction +/// of the requested time and moves on by the whole of it, so the engine keeps its order of events +/// while a session lasts minutes instead of hours. +/// +internal sealed class CompressedClock(double factor, TimeZoneInfo zone) : IClock +{ + private readonly Lock _gate = new(); + private TimeSpan _offset; + + public TimeZoneInfo LocalZone { get; } = zone; + + public DateTimeOffset Now + { + get + { + lock (_gate) + { + return DateTimeOffset.UtcNow + _offset; + } + } + } + + public async Task Delay(TimeSpan time, CancellationToken ct) + { + if (time <= TimeSpan.Zero) + { + ct.ThrowIfCancellationRequested(); + return; + } + + var real = TimeSpan.FromTicks((long)(time.Ticks / factor)); + if (real >= TimeSpan.FromMilliseconds(1)) + { + await Task.Delay(real, ct).ConfigureAwait(false); + } + else + { + ct.ThrowIfCancellationRequested(); + await Task.Yield(); + } + + lock (_gate) + { + _offset += time - real; + } + } +} + +internal static class TestZones +{ + /// + /// A fixed-offset zone where it is between 12:00 and 13:00 now: inside the active window of every caution profile, + /// whatever the hour of the test. + /// + public static TimeZoneInfo Noon() + { + var offset = 12 - DateTimeOffset.UtcNow.Hour; + return TimeZoneInfo.CreateCustomTimeZone("Febe/Mezzogiorno", TimeSpan.FromHours(offset), "Mezzogiorno di prova", "Mezzogiorno di prova"); + } +} + +/// The registry values «CartellaDati» and «NuovaCartellaDati», in memory. +internal sealed class MemoryLocations : IDataFolderLocationStore +{ + public string? Current { get; private set; } + + public string? Pending { get; private set; } + + public void SetCurrent(string? folder) => Current = folder; + + public void SetPending(string? folder) => Pending = folder; +} diff --git a/tests/Febe.Tests.Windows/WebView2CollectionTests.cs b/tests/Febe.Tests.Windows/WebView2CollectionTests.cs new file mode 100644 index 0000000..1a98f5c --- /dev/null +++ b/tests/Febe.Tests.Windows/WebView2CollectionTests.cs @@ -0,0 +1,168 @@ +using System.Net; +using System.Net.Http; +using System.Text; +using System.Text.Json; +using Febe.App; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Desktop; +using Febe.Desktop.Browser; +using Febe.Desktop.Core; +using Febe.SitoDiProva; +using Febe.Tests.Windows.Support; +using Febe.Web.Connection; +using Febe.Web.Native; + +namespace Febe.Tests.Windows; + +/// +/// One real collection session of the shared composition () running on WebView2, as Febe.exe +/// composes it — , DesktopShell, the window «Browser di Febe» on a WPF UI thread — +/// against the local test site, with files arriving in a temporary library. The Linux suite has the equivalent with +/// Chromium (ServerEndToEndTests). Never Instagram: the browser only sees 127.0.0.1. +/// +[TestClass] +public sealed class WebView2CollectionTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestInitialize] + public void RequireWebView2() => WebView2Runtime.Require(); + + [TestMethod] + [Timeout(420_000, CooperativeCancellation = true)] + public async Task ARealSessionOfTheCompositionRunsOnWebView2AndTheFilesArriveInTheLibrary() + { + var ct = TestContext.CancellationToken; + await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct); + using var folder = new TestFolder("raccolta"); + await using var ui = await UiThread.StartAsync(); + var lines = new LogLines(); + var data = folder.Combine("dati"); + string[] arguments = + [ + "--dati", data, "--libreria", folder.Combine("libreria"), + "--sito-di-prova", site.SiteUrl, "--cdn-di-prova", site.CdnUrl, "--accesso-di-prova", "--prima-sessione", "1", + ]; + Assert.IsTrue(DesktopCommandLine.TryParse(arguments, out var options, out var problem), problem); + + // Febe.exe's composition, on a clock ten times faster and in a zone where it is noon. + var zone = TestZones.Noon(); + var clock = new CompressedClock(10, zone); + var shell = new DesktopShell(ui.Dispatcher, null, BrowserShell.Instance); + var platform = new DesktopPlatform(options, shell, new MemoryLocations(), dataFolderFixed: true); + var appOptions = options.AppOptions(data, new DesktopFolders(folder.Combine("AppData"), folder.Combine("Immagini"))) with { Zone = zone, ZoneId = zone.Id }; + var hooks = new FebeAppHooks { Clock = clock, Random = new SeededRandom(20261020), Console = lines, ShutdownTimeout = TimeSpan.FromSeconds(1) }; + await using var app = await FebeApp.StartAsync(appOptions, platform, hooks, ct); + Assert.IsEmpty(app.Problems, string.Join("; ", app.Problems.Select(p => p.Title))); + + // The browser starts from a thread of the composition, the pipeline and the engine follow. + await app.Running.WaitAsync(TimeSpan.FromSeconds(120), ct); + Assert.IsInstanceOfType(app.Browser); + Assert.IsTrue(lines.Any("Browser di Febe pronto: WebView2 "), lines.Text); + Assert.IsFalse(lines.Any("non parte"), lines.Text); + var connection = app.Connection!; + Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State, "the test site's automatic login"); + + // Accounts and «Controlla ora» through the interface, with the token of this start, as the main window does. + using var client = new HttpClient(new HttpClientHandler { UseCookies = false, AllowAutoRedirect = false, UseProxy = false }) + { + BaseAddress = app.Address, + Timeout = TimeSpan.FromSeconds(30), + }; + var origin = $"{app.Address.Scheme}://{app.Address.Authority}"; + async Task JsonAsync(HttpMethod method, string path, string? json = null) + { + using var request = new HttpRequestMessage(method, path); + request.Headers.TryAddWithoutValidation(Febe.Web.Security.AccessToken.HeaderName, platform.AccessToken); + request.Headers.TryAddWithoutValidation("Origin", origin); + if (json is not null) + { + request.Content = new StringContent(json, Encoding.UTF8, "application/json"); + } + + using var response = await client.SendAsync(request, ct); + var text = await response.Content.ReadAsStringAsync(ct); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}"); + return JsonDocument.Parse(text).RootElement.Clone(); + } + + var added = await JsonAsync(HttpMethod.Post, "/api/accounts", """{"usernames":["marta.prova","luca.prova"],"start":"everything"}"""); + Assert.AreEqual(2, added.GetProperty("added").GetInt32()); + var marta = await app.Database.Accounts.FindByUsernameAsync("marta.prova", ct) ?? throw new AssertFailedException("marta.prova manca"); + var check = await JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now"); + if (check.GetProperty("status").GetString() == "needsConfirmation") + { + check = await JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", $$"""{"token":"{{check.GetProperty("token").GetString()}}"}"""); + } + + Assert.AreEqual("queued", check.GetProperty("status").GetString(), check.GetProperty("message").GetString()); + + // A session of the engine acts on the site through WebView2: every action has its Governor's permit. + await WaitUntilAsync( + async () => (await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, clock.Now.AddDays(1), ct)).Any(a => a.AccountId == marta.Id), + TimeSpan.FromSeconds(120), + "un'azione del motore su marta.prova nel registro delle azioni", + lines, + ct); + + // Files arrive in the library, complete, downloaded through the browser from the test site's CDN. + var library = app.Library ?? throw new AssertFailedException("nessuna libreria"); + List stored = []; + await WaitUntilAsync( + async () => + { + stored = await StoredAsync(app, marta.Id, ct); + return stored.Count >= 3; + }, + TimeSpan.FromSeconds(180), + "tre file di marta.prova nella libreria", + lines, + ct); + foreach (var media in stored) + { + var path = library.FullPath(marta, media.RelativePath!); + Assert.IsTrue(File.Exists(path), path); + Assert.AreEqual(media.Bytes, new FileInfo(path).Length, path); + StringAssert.StartsWith(path, folder.Path, "inside the temporary library"); + } + + var actions = await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, clock.Now.AddDays(1), ct); + Assert.IsTrue(actions.All(a => a.SessionId is not null), "every counted action belongs to a session"); + TestContext.WriteLine($"File di marta.prova: {stored.Count}; azioni: {actions.Count}; CDN: {site.Control.CdnFilesServed} file serviti."); + TestContext.WriteLine(lines.Text); + Assert.IsFalse(lines.Any("non parte"), "the browser never failed to start"); + Assert.IsFalse(lines.Any("firma="), "no signed address in the log"); + } + + private static async Task> StoredAsync(FebeApp app, long accountId, CancellationToken ct) + { + var list = new List(); + foreach (var entry in await app.Database.Entries.ListByAccountAsync(accountId, null, ct)) + { + foreach (var media in await app.Database.Media.ListByEntryAsync(entry.Id, ct)) + { + if (media.State == MediaState.Downloaded && media.RelativePath is not null && media.Sha256 is not null && entry.Kind != EntryKind.ProfilePicture) + { + list.Add(media); + } + } + } + + return list; + } + + private static async Task WaitUntilAsync(Func> condition, TimeSpan timeout, string what, LogLines lines, CancellationToken ct) + { + var deadline = DateTime.UtcNow + timeout; + while (!await condition()) + { + if (DateTime.UtcNow > deadline) + { + Assert.Fail($"Tempo scaduto: {what}.\n{lines.Text}"); + } + + await Task.Delay(250, ct); + } + } +}