M6 Windows: composizione condivisa Febe.App per Server e Desktop; Febe per Windows (WPF) con l'interfaccia in WebView2, area di notifica, istanza unica, «Browser di Febe» su WebView2 con CDP filtrato (WebView2CdpSession) e ripieghi di S2 (composizione, Edge), guscio nativo, avvisi, spostamento verificato della cartella dei dati, icona del marchio; un solo Febe.exe, installatore NSIS e zip portabile; guida docs/windows.md e prove dal vivo S1–S3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
73 files changed
+7914
-699
No files matched your search
@@ -0,0 +1,299 @@
|
||||
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 received = bed.Shell.Alerts.Received;
|
||||
|
||||
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 DesktopTestBed.WaitUntilAsync(() => received.Count >= 2, TimeSpan.FromSeconds(10), "due notifiche");
|
||||
var alerts = received.ToArray();
|
||||
Assert.AreEqual(AlertKind.Verification, alerts[0].Kind);
|
||||
Assert.AreEqual("Instagram chiede una verifica", alerts[0].Title);
|
||||
Assert.AreEqual(AlertKind.BackfillDone, alerts[1].Kind);
|
||||
|
||||
// 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 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 Task.Delay(500, TestContext.CancellationToken);
|
||||
Assert.HasCount(2, received);
|
||||
Assert.HasCount(1, bed.App.Alerts!.Channels);
|
||||
}
|
||||
|
||||
[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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Desktop.Core;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Support;
|
||||
using Febe.Web.Api;
|
||||
|
||||
namespace Febe.Tests.Desktop;
|
||||
|
||||
/// <summary>
|
||||
/// The parts of the Windows application that do not need Windows (spec §12): command line, single instance, start-up
|
||||
/// checks, start with the computer, Edge for S2, the switches of S2, the move of the Data folder.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class DesktopLogicTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
public void TheCommandLineIsReadAndWrongValuesAreRefusedInItalian()
|
||||
{
|
||||
Assert.IsTrue(DesktopCommandLine.TryParse([], out var plain, out _));
|
||||
Assert.IsFalse(plain.StartHidden);
|
||||
Assert.IsNull(plain.Hosting);
|
||||
Assert.IsNull(plain.DataFolder);
|
||||
Assert.AreEqual("https://www.instagram.com/accounts/login/", plain.LoginUrl);
|
||||
Assert.AreEqual("instagram", plain.Site.Name);
|
||||
|
||||
var data = Path.Combine(Path.GetTempPath(), "febe-dati");
|
||||
var library = Path.Combine(Path.GetTempPath(), "febe-libreria");
|
||||
Assert.IsTrue(DesktopCommandLine.TryParse(["--nascosto", "--browser", "composizione", "--dati", data, "--sviluppo", "--libreria", library], out var options, out _));
|
||||
Assert.AreEqual(Path.GetFullPath(library), options.AppOptions(data, new DesktopFolders("a", "b")).LibraryFolder);
|
||||
Assert.IsTrue(options.StartHidden);
|
||||
Assert.AreEqual(BrowserHosting.Composition, options.Hosting);
|
||||
Assert.AreEqual(Path.GetFullPath(data), options.DataFolder);
|
||||
Assert.IsTrue(options.DeveloperTools);
|
||||
|
||||
Assert.IsTrue(DesktopCommandLine.TryParse(["--sito-di-prova", "http://127.0.0.1:8481", "--accesso-di-prova", "--prima-sessione", "5", "--browser", "EDGE"], out var test, out _));
|
||||
Assert.AreEqual("http://127.0.0.1:8481/benvenuto", test.LoginUrl);
|
||||
Assert.AreNotEqual("instagram", test.Site.Name);
|
||||
Assert.AreEqual(TimeSpan.FromSeconds(5), test.FirstSessionDelay);
|
||||
Assert.AreEqual(BrowserHosting.Edge, test.Hosting);
|
||||
|
||||
foreach (var (args, fragment) in new (string[], string)[]
|
||||
{
|
||||
(["--browser", "nascosto"], "--browser"),
|
||||
(["--dati", "relativo"], "--dati"),
|
||||
(["--libreria"], "--libreria"),
|
||||
(["--sito-di-prova", "https://www.instagram.com/"], "questo computer"),
|
||||
(["--accesso-di-prova"], "--sito-di-prova"),
|
||||
(["--prima-sessione", "0"], "--prima-sessione"),
|
||||
(["--password", "x"], "Opzione sconosciuta"),
|
||||
})
|
||||
{
|
||||
Assert.IsFalse(DesktopCommandLine.TryParse(args, out _, out var problem), string.Join(' ', args));
|
||||
StringAssert.Contains(problem, fragment);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheHostingNamesAreItalianAndRoundTrip()
|
||||
{
|
||||
foreach (var hosting in Enum.GetValues<BrowserHosting>())
|
||||
{
|
||||
Assert.IsTrue(BrowserHostingNames.TryParse(BrowserHostingNames.Name(hosting), out var back));
|
||||
Assert.AreEqual(hosting, back);
|
||||
}
|
||||
|
||||
Assert.IsFalse(BrowserHostingNames.TryParse(null, out var fallback));
|
||||
Assert.AreEqual(BrowserHosting.Window, fallback, "the default of S2 is the first attempt");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheDefaultFoldersAreLocalAppDataAndPictures()
|
||||
{
|
||||
var folders = new DesktopFolders(Path.Combine("C", "Users", "alberto", "AppData", "Local"), Path.Combine("C", "Users", "alberto", "Pictures"));
|
||||
Assert.AreEqual(Path.Combine(folders.LocalAppData, "Febe"), folders.DefaultDataFolder);
|
||||
Assert.AreEqual(Path.Combine(folders.Pictures, "Febe"), folders.DefaultLibraryFolder);
|
||||
Assert.IsTrue(DesktopCommandLine.TryParse([], out var options, out _));
|
||||
var app = options.AppOptions(folders.DefaultDataFolder, folders);
|
||||
Assert.IsTrue(app.LibraryFolderFromSettings, "the library chosen in Impostazioni wins over the default");
|
||||
Assert.IsNull(app.ImportFolder, "any folder can be imported on Windows");
|
||||
Assert.AreEqual(folders.DefaultLibraryFolder, app.LibraryFolder);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OneInstancePerDataFolderAndTheMessagesBetweenLaunches()
|
||||
{
|
||||
var a = Path.Combine(Path.GetTempPath(), "febe", "dati");
|
||||
Assert.AreEqual(InstanceIdentity.For(a), InstanceIdentity.For(a + Path.DirectorySeparatorChar), "the same folder");
|
||||
Assert.AreEqual(InstanceIdentity.For(a), InstanceIdentity.For(a.ToUpperInvariant()), "whatever the case of the letters");
|
||||
Assert.AreNotEqual(InstanceIdentity.For(a), InstanceIdentity.For(a + "2"), "another account, another instance");
|
||||
StringAssert.StartsWith(InstanceIdentity.MutexName(a), @"Local\Febe-");
|
||||
Assert.AreEqual(21, InstanceIdentity.PipeName(a).Length);
|
||||
|
||||
Assert.IsTrue(DesktopCommandLine.TryParse([], out var normal, out _));
|
||||
Assert.IsTrue(DesktopCommandLine.TryParse(["--nascosto"], out var hidden, out _));
|
||||
Assert.AreEqual(InstanceRequest.Show, InstanceMessages.Parse(InstanceMessages.For(normal)));
|
||||
Assert.AreEqual(InstanceRequest.StayHidden, InstanceMessages.Parse(InstanceMessages.For(hidden)));
|
||||
Assert.AreEqual(InstanceRequest.Show, InstanceMessages.Parse("FEBE1 mostra\n"));
|
||||
foreach (var junk in new[] { null, string.Empty, "mostra", "FEBE2 mostra", "FEBE1 apri C:\\", new string('x', 500) })
|
||||
{
|
||||
Assert.IsNull(InstanceMessages.Parse(junk), junk);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void WithoutWebView2TheProblemNamesTheOfficialPage()
|
||||
{
|
||||
using var temp = new TempFolder("desktop-controlli");
|
||||
var data = temp.Combine("dati");
|
||||
Assert.IsEmpty(DesktopStartupChecks.Run(data, () => "141.0.3537.71"));
|
||||
|
||||
var problems = DesktopStartupChecks.Run(data, () => null);
|
||||
var missing = problems.Single();
|
||||
Assert.AreEqual("webview2-assente", missing.Code);
|
||||
StringAssert.Contains(missing.Remedy, "https://developer.microsoft.com/microsoft-edge/webview2/");
|
||||
StringAssert.Contains(missing.Message, "WebView2");
|
||||
|
||||
// The probe throws when the runtime is missing (WebView2RuntimeNotFoundException): same problem.
|
||||
Assert.AreEqual("webview2-assente", DesktopStartupChecks.Run(data, () => throw new InvalidOperationException("nessun runtime")).Single().Code);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ADataFolderOnANetworkShareOrNotWritableStopsTheEngine()
|
||||
{
|
||||
using var temp = new TempFolder("desktop-controlli");
|
||||
var file = temp.Combine("un-file");
|
||||
File.WriteAllText(file, "x");
|
||||
Assert.AreEqual("dati-non-scrivibili", DesktopStartupChecks.Run(file, () => "1.0").Single().Code);
|
||||
|
||||
if (OperatingSystem.IsLinux())
|
||||
{
|
||||
var share = temp.Combine("rete");
|
||||
var mounts = $"//nas/condivisa {share} cifs rw 0 0\n";
|
||||
var problems = DesktopStartupChecks.Run(share, () => null, new DataFolderCheck(() => mounts));
|
||||
CollectionAssert.AreEqual(new[] { "dati-in-rete", "webview2-assente" }, problems.Select(p => p.Code).ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void StartWithTheComputerWritesTheQuotedExecutableAndRecognisesItsOwnValue()
|
||||
{
|
||||
var exe = Path.Combine(Path.GetTempPath(), "Programmi", "Febe", "Febe.exe");
|
||||
var command = Autostart.Command(exe);
|
||||
Assert.AreEqual($"\"{exe}\" --nascosto", command);
|
||||
Assert.IsTrue(Autostart.PointsTo(command, exe));
|
||||
Assert.IsTrue(Autostart.PointsTo(exe, exe), "a value without quotes");
|
||||
Assert.IsFalse(Autostart.PointsTo(Autostart.Command(exe + ".vecchio"), exe), "another copy of Febe");
|
||||
Assert.IsFalse(Autostart.PointsTo(null, exe));
|
||||
Assert.IsFalse(Autostart.PointsTo("\"senza fine", exe));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => Autostart.Command("C:\\a\"b.exe"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EdgeIsFoundThroughAppPathsThenTheUsualFolders()
|
||||
{
|
||||
var candidates = EdgeLocator.Candidates("\"D:\\Edge\\msedge.exe\"", "C:\\Program Files (x86)", "C:\\Program Files", "C:\\Users\\a\\AppData\\Local");
|
||||
Assert.AreEqual("D:\\Edge\\msedge.exe", candidates[0]);
|
||||
Assert.HasCount(4, candidates);
|
||||
Assert.AreEqual(Path.Combine("C:\\Program Files (x86)", "Microsoft", "Edge", "Application", "msedge.exe"), candidates[1]);
|
||||
|
||||
var exists = new HashSet<string>([candidates[2]]);
|
||||
Assert.AreEqual(candidates[2], EdgeLocator.Find(candidates, exists.Contains));
|
||||
Assert.IsNull(EdgeLocator.Find(candidates, _ => false));
|
||||
Assert.IsNull(EdgeLocator.Find(["C:\\Windows\\notepad.exe"], _ => true), "only msedge.exe");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheSwitchesOfS2PassTheChecksOfRule2AndChangeNothingTheBrowserDeclares()
|
||||
{
|
||||
foreach (var argument in BrowserArguments.KeepPaintingOutOfView)
|
||||
{
|
||||
ChromiumCommandLine.EnsureAllowed(argument);
|
||||
foreach (var declared in new[] { "user-agent", "lang", "headless", "automation", "proxy", "blink-features", "timezone", "fingerprint", "webdriver" })
|
||||
{
|
||||
Assert.DoesNotContain(declared, argument, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.AreEqual("--disable-features=CalculateNativeWinOcclusion --disable-backgrounding-occluded-windows", BrowserArguments.ForWebView2());
|
||||
|
||||
// Edge started as a process gets the same switches, after Febe's own (fixed port on 127.0.0.1, profile, size).
|
||||
var line = ChromiumCommandLine.Build(new Febe.Core.Abstractions.BrowserOptions("profilo", 1280, 900, 9222), new ChromiumLaunchOptions { ExtraArguments = BrowserArguments.ForEdge() });
|
||||
CollectionAssert.IsSubsetOf(BrowserArguments.KeepPaintingOutOfView.ToList(), line.ToList());
|
||||
Assert.IsFalse(line.Any(a => a.StartsWith("--headless", StringComparison.Ordinal) || a.StartsWith("--enable-automation", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheDataFolderMovesOnlyAfterEveryFileIsCopiedAndVerified()
|
||||
{
|
||||
using var temp = new TempFolder("desktop-sposta");
|
||||
var from = temp.Combine("vecchia");
|
||||
var to = temp.Combine("nuova", "Febe");
|
||||
Directory.CreateDirectory(Path.Combine(from, "browser", "Default"));
|
||||
Directory.CreateDirectory(Path.Combine(from, "miniature", "ab"));
|
||||
Directory.CreateDirectory(Path.Combine(from, "vuota"));
|
||||
File.WriteAllText(Path.Combine(from, "febe.sqlite"), "database");
|
||||
File.WriteAllText(Path.Combine(from, "browser", "Default", "Cookies"), "sessione");
|
||||
var big = new byte[3 * 1024 * 1024 + 17];
|
||||
new Random(4).NextBytes(big);
|
||||
File.WriteAllBytes(Path.Combine(from, "miniature", "ab", "x.jpg"), big);
|
||||
|
||||
var store = new MemoryLocationStore();
|
||||
Assert.AreEqual(DataFolderMoveOutcome.NotRequested, DataFolderMove.ApplyPending(store, from).Outcome);
|
||||
|
||||
var change = new DesktopDataFolderChange(store, from, fixedByCommandLine: false);
|
||||
Assert.IsTrue(change.CanChange);
|
||||
var message = change.RequestChangeAsync(to, TestContext.CancellationToken).Result;
|
||||
StringAssert.Contains(message, "prossimo avvio");
|
||||
Assert.AreEqual(Path.GetFullPath(to), store.Pending);
|
||||
Assert.IsFalse(Directory.Exists(to), "nothing moves while Febe runs");
|
||||
|
||||
var reports = new List<DataFolderMoveProgress>();
|
||||
var result = DataFolderMove.ApplyPending(store, from, new SyncProgress(reports.Add));
|
||||
Assert.AreEqual(DataFolderMoveOutcome.Moved, result.Outcome, result.Message);
|
||||
Assert.AreEqual(Path.GetFullPath(to), result.DataFolder);
|
||||
Assert.AreEqual(Path.GetFullPath(to), store.Current);
|
||||
Assert.IsNull(store.Pending);
|
||||
Assert.IsFalse(Directory.Exists(from), "the old folder, with a copy of the session, is gone");
|
||||
Assert.AreEqual("sessione", File.ReadAllText(Path.Combine(to, "browser", "Default", "Cookies")));
|
||||
CollectionAssert.AreEqual(big, File.ReadAllBytes(Path.Combine(to, "miniature", "ab", "x.jpg")));
|
||||
Assert.IsTrue(Directory.Exists(Path.Combine(to, "vuota")), "empty folders too");
|
||||
Assert.AreEqual(3, reports[^1].FilesTotal);
|
||||
Assert.AreEqual(3, reports[^1].FilesDone);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AFailedCopyLeavesTheOldFolderInUseAndRemovesThePartialCopy()
|
||||
{
|
||||
using var temp = new TempFolder("desktop-sposta");
|
||||
var from = temp.Combine("vecchia");
|
||||
Directory.CreateDirectory(from);
|
||||
File.WriteAllText(Path.Combine(from, "febe.sqlite"), "database");
|
||||
var to = temp.Combine("nuova");
|
||||
var store = new MemoryLocationStore { Pending = to };
|
||||
|
||||
// The target appears with a file before the start (someone used it): refused, nothing touched.
|
||||
Directory.CreateDirectory(to);
|
||||
File.WriteAllText(Path.Combine(to, "altro.txt"), "non di Febe");
|
||||
var refused = DataFolderMove.ApplyPending(store, from);
|
||||
Assert.AreEqual(DataFolderMoveOutcome.Failed, refused.Outcome);
|
||||
Assert.AreEqual(from, refused.DataFolder);
|
||||
StringAssert.Contains(refused.Message, "vuota");
|
||||
Assert.IsNull(store.Pending);
|
||||
Assert.IsNull(store.Current);
|
||||
Assert.IsTrue(File.Exists(Path.Combine(from, "febe.sqlite")));
|
||||
Assert.IsTrue(File.Exists(Path.Combine(to, "altro.txt")), "a folder that is not Febe's is never emptied");
|
||||
|
||||
// A copy interrupted half way (the disk fills up after the first file): the old folder stays, the copy goes.
|
||||
File.WriteAllText(Path.Combine(from, "secondo"), "y");
|
||||
var halfway = temp.Combine("quarta");
|
||||
store.Pending = halfway;
|
||||
var interrupted = DataFolderMove.ApplyPending(store, from, new SyncProgress(_ => throw new IOException("disco pieno")));
|
||||
Assert.AreEqual(DataFolderMoveOutcome.Failed, interrupted.Outcome);
|
||||
StringAssert.Contains(interrupted.Message, "disco pieno");
|
||||
Assert.IsFalse(Directory.Exists(halfway), "the partial copy is removed");
|
||||
Assert.IsNull(store.Current);
|
||||
Assert.IsTrue(File.Exists(Path.Combine(from, "febe.sqlite")));
|
||||
|
||||
// A file the copy cannot read: the same.
|
||||
if (OperatingSystem.IsLinux() && Environment.UserName != "root")
|
||||
{
|
||||
var locked = Path.Combine(from, "bloccato");
|
||||
File.WriteAllText(locked, "x");
|
||||
File.SetUnixFileMode(locked, UnixFileMode.None);
|
||||
var target = temp.Combine("terza");
|
||||
store.Pending = target;
|
||||
var failed = DataFolderMove.ApplyPending(store, from);
|
||||
Assert.AreEqual(DataFolderMoveOutcome.Failed, failed.Outcome);
|
||||
Assert.IsFalse(Directory.Exists(target), "the partial copy is removed");
|
||||
Assert.IsTrue(File.Exists(Path.Combine(from, "febe.sqlite")));
|
||||
File.SetUnixFileMode(locked, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheNewDataFolderMustBeEmptyLocalAndOutsideTheCurrentOne()
|
||||
{
|
||||
using var temp = new TempFolder("desktop-sposta");
|
||||
var current = temp.Combine("dati");
|
||||
Directory.CreateDirectory(current);
|
||||
Assert.IsNotNull(DataFolderMove.Validate(current, "relativa"));
|
||||
Assert.IsNotNull(DataFolderMove.Validate(current, current));
|
||||
Assert.IsNotNull(DataFolderMove.Validate(current, Path.Combine(current, "dentro")));
|
||||
Assert.IsNotNull(DataFolderMove.Validate(Path.Combine(current, "sotto"), current));
|
||||
Assert.IsNull(DataFolderMove.Validate(current, temp.Combine("altrove")));
|
||||
Assert.IsFalse(Directory.Exists(temp.Combine("altrove")), "checking a choice does not leave a folder behind");
|
||||
|
||||
var fixedByCommandLine = new DesktopDataFolderChange(new MemoryLocationStore(), current, fixedByCommandLine: true);
|
||||
Assert.IsFalse(fixedByCommandLine.CanChange);
|
||||
Assert.ThrowsExactly<BadRequestException>(() => fixedByCommandLine.RequestChangeAsync(temp.Combine("altrove"), TestContext.CancellationToken).GetAwaiter().GetResult());
|
||||
var store = new MemoryLocationStore();
|
||||
Assert.ThrowsExactly<BadRequestException>(() => new DesktopDataFolderChange(store, current, false).RequestChangeAsync(Path.Combine(current, "x"), TestContext.CancellationToken).GetAwaiter().GetResult());
|
||||
Assert.IsNull(store.Pending);
|
||||
}
|
||||
|
||||
private sealed class SyncProgress(Action<DataFolderMoveProgress> report) : IProgress<DataFolderMoveProgress>
|
||||
{
|
||||
public void Report(DataFolderMoveProgress value) => report(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
using System.Buffers.Binary;
|
||||
using Febe.Desktop.Core;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using SkiaSharp;
|
||||
|
||||
namespace Febe.Tests.Desktop;
|
||||
|
||||
/// <summary>
|
||||
/// The icon of the Windows application (spec §12, appendix C): the brand mark drawn with SkiaSharp and written by the
|
||||
/// hand-made ICO writer, at 16, 24, 32, 48, 64, 128 and 256 pixels. The committed <c>src/Febe.Desktop/Febe.ico</c> must be
|
||||
/// what the code draws: <c>FEBE_RIGENERA_ICONA=1 dotnet test --filter IconTests</c> writes it again.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class IconTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void TheIconHasEverySizeDibBelow256AndPngAt256()
|
||||
{
|
||||
var ico = BrandMark.RenderIcon();
|
||||
var entries = IcoWriter.ReadDirectory(ico);
|
||||
CollectionAssert.AreEqual(new[] { 16, 24, 32, 48, 64, 128, 256 }, entries.Select(e => e.Size).ToArray());
|
||||
Assert.IsTrue(entries.All(e => e.BitsPerPixel == 32));
|
||||
Assert.IsTrue(entries.Where(e => e.Size < 256).All(e => !e.IsPng), "DIB below 256");
|
||||
Assert.IsTrue(entries.Single(e => e.Size == 256).IsPng, "PNG at 256");
|
||||
|
||||
// Entries follow the directory and do not overlap.
|
||||
var end = 6 + (16 * entries.Count);
|
||||
foreach (var entry in entries.OrderBy(e => e.Offset))
|
||||
{
|
||||
Assert.AreEqual(end, entry.Offset);
|
||||
end += entry.Length;
|
||||
}
|
||||
|
||||
Assert.AreEqual(ico.Length, end);
|
||||
|
||||
// A DIB has the doubled height of the XOR + AND images and the right length.
|
||||
foreach (var entry in entries.Where(e => !e.IsPng))
|
||||
{
|
||||
var header = ico.AsSpan(entry.Offset, 40);
|
||||
Assert.AreEqual(40u, BinaryPrimitives.ReadUInt32LittleEndian(header));
|
||||
Assert.AreEqual(entry.Size, BinaryPrimitives.ReadInt32LittleEndian(header[4..]));
|
||||
Assert.AreEqual(entry.Size * 2, BinaryPrimitives.ReadInt32LittleEndian(header[8..]));
|
||||
var maskStride = ((entry.Size + 31) / 32) * 4;
|
||||
Assert.AreEqual(40 + (entry.Size * entry.Size * 4) + (maskStride * entry.Size), entry.Length);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryImageShowsTheMarkTransparentCornersAccentSquareWhiteMoon()
|
||||
{
|
||||
var ico = BrandMark.RenderIcon();
|
||||
foreach (var entry in IcoWriter.ReadDirectory(ico))
|
||||
{
|
||||
using var image = IcoWriter.Decode(ico, entry);
|
||||
var s = entry.Size;
|
||||
Assert.AreEqual(0, image.GetPixel(0, 0).Alpha, $"{s}: transparent corner");
|
||||
Assert.AreEqual(0, image.GetPixel(s - 1, s - 1).Alpha, $"{s}: transparent corner");
|
||||
|
||||
// Inside the square, away from ring and moon (x=4/32, y=28/32): the accent colour #0F5C8C.
|
||||
var accent = image.GetPixel(Scale(4, s), Scale(28, s));
|
||||
if (s >= 24)
|
||||
{
|
||||
AssertClose(new SKColor(0x0F, 0x5C, 0x8C, 0xFF), accent, 6, $"{s}: accent");
|
||||
}
|
||||
|
||||
// The centre of the moon (23.2, 8.8) is white.
|
||||
var moon = image.GetPixel(Scale(23.2, s), Scale(8.8, s));
|
||||
if (s >= 32)
|
||||
{
|
||||
AssertClose(SKColors.White, moon, 10, $"{s}: moon");
|
||||
}
|
||||
|
||||
// The centre of the ring (14.5, 17.5) is the accent, not white: it is a ring, not a disc.
|
||||
var hole = image.GetPixel(Scale(14.5, s), Scale(17.5, s));
|
||||
if (s >= 32)
|
||||
{
|
||||
AssertClose(new SKColor(0x0F, 0x5C, 0x8C, 0xFF), hole, 6, $"{s}: ring hole");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheWriterRefusesImagesThatAreNotSquareOrTooLarge()
|
||||
{
|
||||
using var wide = new SKBitmap(32, 16);
|
||||
using var huge = new SKBitmap(512, 512);
|
||||
Assert.ThrowsExactly<ArgumentException>(() => IcoWriter.Write([wide]));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => IcoWriter.Write([huge]));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => IcoWriter.Write([]));
|
||||
Assert.ThrowsExactly<InvalidDataException>(() => IcoWriter.ReadDirectory([1, 2, 3, 4, 5, 6]));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheCommittedIconIsWhatTheCodeDraws()
|
||||
{
|
||||
var path = Repository.PathOf("src", "Febe.Desktop", "Febe.ico");
|
||||
var fresh = BrandMark.RenderIcon();
|
||||
if (Environment.GetEnvironmentVariable("FEBE_RIGENERA_ICONA") == "1")
|
||||
{
|
||||
File.WriteAllBytes(path, fresh);
|
||||
}
|
||||
|
||||
Assert.IsTrue(File.Exists(path), "src/Febe.Desktop/Febe.ico manca: FEBE_RIGENERA_ICONA=1 lo genera.");
|
||||
var committed = File.ReadAllBytes(path);
|
||||
var a = IcoWriter.ReadDirectory(committed);
|
||||
var b = IcoWriter.ReadDirectory(fresh);
|
||||
CollectionAssert.AreEqual(b.Select(e => e.Size).ToArray(), a.Select(e => e.Size).ToArray());
|
||||
|
||||
// Pixel by pixel, with a small tolerance (antialiasing may differ by a unit between SkiaSharp builds).
|
||||
for (var i = 0; i < a.Count; i++)
|
||||
{
|
||||
using var left = IcoWriter.Decode(committed, a[i]);
|
||||
using var right = IcoWriter.Decode(fresh, b[i]);
|
||||
for (var y = 0; y < left.Height; y++)
|
||||
{
|
||||
for (var x = 0; x < left.Width; x++)
|
||||
{
|
||||
AssertClose(right.GetPixel(x, y), left.GetPixel(x, y), 3, $"{a[i].Size} px ({x},{y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int Scale(double coordinate, int size) => Math.Clamp((int)Math.Floor(coordinate * size / 32), 0, size - 1);
|
||||
|
||||
private static void AssertClose(SKColor expected, SKColor actual, int tolerance, string what)
|
||||
{
|
||||
var ok = Math.Abs(expected.Red - actual.Red) <= tolerance
|
||||
&& Math.Abs(expected.Green - actual.Green) <= tolerance
|
||||
&& Math.Abs(expected.Blue - actual.Blue) <= tolerance
|
||||
&& Math.Abs(expected.Alpha - actual.Alpha) <= tolerance;
|
||||
Assert.IsTrue(ok, $"{what}: atteso {expected}, trovato {actual}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Desktop;
|
||||
|
||||
/// <summary>
|
||||
/// The installer of Windows (spec §12, question 6 of §16): <c>installer/febe.nsi</c> compiles with makensis (a dry
|
||||
/// compile with a stand-in Febe.exe; skipped where NSIS is not installed), installs per user without administrator
|
||||
/// rights, registers its uninstaller in HKCU, and its uninstaller never deletes the Data folder or the library.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed partial class InstallerTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task TheScriptCompilesWithMakensisWithoutWarnings()
|
||||
{
|
||||
var makensis = FindOnPath("makensis");
|
||||
if (makensis is null)
|
||||
{
|
||||
Assert.Inconclusive("makensis non è installato (apt-get install nsis): la prova del programma di installazione si salta.");
|
||||
}
|
||||
|
||||
var script = Repository.PathOf("installer", "febe.nsi");
|
||||
using var temp = new TempFolder("nsis");
|
||||
await File.WriteAllTextAsync(temp.Combine("Febe.exe"), "MZ finto per la prova", TestContext.CancellationToken);
|
||||
var output = temp.Combine("Febe-Setup-0.0.1.exe");
|
||||
var start = new ProcessStartInfo(makensis)
|
||||
{
|
||||
WorkingDirectory = Path.GetDirectoryName(script)!,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
};
|
||||
foreach (var argument in new[] { "-V2", "-WX", "-INPUTCHARSET", "UTF8", "-DVERSION=0.0.1", "-DVERSIONE_FILE=0.0.1.0", $"-DSORGENTE={temp.Path}", $"-DUSCITA={output}", "febe.nsi" })
|
||||
{
|
||||
start.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
using var process = Process.Start(start)!;
|
||||
var stdout = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken);
|
||||
var stderr = process.StandardError.ReadToEndAsync(TestContext.CancellationToken);
|
||||
await process.WaitForExitAsync(TestContext.CancellationToken);
|
||||
Assert.AreEqual(0, process.ExitCode, $"makensis (avvisi = errori):\n{await stdout}\n{await stderr}");
|
||||
Assert.IsTrue(File.Exists(output));
|
||||
Assert.IsGreaterThan(100_000L, new FileInfo(output).Length);
|
||||
|
||||
// Without the version the script refuses to compile: it always comes from the build.
|
||||
using var noVersion = Process.Start(new ProcessStartInfo(makensis, ["-V1", $"-DSORGENTE={temp.Path}", $"-DUSCITA={temp.Combine("x.exe")}", "febe.nsi"])
|
||||
{
|
||||
WorkingDirectory = Path.GetDirectoryName(script)!,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
})!;
|
||||
await noVersion.WaitForExitAsync(TestContext.CancellationToken);
|
||||
Assert.AreNotEqual(0, noVersion.ExitCode);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheScriptInstallsPerUserAndItsUninstallerNeverTouchesTheData()
|
||||
{
|
||||
var text = File.ReadAllText(Repository.PathOf("installer", "febe.nsi"));
|
||||
StringAssert.Contains(text, "Unicode true");
|
||||
StringAssert.Contains(text, "RequestExecutionLevel user");
|
||||
StringAssert.Contains(text, "InstallDir \"$LOCALAPPDATA\\Programs\\Febe\"");
|
||||
StringAssert.Contains(text, "MUI_LANGUAGE \"Italian\"");
|
||||
StringAssert.Contains(text, "$SMPROGRAMS\\Febe.lnk");
|
||||
StringAssert.Contains(text, "Section \"Collegamento sul desktop\"");
|
||||
foreach (var value in new[] { "DisplayName", "DisplayVersion", "Publisher", "DisplayIcon", "UninstallString" })
|
||||
{
|
||||
StringAssert.Contains(text, $"WriteRegStr HKCU \"${{CHIAVE_DISINSTALLA}}\" \"{value}\"");
|
||||
}
|
||||
|
||||
StringAssert.Contains(text, "\"DisplayVersion\" \"${VERSION}\"");
|
||||
StringAssert.Contains(text, "\"Publisher\" \"${EDITORE}\"");
|
||||
StringAssert.Contains(text, "!define EDITORE \"Alberto Balbo\"");
|
||||
StringAssert.Contains(text, "EdgeUpdate\\Clients\\${WEBVIEW2_GUID}");
|
||||
StringAssert.Contains(text, "https://developer.microsoft.com/microsoft-edge/webview2/");
|
||||
Assert.DoesNotContain("HKLM\" \"${CHIAVE", text, "nothing written for every user");
|
||||
Assert.IsFalse(Regex.IsMatch(text, @"Write\w*\s+HKLM"), "no machine-wide registry");
|
||||
|
||||
// The uninstall section deletes only the program, its shortcuts and its registry entries.
|
||||
var uninstall = text[text.IndexOf("Section \"Uninstall\"", StringComparison.Ordinal)..];
|
||||
uninstall = uninstall[..uninstall.IndexOf("SectionEnd", StringComparison.Ordinal)];
|
||||
foreach (Match removal in Removals().Matches(uninstall))
|
||||
{
|
||||
var target = removal.Groups["target"].Value;
|
||||
Assert.IsTrue(
|
||||
target.StartsWith("$INSTDIR\\", StringComparison.Ordinal) || target == "$INSTDIR"
|
||||
|| target is "$SMPROGRAMS\\Febe.lnk" or "$DESKTOP\\Febe.lnk" or "$TEMP\\.net\\Febe",
|
||||
$"the uninstaller removes «{target}»: only the program may go");
|
||||
}
|
||||
|
||||
Assert.DoesNotContain("$LOCALAPPDATA\\Febe", uninstall.Replace("StrCpy $R8 \"$LOCALAPPDATA\\Febe\"", string.Empty, StringComparison.Ordinal), "never the Data folder");
|
||||
Assert.DoesNotContain("$PICTURES", uninstall, "never the library");
|
||||
Assert.DoesNotContain("MB_YESNO", uninstall, "it asks nothing about the data");
|
||||
StringAssert.Contains(uninstall, "DeleteRegValue HKCU \"${CHIAVE_AVVIO}\" \"Febe\"", "the start with the computer goes with the program");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheBuildScriptIsValidBashAndProducesTheTwoFilesUnder100Mb()
|
||||
{
|
||||
var script = Repository.PathOf("installer", "costruisci.sh");
|
||||
var text = File.ReadAllText(script);
|
||||
StringAssert.Contains(text, "set -euo pipefail");
|
||||
StringAssert.Contains(text, "-p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:EnableCompressionInSingleFile=true");
|
||||
StringAssert.Contains(text, "Febe-Setup-$versione.exe");
|
||||
StringAssert.Contains(text, "Febe-$versione-portabile.zip");
|
||||
StringAssert.Contains(text, "100 * 1024 * 1024");
|
||||
Assert.DoesNotContain("\r\n", text, "Unix line ends: bash would choke on CR");
|
||||
|
||||
var bash = FindOnPath("bash");
|
||||
if (bash is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
using var process = Process.Start(new ProcessStartInfo(bash, ["-n", script]) { RedirectStandardError = true })!;
|
||||
var errors = process.StandardError.ReadToEnd();
|
||||
process.WaitForExit();
|
||||
Assert.AreEqual(0, process.ExitCode, errors);
|
||||
}
|
||||
|
||||
private static string? FindOnPath(string name)
|
||||
{
|
||||
foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
foreach (var candidate in new[] { name, name + ".exe" })
|
||||
{
|
||||
var path = Path.Combine(folder, candidate);
|
||||
if (File.Exists(path))
|
||||
{
|
||||
return path;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"^\s*(?:Delete|RMDir)(?:\s+/\w+)*\s+""(?<target>[^""]+)""", RegexOptions.Multiline)]
|
||||
private static partial Regex Removals();
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using Febe.App;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Desktop;
|
||||
|
||||
/// <summary>
|
||||
/// Pieces of the shared composition (<see cref="FebeApp"/>) that both shells use: the alerts hook (spec §13.3) and the
|
||||
/// library folder that changes while Febe runs (desktop, spec §4.7). The Docker composition on top of it is proved by
|
||||
/// the Server tests (end-to-end with a real Chromium), unchanged.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class SharedCompositionTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
public void TheEventsOfSpec13_3BecomeAlertsAndNothingElse()
|
||||
{
|
||||
var at = new DateTimeOffset(2026, 10, 13, 9, 0, 0, TimeSpan.Zero);
|
||||
EventRecord Event(string code, string message = "testo") => new() { At = at, Severity = EventSeverity.Info, Code = code, Message = message };
|
||||
|
||||
var expected = new Dictionary<string, AlertKind>
|
||||
{
|
||||
[EngineEventCodes.ChallengeStop] = AlertKind.Verification,
|
||||
[EngineEventCodes.DisconnectStop] = AlertKind.Disconnection,
|
||||
[EngineEventCodes.ThrottleStop] = AlertKind.Throttle,
|
||||
[EngineEventCodes.ThrottleEnd] = AlertKind.Throttle,
|
||||
[EngineEventCodes.Resumed] = AlertKind.Throttle,
|
||||
[EngineEventCodes.BackfillCompleted] = AlertKind.BackfillDone,
|
||||
[EngineEventCodes.FormatUnrecognized] = AlertKind.UnknownFormat,
|
||||
[AlertRules.DiskLowCode] = AlertKind.DiskLow,
|
||||
};
|
||||
foreach (var (code, kind) in expected)
|
||||
{
|
||||
var alert = AlertRules.FromEvent(Event(code));
|
||||
Assert.IsNotNull(alert, code);
|
||||
Assert.AreEqual(kind, alert.Kind, code);
|
||||
Assert.AreEqual(at, alert.At);
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(alert.Title));
|
||||
}
|
||||
|
||||
foreach (var code in new[] { EngineEventCodes.SessionEnded, EngineEventCodes.BudgetReached, EngineEventCodes.Paused, "ricetta.ProfileCheck", "collegamento.primo" })
|
||||
{
|
||||
Assert.IsNull(AlertRules.FromEvent(Event(code)), code);
|
||||
}
|
||||
|
||||
// A long line (the key structure of an unknown format) is cut for a notification.
|
||||
var long_ = AlertRules.FromEvent(Event(EngineEventCodes.FormatUnrecognized, new string('k', 1000)))!;
|
||||
Assert.IsLessThanOrEqualTo(240, long_.Message.Length);
|
||||
|
||||
var none = new AlertEvents(false, false, false, false, false, false);
|
||||
Assert.IsFalse(Enum.GetValues<AlertKind>().Any(k => AlertRules.Wanted(k, none)));
|
||||
Assert.IsTrue(Enum.GetValues<AlertKind>().All(k => AlertRules.Wanted(k, AlertEvents.All)));
|
||||
Assert.IsFalse(AlertRules.Wanted(AlertKind.Throttle, AlertEvents.All with { Throttle = false }));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AChangedLibraryFolderTakesTheNextFilesWithoutMovingAnything()
|
||||
{
|
||||
using var temp = new TempFolder("cartella-libreria");
|
||||
await using var library = await TestLibrary.CreateAsync(temp);
|
||||
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
|
||||
var before = await library.SaveAsync(account, Make.Entry(account.Id, "1", Make.T0), [TestFile.Photo(1, 31)]);
|
||||
var oldFile = library.Layout.FullPath(account, before.Media[0].RelativePath!);
|
||||
Assert.IsTrue(File.Exists(oldFile));
|
||||
|
||||
// Impostazioni ▸ Generali ▸ «Cambia…» (desktop): the account with files keeps its folder, as the API does.
|
||||
var newRoot = temp.Combine("nuova libreria");
|
||||
await library.Db.Accounts.UpdateAsync(account with { Folder = library.Layout.AccountFolder(account) }, TestContext.CancellationToken);
|
||||
var other = await library.Db.Accounts.AddAsync(Make.Account("luca.demo", "200"));
|
||||
library.Ingest.UseLayout(new LibraryLayout(newRoot));
|
||||
Assert.AreEqual(newRoot, library.Ingest.Layout.Root);
|
||||
|
||||
var fixedAccount = (await library.Db.Accounts.GetAsync(account.Id, TestContext.CancellationToken))!;
|
||||
var again = await library.SaveAsync(fixedAccount, Make.Entry(account.Id, "2", Make.T0.AddDays(1)), [TestFile.Photo(1, 32)]);
|
||||
var fresh = await library.SaveAsync(other, Make.Entry(other.Id, "3", Make.T0.AddDays(2)), [TestFile.Photo(1, 33)]);
|
||||
|
||||
Assert.IsTrue(File.Exists(oldFile), "nothing moves (rule 12)");
|
||||
StringAssert.StartsWith(new LibraryLayout(newRoot).FullPath(fixedAccount, again.Media[0].RelativePath!), library.Layout.AccountFolder(account), "an account with files stays where it is");
|
||||
Assert.IsTrue(File.Exists(Path.Combine(newRoot, "luca.demo", fresh.Media[0].RelativePath!.Replace('/', Path.DirectorySeparatorChar))), "a new account goes to the new folder");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Febe.App;
|
||||
using Febe.Desktop.Core;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Desktop.Support;
|
||||
|
||||
/// <summary>
|
||||
/// The Windows composition on Linux: the shared <see cref="FebeApp"/> with the real <see cref="DesktopPlatform"/>
|
||||
/// (token of this start, 127.0.0.1 on a port chosen at start-up, start-up checks, hosting of S2, native services) and
|
||||
/// a fake of the Windows-only part (<see cref="FakeDesktopShell"/>). Data and library in a temporary folder; the
|
||||
/// interface is asked like the main window asks it, with the token and the Origin of the interface.
|
||||
/// </summary>
|
||||
internal sealed class DesktopTestBed : IAsyncDisposable
|
||||
{
|
||||
private readonly bool _ownsTemp;
|
||||
|
||||
private DesktopTestBed(TempFolder temp, bool ownsTemp, FakeDesktopShell shell, MemoryLocationStore locations, DesktopPlatform platform, FebeApp app)
|
||||
{
|
||||
Temp = temp;
|
||||
_ownsTemp = ownsTemp;
|
||||
Shell = shell;
|
||||
Locations = locations;
|
||||
Platform = platform;
|
||||
App = app;
|
||||
Client = new HttpClient(new HttpClientHandler { UseCookies = false, AllowAutoRedirect = false }) { BaseAddress = app.Address, Timeout = TimeSpan.FromSeconds(30) };
|
||||
}
|
||||
|
||||
public TempFolder Temp { get; }
|
||||
|
||||
public FakeDesktopShell Shell { get; }
|
||||
|
||||
public MemoryLocationStore Locations { get; }
|
||||
|
||||
public DesktopPlatform Platform { get; }
|
||||
|
||||
public FebeApp App { get; }
|
||||
|
||||
public HttpClient Client { get; }
|
||||
|
||||
public DesktopFolders Folders => new(Temp.Combine("AppData", "Local"), Temp.Combine("Immagini"));
|
||||
|
||||
/// <summary>The fake window «Browser di Febe» (null with a configuration problem or with Edge).</summary>
|
||||
public FakeBrowser? Browser => App.Browser as FakeBrowser;
|
||||
|
||||
public string Origin => $"{App.Address.Scheme}://{App.Address.Authority}";
|
||||
|
||||
public static async Task<DesktopTestBed> StartAsync(string[]? args = null, FakeDesktopShell? shell = null, TempFolder? temp = null, MemoryLocationStore? locations = null)
|
||||
{
|
||||
var ownsTemp = temp is null;
|
||||
temp ??= new TempFolder("desktop");
|
||||
shell ??= new FakeDesktopShell();
|
||||
locations ??= new MemoryLocationStore();
|
||||
if (!DesktopCommandLine.TryParse(args ?? [], out var options, out var problem))
|
||||
{
|
||||
throw new ArgumentException(problem);
|
||||
}
|
||||
|
||||
var folders = new DesktopFolders(temp.Combine("AppData", "Local"), temp.Combine("Immagini"));
|
||||
var platform = new DesktopPlatform(options, shell, locations, dataFolderFixed: options.DataFolder is not null);
|
||||
var app = await FebeApp.StartAsync(options.AppOptions(options.DataFolder ?? folders.DefaultDataFolder, folders), platform, new FebeAppHooks { ShutdownTimeout = TimeSpan.FromSeconds(1) });
|
||||
return new DesktopTestBed(temp, ownsTemp, shell, locations, platform, app);
|
||||
}
|
||||
|
||||
/// <summary>A request as the main window sends it: the token (here as the header the cookie stands for) and the Origin.</summary>
|
||||
public async Task<HttpResponseMessage> SendAsync(HttpMethod method, string path, string? json = null, bool token = true)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, path);
|
||||
if (token)
|
||||
{
|
||||
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");
|
||||
}
|
||||
|
||||
return await Client.SendAsync(request);
|
||||
}
|
||||
|
||||
public async Task<JsonElement> JsonAsync(HttpMethod method, string path, string? json = null)
|
||||
{
|
||||
using var response = await SendAsync(method, path, json);
|
||||
var text = await response.Content.ReadAsStringAsync();
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
|
||||
return JsonDocument.Parse(text).RootElement.Clone();
|
||||
}
|
||||
|
||||
public static async Task WaitUntilAsync(Func<bool> condition, TimeSpan timeout, string what)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (!condition())
|
||||
{
|
||||
if (DateTime.UtcNow > deadline)
|
||||
{
|
||||
Assert.Fail($"Tempo scaduto: {what}.");
|
||||
}
|
||||
|
||||
await Task.Delay(50);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stops the composition; the folders stay for a second start (dispose <see cref="Temp"/> at the end).</summary>
|
||||
public async ValueTask StopAsync()
|
||||
{
|
||||
Client.Dispose();
|
||||
await App.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>Stops; deletes the temporary folder only when the bed created it (a shared one is the caller's).</summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await StopAsync();
|
||||
if (_ownsTemp)
|
||||
{
|
||||
Temp.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.App;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Desktop.Core;
|
||||
using Febe.Web.Native;
|
||||
|
||||
namespace Febe.Tests.Desktop.Support;
|
||||
|
||||
/// <summary>The Windows-only part of the desktop, faked: what the platform asks of it is recorded.</summary>
|
||||
internal sealed class FakeDesktopShell : IDesktopShell
|
||||
{
|
||||
public FakeNativeShell NativeShell { get; } = new();
|
||||
|
||||
public RecordingAlertChannel Alerts { get; } = new();
|
||||
|
||||
public INativeShell Native => NativeShell;
|
||||
|
||||
public IAlertChannel? Notifications => Alerts;
|
||||
|
||||
/// <summary>The WebView2 runtime this «Windows» has (null: missing).</summary>
|
||||
public string? RuntimeVersion { get; set; } = "141.0.3537.71";
|
||||
|
||||
/// <summary>Where «Edge» is (null: not installed).</summary>
|
||||
public string? EdgePath { get; set; }
|
||||
|
||||
/// <summary>The browsers created, with the settings the platform gave them.</summary>
|
||||
public ConcurrentQueue<(WebView2BrowserSettings Settings, FakeBrowser Browser)> Created { get; } = new();
|
||||
|
||||
public ConcurrentQueue<string> ProcessWindows { get; } = new();
|
||||
|
||||
public string? WebView2Version() => RuntimeVersion;
|
||||
|
||||
public IFebeBrowser CreateWebView2Browser(WebView2BrowserSettings settings, FebePlatformContext context)
|
||||
{
|
||||
var browser = new FakeBrowser(settings.ProfileDirectory, settings.Width, settings.Height, context);
|
||||
Created.Enqueue((settings, browser));
|
||||
return browser;
|
||||
}
|
||||
|
||||
public string? FindEdge() => EdgePath;
|
||||
|
||||
public Task ShowProcessWindowAsync(int processId, CancellationToken ct)
|
||||
{
|
||||
ProcessWindows.Enqueue("mostra " + processId);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task HideProcessWindowAsync(int processId, CancellationToken ct)
|
||||
{
|
||||
ProcessWindows.Enqueue("nascondi " + processId);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Folder picker, explorer, default browser, notifications and autostart, faked.</summary>
|
||||
internal sealed class FakeNativeShell : INativeShell
|
||||
{
|
||||
public bool CanPickFolder => true;
|
||||
|
||||
public bool CanShowInFolder => true;
|
||||
|
||||
public bool CanOpenUrl => true;
|
||||
|
||||
public bool CanNotify => true;
|
||||
|
||||
public bool SupportsAutostart => true;
|
||||
|
||||
public bool Autostart { get; private set; }
|
||||
|
||||
public string? FolderToPick { get; set; }
|
||||
|
||||
public ConcurrentQueue<string> Shown { get; } = new();
|
||||
|
||||
public ConcurrentQueue<Uri> Opened { get; } = new();
|
||||
|
||||
public ConcurrentQueue<(string Title, string Message)> Notified { get; } = new();
|
||||
|
||||
public Task<string?> PickFolderAsync(string title, string? initialFolder, CancellationToken ct) => Task.FromResult(FolderToPick);
|
||||
|
||||
public Task<bool> ShowInFolderAsync(string fullPath, CancellationToken ct)
|
||||
{
|
||||
Shown.Enqueue(fullPath);
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
public Task<bool> OpenUrlAsync(Uri address, CancellationToken ct)
|
||||
{
|
||||
Opened.Enqueue(address);
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
public Task NotifyAsync(string title, string message, CancellationToken ct)
|
||||
{
|
||||
Notified.Enqueue((title, message));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<bool> GetAutostartAsync(CancellationToken ct) => Task.FromResult(Autostart);
|
||||
|
||||
public Task SetAutostartAsync(bool enabled, CancellationToken ct)
|
||||
{
|
||||
Autostart = enabled;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The Windows notifications, recorded.</summary>
|
||||
internal sealed class RecordingAlertChannel : IAlertChannel
|
||||
{
|
||||
public ConcurrentQueue<FebeAlert> Received { get; } = new();
|
||||
|
||||
public bool IsEnabled(AlertSettings settings) => settings.WindowsNotifications;
|
||||
|
||||
public Task SendAsync(FebeAlert alert, AlertSettings settings, CancellationToken ct)
|
||||
{
|
||||
Received.Enqueue(alert);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The window «Browser di Febe», faked: a CDP session that answers like a browser on a blank page, a session cookie
|
||||
/// that exists once «Alberto» has logged in, and a record of every time the window came to the front or went away.
|
||||
/// </summary>
|
||||
internal sealed class FakeBrowser : IFebeBrowser
|
||||
{
|
||||
private readonly FebePlatformContext _context;
|
||||
private IDisposable? _lease;
|
||||
|
||||
public FakeBrowser(string profileDirectory, int width, int height, FebePlatformContext context)
|
||||
{
|
||||
ProfileDirectory = profileDirectory;
|
||||
WindowWidth = width;
|
||||
WindowHeight = height;
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public FakeCdp FakeCdp { get; } = new();
|
||||
|
||||
public ICdpSession Cdp => FakeCdp;
|
||||
|
||||
public UserDrivingGate UserDriving { get; } = new();
|
||||
|
||||
public bool UserIsDriving => UserDriving.IsDriving;
|
||||
|
||||
public bool IsAvailable { get; private set; }
|
||||
|
||||
public string? LastError => null;
|
||||
|
||||
public string ProfileDirectory { get; }
|
||||
|
||||
public int WindowWidth { get; }
|
||||
|
||||
public int WindowHeight { get; }
|
||||
|
||||
public int Shown { get; private set; }
|
||||
|
||||
public int Hidden { get; private set; }
|
||||
|
||||
public int EmptiedProfiles { get; private set; }
|
||||
|
||||
public bool Disposed { get; private set; }
|
||||
|
||||
public Task RunAsync(CancellationToken ct)
|
||||
{
|
||||
Directory.CreateDirectory(ProfileDirectory);
|
||||
IsAvailable = true;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<NavigationResult> RestAsync(CancellationToken ct) => FakeCdp.NavigateAsync(CdpPageExtensions.RestUrl, ct);
|
||||
|
||||
/// <summary>Like the real window: in front, Alberto is driving.</summary>
|
||||
public Task ShowToUserAsync(CancellationToken ct)
|
||||
{
|
||||
Shown++;
|
||||
_lease ??= UserDriving.Begin();
|
||||
_context.Tracker.MarkUsed(_context.Clock.Now);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task HideFromUserAsync(CancellationToken ct)
|
||||
{
|
||||
Hidden++;
|
||||
_lease?.Dispose();
|
||||
_lease = null;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>The next «Scollega» finds a file held by another process (Windows) and cannot delete the profile.</summary>
|
||||
public bool ProfileLocked { get; set; }
|
||||
|
||||
public Task RestartWithEmptyProfileAsync(CancellationToken ct)
|
||||
{
|
||||
if (ProfileLocked)
|
||||
{
|
||||
throw new IOException("Il file Cookies è in uso da un altro processo.");
|
||||
}
|
||||
|
||||
if (Directory.Exists(ProfileDirectory))
|
||||
{
|
||||
Directory.Delete(ProfileDirectory, recursive: true);
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(ProfileDirectory);
|
||||
FakeCdp.LoggedIn = false;
|
||||
EmptiedProfiles++;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
Disposed = true;
|
||||
IsAvailable = false;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A CDP session answering like a page: frame tree, navigation, the session cookie (name only).</summary>
|
||||
internal sealed class FakeCdp : ICdpSession
|
||||
{
|
||||
public bool LoggedIn { get; set; }
|
||||
|
||||
public string Url { get; private set; } = "about:blank";
|
||||
|
||||
public ConcurrentQueue<string> Methods { get; } = new();
|
||||
|
||||
public Task<JsonElement> SendAsync(string method, object? parameters = null, CancellationToken ct = default)
|
||||
{
|
||||
CdpCommandPolicy.EnsureAllowed(method);
|
||||
Methods.Enqueue(method);
|
||||
JsonNode result = method switch
|
||||
{
|
||||
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = Url } } },
|
||||
"Page.navigate" => Navigate(parameters),
|
||||
"Network.getCookies" => new JsonObject { ["cookies"] = LoggedIn ? new JsonArray(new JsonObject { ["name"] = "sessionid" }) : new JsonArray() },
|
||||
_ => new JsonObject(),
|
||||
};
|
||||
return Task.FromResult(JsonDocument.Parse(result.ToJsonString()).RootElement.Clone());
|
||||
}
|
||||
|
||||
public IDisposable On(string eventName, Action<JsonElement> handler) => new Nothing();
|
||||
|
||||
private JsonObject Navigate(object? parameters)
|
||||
{
|
||||
Url = (parameters as JsonObject)?["url"]?.GetValue<string>() ?? Url;
|
||||
return new JsonObject { ["frameId"] = "F1" };
|
||||
}
|
||||
|
||||
private sealed class Nothing : IDisposable
|
||||
{
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Febe.Browser.Diagnostics;
|
||||
using Febe.Browser.WebView2;
|
||||
|
||||
namespace Febe.Tests.Desktop.Support;
|
||||
|
||||
/// <summary>
|
||||
/// A stand-in for the two WebView2 calls (<c>CallDevToolsProtocolMethodAsync</c>, <c>GetDevToolsProtocolEventReceiver</c>):
|
||||
/// records what reaches «WebView2», answers with <see cref="Answer"/>, and raises events like WebView2 does, on the
|
||||
/// thread of the caller (WebView2's UI thread in the real application).
|
||||
/// </summary>
|
||||
internal sealed class FakeDevTools : IWebView2DevTools
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, List<Action<string>>> _receivers = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Every call that reached «WebView2»: method and parameters as JSON.</summary>
|
||||
public ConcurrentQueue<(string Method, string Json)> Calls { get; } = new();
|
||||
|
||||
/// <summary>The answer to a call (default: an empty result object).</summary>
|
||||
public Func<string, string, Task<string>> Answer { get; set; } = (_, _) => Task.FromResult("{}");
|
||||
|
||||
/// <summary>How many event handlers are attached to «WebView2» right now, by event name.</summary>
|
||||
public int Subscribed(string eventName) => _receivers.TryGetValue(eventName, out var list) ? list.Count : 0;
|
||||
|
||||
/// <summary>Total subscriptions ever made (to see re-subscriptions after a new WebView).</summary>
|
||||
public int SubscriptionsMade { get; private set; }
|
||||
|
||||
public Task<string> CallMethodAsync(string methodName, string parametersAsJson)
|
||||
{
|
||||
Calls.Enqueue((methodName, parametersAsJson));
|
||||
return Answer(methodName, parametersAsJson);
|
||||
}
|
||||
|
||||
public IDisposable Subscribe(string eventName, Action<string> onEvent)
|
||||
{
|
||||
var list = _receivers.GetOrAdd(eventName, _ => []);
|
||||
lock (list)
|
||||
{
|
||||
list.Add(onEvent);
|
||||
}
|
||||
|
||||
SubscriptionsMade++;
|
||||
return new Removal(() =>
|
||||
{
|
||||
lock (list)
|
||||
{
|
||||
list.Remove(onEvent);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>«WebView2» receives a protocol event: <c>ParameterObjectAsJson</c> goes to the handlers.</summary>
|
||||
public void Raise(string eventName, string parametersJson)
|
||||
{
|
||||
if (!_receivers.TryGetValue(eventName, out var list))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Action<string>[] handlers;
|
||||
lock (list)
|
||||
{
|
||||
handlers = [.. list];
|
||||
}
|
||||
|
||||
foreach (var handler in handlers)
|
||||
{
|
||||
handler(parametersJson);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Removal(Action remove) : IDisposable
|
||||
{
|
||||
private Action? _remove = remove;
|
||||
|
||||
public void Dispose() => Interlocked.Exchange(ref _remove, null)?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Collects what the browser layer logs (to prove that only names get there).</summary>
|
||||
internal sealed class RecordingBrowserLog : IBrowserLog
|
||||
{
|
||||
public ConcurrentQueue<string> Lines { get; } = new();
|
||||
|
||||
public void Write(BrowserLogLevel level, string message, Exception? exception = null) =>
|
||||
Lines.Enqueue($"{level} {message} {exception?.GetType().Name} {exception?.Message}");
|
||||
|
||||
public string All => string.Join('\n', Lines);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using Febe.Desktop.Core;
|
||||
|
||||
namespace Febe.Tests.Desktop.Support;
|
||||
|
||||
/// <summary>The registry values «CartellaDati» and «NuovaCartellaDati», in memory.</summary>
|
||||
internal sealed class MemoryLocationStore : IDataFolderLocationStore
|
||||
{
|
||||
public string? Current { get; set; }
|
||||
|
||||
public string? Pending { get; set; }
|
||||
|
||||
public void SetCurrent(string? folder) => Current = folder;
|
||||
|
||||
public void SetPending(string? folder) => Pending = folder;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
namespace Febe.Tests.Desktop.Support;
|
||||
|
||||
/// <summary>Files of the repository the desktop tests look at (the committed icon, the NSIS script).</summary>
|
||||
internal static class Repository
|
||||
{
|
||||
/// <summary>The folder with Febe.slnx, found from the test binaries upward; null outside a checkout.</summary>
|
||||
public static string? Root()
|
||||
{
|
||||
for (var folder = new DirectoryInfo(AppContext.BaseDirectory); folder is not null; folder = folder.Parent)
|
||||
{
|
||||
if (File.Exists(Path.Combine(folder.FullName, "Febe.slnx")))
|
||||
{
|
||||
return folder.FullName;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>A file of the repository; the test is inconclusive when the checkout is not there.</summary>
|
||||
public static string PathOf(params string[] parts)
|
||||
{
|
||||
var root = Root();
|
||||
if (root is null)
|
||||
{
|
||||
Assert.Inconclusive("Il repository non è accanto alle prove.");
|
||||
}
|
||||
|
||||
return Path.Combine([root, .. parts]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.WebView2;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
|
||||
namespace Febe.Tests.Desktop;
|
||||
|
||||
/// <summary>
|
||||
/// The CDP adapter of WebView2 (spec §6.1, Windows) with a fake of the two WebView2 calls: the same allowlist and
|
||||
/// refusals as the Chromium client, JSON in and out, events routed in order to their handlers, names only in the log.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class WebView2CdpSessionTests
|
||||
{
|
||||
private const string Secret = "segreto-che-non-deve-uscire";
|
||||
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
public async Task AllowedCommandsReachWebView2AsJsonAndResultsComeBackAsElements()
|
||||
{
|
||||
var devTools = new FakeDevTools
|
||||
{
|
||||
Answer = (method, _) => Task.FromResult(method == "Page.getFrameTree"
|
||||
? """{"frameTree":{"frame":{"id":"F1","url":"about:blank"}}}"""
|
||||
: "{}"),
|
||||
};
|
||||
await using var session = new WebView2CdpSession();
|
||||
session.Attach(devTools);
|
||||
|
||||
var tree = await session.SendAsync("Page.getFrameTree", ct: TestContext.CancellationToken);
|
||||
Assert.AreEqual("F1", tree.GetProperty("frameTree").GetProperty("frame").GetProperty("id").GetString());
|
||||
Assert.AreEqual("about:blank", await session.GetMainFrameUrlAsync(TestContext.CancellationToken));
|
||||
|
||||
await session.SendAsync("Page.navigate", new JsonObject { ["url"] = "http://127.0.0.1:8481/" }, TestContext.CancellationToken);
|
||||
await session.SendAsync("Input.dispatchMouseEvent", new { type = "mouseWheel", x = 10, y = 20, deltaX = 0, deltaY = 120 }, TestContext.CancellationToken);
|
||||
await session.SendAsync("Page.enable", ct: TestContext.CancellationToken);
|
||||
|
||||
var calls = devTools.Calls.ToArray();
|
||||
Assert.AreEqual("Page.navigate", calls[2].Method);
|
||||
Assert.AreEqual("http://127.0.0.1:8481/", JsonNode.Parse(calls[2].Json)!["url"]!.GetValue<string>());
|
||||
var mouse = JsonNode.Parse(calls[3].Json)!;
|
||||
Assert.AreEqual("mouseWheel", mouse["type"]!.GetValue<string>());
|
||||
Assert.AreEqual(120, mouse["deltaY"]!.GetValue<int>());
|
||||
Assert.AreEqual("{}", calls[4].Json, "no parameters: an empty object, as WebView2 wants");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task EveryCommandOutsideTheAllowlistIsRefusedBeforeWebView2()
|
||||
{
|
||||
var devTools = new FakeDevTools();
|
||||
await using var session = new WebView2CdpSession();
|
||||
session.Attach(devTools);
|
||||
foreach (var method in new[]
|
||||
{
|
||||
"Network.setUserAgentOverride", "Network.setExtraHTTPHeaders", "Page.addScriptToEvaluateOnNewDocument",
|
||||
"Emulation.setTimezoneOverride", "Emulation.setUserAgentOverride", "Fetch.enable", "Fetch.continueRequest",
|
||||
"Target.createTarget", "Page.reload", "Runtime.callFunctionOn", "Network.setCookie", "Storage.getCookies",
|
||||
"DOM.setAttributeValue", "Browser.close",
|
||||
})
|
||||
{
|
||||
var error = await Assert.ThrowsAsync<CdpCommandNotAllowedException>(() => session.SendAsync(method, new { value = Secret }, TestContext.CancellationToken));
|
||||
Assert.AreEqual(method, error.Method);
|
||||
Assert.DoesNotContain(Secret, error.Message);
|
||||
}
|
||||
|
||||
Assert.IsEmpty(devTools.Calls, "nothing refused ever reaches WebView2");
|
||||
|
||||
// Every command of the allowlist passes (Runtime.evaluate only read-only).
|
||||
foreach (var method in CdpCommandPolicy.Allowed.Where(m => m != "Runtime.evaluate"))
|
||||
{
|
||||
await session.SendAsync(method, ct: TestContext.CancellationToken);
|
||||
}
|
||||
|
||||
Assert.HasCount(CdpCommandPolicy.Allowed.Count - 1, devTools.Calls);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RuntimeEvaluateOnlyReadsThePage()
|
||||
{
|
||||
var devTools = new FakeDevTools { Answer = (_, _) => Task.FromResult("""{"result":{"type":"string","value":"complete"}}""") };
|
||||
await using var session = new WebView2CdpSession();
|
||||
session.Attach(devTools);
|
||||
|
||||
var value = await session.EvaluateAsync("document.readyState", TestContext.CancellationToken);
|
||||
Assert.AreEqual("complete", value.GetString());
|
||||
|
||||
foreach (var expression in new[] { "document.querySelector('a').click()", "window.scrollBy(0, 400)", "document.cookie", "fetch('/api')", "location = 'https://example.org'" })
|
||||
{
|
||||
await Assert.ThrowsAsync<CdpCommandNotAllowedException>(() => session.SendAsync("Runtime.evaluate", new JsonObject { ["expression"] = expression }, TestContext.CancellationToken));
|
||||
}
|
||||
|
||||
Assert.HasCount(1, devTools.Calls, "only the read-only expression was sent");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task EventsReachTheirHandlersInOrderOffTheCallersThreadAndStopWhenUnsubscribed()
|
||||
{
|
||||
var devTools = new FakeDevTools();
|
||||
await using var session = new WebView2CdpSession();
|
||||
session.Attach(devTools);
|
||||
var received = new ConcurrentQueue<(string Handler, int N)>();
|
||||
var handlerThreads = new ConcurrentBag<int>();
|
||||
using var first = session.On("Network.responseReceived", e =>
|
||||
{
|
||||
handlerThreads.Add(Environment.CurrentManagedThreadId);
|
||||
received.Enqueue(("a", e.GetProperty("n").GetInt32()));
|
||||
});
|
||||
var second = session.On("Network.responseReceived", e => received.Enqueue(("b", e.GetProperty("n").GetInt32())));
|
||||
using var other = session.On("Page.frameNavigated", e => received.Enqueue(("nav", 0)));
|
||||
Assert.AreEqual(1, devTools.Subscribed("Network.responseReceived"), "one WebView2 receiver per event name");
|
||||
|
||||
// WebView2 raises events on its UI thread: here a thread of its own, which no handler may run on.
|
||||
var raisingThread = 0;
|
||||
var ui = new Thread(() =>
|
||||
{
|
||||
raisingThread = Environment.CurrentManagedThreadId;
|
||||
for (var i = 1; i <= 50; i++)
|
||||
{
|
||||
devTools.Raise("Network.responseReceived", $$"""{"n":{{i}}}""");
|
||||
}
|
||||
|
||||
devTools.Raise("Page.frameNavigated", """{"frame":{"id":"F1"}}""");
|
||||
devTools.Raise("Network.loadingFinished", """{"requestId":"1"}"""); // nobody listens
|
||||
});
|
||||
ui.Start();
|
||||
ui.Join();
|
||||
await session.DrainAsync();
|
||||
|
||||
var a = received.Where(r => r.Handler == "a").Select(r => r.N).ToArray();
|
||||
CollectionAssert.AreEqual(Enumerable.Range(1, 50).ToArray(), a, "in order");
|
||||
Assert.AreEqual(50, received.Count(r => r.Handler == "b"));
|
||||
Assert.AreEqual(1, received.Count(r => r.Handler == "nav"));
|
||||
Assert.IsFalse(handlerThreads.Contains(raisingThread), "handlers never run on WebView2's (UI) thread");
|
||||
|
||||
second.Dispose();
|
||||
devTools.Raise("Network.responseReceived", """{"n":51}""");
|
||||
await session.DrainAsync();
|
||||
Assert.AreEqual(50, received.Count(r => r.Handler == "b"), "an unsubscribed handler gets nothing");
|
||||
Assert.AreEqual(51, received.Count(r => r.Handler == "a"));
|
||||
|
||||
first.Dispose();
|
||||
Assert.AreEqual(0, devTools.Subscribed("Network.responseReceived"), "the last handler removes the WebView2 receiver");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AHandlerThatThrowsOrSendsACommandDoesNotStopTheOthers()
|
||||
{
|
||||
var devTools = new FakeDevTools { Answer = (_, _) => Task.FromResult("""{"body":"x","base64Encoded":false}""") };
|
||||
var log = new RecordingBrowserLog();
|
||||
await using var session = new WebView2CdpSession(log);
|
||||
session.Attach(devTools);
|
||||
var bodies = new ConcurrentQueue<string>();
|
||||
using var bad = session.On("Network.loadingFinished", _ => throw new InvalidOperationException(Secret));
|
||||
|
||||
// The pattern of ResponseTap: the handler queues the command, it never blocks.
|
||||
using var good = session.On("Network.loadingFinished", e => _ = Task.Run(async () =>
|
||||
{
|
||||
var body = await session.SendAsync("Network.getResponseBody", new JsonObject { ["requestId"] = e.GetProperty("requestId").GetString() });
|
||||
bodies.Enqueue(body.GetProperty("body").GetString()!);
|
||||
}));
|
||||
devTools.Raise("Network.loadingFinished", """{"requestId":"7"}""");
|
||||
await session.DrainAsync();
|
||||
for (var i = 0; i < 50 && bodies.IsEmpty; i++)
|
||||
{
|
||||
await Task.Delay(20, TestContext.CancellationToken);
|
||||
}
|
||||
|
||||
Assert.AreEqual("x", bodies.Single());
|
||||
StringAssert.Contains(log.All, "Network.loadingFinished");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheLogHasCommandAndEventNamesOnlyNeverParametersResultsOrErrorsText()
|
||||
{
|
||||
var log = new RecordingBrowserLog();
|
||||
var devTools = new FakeDevTools
|
||||
{
|
||||
Answer = (method, json) => method switch
|
||||
{
|
||||
"Network.getCookies" => Task.FromResult($$"""{"cookies":[{"name":"sessionid","value":"{{Secret}}"}]}"""),
|
||||
|
||||
// WebView2 reports a protocol error as an exception whose message carries the error object (and here
|
||||
// also the parameters, which must not get anywhere).
|
||||
"Network.getResponseBody" => Task.FromException<string>(new InvalidOperationException(
|
||||
$$"""Errore 0x80004005 per {{json}}: {"code":-32000,"message":"No resource with given identifier found","data":"{{Secret}}"}""")),
|
||||
_ => Task.FromResult("{}"),
|
||||
},
|
||||
};
|
||||
await using var session = new WebView2CdpSession(log);
|
||||
session.Attach(devTools);
|
||||
|
||||
await session.SendAsync("Input.dispatchKeyEvent", new { type = "char", text = Secret }, TestContext.CancellationToken);
|
||||
var cookies = await session.SendAsync("Network.getCookies", new { urls = new[] { "https://www.instagram.com/?x=" + Secret } }, TestContext.CancellationToken);
|
||||
Assert.AreEqual("sessionid", cookies.GetProperty("cookies")[0].GetProperty("name").GetString());
|
||||
var error = await Assert.ThrowsAsync<CdpCommandException>(() => session.SendAsync("Network.getResponseBody", new { requestId = Secret }, TestContext.CancellationToken));
|
||||
Assert.AreEqual(-32000, error.Code);
|
||||
Assert.AreEqual("No resource with given identifier found", error.BrowserMessage);
|
||||
Assert.DoesNotContain(Secret, error.Message, "only the code and the message of the protocol error");
|
||||
|
||||
using (session.On("Network.responseReceived", _ => throw new InvalidOperationException("gestore")))
|
||||
{
|
||||
devTools.Raise("Network.responseReceived", $$$"""{"response":{"url":"https://cdn/{{{Secret}}}"}}""");
|
||||
await session.DrainAsync();
|
||||
}
|
||||
|
||||
var all = log.All;
|
||||
StringAssert.Contains(all, "Input.dispatchKeyEvent");
|
||||
StringAssert.Contains(all, "Network.getCookies");
|
||||
StringAssert.Contains(all, "Network.getResponseBody");
|
||||
StringAssert.Contains(all, "Network.responseReceived");
|
||||
Assert.DoesNotContain(Secret, all, "never parameters, results, events or error text in the log");
|
||||
Assert.DoesNotContain("instagram.com", all);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AFailureWithoutAProtocolErrorKeepsOnlyItsCode()
|
||||
{
|
||||
var devTools = new FakeDevTools { Answer = (_, _) => Task.FromException<string>(new InvalidOperationException("c:\\Users\\alberto " + Secret) { HResult = unchecked((int)0x8007139F) }) };
|
||||
await using var session = new WebView2CdpSession();
|
||||
session.Attach(devTools);
|
||||
var error = await Assert.ThrowsAsync<CdpCommandException>(() => session.SendAsync("Page.enable", ct: TestContext.CancellationToken));
|
||||
Assert.AreEqual(unchecked((int)0x8007139F), error.Code);
|
||||
Assert.DoesNotContain(Secret, error.Message);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutAWebViewCommandsFailFastAndAClosingWebViewIsADisconnection()
|
||||
{
|
||||
await using var session = new WebView2CdpSession();
|
||||
await Assert.ThrowsAsync<BrowserUnavailableException>(() => session.SendAsync("Page.enable", ct: TestContext.CancellationToken));
|
||||
|
||||
// Policy first: a forbidden command is reported as such even without a WebView.
|
||||
await Assert.ThrowsAsync<CdpCommandNotAllowedException>(() => session.SendAsync("Emulation.setLocaleOverride", ct: TestContext.CancellationToken));
|
||||
|
||||
var devTools = new FakeDevTools { Answer = (_, _) => Task.FromException<string>(new CdpDisconnectedException("chiuso")) };
|
||||
session.Attach(devTools);
|
||||
await Assert.ThrowsAsync<CdpDisconnectedException>(() => session.SendAsync("Page.enable", ct: TestContext.CancellationToken));
|
||||
|
||||
session.Detach();
|
||||
Assert.IsFalse(session.IsAttached);
|
||||
await Assert.ThrowsAsync<BrowserUnavailableException>(() => session.SendAsync("Page.enable", ct: TestContext.CancellationToken));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ACommandWithoutAnswerTimesOutAndCancellationIsHonoured()
|
||||
{
|
||||
var never = new TaskCompletionSource<string>();
|
||||
var devTools = new FakeDevTools { Answer = (_, _) => never.Task };
|
||||
await using var session = new WebView2CdpSession(options: new WebView2CdpOptions(TimeSpan.FromMilliseconds(200)));
|
||||
session.Attach(devTools);
|
||||
var timeout = await Assert.ThrowsAsync<TimeoutException>(() => session.SendAsync("Page.enable", ct: TestContext.CancellationToken));
|
||||
StringAssert.Contains(timeout.Message, "Page.enable");
|
||||
|
||||
using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(50));
|
||||
await Assert.ThrowsAsync<TaskCanceledException>(() => session.SendAsync("Page.enable", ct: cancel.Token));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ANewWebViewKeepsTheSubscriptionsAndSaysItReconnected()
|
||||
{
|
||||
await using var session = new WebView2CdpSession();
|
||||
var reconnected = 0;
|
||||
session.Reconnected += (_, _) => reconnected++;
|
||||
var received = new ConcurrentQueue<string>();
|
||||
using var subscription = session.On("Page.screencastFrame", e => received.Enqueue(e.GetProperty("data").GetString()!));
|
||||
|
||||
var first = new FakeDevTools();
|
||||
session.Attach(first);
|
||||
Assert.AreEqual(0, reconnected, "the first WebView is not a reconnection");
|
||||
first.Raise("Page.screencastFrame", """{"data":"uno","sessionId":1}""");
|
||||
await session.DrainAsync();
|
||||
|
||||
// The browser process restarted («Scollega», crash): a new WebView, the same session object.
|
||||
session.Detach();
|
||||
Assert.AreEqual(0, first.Subscribed("Page.screencastFrame"), "the old WebView's receivers are removed");
|
||||
var second = new FakeDevTools();
|
||||
session.Attach(second);
|
||||
Assert.AreEqual(1, reconnected);
|
||||
Assert.AreEqual(1, second.Subscribed("Page.screencastFrame"), "subscriptions survive");
|
||||
first.Raise("Page.screencastFrame", """{"data":"vecchio"}""");
|
||||
second.Raise("Page.screencastFrame", """{"data":"due","sessionId":2}""");
|
||||
await session.DrainAsync();
|
||||
CollectionAssert.AreEqual(new[] { "uno", "due" }, received.ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ProtocolErrorsAreReadFromTheMessageOfWebView2()
|
||||
{
|
||||
var error = WebView2CdpSession.ProtocolError("IO.read", new InvalidOperationException("""{"code":-32602,"message":"Invalid parameters","data":"handle: string value expected"}"""));
|
||||
Assert.AreEqual(-32602, error.Code);
|
||||
Assert.AreEqual("Invalid parameters", error.BrowserMessage);
|
||||
Assert.AreEqual("IO.read", error.Method);
|
||||
|
||||
var garbled = WebView2CdpSession.ProtocolError("IO.read", new InvalidOperationException("{ non è json }"));
|
||||
Assert.AreEqual("errore di WebView2", garbled.BrowserMessage);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UnreadableEventsAreSkippedAndLoggedByNameOnly()
|
||||
{
|
||||
var log = new RecordingBrowserLog();
|
||||
var devTools = new FakeDevTools();
|
||||
await using var session = new WebView2CdpSession(log);
|
||||
session.Attach(devTools);
|
||||
var good = 0;
|
||||
using var subscription = session.On("Page.loadEventFired", _ => good++);
|
||||
devTools.Raise("Page.loadEventFired", "{non json " + Secret);
|
||||
devTools.Raise("Page.loadEventFired", """{"timestamp":1}""");
|
||||
await session.DrainAsync();
|
||||
Assert.AreEqual(1, good);
|
||||
StringAssert.Contains(log.All, "Page.loadEventFired");
|
||||
Assert.DoesNotContain(Secret, log.All);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ResultsAreSelfContainedElements()
|
||||
{
|
||||
var devTools = new FakeDevTools { Answer = (_, _) => Task.FromResult("""{"data":"AAEC","base64Encoded":true,"eof":true}""") };
|
||||
await using var session = new WebView2CdpSession();
|
||||
session.Attach(devTools);
|
||||
var chunk = await session.SendAsync("IO.read", new { handle = "h" }, TestContext.CancellationToken);
|
||||
GC.Collect();
|
||||
Assert.AreEqual(JsonValueKind.True, chunk.GetProperty("eof").ValueKind);
|
||||
CollectionAssert.AreEqual(new byte[] { 0, 1, 2 }, Convert.FromBase64String(chunk.GetProperty("data").GetString()!));
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,9 @@
|
||||
<ProjectReference Include="..\..\src\Febe.Data\Febe.Data.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.Browser\Febe.Browser.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.Web\Febe.Web.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.App\Febe.App.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.Server\Febe.Server.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.Desktop.Core\Febe.Desktop.Core.csproj" />
|
||||
<ProjectReference Include="..\..\tools\Febe.Sonda\Febe.Sonda.csproj" />
|
||||
<ProjectReference Include="..\..\tools\Febe.SitoDiProva\Febe.SitoDiProva.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -77,7 +77,7 @@ public sealed partial class ServerEndToEndTests
|
||||
var finish = await connection.FinishAsync(ct);
|
||||
Assert.IsTrue(finish.Connected, finish.Message);
|
||||
Assert.IsFalse(server.Browser.UserIsDriving, "«Ho finito» ends the driving");
|
||||
Assert.IsNotNull(await server.Database.Settings.GetInt64Async(Febe.Server.ServerConnectionService.FirstConnectionKey, ct), "first connection recorded");
|
||||
Assert.IsNotNull(await server.Database.Settings.GetInt64Async(Febe.App.BrowserConnectionService.FirstConnectionKey, ct), "first connection recorded");
|
||||
Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State);
|
||||
|
||||
// «Controlla ora».
|
||||
|
||||
@@ -113,12 +113,12 @@ public sealed class ServerOptionsTests
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 10, 13, 10, 0, 0, TimeSpan.Zero), TestZones.Rome);
|
||||
var folder = temp.Combine("registro");
|
||||
Directory.CreateDirectory(folder);
|
||||
var old = Path.Combine(folder, ServerLog.FileNameFor(new DateOnly(2026, 9, 1)));
|
||||
var old = Path.Combine(folder, Febe.App.FebeLog.FileNameFor(new DateOnly(2026, 9, 1)));
|
||||
File.WriteAllText(old, "vecchio");
|
||||
var unrelated = Path.Combine(folder, "appunti.txt");
|
||||
File.WriteAllText(unrelated, "di Alberto");
|
||||
using var console = new StringWriter();
|
||||
using (var log = new ServerLog(folder, console, clock))
|
||||
using (var log = new Febe.App.FebeLog(folder, console, clock))
|
||||
{
|
||||
log.Info("prova", "Scaricato https://cdn.example/m/abc.jpg?firma=SEGRETA da marta.prova");
|
||||
log.Warn("prova", "Errore", new InvalidOperationException("riga uno https://x.example/?t=1\nriga due"));
|
||||
@@ -126,14 +126,14 @@ public sealed class ServerOptionsTests
|
||||
log.Info("prova", "Il giorno dopo");
|
||||
}
|
||||
|
||||
var first = File.ReadAllText(Path.Combine(folder, ServerLog.FileNameFor(new DateOnly(2026, 10, 13))));
|
||||
var first = File.ReadAllText(Path.Combine(folder, Febe.App.FebeLog.FileNameFor(new DateOnly(2026, 10, 13))));
|
||||
Assert.DoesNotContain("SEGRETA", first);
|
||||
Assert.DoesNotContain("cdn.example", first);
|
||||
StringAssert.Contains(first, "<indirizzo>");
|
||||
StringAssert.Contains(first, "marta.prova");
|
||||
StringAssert.Contains(first, "InvalidOperationException: riga uno <indirizzo>");
|
||||
Assert.DoesNotContain("riga due", first);
|
||||
StringAssert.Contains(File.ReadAllText(Path.Combine(folder, ServerLog.FileNameFor(new DateOnly(2026, 10, 14)))), "Il giorno dopo");
|
||||
StringAssert.Contains(File.ReadAllText(Path.Combine(folder, Febe.App.FebeLog.FileNameFor(new DateOnly(2026, 10, 14)))), "Il giorno dopo");
|
||||
Assert.IsFalse(File.Exists(old), "older than fourteen days");
|
||||
Assert.IsTrue(File.Exists(unrelated), "only febe-*.log files are removed");
|
||||
StringAssert.Contains(console.ToString(), "Il giorno dopo");
|
||||
@@ -144,7 +144,7 @@ public sealed class ServerOptionsTests
|
||||
{
|
||||
using var temp = new TempFolder("registro");
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 10, 13, 10, 0, 0, TimeSpan.Zero), TestZones.Rome);
|
||||
using (var log = new ServerLog(temp.Path, null, clock, maxBytesPerDay: 2000))
|
||||
using (var log = new Febe.App.FebeLog(temp.Path, null, clock, maxBytesPerDay: 2000))
|
||||
{
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
@@ -152,7 +152,7 @@ public sealed class ServerOptionsTests
|
||||
}
|
||||
}
|
||||
|
||||
var file = Path.Combine(temp.Path, ServerLog.FileNameFor(new DateOnly(2026, 10, 13)));
|
||||
var file = Path.Combine(temp.Path, Febe.App.FebeLog.FileNameFor(new DateOnly(2026, 10, 13)));
|
||||
Assert.IsLessThan(2200L, new FileInfo(file).Length);
|
||||
StringAssert.Contains(File.ReadAllText(file), "troppo lungo");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user