Prove per Windows con WebView2 vero, e la prova che riproduce l'avvio mancato
Nuovo progetto tests/Febe.Tests.Windows (net10.0-windows, WPF, solo MSTest e riferimenti ai progetti): un thread STA con un Dispatcher di WPF vero, come il thread dell'interfaccia di Febe.exe, e il browser di Febe costruito come lo costruisce la composizione e avviato da un thread del pool, come fa FebeApp. Si compila anche da Linux (EnableWindowsTargeting, come Febe.Desktop) perché la CI compila tutta la soluzione, ma gira solo su Windows; dove manca il runtime WebView2 le prove risultano inconcludenti. La prima prova riproduce il registro di Alberto del 14 e del 19 ottobre: «WebView2 non parte (InvalidOperationException: CoreWebView2Environment members can only be accessed from the UI thread.)» a ogni tentativo. Con il codice di questo commit fallisce così; la correzione è nel commit seguente. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
edade61b72
commit
a25f60970d
10 files changed
+375
No files matched your search
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// The browser of Febe for Windows on its own, as the composition builds it (<see cref="DesktopPlatform"/> through
|
||||
/// <c>DesktopShell</c>): a <see cref="WebView2Browser"/> 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.
|
||||
/// </summary>
|
||||
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; }
|
||||
|
||||
/// <summary>What Febe wrote in its log.</summary>
|
||||
public LogLines Lines { get; }
|
||||
|
||||
public FebeLog Log { get; }
|
||||
|
||||
public FebeDatabase Database { get; }
|
||||
|
||||
public WebView2Browser Browser { get; }
|
||||
|
||||
public static async Task<BrowserBed> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts the browser from a thread-pool thread, like <c>FebeApp.BringUpBrowserAsync</c>, and waits until
|
||||
/// <see cref="WebView2Browser.RunAsync"/> returns. Fails at once when the log reports a failed start: the loop of
|
||||
/// retries would otherwise go on for ever.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>The «console» of <see cref="Febe.App.FebeLog"/> in a test: the lines Alberto would find in his log.</summary>
|
||||
internal sealed class LogLines : TextWriter
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<string> _lines = [];
|
||||
private readonly StringBuilder _current = new();
|
||||
|
||||
public override Encoding Encoding => Encoding.UTF8;
|
||||
|
||||
public IReadOnlyList<string> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>
|
||||
/// A temporary folder under <see cref="Path.GetTempPath"/> (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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System.Windows.Threading;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>
|
||||
/// A UI thread like the one of Febe.exe: an STA thread running a WPF <see cref="System.Windows.Threading.Dispatcher"/>
|
||||
/// (its message pump and its <see cref="DispatcherSynchronizationContext"/>). The browser of Febe is created on it,
|
||||
/// while the test itself — like the engine of Febe — runs on thread-pool threads.
|
||||
/// </summary>
|
||||
internal sealed class UiThread : IAsyncDisposable
|
||||
{
|
||||
private readonly Thread _thread;
|
||||
|
||||
private UiThread(Thread thread, Dispatcher dispatcher)
|
||||
{
|
||||
_thread = thread;
|
||||
Dispatcher = dispatcher;
|
||||
}
|
||||
|
||||
public Dispatcher Dispatcher { get; }
|
||||
|
||||
/// <summary>The managed id of the UI thread (to tell where code ran).</summary>
|
||||
public int ThreadId => _thread.ManagedThreadId;
|
||||
|
||||
public static async Task<UiThread> StartAsync()
|
||||
{
|
||||
var ready = new TaskCompletionSource<Dispatcher>(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);
|
||||
}
|
||||
|
||||
/// <summary>Runs <paramref name="action"/> on the UI thread and waits for it.</summary>
|
||||
public Task<T> InvokeAsync<T>(Func<T> 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>Whether these tests can run here: Windows with the WebView2 runtime (the tests are inconclusive otherwise).</summary>
|
||||
internal static class WebView2Runtime
|
||||
{
|
||||
/// <summary>Null when WebView2 can run; otherwise why not, in Italian (the text of the inconclusive result).</summary>
|
||||
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}).";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The version of the installed WebView2 runtime, e.g. «141.0.3537.71».</summary>
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
public static string? InstalledVersion() => CoreWebView2Environment.GetAvailableBrowserVersionString();
|
||||
|
||||
/// <summary>Marks the test inconclusive where WebView2 cannot run.</summary>
|
||||
public static void Require()
|
||||
{
|
||||
if (UnavailableReason() is { } reason)
|
||||
{
|
||||
Assert.Inconclusive(reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user