Prove per Windows: la composizione di Febe.exe preparata in un posto solo

Sito di prova, cartelle, thread dell'interfaccia, DesktopPlatform con DesktopShell, orologio veloce e richieste all'interfaccia con il gettone passano dalla prova della sessione di raccolta a DesktopBed, così la prova del collegamento che segue usa la stessa composizione senza copiarla.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-20 10:53:48 +02:00
1 parent e5e2b6864f
commit 66a3fc7db6
2 files changed
+172 -88

No files matched your search

@@ -0,0 +1,150 @@
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using Febe.App;
using Febe.Core.Abstractions;
using Febe.Desktop;
using Febe.Desktop.Browser;
using Febe.Desktop.Core;
using Febe.SitoDiProva;
using Febe.Web.Native;
namespace Febe.Tests.Windows.Support;
/// <summary>
/// The shared composition (<see cref="FebeApp"/>) as Febe.exe composes it — <see cref="DesktopPlatform"/>,
/// <c>DesktopShell</c>, the window «Browser di Febe» on a WPF UI thread — against its own test site, in temporary
/// folders, on a clock ten times faster and in a zone where it is noon. The interface is asked like the main window asks
/// it: with the token of this start and the Origin of the interface.
/// </summary>
internal sealed class DesktopBed : IAsyncDisposable
{
private readonly HttpClient _client;
private DesktopBed(TestSite site, TestFolder folder, UiThread ui, LogLines lines, CompressedClock clock, DesktopPlatform platform, FebeApp app)
{
Site = site;
Folder = folder;
Ui = ui;
Lines = lines;
Clock = clock;
Platform = platform;
App = app;
_client = new HttpClient(new HttpClientHandler { UseCookies = false, AllowAutoRedirect = false, UseProxy = false })
{
BaseAddress = app.Address,
Timeout = TimeSpan.FromSeconds(30),
};
}
public TestSite Site { get; }
public TestFolder Folder { get; }
public UiThread Ui { get; }
/// <summary>What Febe wrote in its log.</summary>
public LogLines Lines { get; }
public CompressedClock Clock { get; }
public DesktopPlatform Platform { get; }
public FebeApp App { get; }
/// <summary>The browser of Febe: WebView2 (Febe.exe never uses another one unless asked with <c>--browser edge</c>).</summary>
public WebView2Browser Browser => App.Browser as WebView2Browser ?? throw new AssertFailedException("Il browser della composizione non è WebView2.");
/// <param name="name">Prefix of the temporary folder.</param>
/// <param name="autoLogin"><c>--accesso-di-prova</c>: the composition opens the test site once at start-up.</param>
public static async Task<DesktopBed> StartAsync(string name, bool autoLogin, CancellationToken ct)
{
var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
var folder = new TestFolder(name);
var ui = await UiThread.StartAsync();
try
{
var lines = new LogLines();
var data = folder.Combine("dati");
List<string> arguments =
[
"--dati", data, "--libreria", folder.Combine("libreria"),
"--sito-di-prova", site.SiteUrl, "--cdn-di-prova", site.CdnUrl, "--prima-sessione", "1",
];
if (autoLogin)
{
arguments.Add("--accesso-di-prova");
}
if (!DesktopCommandLine.TryParse([.. arguments], out var options, out var problem))
{
throw new ArgumentException(problem);
}
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) };
var app = await FebeApp.StartAsync(appOptions, platform, hooks, ct);
return new DesktopBed(site, folder, ui, lines, clock, platform, app);
}
catch
{
await ui.DisposeAsync();
folder.Dispose();
await site.DisposeAsync();
throw;
}
}
/// <summary>A request as the main window sends it; the answer must be 200 with JSON.</summary>
public async Task<JsonElement> JsonAsync(HttpMethod method, string path, string? json, CancellationToken ct)
{
using var request = new HttpRequestMessage(method, path);
request.Headers.TryAddWithoutValidation(Febe.Web.Security.AccessToken.HeaderName, Platform.AccessToken);
request.Headers.TryAddWithoutValidation("Origin", $"{App.Address.Scheme}://{App.Address.Authority}");
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();
}
/// <summary>Waits (real time) until <paramref name="condition"/> holds; fails with <paramref name="what"/> and the log otherwise.</summary>
public async Task WaitUntilAsync(Func<Task<bool>> condition, TimeSpan timeout, string what, 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);
}
}
/// <summary>Stops the composition (the browser of Febe closes on its UI thread), then the UI thread, folders, site.</summary>
public async ValueTask DisposeAsync()
{
_client.Dispose();
try
{
await App.DisposeAsync();
}
finally
{
await Ui.DisposeAsync();
Folder.Dispose();
await Site.DisposeAsync();
}
}
}
@@ -1,25 +1,15 @@
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;
/// <summary>
/// One real collection session of the shared composition (<see cref="FebeApp"/>) running on WebView2, as Febe.exe
/// composes it — <see cref="DesktopPlatform"/>, <c>DesktopShell</c>, 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.
/// composes it, 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.
/// </summary>
[TestClass]
public sealed class WebView2CollectionTests
@@ -34,82 +24,41 @@ public sealed class WebView2CollectionTests
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);
await using var bed = await DesktopBed.StartAsync("raccolta", autoLogin: true, ct);
var app = bed.App;
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.
// The browser starts from a thread of the composition (the path that failed on Alberto's PC), the pipeline and
// the engine follow.
await app.Running.WaitAsync(TimeSpan.FromSeconds(120), ct);
Assert.IsInstanceOfType<WebView2Browser>(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");
Assert.IsTrue(bed.Lines.Any("Browser di Febe pronto: WebView2 "), bed.Lines.Text);
Assert.IsFalse(bed.Lines.Any("non parte"), bed.Lines.Text);
Assert.AreEqual(Febe.Web.Connection.ConnectionState.Connected, (await app.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<JsonElement> 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"}""");
// Accounts and «Controlla ora» through the interface, as from the main window.
var added = await bed.JsonAsync(HttpMethod.Post, "/api/accounts", """{"usernames":["marta.prova","luca.prova"],"start":"everything"}""", ct);
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");
var check = await bed.JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", null, ct);
if (check.GetProperty("status").GetString() == "needsConfirmation")
{
check = await JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", $$"""{"token":"{{check.GetProperty("token").GetString()}}"}""");
check = await bed.JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", $$"""{"token":"{{check.GetProperty("token").GetString()}}"}""", ct);
}
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),
await bed.WaitUntilAsync(
async () => (await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, bed.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<Media> stored = [];
await WaitUntilAsync(
await bed.WaitUntilAsync(
async () =>
{
stored = await StoredAsync(app, marta.Id, ct);
@@ -117,22 +66,21 @@ public sealed class WebView2CollectionTests
},
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");
StringAssert.StartsWith(path, bed.Folder.Path, "inside the temporary library");
}
var actions = await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, clock.Now.AddDays(1), ct);
var actions = await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, bed.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");
TestContext.WriteLine($"File di marta.prova: {stored.Count}; azioni: {actions.Count}; CDN: {bed.Site.Control.CdnFilesServed} file serviti.");
TestContext.WriteLine(bed.Lines.Text);
Assert.IsFalse(bed.Lines.Any("non parte"), "the browser never failed to start");
Assert.IsFalse(bed.Lines.Any("firma="), "no signed address in the log");
}
private static async Task<List<Media>> StoredAsync(FebeApp app, long accountId, CancellationToken ct)
@@ -151,18 +99,4 @@ public sealed class WebView2CollectionTests
return list;
}
private static async Task WaitUntilAsync(Func<Task<bool>> 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);
}
}
}