Files
Febe/tests/Febe.Tests/Web/Support/UiBrowser.cs
T
Alby96andClaude Opus 5.5 248e9f74ce Prove dell'interfaccia: la risposta in ritardo si trattiene (issue #8)
APageLeftWhileLoadingLeavesNothingBehind apriva Attività e tornava alla
Libreria con un setTimeout di 200 ms, poi aspettava la risposta in
ritardo di /api/alerts. Su una macchina lenta, a 200 ms Attività non
aveva ancora caricato activity.js e day-strip.js: la pagina veniva
lasciata prima di montarsi, /api/alerts non partiva mai e l'attesa
scadeva dopo 30 s, come nell'esecuzione 22 della CI. Con Chrome
rallentato 20 volte (Emulation.setCPUThrottlingRate, solo in locale)
fallisce 3 volte su 3 con lo stesso messaggio e la stessa riga, e in 4
giri su 5 i due moduli arrivano dopo il ritorno alla Libreria (fra 212 e
549 ms). ABrowserPageLeftWhileLoadingNeverTakesTheBrowser aveva la
stessa finestra, di 150 ms, e a 20x falliva anche lei. Il prodotto non
c'entra.

UiBrowser.Requests prende il posto di FetchDelays: trattiene le
richieste scelte finché la prova non le rilascia, conta quelle partite e
quelle finite (dopo la continuazione della pagina e, se lo legge, dopo
il corpo della risposta) e registra ogni richiesta della pagina. Le due
prove aspettano che la pagina abbia chiesto la risposta, la lasciano, la
rilasciano e controllano quando la pagina ne ha finito: nessun timer
rimasto, niente di Attività sulla Libreria, nessun browser preso né
vista aperta. Allo stesso modo la risposta vecchia della Libreria e le
tessere in ritardo di «In evidenza» arrivano sempre dopo il disegno
nuovo, invece che dopo 600 o 700 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 10:42:17 +02:00

485 lines
20 KiB
C#

using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Tests.Browser.TestSupport;
namespace Febe.Tests.Web.Support;
/// <summary>
/// A headless Chromium that drives Febe's own interface, like <c>tools/schermate</c>: only addresses on 127.0.0.1, never
/// Instagram (spec §2). It speaks the DevTools protocol directly, without the command policy of Febe's own client,
/// because here the tests click, type and run scripts in Febe's pages. Inconclusive when Chromium is missing.
/// </summary>
internal sealed class UiBrowser : IAsyncDisposable
{
/// <summary>
/// Installed before the page scripts: what the page asks of the server, and answers that come when the test says.
/// <list type="bullet">
/// <item><c>window.__asked</c>: every request the page started, in order («GET /api/connection», «POST
/// /api/connection/begin», «WS /api/vista»); <c>window.__sockets</c>: its WebSockets.</item>
/// <item><c>window.__busy()</c>: the requests not over yet. A fetch is over once the page's own continuation of
/// its answer has run, and the body it reads there (as api.js does) has arrived; a WebSocket once it is open or
/// closed. See <see cref="WaitForQuietAsync"/>.</item>
/// <item><c>window.__hold(match)</c> holds back every fetch whose address contains match until
/// <c>window.__release(match)</c>, also one the page aborts meanwhile; <c>window.__started[match]</c> counts the
/// held-back requests that started, <c>window.__done[match]</c> those that are over.</item>
/// </list>
/// An answer is late because the test holds it, never because of a delay the page might outlast on a slow machine:
/// the test waits until the page has asked (<c>__started</c>), does what has to come first, releases it, and
/// checks once the page is done with it (<c>__done</c>).
/// </summary>
public const string Requests = """
(() => {
const fetchNow = window.fetch.bind(window);
const later = window.setTimeout.bind(window);
const NativeSocket = window.WebSocket;
const holds = [];
let busy = 0;
const count = (counts, key) => { counts[key] = (counts[key] || 0) + 1; };
const pathOf = (url) => { const u = new URL(url, location.href); return u.pathname + u.search; };
window.__asked = [];
window.__sockets = [];
window.__started = {};
window.__done = {};
window.__busy = () => busy;
window.__hold = (match) => {
let release;
holds.push({ match, gate: new Promise((resolve) => { release = resolve; }), release: () => release() });
return true;
};
window.__release = (match) => {
const hold = holds.find((h) => h.match === match);
if (!hold) throw new Error(`nessuna richiesta trattenuta per ${match}`);
hold.release();
return true;
};
window.fetch = async (input, init) => {
const url = input instanceof Request ? input.url : String(input);
const method = ((init && init.method) || (input instanceof Request ? input.method : 'GET')).toUpperCase();
const hold = holds.find((h) => url.includes(h.match));
window.__asked.push(`${method} ${pathOf(url)}`);
if (hold) count(window.__started, hold.match);
busy += 1;
let read = Promise.resolve();
try {
if (hold) await hold.gate;
const response = await fetchNow(input, init);
for (const name of ['json', 'text', 'blob', 'arrayBuffer']) {
const body = response[name].bind(response);
response[name] = () => {
const reading = body();
read = reading.then(() => {}, () => {});
return reading;
};
}
return response;
} finally {
// The page's continuation of this answer runs before the first timer and, if it reads the body, the
// continuation of that read runs before the second.
later(() => read.then(() => later(() => {
busy -= 1;
if (hold) count(window.__done, hold.match);
})));
}
};
window.WebSocket = class extends NativeSocket {
constructor(...args) {
super(...args);
window.__asked.push(`WS ${pathOf(this.url)}`);
window.__sockets.push(this);
busy += 1;
let connecting = true;
const over = () => {
if (!connecting) return;
connecting = false;
busy -= 1;
};
this.addEventListener('open', over);
this.addEventListener('close', over);
}
};
})();
""";
private readonly Process _process;
private readonly ClientWebSocket _socket;
private readonly string _profile;
private readonly ConcurrentDictionary<int, TaskCompletionSource<JsonElement>> _pending = new();
private readonly CancellationTokenSource _stop = new();
private readonly SemaphoreSlim _send = new(1, 1);
private readonly Task _reader;
private int _id;
private UiBrowser(Process process, ClientWebSocket socket, string profile)
{
_process = process;
_socket = socket;
_profile = profile;
_reader = Task.Run(ReadLoopAsync);
}
/// <summary>Uncaught exceptions and console errors of the pages (shown when a test fails).</summary>
public ConcurrentQueue<string> Problems { get; } = new();
public static async Task<UiBrowser> StartAsync(int width = 1280, int height = 900)
{
if (!OperatingSystem.IsLinux() || RealBrowser.ChromiumPath() is not { } chromium)
{
Assert.Inconclusive("Chromium non trovato (impostare FEBE_CHROMIUM): le prove dell'interfaccia nel browser non girano.");
throw new UnreachableException();
}
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,
};
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",
})
{
info.ArgumentList.Add(argument);
}
if (RealBrowser.IsRoot)
{
info.ArgumentList.Add("--no-sandbox");
}
foreach (var (key, value) in RealBrowser.BrowserEnvironment)
{
if (value is null)
{
info.Environment.Remove(key);
}
else
{
info.Environment[key] = value;
}
}
var process = Process.Start(info) ?? throw new InvalidOperationException("Chromium non parte.");
process.OutputDataReceived += (_, _) => { };
process.ErrorDataReceived += (_, _) => { };
process.BeginOutputReadLine();
process.BeginErrorReadLine();
try
{
using var http = new HttpClient(new HttpClientHandler { UseProxy = false }) { Timeout = TimeSpan.FromSeconds(2) };
string? debugger = null;
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(20);
while (debugger is null && DateTime.UtcNow < deadline)
{
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)
{
await Task.Delay(100);
}
}
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);
await browser.SendAsync("Runtime.enable");
await browser.SendAsync("Page.enable");
await browser.SendAsync("Log.enable");
return browser;
}
catch
{
Kill(process);
RealBrowser.TryDelete(profile);
throw;
}
}
/// <summary>One command of the DevTools protocol; its result (an error of the protocol fails the test).</summary>
public async Task<JsonElement> SendAsync(string method, JsonObject? parameters = null)
{
var id = Interlocked.Increment(ref _id);
var answer = new TaskCompletionSource<JsonElement>(TaskCreationOptions.RunContinuationsAsynchronously);
_pending[id] = answer;
var message = new JsonObject { ["id"] = id, ["method"] = method, ["params"] = parameters ?? new JsonObject() };
await _send.WaitAsync();
try
{
await _socket.SendAsync(Encoding.UTF8.GetBytes(message.ToJsonString()), WebSocketMessageType.Text, endOfMessage: true, CancellationToken.None);
}
finally
{
_send.Release();
}
return await answer.Task.WaitAsync(TimeSpan.FromSeconds(30));
}
/// <summary>Runs a script in the page (promises awaited) and returns its value; an exception fails the test.</summary>
public async Task<JsonElement> EvalAsync(string expression)
{
var result = await SendAsync("Runtime.evaluate", new JsonObject
{
["expression"] = expression,
["awaitPromise"] = true,
["returnByValue"] = true,
});
if (result.TryGetProperty("exceptionDetails", out var details))
{
var text = details.TryGetProperty("exception", out var ex) && ex.TryGetProperty("description", out var d) ? d.GetString() : details.GetProperty("text").GetString();
throw new AssertFailedException($"Errore nella pagina: {text}\n{Report()}");
}
return result.GetProperty("result").TryGetProperty("value", out var value) ? value.Clone() : default;
}
public async Task<T> EvalAsync<T>(string expression) => (await EvalAsync(expression)).Deserialize<T>(WebTestServer.Json)!;
/// <summary>
/// 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)
{
var deadline = DateTime.UtcNow + TimeSpan.FromMilliseconds(milliseconds);
string? last = null;
while (DateTime.UtcNow < deadline)
{
try
{
if ((await EvalAsync($"(async () => Boolean(await ({condition})))()")).ValueKind == JsonValueKind.True)
{
return;
}
}
catch (AssertFailedException ex)
{
last = ex.Message;
}
await Task.Delay(50);
}
Assert.Fail($"timeout: {what}{(last is null ? string.Empty : "\n" + last)}\n{Report()}");
}
/// <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)
{
var deadline = DateTime.UtcNow + TimeSpan.FromMilliseconds(milliseconds);
while (DateTime.UtcNow < deadline)
{
if (condition())
{
return;
}
await Task.Delay(50);
}
Assert.Fail($"timeout: {what}\n{Report()}");
}
/// <summary>A script that runs in every new document before its own scripts.</summary>
public Task AddInitScriptAsync(string source) =>
SendAsync("Page.addScriptToEvaluateOnNewDocument", new JsonObject { ["source"] = source });
/// <summary>
/// Waits until no request of the page is in flight (<see cref="Requests"/>): every command it sent has reached the
/// server and been answered, and whatever the page did with the answers, a new request included, has been done. The
/// moment to check that something did not happen, instead of a pause a slow machine may not wait out.
/// </summary>
public Task WaitForQuietAsync(string what) => WaitAsync("window.__busy() === 0", what);
/// <summary>The requests the page started so far (<see cref="Requests"/>) whose «METHOD path» contains the text.</summary>
public Task<string[]> AskedAsync(string match) =>
EvalAsync<string[]>($"window.__asked.filter((r) => r.includes({JsonSerializer.Serialize(match)}))");
/// <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 });
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}");
}
/// <summary>Goes to an internal address the way a link of the interface does (unsaved-changes guard included).</summary>
public Task NavigateAsync(string path) =>
EvalAsync($"import('/js/core/shell.js').then((m) => {{ m.navigate({JsonSerializer.Serialize(path)}); return true; }})");
/// <summary>Centre of the first element matching the selector, in viewport pixels (scrolled into view first).</summary>
public async Task<(double X, double Y, double Width, double Height)> BoxAsync(string selector)
{
var box = await EvalAsync($$"""
(() => {
const el = document.querySelector({{JsonSerializer.Serialize(selector)}});
if (!el) return null;
el.scrollIntoView({ block: 'center', inline: 'center' });
const r = el.getBoundingClientRect();
return { x: r.left + r.width / 2, y: r.top + r.height / 2, width: r.width, height: r.height };
})()
""");
Assert.AreEqual(JsonValueKind.Object, box.ValueKind, $"elemento non trovato: {selector}");
return (box.GetProperty("x").GetDouble(), box.GetProperty("y").GetDouble(), box.GetProperty("width").GetDouble(), box.GetProperty("height").GetDouble());
}
/// <summary>A real mouse event (Input.dispatchMouseEvent): «mousePressed», «mouseMoved», «mouseReleased».</summary>
public Task MouseAsync(string type, double x, double y, int buttons = 0) =>
SendAsync("Input.dispatchMouseEvent", new JsonObject
{
["type"] = type,
["x"] = x,
["y"] = y,
["button"] = type == "mouseMoved" && buttons == 0 ? "none" : "left",
["buttons"] = buttons,
["clickCount"] = type == "mouseMoved" ? 0 : 1,
});
/// <summary>What went wrong in the pages so far, for failure messages.</summary>
public string Report() => Problems.IsEmpty ? string.Empty : "Pagina: " + string.Join(" | ", Problems);
public async ValueTask DisposeAsync()
{
await _stop.CancelAsync();
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
await _socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "fine", timeout.Token);
}
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException)
{
}
Kill(_process);
try
{
await _reader.WaitAsync(TimeSpan.FromSeconds(5));
}
catch (Exception ex) when (ex is TimeoutException or WebSocketException or OperationCanceledException)
{
}
_socket.Dispose();
_process.Dispose();
_stop.Dispose();
_send.Dispose();
RealBrowser.TryDelete(_profile);
}
private static void Kill(Process process)
{
try
{
if (!process.HasExited)
{
process.Kill(entireProcessTree: true);
process.WaitForExit(5000);
}
}
catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception)
{
}
}
private async Task ReadLoopAsync()
{
var buffer = new byte[64 * 1024];
using var message = new MemoryStream();
try
{
while (!_stop.IsCancellationRequested && _socket.State == WebSocketState.Open)
{
message.SetLength(0);
WebSocketReceiveResult result;
do
{
result = await _socket.ReceiveAsync(buffer, _stop.Token);
if (result.MessageType == WebSocketMessageType.Close)
{
return;
}
message.Write(buffer, 0, result.Count);
}
while (!result.EndOfMessage);
Dispatch(message.ToArray());
}
}
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException)
{
}
finally
{
foreach (var pending in _pending.Values)
{
pending.TrySetException(new InvalidOperationException("Chromium si è chiuso."));
}
}
}
private void Dispatch(byte[] data)
{
using var document = JsonDocument.Parse(data);
var root = document.RootElement;
if (root.TryGetProperty("id", out var idElement) && _pending.TryRemove(idElement.GetInt32(), out var answer))
{
if (root.TryGetProperty("error", out var error))
{
answer.TrySetException(new InvalidOperationException("DevTools: " + error.GetRawText()));
}
else
{
answer.TrySetResult(root.GetProperty("result").Clone());
}
return;
}
if (!root.TryGetProperty("method", out var method))
{
return;
}
var parameters = root.GetProperty("params");
switch (method.GetString())
{
case "Runtime.exceptionThrown":
var details = parameters.GetProperty("exceptionDetails");
Problems.Enqueue("eccezione: " + (details.TryGetProperty("exception", out var ex) && ex.TryGetProperty("description", out var d) ? d.GetString() : details.GetProperty("text").GetString()));
break;
case "Runtime.consoleAPICalled" when parameters.GetProperty("type").GetString() == "error":
Problems.Enqueue("console: " + string.Join(' ', parameters.GetProperty("args").EnumerateArray().Select(a => a.TryGetProperty("value", out var v) ? v.ToString() : a.TryGetProperty("description", out var s) ? s.GetString() : "?")));
break;
}
}
}