Prove che cadevano con il runner carico (#46)
Le prove cadevano a ogni carico della CI, ogni volta prove diverse. Dietro alcune c'erano difetti veri: FebeDatabase lasciava i file aperti dopo DisposeAsync (comandi SQLite non chiusi, pool di lettura chiuso dopo lo scrittore), e il WAL spariva durante lo spostamento della cartella Dati; la scheda dell'account senza statistiche leggeva i file di tutta la libreria; l'arresto di FebeApp non aspettava i lavori aggiunti da un avvio in corso. Chromium ha 120 s per avviarsi e aprire la prima scheda, e il ricollegamento smette appena il processo cambia. Nelle prove i limiti di tempo diventano protezioni contro un blocco: attese per condizione con un aiuto comune, limiti per classe nella prova di scala con il tempo migliore, porta 0 e stderr di Chromium nel browser delle prove, e la prova di «Scollega» di WebView2 controlla che il processo esca davvero. Provato su Windows con tutti i core occupati. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e2e64c09e8
commit
0775a1460f
34 files changed
+875
-245
No files matched your search
@@ -108,7 +108,15 @@ internal sealed class UiBrowser : IAsyncDisposable
|
||||
})();
|
||||
""";
|
||||
|
||||
/// <summary>
|
||||
/// The hang guard of every wait of this browser: its start, each DevTools command, each condition. The waits end as
|
||||
/// soon as their condition holds; the guard only bounds a hang, sized for a loaded runner (#46). A browser that dies
|
||||
/// fails the wait at once.
|
||||
/// </summary>
|
||||
internal static readonly TimeSpan Patience = TimeSpan.FromMinutes(2);
|
||||
|
||||
private readonly Process _process;
|
||||
private readonly ConcurrentQueue<string> _stderr;
|
||||
private readonly ClientWebSocket _socket;
|
||||
private readonly string _profile;
|
||||
private readonly ConcurrentDictionary<int, TaskCompletionSource<JsonElement>> _pending = new();
|
||||
@@ -117,9 +125,10 @@ internal sealed class UiBrowser : IAsyncDisposable
|
||||
private readonly Task _reader;
|
||||
private int _id;
|
||||
|
||||
private UiBrowser(Process process, ClientWebSocket socket, string profile)
|
||||
private UiBrowser(Process process, ConcurrentQueue<string> stderr, ClientWebSocket socket, string profile)
|
||||
{
|
||||
_process = process;
|
||||
_stderr = stderr;
|
||||
_socket = socket;
|
||||
_profile = profile;
|
||||
_reader = Task.Run(ReadLoopAsync);
|
||||
@@ -137,19 +146,20 @@ internal sealed class UiBrowser : IAsyncDisposable
|
||||
}
|
||||
|
||||
var profile = Path.Combine(Path.GetTempPath(), "febe-interfaccia-" + Guid.NewGuid().ToString("N"));
|
||||
var port = LocalTestSite.FreePort();
|
||||
var info = new ProcessStartInfo(chromium)
|
||||
{
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
};
|
||||
// Port 0: Chromium picks a free port and says which (stderr and DevToolsActivePort), so no other process can take
|
||||
// it between a free-port probe and the bind. Only this test browser: Febe's own browser keeps a fixed port (§6.1).
|
||||
foreach (var argument in new[]
|
||||
{
|
||||
"--headless", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check",
|
||||
"--disable-extensions", "--disable-background-networking", "--disable-component-update", "--no-proxy-server",
|
||||
"--mute-audio", $"--window-size={width},{height}", $"--user-data-dir={profile}",
|
||||
$"--remote-debugging-port={port}", "--remote-debugging-address=127.0.0.1", "about:blank",
|
||||
"--remote-debugging-port=0", "--remote-debugging-address=127.0.0.1", "about:blank",
|
||||
})
|
||||
{
|
||||
info.ArgumentList.Add(argument);
|
||||
@@ -173,29 +183,60 @@ internal sealed class UiBrowser : IAsyncDisposable
|
||||
}
|
||||
|
||||
var process = Process.Start(info) ?? throw new InvalidOperationException("Chromium non parte.");
|
||||
var stderr = new ConcurrentQueue<string>();
|
||||
var listening = 0;
|
||||
process.OutputDataReceived += (_, _) => { };
|
||||
process.ErrorDataReceived += (_, _) => { };
|
||||
process.ErrorDataReceived += (_, e) =>
|
||||
{
|
||||
if (e.Data is { } line)
|
||||
{
|
||||
if (ListeningPort(line) is > 0 and var found)
|
||||
{
|
||||
Interlocked.CompareExchange(ref listening, found, 0);
|
||||
}
|
||||
|
||||
stderr.Enqueue(line);
|
||||
while (stderr.Count > 20 && stderr.TryDequeue(out string? _))
|
||||
{
|
||||
}
|
||||
}
|
||||
};
|
||||
process.BeginOutputReadLine();
|
||||
process.BeginErrorReadLine();
|
||||
|
||||
try
|
||||
{
|
||||
using var http = new HttpClient(new HttpClientHandler { UseProxy = false }) { Timeout = TimeSpan.FromSeconds(2) };
|
||||
// By condition: the port Chromium chose, then a page target. Fails at once if Chromium exits.
|
||||
using var http = new HttpClient(new HttpClientHandler { UseProxy = false }) { Timeout = TimeSpan.FromSeconds(10) };
|
||||
string? debugger = null;
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(20);
|
||||
while (debugger is null && DateTime.UtcNow < deadline)
|
||||
var watch = Stopwatch.StartNew();
|
||||
while (debugger is null)
|
||||
{
|
||||
try
|
||||
if (process.HasExited)
|
||||
{
|
||||
using var list = JsonDocument.Parse(await http.GetStringAsync(new Uri($"http://127.0.0.1:{port}/json/list")));
|
||||
debugger = list.RootElement.EnumerateArray()
|
||||
.Where(t => t.GetProperty("type").GetString() == "page")
|
||||
.Select(t => t.GetProperty("webSocketDebuggerUrl").GetString())
|
||||
.FirstOrDefault();
|
||||
throw new InvalidOperationException($"Chromium si è chiuso all'avvio (codice {process.ExitCode}). {Tail(stderr)}");
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException)
|
||||
|
||||
if (watch.Elapsed > Patience)
|
||||
{
|
||||
// Chromium is still starting.
|
||||
throw new TimeoutException($"Chromium non risponde sulla porta di debug dopo {Patience.TotalSeconds:0} s. {Tail(stderr)}");
|
||||
}
|
||||
|
||||
var port = Volatile.Read(ref listening) is > 0 and var known ? known : ReadActivePort(profile);
|
||||
if (port > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var list = JsonDocument.Parse(await http.GetStringAsync(new Uri($"http://127.0.0.1:{port}/json/list")));
|
||||
debugger = list.RootElement.EnumerateArray()
|
||||
.Where(t => t.GetProperty("type").GetString() == "page")
|
||||
.Select(t => t.GetProperty("webSocketDebuggerUrl").GetString())
|
||||
.FirstOrDefault();
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException)
|
||||
{
|
||||
// Chromium is still starting.
|
||||
}
|
||||
}
|
||||
|
||||
if (debugger is null)
|
||||
@@ -204,15 +245,14 @@ internal sealed class UiBrowser : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
if (debugger is null)
|
||||
{
|
||||
throw new TimeoutException("Chromium non risponde sulla porta di debug.");
|
||||
}
|
||||
|
||||
var socket = new ClientWebSocket();
|
||||
socket.Options.Proxy = null;
|
||||
await socket.ConnectAsync(new Uri(debugger), CancellationToken.None);
|
||||
var browser = new UiBrowser(process, socket, profile);
|
||||
using (var connect = new CancellationTokenSource(Patience))
|
||||
{
|
||||
await socket.ConnectAsync(new Uri(debugger), connect.Token);
|
||||
}
|
||||
|
||||
var browser = new UiBrowser(process, stderr, socket, profile);
|
||||
await browser.SendAsync("Runtime.enable");
|
||||
await browser.SendAsync("Page.enable");
|
||||
await browser.SendAsync("Log.enable");
|
||||
@@ -243,7 +283,17 @@ internal sealed class UiBrowser : IAsyncDisposable
|
||||
_send.Release();
|
||||
}
|
||||
|
||||
return await answer.Task.WaitAsync(TimeSpan.FromSeconds(30));
|
||||
// A browser that dies fails the answer at once (ReadLoopAsync); a slow one is waited for.
|
||||
try
|
||||
{
|
||||
return await answer.Task.WaitAsync(Patience);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
_pending.TryRemove(id, out _);
|
||||
throw new TimeoutException(
|
||||
$"Chromium non ha risposto a {method} in {Patience.TotalSeconds:0} s{(_process.HasExited ? " (si è chiuso)" : string.Empty)}. {Tail(_stderr)}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Runs a script in the page (promises awaited) and returns its value; an exception fails the test.</summary>
|
||||
@@ -270,9 +320,9 @@ internal sealed class UiBrowser : IAsyncDisposable
|
||||
/// Polls until a condition of the page holds (an expression, or a promise of one; errors while the page changes
|
||||
/// count as «not yet»).
|
||||
/// </summary>
|
||||
public async Task WaitAsync(string condition, string what, int milliseconds = 30_000)
|
||||
public async Task WaitAsync(string condition, string what, TimeSpan? limit = null)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromMilliseconds(milliseconds);
|
||||
var deadline = DateTime.UtcNow + (limit ?? Patience);
|
||||
string? last = null;
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
@@ -295,9 +345,9 @@ internal sealed class UiBrowser : IAsyncDisposable
|
||||
}
|
||||
|
||||
/// <summary>Polls a condition of the test (the server side) while the page works.</summary>
|
||||
public async Task WaitForAsync(Func<bool> condition, string what, int milliseconds = 30_000)
|
||||
public async Task WaitForAsync(Func<bool> condition, string what, TimeSpan? limit = null)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromMilliseconds(milliseconds);
|
||||
var deadline = DateTime.UtcNow + (limit ?? Patience);
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
if (condition())
|
||||
@@ -333,7 +383,13 @@ internal sealed class UiBrowser : IAsyncDisposable
|
||||
/// <summary>Loads an address of the interface and waits until the frame and the first page are drawn.</summary>
|
||||
public async Task OpenAsync(Uri address)
|
||||
{
|
||||
await SendAsync("Page.navigate", new JsonObject { ["url"] = address.AbsoluteUri });
|
||||
// A navigation that fails says so at once, instead of a wait for a page that never comes.
|
||||
var navigation = await SendAsync("Page.navigate", new JsonObject { ["url"] = address.AbsoluteUri });
|
||||
if (navigation.TryGetProperty("errorText", out var error) && error.GetString() is { Length: > 0 } text)
|
||||
{
|
||||
Assert.Fail($"apertura di {address}: {text}\n{Report()}");
|
||||
}
|
||||
|
||||
await WaitAsync(
|
||||
$"location.href.startsWith({JsonSerializer.Serialize(address.GetLeftPart(UriPartial.Authority))}) && document.readyState === 'complete' && !document.documentElement.hasAttribute('aria-busy') && document.querySelector('main.pagina .corpo') !== null",
|
||||
$"apertura di {address}");
|
||||
@@ -402,7 +458,45 @@ internal sealed class UiBrowser : IAsyncDisposable
|
||||
RealBrowser.TryDelete(_profile);
|
||||
}
|
||||
|
||||
/// <summary>The port of «DevTools listening on ws://127.0.0.1:<port>/devtools/browser/…», or 0.</summary>
|
||||
private static int ListeningPort(string line)
|
||||
{
|
||||
const string Marker = "DevTools listening on ws://127.0.0.1:";
|
||||
var at = line.IndexOf(Marker, StringComparison.Ordinal);
|
||||
if (at < 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var rest = line[(at + Marker.Length)..];
|
||||
var end = rest.IndexOf('/', StringComparison.Ordinal);
|
||||
return int.TryParse(end < 0 ? rest : rest[..end], out var port) ? port : 0;
|
||||
}
|
||||
|
||||
/// <summary>The port Chromium wrote in DevToolsActivePort (first line), or 0 while it has not.</summary>
|
||||
private static int ReadActivePort(string profile)
|
||||
{
|
||||
try
|
||||
{
|
||||
var lines = File.ReadAllLines(Path.Combine(profile, "DevToolsActivePort"));
|
||||
return lines.Length > 0 && int.TryParse(lines[0], out var port) ? port : 0;
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The last lines Chromium wrote on stderr, for failure messages.</summary>
|
||||
private static string Tail(ConcurrentQueue<string> stderr) =>
|
||||
stderr.IsEmpty ? "Chromium non ha scritto nulla su stderr." : "Ultime righe di Chromium: " + string.Join(" | ", stderr);
|
||||
|
||||
private static void Kill(Process process)
|
||||
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user