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
@@ -11,6 +11,7 @@
|
|||||||
</Folder>
|
</Folder>
|
||||||
<Folder Name="/tests/">
|
<Folder Name="/tests/">
|
||||||
<Project Path="tests/Febe.Tests/Febe.Tests.csproj" />
|
<Project Path="tests/Febe.Tests/Febe.Tests.csproj" />
|
||||||
|
<Project Path="tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj" />
|
||||||
</Folder>
|
</Folder>
|
||||||
<Folder Name="/tools/">
|
<Folder Name="/tools/">
|
||||||
<Project Path="tools/Febe.Sonda/Febe.Sonda.csproj" />
|
<Project Path="tools/Febe.Sonda/Febe.Sonda.csproj" />
|
||||||
|
|||||||
@@ -38,6 +38,10 @@
|
|||||||
<ProjectReference Include="..\Febe.Desktop.Core\Febe.Desktop.Core.csproj" />
|
<ProjectReference Include="..\Febe.Desktop.Core\Febe.Desktop.Core.csproj" />
|
||||||
<PackageReference Include="Microsoft.Web.WebView2" />
|
<PackageReference Include="Microsoft.Web.WebView2" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<!-- Le prove che girano solo su Windows (WebView2 vero sul thread dell'interfaccia). -->
|
||||||
|
<InternalsVisibleTo Include="Febe.Tests.Windows" />
|
||||||
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<!-- L'icona del marchio (appendice C), generata da BrandMark e IcoWriter: finestre e area di notifica la leggono da qui. -->
|
<!-- L'icona del marchio (appendice C), generata da BrandMark e IcoWriter: finestre e area di notifica la leggono da qui. -->
|
||||||
<EmbeddedResource Include="Febe.ico" LogicalName="Febe.ico" />
|
<EmbeddedResource Include="Febe.ico" LogicalName="Febe.ico" />
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<!-- Prove che girano solo su Windows, con il WebView2 vero: il thread dell'interfaccia di WPF, il browser di Febe,
|
||||||
|
il protocollo DevTools sul sito di prova locale e una sessione di raccolta della composizione condivisa.
|
||||||
|
Si compila anche da Linux (EnableWindowsTargeting, come Febe.Desktop: la CI compila tutta la soluzione), ma si
|
||||||
|
esegue solo su Windows (dotnet test tests/Febe.Tests.Windows); dove manca il runtime WebView2 le prove risultano
|
||||||
|
inconcludenti. Mai Instagram: il browser vede solo 127.0.0.1. -->
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0-windows</TargetFramework>
|
||||||
|
<UseWPF>true</UseWPF>
|
||||||
|
<EnableWindowsTargeting>true</EnableWindowsTargeting>
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
<IsTestProject>true</IsTestProject>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<!-- Con WPF l'SDK toglie System.IO dagli using impliciti (Path di System.Windows.Shapes): qui serve. -->
|
||||||
|
<Using Include="System.IO" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="MSTest" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\src\Febe.Core\Febe.Core.csproj" />
|
||||||
|
<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.Desktop.Core\Febe.Desktop.Core.csproj" />
|
||||||
|
<ProjectReference Include="..\..\src\Febe.Desktop\Febe.Desktop.csproj" />
|
||||||
|
<ProjectReference Include="..\..\tools\Febe.SitoDiProva\Febe.SitoDiProva.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
// One WebView2 at a time: every test starts its own browser process, window and UI thread.
|
||||||
|
[assembly: DoNotParallelize]
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using Febe.Browser.Cdp;
|
||||||
|
using Febe.Tests.Windows.Support;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Windows;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
[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();
|
||||||
|
}
|
||||||
Reference in new issue
Block a user