diff --git a/tests/Febe.Tests.Windows/Support/DesktopBed.cs b/tests/Febe.Tests.Windows/Support/DesktopBed.cs
new file mode 100644
index 0000000..8a1e1af
--- /dev/null
+++ b/tests/Febe.Tests.Windows/Support/DesktopBed.cs
@@ -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;
+
+///
+/// The shared composition () as Febe.exe composes it — ,
+/// DesktopShell, 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.
+///
+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; }
+
+ /// What Febe wrote in its log.
+ public LogLines Lines { get; }
+
+ public CompressedClock Clock { get; }
+
+ public DesktopPlatform Platform { get; }
+
+ public FebeApp App { get; }
+
+ /// The browser of Febe: WebView2 (Febe.exe never uses another one unless asked with --browser edge).
+ public WebView2Browser Browser => App.Browser as WebView2Browser ?? throw new AssertFailedException("Il browser della composizione non è WebView2.");
+
+ /// Prefix of the temporary folder.
+ /// --accesso-di-prova: the composition opens the test site once at start-up.
+ public static async Task 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 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;
+ }
+ }
+
+ /// A request as the main window sends it; the answer must be 200 with JSON.
+ public async Task 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();
+ }
+
+ /// Waits (real time) until holds; fails with and the log otherwise.
+ public async Task WaitUntilAsync(Func> 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);
+ }
+ }
+
+ /// Stops the composition (the browser of Febe closes on its UI thread), then the UI thread, folders, site.
+ public async ValueTask DisposeAsync()
+ {
+ _client.Dispose();
+ try
+ {
+ await App.DisposeAsync();
+ }
+ finally
+ {
+ await Ui.DisposeAsync();
+ Folder.Dispose();
+ await Site.DisposeAsync();
+ }
+ }
+}
diff --git a/tests/Febe.Tests.Windows/WebView2CollectionTests.cs b/tests/Febe.Tests.Windows/WebView2CollectionTests.cs
index 1a98f5c..d645996 100644
--- a/tests/Febe.Tests.Windows/WebView2CollectionTests.cs
+++ b/tests/Febe.Tests.Windows/WebView2CollectionTests.cs
@@ -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;
///
/// 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.
+/// 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.
///
[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(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 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 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> StoredAsync(FebeApp app, long accountId, CancellationToken ct)
@@ -151,18 +99,4 @@ public sealed class WebView2CollectionTests
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);
- }
- }
}