Files
Febe/tests/Febe.Tests/Desktop/DesktopCompositionTests.cs
Alby96andClaude Opus 5.5 c4c035d61f
verifica / controlli (push) Successful in 29s
verifica / prove (push) Successful in 15m0s
verifica / installatore (push) Successful in 4m36s
verifica / immagine (push) Successful in 14m52s
Porte delle prove fuori dall'intervallo effimero (#52)
Nella CI 350 Chromium non è partito: la porta di debug, presa dalla porta 0
del sistema e chiusa prima dell'avvio, era nell'intervallo effimero di Linux
e un'altra prova parallela l'aveva occupata nel frattempo. FreePort dà ora
porte fra 20000 e 29999, una volta sola per processo e provate prima di
darle; anche DesktopCompositionTests usa lo stesso aiuto.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:12:08 +01:00

341 lines
20 KiB
C#

using System.Net;
using System.Text.Json;
using Febe.App;
using Febe.Core.Alerts;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Desktop.Core;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Desktop;
/// <summary>
/// The Windows edition composed on Linux (spec §5 «I due involucri», §12, §13.1): the same <see cref="FebeApp"/> as
/// Docker with the <see cref="DesktopPlatform"/>, and a fake only for what needs Windows (WebView2, registry, icon).
/// Never Instagram: the fake browser answers by itself.
/// </summary>
[TestClass]
public sealed class DesktopCompositionTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheInterfaceAnswersOnlyOnLoopbackWithTheTokenOfThisStart()
{
await using var bed = await DesktopTestBed.StartAsync();
Assert.IsEmpty(bed.App.Problems);
Assert.AreEqual("127.0.0.1", bed.App.Address.Host);
Assert.AreNotEqual(8480, bed.App.Address.Port, "a port chosen at start-up");
// Without the token: refused, also for the pages.
foreach (var path in new[] { "/api/capabilities", "/api/accounts", "/" })
{
using var anonymous = await bed.SendAsync(HttpMethod.Get, path, token: false);
Assert.AreEqual(HttpStatusCode.Unauthorized, anonymous.StatusCode, path);
}
// The window opens /?gettone=… once: the token becomes an HttpOnly cookie and leaves the address.
var first = bed.Platform.FirstAddress(bed.App.Address);
StringAssert.StartsWith(first.Query, "?gettone=");
using (var opening = await bed.Client.GetAsync(first.PathAndQuery, TestContext.CancellationToken))
{
Assert.AreEqual(HttpStatusCode.Redirect, opening.StatusCode);
Assert.AreEqual("/", opening.Headers.Location?.OriginalString);
var cookie = opening.Headers.GetValues("Set-Cookie").Single();
StringAssert.Contains(cookie, "httponly");
StringAssert.Contains(cookie, "samesite=strict");
}
// Another token (a page of another start, another program) is refused.
using (var wrong = await bed.Client.GetAsync("/?gettone=" + Febe.Web.Security.AccessToken.Create(), TestContext.CancellationToken))
{
Assert.AreEqual(HttpStatusCode.Unauthorized, wrong.StatusCode);
}
// DNS rebinding: a Host that is not 127.0.0.1/localhost is refused even with the token.
using (var request = new HttpRequestMessage(HttpMethod.Get, "/api/capabilities"))
{
request.Headers.Host = "attacco.example:" + bed.App.Address.Port;
request.Headers.TryAddWithoutValidation(Febe.Web.Security.AccessToken.HeaderName, bed.Platform.AccessToken);
using var rebinding = await bed.Client.SendAsync(request, TestContext.CancellationToken);
Assert.AreEqual(HttpStatusCode.BadRequest, rebinding.StatusCode);
}
// Commands from another origin are refused even with the token.
using (var request = new HttpRequestMessage(HttpMethod.Post, "/api/engine/pause"))
{
request.Headers.TryAddWithoutValidation(Febe.Web.Security.AccessToken.HeaderName, bed.Platform.AccessToken);
request.Headers.TryAddWithoutValidation("Origin", "https://www.esempio.it");
using var foreign = await bed.Client.SendAsync(request, TestContext.CancellationToken);
Assert.AreEqual(HttpStatusCode.Forbidden, foreign.StatusCode);
}
var caps = await bed.JsonAsync(HttpMethod.Get, "/api/capabilities");
Assert.AreEqual("desktop", caps.GetProperty("edition").GetString());
Assert.AreEqual("token", caps.GetProperty("access").GetString());
foreach (var flag in new[] { "showInFolder", "pickFolder", "autostart", "browserWindow", "notifications", "openUrlNative" })
{
Assert.IsTrue(caps.GetProperty(flag).GetBoolean(), flag);
}
Assert.IsFalse(caps.GetProperty("foldersReadOnly").GetBoolean());
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheBrowserWindowComesToTheFrontForTheLoginAndGoesOutOfViewAfterHoFinito()
{
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), TestContext.CancellationToken);
var (settings, browser) = bed.Shell.Created.Single();
Assert.AreEqual(BrowserHosting.Window, settings.Hosting, "the first attempt of S2 by default");
Assert.AreEqual(Path.Combine(bed.Folders.DefaultDataFolder, "browser"), settings.ProfileDirectory, "Dati\\browser");
Assert.AreEqual((1280, 900), (settings.Width, settings.Height));
StringAssert.Contains(settings.AdditionalBrowserArguments, "CalculateNativeWinOcclusion");
Assert.AreEqual(BrowserHosting.Window, bed.Platform.Hosting);
var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection");
Assert.AreEqual("notConnected", status.GetProperty("state").GetString());
// «Accedi a Instagram»: the login page in the browser window, which comes to the front; the engine is still.
using (var begin = await bed.SendAsync(HttpMethod.Post, "/api/connection/begin", """{"openLogin":true}"""))
{
Assert.AreEqual(HttpStatusCode.NoContent, begin.StatusCode);
}
Assert.AreEqual(1, browser.Shown);
Assert.IsTrue(browser.UserIsDriving);
Assert.IsTrue(bed.App.Engine!.Services.Runtime.UserIsDriving, "the engine sees Alberto at the wheel");
Assert.AreEqual("https://www.instagram.com/accounts/login/", browser.FakeCdp.Url, "the real login page (never opened here: the browser is a fake)");
// Alberto logs in by himself in the window; «Ho finito» checks the cookie and puts the window out of view.
browser.FakeCdp.LoggedIn = true;
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsTrue(finish.GetProperty("connected").GetBoolean(), finish.GetProperty("message").GetString());
Assert.IsGreaterThanOrEqualTo(1, browser.Hidden);
Assert.IsFalse(browser.UserIsDriving);
Assert.AreEqual("about:blank", browser.FakeCdp.Url, "back to the rest page");
Assert.IsNotNull(bed.App.Tracker.LastUsedAt, "«Riprendi» knows the browser was used");
Assert.IsNotNull(await bed.App.Database.Settings.GetInt64Async(BrowserConnectionService.FirstConnectionKey, TestContext.CancellationToken));
Assert.AreEqual("connected", (await bed.JsonAsync(HttpMethod.Get, "/api/connection")).GetProperty("state").GetString());
Assert.IsFalse(browser.FakeCdp.Methods.Contains("Network.setCookie"), "only the existence of the cookie is read");
// «Apri il browser» (Attività, red strip) and «Portalo in primo piano» (Collegamento).
await bed.JsonAsync(HttpMethod.Post, "/api/browser/show");
Assert.AreEqual(2, browser.Shown);
using (var front = await bed.SendAsync(HttpMethod.Post, "/api/connection/begin", """{"openLogin":false}"""))
{
Assert.AreEqual(HttpStatusCode.NoContent, front.StatusCode);
}
Assert.AreEqual(3, browser.Shown);
using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel"))
{
Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode);
}
Assert.IsFalse(browser.UserIsDriving);
// «Scollega»: the window goes away, the profile folder with the session is deleted, the browser starts empty.
var marker = Path.Combine(browser.ProfileDirectory, "Cookies");
await File.WriteAllTextAsync(marker, "sessione", TestContext.CancellationToken);
using (var disconnect = await bed.SendAsync(HttpMethod.Post, "/api/connection/disconnect"))
{
Assert.AreEqual(HttpStatusCode.NoContent, disconnect.StatusCode);
}
Assert.IsFalse(File.Exists(marker));
Assert.AreEqual(1, browser.EmptiedProfiles);
Assert.AreEqual("notConnected", (await bed.JsonAsync(HttpMethod.Get, "/api/connection")).GetProperty("state").GetString());
// A profile that cannot be deleted is said in Italian; the engine starts again and the session is looked at again.
browser.FakeCdp.LoggedIn = true;
browser.ProfileLocked = true;
using (var locked = await bed.SendAsync(HttpMethod.Post, "/api/connection/disconnect"))
{
Assert.AreEqual(HttpStatusCode.BadRequest, locked.StatusCode);
using var problem = JsonDocument.Parse(await locked.Content.ReadAsStringAsync(TestContext.CancellationToken));
StringAssert.Contains(problem.RootElement.GetProperty("message").GetString(), "non è riuscito del tutto");
}
Assert.IsTrue(bed.App.Engine.Services.Runtime.IsRunning, "the engine loop runs again");
Assert.AreEqual("connected", (await bed.JsonAsync(HttpMethod.Get, "/api/connection")).GetProperty("state").GetString(), "never claimed disconnected");
Assert.IsFalse(browser.UserIsDriving);
await bed.StopAsync();
Assert.IsTrue(browser.Disposed, "the browser is closed when Febe stops (S3: session on disk)");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task FoldersAutostartAndTheDataFolderChangeGoThroughTheNativeShell()
{
await using var bed = await DesktopTestBed.StartAsync();
var general = await bed.JsonAsync(HttpMethod.Get, "/api/settings/general");
Assert.AreEqual(bed.Folders.DefaultLibraryFolder, general.GetProperty("library").GetProperty("path").GetString(), "Immagini\\Febe");
Assert.AreEqual(bed.Folders.DefaultDataFolder, general.GetProperty("data").GetProperty("path").GetString(), "%LOCALAPPDATA%\\Febe");
Assert.IsTrue(general.GetProperty("canChangeDataFolder").GetBoolean());
Assert.IsFalse(general.GetProperty("autostart").GetBoolean());
// A new library folder: the next downloads go there at once, and the next start uses it.
var library = bed.Temp.Combine("Foto di Instagram");
var saved = await bed.JsonAsync(HttpMethod.Put, "/api/settings/general", $$"""
{"libraryFolder":{{JsonSerializer.Serialize(library)}},"namingScheme":{{JsonSerializer.Serialize(NamingScheme.DefaultGeneral)}},"highlightScheme":{{JsonSerializer.Serialize(NamingScheme.DefaultHighlight)}},"setFileTime":true,"autostart":true,"keepInTray":true}
""");
Assert.AreEqual(library, saved.GetProperty("library").GetProperty("path").GetString());
Assert.IsTrue(bed.Shell.NativeShell.Autostart, "«Avvia Febe all'accensione del computer»");
var ingest = bed.App.Web.Services.GetRequiredService<LibraryIngest>();
Assert.AreEqual(library, ingest.Layout.Root);
// «Cambia…» of the Data folder: recorded for the next start, nothing moves now.
var newData = bed.Temp.Combine("NuoviDati");
var answer = await bed.JsonAsync(HttpMethod.Post, "/api/settings/data-folder", $$"""{"path":{{JsonSerializer.Serialize(newData)}}}""");
StringAssert.Contains(answer.GetProperty("message").GetString(), "prossimo avvio");
Assert.AreEqual(newData, bed.Locations.Pending);
Assert.IsFalse(Directory.Exists(newData));
// «Mostra nella cartella» and the folder picker go to the shell.
bed.Shell.NativeShell.FolderToPick = bed.Temp.Combine("scelta");
var picked = await bed.JsonAsync(HttpMethod.Post, "/api/settings/pick-folder", """{"which":"library"}""");
Assert.AreEqual(bed.Temp.Combine("scelta"), picked.GetProperty("path").GetString());
// The next start, after the move: the library chosen in Impostazioni is used.
await bed.StopAsync();
var moved = DataFolderMove.ApplyPending(bed.Locations, bed.Folders.DefaultDataFolder);
Assert.AreEqual(DataFolderMoveOutcome.Moved, moved.Outcome, moved.Message);
Assert.IsTrue(File.Exists(Path.Combine(newData, "febe.sqlite")));
await using var again = await DesktopTestBed.StartAsync(["--dati", newData]);
Assert.AreEqual(library, again.App.Library!.Root);
Assert.IsFalse((await again.JsonAsync(HttpMethod.Get, "/api/settings/general")).GetProperty("canChangeDataFolder").GetBoolean(), "with --dati the command line decides");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheAlertsOfTheEngineBecomeWindowsNotifications()
{
await using var bed = await DesktopTestBed.StartAsync();
var events = bed.App.Engine!.Services.Events;
var alerts = bed.App.Alerts!;
var received = bed.Shell.NativeShell.Notified;
// The shared alert service of M8, the same as Docker's: Windows notifications through the native shell.
await events.WriteAsync(EventSeverity.Error, EngineEventCodes.ChallengeStop, "Instagram ha chiesto una verifica: Febe si è fermato.", ct: TestContext.CancellationToken);
await events.WriteAsync(EventSeverity.Info, EngineEventCodes.SessionEnded, "Sessione finita.", ct: TestContext.CancellationToken);
await events.WriteAsync(EventSeverity.Success, EngineEventCodes.BackfillCompleted, "Storico di marta.prova completato.", ct: TestContext.CancellationToken);
await alerts.FlushAsync();
await DesktopTestBed.WaitUntilAsync(() => received.Count >= 2, TimeSpan.FromSeconds(10), "due notifiche");
var notified = received.ToArray();
Assert.HasCount(2, notified);
Assert.AreEqual(AlertCatalog.Title(AlertKind.Verification), notified[0].Title);
StringAssert.Contains(notified[0].Message, "«Riprendi»");
Assert.AreEqual(AlertCatalog.Title(AlertKind.BackfillDone), notified[1].Title);
// Alberto turns off «Storico completato» and then the Windows notifications: nothing more arrives.
var settings = AlertSettings.Default with { Events = AlertEvents.All with { BackfillDone = false } };
await AlertSettingsStore.SaveAsync(bed.App.Database.Settings, settings, TestContext.CancellationToken);
await events.WriteAsync(EventSeverity.Success, EngineEventCodes.BackfillCompleted, "Storico di luca.prova completato.", ct: TestContext.CancellationToken);
await alerts.FlushAsync();
await AlertSettingsStore.SaveAsync(bed.App.Database.Settings, settings with { WindowsNotifications = false }, TestContext.CancellationToken);
await events.WriteAsync(EventSeverity.Error, EngineEventCodes.DisconnectStop, "Sessione terminata.", ct: TestContext.CancellationToken);
await alerts.FlushAsync();
Assert.HasCount(2, received);
// Impostazioni ▸ Notifiche: Windows notifications through the shell, Telegram through the composition's channel.
var status = await bed.JsonAsync(HttpMethod.Get, "/api/settings/notifications");
Assert.IsTrue(status.GetProperty("windowsAvailable").GetBoolean(), status.ToString());
Assert.IsTrue(status.GetProperty("telegramAvailable").GetBoolean(), status.ToString());
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task WithoutWebView2NothingStartsAndTheProblemIsKnown()
{
var shell = new FakeDesktopShell { RuntimeVersion = null };
await using var bed = await DesktopTestBed.StartAsync(shell: shell);
Assert.AreEqual(DesktopStartupChecks.WebView2Missing, bed.App.Problems.Single().Code);
Assert.IsNull(bed.App.Browser);
Assert.IsNull(bed.App.Engine);
Assert.IsEmpty(shell.Created);
Assert.IsFalse(File.Exists(Path.Combine(bed.Folders.DefaultDataFolder, "febe.sqlite")), "nothing written in the Data folder");
Assert.IsFalse(Directory.Exists(Path.Combine(bed.Folders.DefaultDataFolder, "registro")));
var caps = await bed.JsonAsync(HttpMethod.Get, "/api/capabilities");
Assert.AreEqual("webview2-assente", caps.GetProperty("problems")[0].GetProperty("code").GetString());
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheHostingOfS2IsChosenOnTheCommandLineKeptForTheNextStartsAndEdgeFallsBackWhenMissing()
{
using var temp = new TempFolder("desktop-s2");
var locations = new MemoryLocationStore();
await using (var composition = await DesktopTestBed.StartAsync(["--browser", "composizione"], temp: temp, locations: locations))
{
Assert.AreEqual(BrowserHosting.Composition, composition.Shell.Created.Single().Settings.Hosting);
await composition.StopAsync();
}
await using (var kept = await DesktopTestBed.StartAsync(temp: temp, locations: locations))
{
Assert.AreEqual(BrowserHosting.Composition, kept.Shell.Created.Single().Settings.Hosting, "stored in the settings");
await kept.StopAsync();
}
// Edge chosen but not installed: the window of WebView2, with a warning in the log.
await using (var noEdge = await DesktopTestBed.StartAsync(["--browser", "edge"], temp: temp, locations: locations))
{
Assert.AreEqual(BrowserHosting.Window, noEdge.Platform.Hosting);
Assert.AreEqual(BrowserHosting.Window, noEdge.Shell.Created.Single().Settings.Hosting);
await noEdge.StopAsync();
}
// Edge installed: Chromium's host on Edge, its profile inside Dati\browser, so «Scollega» deletes both.
var shell = new FakeDesktopShell { EdgePath = temp.Combine("Edge", "msedge.exe") };
await using var edge = await DesktopTestBed.StartAsync(temp: temp, locations: locations, shell: shell);
Assert.AreEqual(BrowserHosting.Edge, edge.Platform.Hosting);
Assert.IsEmpty(shell.Created, "no WebView2 for the browser");
var browser = (EdgeBrowser)edge.App.Browser!;
Assert.AreEqual(Path.Combine(edge.Folders.DefaultDataFolder, "browser", "edge"), browser.ProfileDirectory);
Assert.AreEqual(edge.Shell.EdgePath, browser.Inner.BrowserOptions.ExecutablePath);
Assert.IsNull(browser.Inner.BrowserOptions.Display, "a normal window on Windows, no Xvfb");
await DesktopTestBed.WaitUntilAsync(() => browser.LastError is not null, TimeSpan.FromSeconds(10), "il tentativo di avviare Edge");
Assert.IsFalse(browser.IsAvailable, "the fake msedge.exe does not exist: the browser is retried, nothing else breaks");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task EveryEdgeFebeStartsIsTiedToFebeSoACrashLeavesNoEdgeHoldingThePort()
{
if (!OperatingSystem.IsLinux())
{
Assert.Inconclusive("Il finto msedge.exe di questa prova è uno script di shell.");
return;
}
// An «Edge» that starts and closes at once: every start must be tied to Febe before anything else happens, also
// the starts that fail and the ones after (pkg-6: an Edge left behind by a crash keeps the port 9222).
using var temp = new TempFolder("desktop-edge");
var edge = temp.Combine("Edge", "msedge.exe");
Directory.CreateDirectory(Path.GetDirectoryName(edge)!);
await File.WriteAllTextAsync(edge, "#!/bin/sh\nexit 3\n", TestContext.CancellationToken);
File.SetUnixFileMode(edge, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
var shell = new FakeDesktopShell { EdgePath = edge, TieSucceeds = false };
await using var bed = await DesktopTestBed.StartAsync(["--browser", "edge"], shell, temp, adjust: o => o with { EdgeDebugPort = FreePort() });
await DesktopTestBed.WaitUntilAsync(() => !shell.TiedToFebe.IsEmpty, TimeSpan.FromSeconds(20), "Edge legato alla vita di Febe");
var browser = (EdgeBrowser)bed.App.Browser!;
await DesktopTestBed.WaitUntilAsync(() => browser.LastError is not null, TimeSpan.FromSeconds(20), "il primo avvio di Edge, che si chiude subito");
Assert.IsFalse(browser.IsAvailable);
await bed.StopAsync();
// Windows refused: the log says what to do, in Italian.
var log = string.Concat(Directory.EnumerateFiles(Path.Combine(bed.Folders.DefaultDataFolder, "registro")).Select(File.ReadAllText));
StringAssert.Contains(log, "Windows non ha legato Edge a Febe");
}
private static int FreePort() => Febe.Tests.Browser.TestSupport.LocalTestSite.FreePort();
}