Files
Febe/tests/Febe.Tests/Browser/HostingTests.cs
T
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

160 lines
6.7 KiB
C#

using System.Diagnostics;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
namespace Febe.Tests.Browser;
[TestClass]
public sealed class HostingTests
{
private static readonly BrowserOptions Options = new("/tmp/febe-profilo", 1280, 900, 9333);
[TestMethod]
public void CommandLineIsANormalWindowedBrowserWithFixedLoopbackPort()
{
var args = ChromiumCommandLine.Build(Options, new ChromiumLaunchOptions());
CollectionAssert.Contains(args.ToList(), "--remote-debugging-port=9333");
// The profile reaches Chromium as a full path: «/tmp/febe-profilo» on Linux, rooted on the current drive on Windows.
CollectionAssert.Contains(args.ToList(), $"--user-data-dir={Path.GetFullPath(Options.ProfileDirectory)}");
CollectionAssert.Contains(args.ToList(), "--no-first-run");
CollectionAssert.Contains(args.ToList(), "--no-default-browser-check");
CollectionAssert.Contains(args.ToList(), "--window-size=1280,900");
CollectionAssert.Contains(args.ToList(), "--password-store=basic");
CollectionAssert.Contains(args.ToList(), "--disable-dev-shm-usage");
Assert.AreEqual("about:blank", args[^1]);
string[] never = ["--headless", "--enable-automation", "--remote-debugging-pipe", "--user-agent", "--lang", "--no-sandbox", "--proxy-server", "--remote-debugging-address"];
foreach (var flag in never)
{
Assert.IsFalse(args.Any(a => a.StartsWith(flag, StringComparison.Ordinal)), $"{flag} must not be on the command line.");
}
}
[TestMethod]
[DataRow(0)]
[DataRow(80)]
[DataRow(70000)]
public void PortZeroOrPrivilegedIsRefused(int port) =>
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => ChromiumCommandLine.Build(Options with { DebugPort = port }, new ChromiumLaunchOptions()));
[TestMethod]
public void NoSandboxOnlyWhenAskedExplicitly()
{
var args = ChromiumCommandLine.Build(Options, new ChromiumLaunchOptions { NoSandbox = true });
CollectionAssert.Contains(args.ToList(), "--no-sandbox");
}
[TestMethod]
[DataRow("--headless")]
[DataRow("--headless=new")]
[DataRow("--enable-automation")]
[DataRow("--remote-debugging-pipe")]
[DataRow("--remote-debugging-port=0")]
[DataRow("--user-agent=Febe")]
[DataRow("--lang=en-US")]
[DataRow("--proxy-server=socks5://x")]
[DataRow("--disable-blink-features=AutomationControlled")]
[DataRow("--no-sandbox")]
[DataRow("headless")]
public void ForbiddenExtraArgumentsAreRefused(string argument) =>
Assert.ThrowsExactly<ArgumentException>(() => ChromiumCommandLine.Build(Options, new ChromiumLaunchOptions { ExtraArguments = [argument] }));
[TestMethod]
public void HarmlessExtraArgumentsPass()
{
var args = ChromiumCommandLine.Build(Options, new ChromiumLaunchOptions { ExtraArguments = ["--force-color-profile=srgb"] });
CollectionAssert.Contains(args.ToList(), "--force-color-profile=srgb");
}
[TestMethod]
public void RestartBackoffDoublesUpToTheCap()
{
var policy = new RestartPolicy(TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(2));
Assert.AreEqual(TimeSpan.FromSeconds(2), policy.DelayFor(0));
Assert.AreEqual(TimeSpan.FromSeconds(4), policy.DelayFor(1));
Assert.AreEqual(TimeSpan.FromSeconds(16), policy.DelayFor(3));
Assert.AreEqual(TimeSpan.FromSeconds(30), policy.DelayFor(4));
Assert.AreEqual(TimeSpan.FromSeconds(30), policy.DelayFor(100));
}
[TestMethod]
public void UserDrivingGateNestsLeases()
{
var gate = new UserDrivingGate();
var changes = new List<bool>();
gate.Changed += (_, value) => changes.Add(value);
var remoteView = gate.Begin();
var loginPage = gate.Begin();
Assert.IsTrue(gate.IsDriving);
remoteView.Dispose();
remoteView.Dispose();
Assert.IsTrue(gate.IsDriving, "Still driving while the second lease is open.");
loginPage.Dispose();
Assert.IsFalse(gate.IsDriving);
CollectionAssert.AreEqual(new[] { true, false }, changes);
}
[TestMethod]
public async Task SupervisorRestartsAProcessThatExitsAndStopsCleanly()
{
if (!OperatingSystem.IsLinux() || !File.Exists("/bin/sleep"))
{
Assert.Inconclusive("Serve /bin/sleep (Linux).");
}
var restarted = 0;
var twice = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var supervisor = new SupervisedProcess(
"prova",
() => new ProcessStartInfo("/bin/sleep", "0.2"),
(_, _) => Task.CompletedTask,
new SystemClock(),
policy: new RestartPolicy(TimeSpan.FromMilliseconds(50), TimeSpan.FromMilliseconds(200), TimeSpan.FromMinutes(1)));
supervisor.Restarted += (_, _) =>
{
if (Interlocked.Increment(ref restarted) >= 2)
{
twice.TrySetResult();
}
};
await supervisor.StartAsync(CancellationToken.None);
// By condition; the limit only bounds a supervisor that never restarts (process starts are slow under load, #46).
await twice.Task.WaitAsync(TimeSpan.FromSeconds(30));
Assert.IsTrue(Volatile.Read(ref restarted) >= 2, "The process was restarted after exiting.");
await supervisor.StopAsync(TimeSpan.FromSeconds(2));
Assert.AreEqual(SupervisedState.Stopped, supervisor.State);
var after = Volatile.Read(ref restarted);
await Task.Delay(600);
Assert.AreEqual(after, Volatile.Read(ref restarted), "No restarts after stop.");
}
[TestMethod]
public async Task SupervisorEndsALongRunningProcessPolitely()
{
if (!OperatingSystem.IsLinux() || !File.Exists("/bin/sleep"))
{
Assert.Inconclusive("Serve /bin/sleep (Linux).");
}
await using var supervisor = new SupervisedProcess(
"prova",
() => new ProcessStartInfo("/bin/sleep", "60"),
(_, _) => Task.CompletedTask,
new SystemClock());
await supervisor.StartAsync(CancellationToken.None);
var pid = supervisor.ProcessId;
Assert.IsNotNull(pid);
// The kill would come only after 120 s: any stop well before that was SIGTERM, with room for a loaded runner (#46).
var watch = Stopwatch.StartNew();
await supervisor.StopAsync(TimeSpan.FromSeconds(120));
Assert.IsLessThan(TimeSpan.FromSeconds(30), watch.Elapsed, "SIGTERM ends sleep at once; no need to wait for the kill.");
Assert.IsFalse(Process.GetProcesses().Any(p => p.Id == pid && !p.HasExited && p.ProcessName == "sleep"));
}
}