diff --git a/Febe.slnx b/Febe.slnx index 62cccd4..38a7235 100644 --- a/Febe.slnx +++ b/Febe.slnx @@ -11,6 +11,7 @@ + diff --git a/src/Febe.Desktop/Febe.Desktop.csproj b/src/Febe.Desktop/Febe.Desktop.csproj index d66b943..4e44622 100644 --- a/src/Febe.Desktop/Febe.Desktop.csproj +++ b/src/Febe.Desktop/Febe.Desktop.csproj @@ -38,6 +38,10 @@ + + + + diff --git a/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj b/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj new file mode 100644 index 0000000..404c8cf --- /dev/null +++ b/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj @@ -0,0 +1,31 @@ + + + + net10.0-windows + true + true + false + true + + + + + + + + + + + + + + + + + + + diff --git a/tests/Febe.Tests.Windows/MSTestSettings.cs b/tests/Febe.Tests.Windows/MSTestSettings.cs new file mode 100644 index 0000000..2900593 --- /dev/null +++ b/tests/Febe.Tests.Windows/MSTestSettings.cs @@ -0,0 +1,2 @@ +// One WebView2 at a time: every test starts its own browser process, window and UI thread. +[assembly: DoNotParallelize] diff --git a/tests/Febe.Tests.Windows/Support/BrowserBed.cs b/tests/Febe.Tests.Windows/Support/BrowserBed.cs new file mode 100644 index 0000000..5315764 --- /dev/null +++ b/tests/Febe.Tests.Windows/Support/BrowserBed.cs @@ -0,0 +1,100 @@ +using Febe.App; +using Febe.Core.Abstractions; +using Febe.Core.Library; +using Febe.Data; +using Febe.Desktop.Browser; +using Febe.Desktop.Core; +using Febe.Web.Engine; + +namespace Febe.Tests.Windows.Support; + +/// +/// The browser of Febe for Windows on its own, as the composition builds it ( through +/// DesktopShell): a with its window «Browser di Febe» and WebView2 on a real UI +/// thread, a profile in a temporary Data folder, the switches of S2 and the log of Febe captured. +/// +internal sealed class BrowserBed : IAsyncDisposable +{ + private BrowserBed(TestFolder folder, UiThread ui, LogLines lines, FebeLog log, FebeDatabase database, WebView2Browser browser) + { + Folder = folder; + Ui = ui; + Lines = lines; + Log = log; + Database = database; + Browser = browser; + } + + public TestFolder Folder { get; } + + public UiThread Ui { get; } + + /// What Febe wrote in its log. + public LogLines Lines { get; } + + public FebeLog Log { get; } + + public FebeDatabase Database { get; } + + public WebView2Browser Browser { get; } + + public static async Task CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window) + { + var folder = new TestFolder(name); + var ui = await UiThread.StartAsync(); + var lines = new LogLines(); + var clock = new SystemClock(); + var log = new FebeLog(null, lines, clock); + var data = new DataFolderLayout(folder.Combine("dati")); + var database = await FebeDatabase.OpenAsync(data.Root); + var options = new FebeAppOptions { DataFolder = data.Root, LibraryFolder = folder.Combine("libreria") }; + var context = new FebePlatformContext(options, data, database, clock, log, new BrowserUseTracker()); + var settings = new WebView2BrowserSettings(data.BrowserProfile, 1280, 900, hosting, BrowserArguments.ForWebView2()); + + // Built off the UI thread, as DesktopPlatform.CreateBrowserAsync does after its awaits. + var browser = new WebView2Browser(ui.Dispatcher, settings, context, icon: null); + return new BrowserBed(folder, ui, lines, log, database, browser); + } + + /// + /// Starts the browser from a thread-pool thread, like FebeApp.BringUpBrowserAsync, and waits until + /// returns. Fails at once when the log reports a failed start: the loop of + /// retries would otherwise go on for ever. + /// + public async Task StartAsync(CancellationToken ct, TimeSpan? timeout = null) + { + var run = Task.Run(() => Browser.RunAsync(ct), ct); + var deadline = DateTime.UtcNow + (timeout ?? TimeSpan.FromSeconds(60)); + while (!run.IsCompleted) + { + if (Lines.Any("non parte")) + { + Assert.Fail("Il browser di Febe non è partito al primo tentativo:\n" + Lines.Text); + } + + if (DateTime.UtcNow > deadline) + { + Assert.Fail("Il browser di Febe non è diventato disponibile in tempo:\n" + Lines.Text); + } + + await Task.Delay(50, ct); + } + + await run; + } + + public async ValueTask DisposeAsync() + { + try + { + await Browser.DisposeAsync(); + } + finally + { + await Ui.DisposeAsync(); + await Database.DisposeAsync(); + Log.Dispose(); + Folder.Dispose(); + } + } +} diff --git a/tests/Febe.Tests.Windows/Support/LogLines.cs b/tests/Febe.Tests.Windows/Support/LogLines.cs new file mode 100644 index 0000000..4354225 --- /dev/null +++ b/tests/Febe.Tests.Windows/Support/LogLines.cs @@ -0,0 +1,54 @@ +using System.Text; + +namespace Febe.Tests.Windows.Support; + +/// The «console» of in a test: the lines Alberto would find in his log. +internal sealed class LogLines : TextWriter +{ + private readonly Lock _gate = new(); + private readonly List _lines = []; + private readonly StringBuilder _current = new(); + + public override Encoding Encoding => Encoding.UTF8; + + public IReadOnlyList Lines + { + get + { + lock (_gate) + { + return [.. _lines]; + } + } + } + + public string Text => string.Join('\n', Lines); + + public bool Any(string fragment) => Lines.Any(l => l.Contains(fragment, StringComparison.Ordinal)); + + public override void Write(char value) + { + lock (_gate) + { + if (value == '\n') + { + _lines.Add(_current.ToString().TrimEnd('\r')); + _current.Clear(); + } + else + { + _current.Append(value); + } + } + } + + public override void WriteLine(string? value) + { + lock (_gate) + { + _current.Append(value); + _lines.Add(_current.ToString()); + _current.Clear(); + } + } +} diff --git a/tests/Febe.Tests.Windows/Support/TestFolder.cs b/tests/Febe.Tests.Windows/Support/TestFolder.cs new file mode 100644 index 0000000..d121231 --- /dev/null +++ b/tests/Febe.Tests.Windows/Support/TestFolder.cs @@ -0,0 +1,39 @@ +namespace Febe.Tests.Windows.Support; + +/// +/// A temporary folder under (TEMP: on Alberto's PC a work folder outside drive C:), +/// removed at the end of the test. WebView2 may hold a file of its profile for a moment after it closed: removal is +/// retried and a leftover folder is not an error. +/// +internal sealed class TestFolder : IDisposable +{ + public TestFolder(string prefix) + { + Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "febe-prove-windows", prefix + "-" + Guid.NewGuid().ToString("N")[..10]); + Directory.CreateDirectory(Path); + } + + public string Path { get; } + + public string Combine(params string[] parts) => System.IO.Path.Combine([Path, .. parts]); + + public void Dispose() + { + for (var attempt = 0; attempt < 10; attempt++) + { + try + { + if (Directory.Exists(Path)) + { + Directory.Delete(Path, recursive: true); + } + + return; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Thread.Sleep(300); + } + } + } +} diff --git a/tests/Febe.Tests.Windows/Support/UiThread.cs b/tests/Febe.Tests.Windows/Support/UiThread.cs new file mode 100644 index 0000000..441b7c1 --- /dev/null +++ b/tests/Febe.Tests.Windows/Support/UiThread.cs @@ -0,0 +1,55 @@ +using System.Windows.Threading; + +namespace Febe.Tests.Windows.Support; + +/// +/// A UI thread like the one of Febe.exe: an STA thread running a WPF +/// (its message pump and its ). The browser of Febe is created on it, +/// while the test itself — like the engine of Febe — runs on thread-pool threads. +/// +internal sealed class UiThread : IAsyncDisposable +{ + private readonly Thread _thread; + + private UiThread(Thread thread, Dispatcher dispatcher) + { + _thread = thread; + Dispatcher = dispatcher; + } + + public Dispatcher Dispatcher { get; } + + /// The managed id of the UI thread (to tell where code ran). + public int ThreadId => _thread.ManagedThreadId; + + public static async Task StartAsync() + { + var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var thread = new Thread(() => + { + ready.SetResult(Dispatcher.CurrentDispatcher); + Dispatcher.Run(); + }) + { + IsBackground = true, + Name = "Febe: thread dell'interfaccia (prove)", + }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + var dispatcher = await ready.Task.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false); + return new UiThread(thread, dispatcher); + } + + /// Runs on the UI thread and waits for it. + public Task InvokeAsync(Func action) => Dispatcher.InvokeAsync(action).Task; + + public async ValueTask DisposeAsync() + { + if (!Dispatcher.HasShutdownStarted) + { + Dispatcher.BeginInvokeShutdown(DispatcherPriority.Background); + } + + await Task.Run(() => _thread.Join(TimeSpan.FromSeconds(15))).ConfigureAwait(false); + } +} diff --git a/tests/Febe.Tests.Windows/Support/WebView2Runtime.cs b/tests/Febe.Tests.Windows/Support/WebView2Runtime.cs new file mode 100644 index 0000000..b9a52c6 --- /dev/null +++ b/tests/Febe.Tests.Windows/Support/WebView2Runtime.cs @@ -0,0 +1,39 @@ +using System.Runtime.CompilerServices; +using Microsoft.Web.WebView2.Core; + +namespace Febe.Tests.Windows.Support; + +/// Whether these tests can run here: Windows with the WebView2 runtime (the tests are inconclusive otherwise). +internal static class WebView2Runtime +{ + /// Null when WebView2 can run; otherwise why not, in Italian (the text of the inconclusive result). + public static string? UnavailableReason() + { + if (!OperatingSystem.IsWindows()) + { + return "Prova solo per Windows: qui non c'è WebView2."; + } + + try + { + return InstalledVersion() is null ? "Runtime WebView2 non installato su questo Windows." : null; + } + catch (Exception ex) when (ex is WebView2RuntimeNotFoundException or DllNotFoundException or BadImageFormatException) + { + return $"Runtime WebView2 non disponibile ({ex.GetType().Name})."; + } + } + + /// The version of the installed WebView2 runtime, e.g. «141.0.3537.71». + [MethodImpl(MethodImplOptions.NoInlining)] + public static string? InstalledVersion() => CoreWebView2Environment.GetAvailableBrowserVersionString(); + + /// Marks the test inconclusive where WebView2 cannot run. + public static void Require() + { + if (UnavailableReason() is { } reason) + { + Assert.Inconclusive(reason); + } + } +} diff --git a/tests/Febe.Tests.Windows/WebView2BrowserStartTests.cs b/tests/Febe.Tests.Windows/WebView2BrowserStartTests.cs new file mode 100644 index 0000000..1d00073 --- /dev/null +++ b/tests/Febe.Tests.Windows/WebView2BrowserStartTests.cs @@ -0,0 +1,50 @@ +using System.Text.RegularExpressions; +using Febe.Browser.Cdp; +using Febe.Tests.Windows.Support; + +namespace Febe.Tests.Windows; + +/// +/// The start of the browser of Febe on a real Windows (regression of 14 and 19 October 2026: «WebView2 non parte +/// (InvalidOperationException: CoreWebView2Environment members can only be accessed from the UI thread.)» at every +/// attempt, for ever). The composition starts the browser from a thread-pool thread; every WebView2 object lives on the +/// UI thread of WPF. +/// +[TestClass] +public sealed partial class WebView2BrowserStartTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestInitialize] + public void RequireWebView2() => WebView2Runtime.Require(); + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task StartedFromAThreadPoolThreadTheBrowserIsReadyAtTheFirstAttempt() + { + var ct = TestContext.CancellationToken; + await using var bed = await BrowserBed.CreateAsync("avvio"); + + await bed.StartAsync(ct); + + TestContext.WriteLine(bed.Lines.Text); + Assert.IsTrue(bed.Browser.IsAvailable, "the browser is available once RunAsync returned"); + Assert.IsNull(bed.Browser.LastError); + var ready = bed.Lines.Lines.Where(l => l.Contains("Browser di Febe pronto: WebView2 ", StringComparison.Ordinal)).ToList(); + Assert.HasCount(1, ready, "one «ready» line: " + bed.Lines.Text); + Assert.MatchesRegex(ReadyLine(), ready[0]); + Assert.IsFalse(bed.Lines.Any("non parte"), "no failed attempt: " + bed.Lines.Text); + Assert.IsFalse(bed.Lines.Any("ERRORE"), "no error at all: " + bed.Lines.Text); + + // The version is a plain value now: it can be read from any thread. + var version = await Task.Run(() => bed.Browser.Host.Version, ct); + Assert.IsNotNull(version); + StringAssert.Contains(ready[0], version); + + // The engine's threads use the page through the session: the command hops to the UI thread and back. + Assert.AreEqual("about:blank", await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct)); + } + + [GeneratedRegex(@"\[browser\] Browser di Febe pronto: WebView2 \d+\.\d+\.\d+\.\d+, pagina 1280×900, finestra, fuori vista\.$")] + private static partial Regex ReadyLine(); +}