Files
Alby96andClaude Opus 5.5 0775a1460f
verifica / controlli (push) Successful in 25s
verifica / prove (push) Successful in 25m9s
verifica / installatore (push) Successful in 7m37s
verifica / immagine (push) Successful in 20m21s
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>
2026-11-13 19:50:40 +01:00

221 lines
7.2 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections.Concurrent;
using System.Text.Json;
using Febe.Browser.Cdp;
using Febe.Browser.Diagnostics;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
namespace Febe.Tests.Browser.TestSupport;
/// <summary>
/// A real Chromium on a private Xvfb display, driven by <see cref="ChromiumProcessHost"/>, plus a local test site.
/// Integration tests become inconclusive when Chromium or Xvfb is missing.
/// </summary>
public sealed class RealBrowser : IAsyncDisposable
{
/// <summary>Chromium of this development environment; FEBE_CHROMIUM overrides it.</summary>
private const string KnownChromium = "/opt/pw-browsers/chromium-1194/chrome-linux/chrome";
private RealBrowser(XvfbProcess xvfb, ChromiumProcessHost host, LocalTestSite site, string profileDirectory, int port, bool ownsProfile, bool ownsSite, ConcurrentQueue<string> log)
{
Log = log;
OwnsSite = ownsSite;
Xvfb = xvfb;
Host = host;
Site = site;
ProfileDirectory = profileDirectory;
Port = port;
OwnsProfile = ownsProfile;
}
public XvfbProcess Xvfb { get; }
public ChromiumProcessHost Host { get; }
public LocalTestSite Site { get; }
public string ProfileDirectory { get; }
public int Port { get; }
public ICdpSession Cdp => Host.Cdp;
public IClock Clock { get; } = new SystemClock();
public HostClassifier Hosts => new([Site.SiteHost], [Site.CdnHost]);
public ConcurrentQueue<string> Log { get; }
private bool OwnsProfile { get; }
private bool OwnsSite { get; }
public static bool IsRoot => Environment.UserName == "root";
public static string? ChromiumPath()
{
var fromEnv = Environment.GetEnvironmentVariable("FEBE_CHROMIUM");
if (!string.IsNullOrWhiteSpace(fromEnv) && File.Exists(fromEnv))
{
return fromEnv;
}
return File.Exists(KnownChromium) ? KnownChromium : ChromiumCommandLine.FindExecutable();
}
public static string? UnavailableReason()
{
if (!OperatingSystem.IsLinux())
{
return "Le prove con Chromium su Xvfb girano solo su Linux.";
}
if (ChromiumPath() is null)
{
return "Chromium non trovato (impostare FEBE_CHROMIUM).";
}
return XvfbProcess.FindExecutable() is null ? "Xvfb non trovato." : null;
}
/// <summary>Environment of the browser process: Italian language and Rome time zone; no proxy for the test browser.</summary>
public static IReadOnlyDictionary<string, string?> BrowserEnvironment => new Dictionary<string, string?>
{
["LANG"] = "it_IT.UTF-8",
["TZ"] = "Europe/Rome",
["LANGUAGE"] = null,
["LC_ALL"] = null,
["http_proxy"] = null,
["https_proxy"] = null,
["HTTP_PROXY"] = null,
["HTTPS_PROXY"] = null,
["ALL_PROXY"] = null,
["all_proxy"] = null,
["no_proxy"] = null,
["NO_PROXY"] = null,
};
public static async Task<RealBrowser> StartAsync(string? profileDirectory = null, LocalTestSite? site = null, RestartPolicy? restart = null)
{
var display = XvfbProcess.FindFreeDisplay(100, 199) ?? throw new InvalidOperationException("Nessun display libero.");
var log = new ConcurrentQueue<string>();
var browserLog = new DelegateBrowserLog((level, message, ex) => log.Enqueue($"{level}: {message} {ex?.Message}"));
var xvfb = new XvfbProcess(display, 1280, 900, log: browserLog);
await xvfb.StartAsync(CancellationToken.None);
var ownsProfile = profileDirectory is null;
var profile = profileDirectory ?? Path.Combine(Path.GetTempPath(), "febe-prova-" + Guid.NewGuid().ToString("N"));
var port = LocalTestSite.FreePort();
var host = new ChromiumProcessHost(
new ChromiumLaunchOptions
{
NoSandbox = IsRoot,
Environment = BrowserEnvironment,
Restart = restart ?? new RestartPolicy(TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(2)),
},
log: browserLog);
var testSite = site ?? new LocalTestSite();
try
{
await host.StartAsync(new BrowserOptions(profile, 1280, 900, port, ChromiumPath(), display), CancellationToken.None);
}
catch
{
await host.DisposeAsync();
await xvfb.DisposeAsync();
if (site is null)
{
testSite.Dispose();
}
throw;
}
return new RealBrowser(xvfb, host, testSite, profile, port, ownsProfile, site is null, log);
}
/// <summary>Opens a page of the test site and waits until it has loaded.</summary>
public async Task GoAsync(string path)
{
var result = await Cdp.NavigateAsync(Site.Url(path));
if (!result.Succeeded)
{
throw new InvalidOperationException($"Navigazione fallita: {result.ErrorText}");
}
// The limit only bounds a hang: the wait ends with the load (#46).
if (!await Cdp.WaitForLoadAsync(Clock, TimeSpan.FromSeconds(60)))
{
throw new TimeoutException("La pagina non ha finito di caricare.");
}
// Like the post-load wait of the recipes (1–6 s, shortened here): Chromium ignores input that arrives
// right after a navigation, before the page has painted. On a loaded runner the first paint comes later.
await WaitForPaintAsync();
await Task.Delay(SettleAfterLoad);
}
/// <summary>
/// Waits until the page reports its first paint (a read-only look at the paint entries), up to 15 s. Not reported
/// in time is not an error: the settle after it stays as before.
/// </summary>
public async Task<bool> WaitForPaintAsync()
{
var watch = System.Diagnostics.Stopwatch.StartNew();
while (watch.Elapsed < TimeSpan.FromSeconds(15))
{
if (await EvalAsync<bool>("performance.getEntriesByType('paint').length > 0"))
{
return true;
}
await Task.Delay(50);
}
return false;
}
public static TimeSpan SettleAfterLoad { get; } = TimeSpan.FromMilliseconds(500);
public async Task<T> EvalAsync<T>(string expression) =>
(await Cdp.EvaluateAsync(expression)).Deserialize<T>()!;
/// <summary>Stops the browser but keeps the profile and the site (for restart tests).</summary>
public async Task StopBrowserAsync()
{
await Host.DisposeAsync();
await Xvfb.DisposeAsync();
}
public async ValueTask DisposeAsync()
{
await Host.DisposeAsync();
await Xvfb.DisposeAsync();
if (OwnsSite)
{
Site.Dispose();
}
if (OwnsProfile)
{
TryDelete(ProfileDirectory);
}
}
public static void TryDelete(string directory)
{
try
{
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
}
}
}