Files
Febe/tests/Febe.Tests/Browser/HostingTests.cs
T

152 lines
6.2 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");
CollectionAssert.Contains(args.ToList(), "--user-data-dir=/tmp/febe-profilo");
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;
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 += (_, _) => Interlocked.Increment(ref restarted);
await supervisor.StartAsync(CancellationToken.None);
for (var i = 0; i < 100 && Volatile.Read(ref restarted) < 2; i++)
{
await Task.Delay(50);
}
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);
var watch = Stopwatch.StartNew();
await supervisor.StopAsync(TimeSpan.FromSeconds(5));
Assert.IsTrue(watch.Elapsed < TimeSpan.FromSeconds(4), "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"));
}
}