Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
151 lines
6.2 KiB
C#
151 lines
6.2 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Diagnostics;
|
|
using System.Text.Json;
|
|
using Febe.Browser.Capture;
|
|
using Febe.Browser.Cdp;
|
|
using Febe.Browser.Hosting;
|
|
using Febe.Core.Collection;
|
|
using Febe.Tests.Browser.TestSupport;
|
|
|
|
namespace Febe.Tests.Browser;
|
|
|
|
/// <summary>Supervision of the real browser: crash and restart, clean stop, session kept in the profile.</summary>
|
|
[TestClass]
|
|
[DoNotParallelize]
|
|
public sealed class BrowserLifecycleTests
|
|
{
|
|
public TestContext TestContext { get; set; } = null!;
|
|
|
|
[TestInitialize]
|
|
public void RequireBrowser()
|
|
{
|
|
if (RealBrowser.UnavailableReason() is { } reason)
|
|
{
|
|
Assert.Inconclusive(reason);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task AfterACrashChromiumRestartsAndSubscriptionsSurvive()
|
|
{
|
|
await using var browser = await RealBrowser.StartAsync();
|
|
var reconnected = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
browser.Host.Connection.Reconnected += (_, _) => reconnected.TrySetResult();
|
|
|
|
var consumer = new Collector();
|
|
await using var tap = new ResponseTap(browser.Cdp, browser.Hosts, browser.Clock);
|
|
tap.AddConsumer(consumer);
|
|
await tap.StartAsync();
|
|
|
|
var firstPid = browser.Host.ProcessId;
|
|
browser.Host.KillForRestart();
|
|
await reconnected.Task.WaitAsync(TimeSpan.FromSeconds(30));
|
|
var watch = Stopwatch.StartNew();
|
|
while (browser.Host.Restarts == 0 && watch.Elapsed < TimeSpan.FromSeconds(10))
|
|
{
|
|
await Task.Delay(20);
|
|
}
|
|
|
|
Assert.AreEqual(1, browser.Host.Restarts, "The supervisor restarted the process (not just the connection).");
|
|
Assert.AreNotEqual(firstPid, browser.Host.ProcessId);
|
|
Assert.AreEqual(SupervisedState.Running, browser.Host.State);
|
|
Assert.AreEqual(2, (await browser.Cdp.EvaluateAsync("1 + 1")).GetInt32(), "The same session object works after the restart.");
|
|
Assert.IsTrue(LoopbackPortCheck.IsLoopbackOnly(browser.Port, out _));
|
|
|
|
// The tap subscribed before the crash: it re-enabled the Network domain by itself.
|
|
await browser.GoAsync("/cattura");
|
|
watch.Restart();
|
|
while (!consumer.Paths.Contains("/api/dati.json") && watch.Elapsed < TimeSpan.FromSeconds(10))
|
|
{
|
|
await Task.Delay(50);
|
|
}
|
|
|
|
Assert.IsTrue(consumer.Paths.Contains("/api/dati.json"), "Responses are captured after the restart.");
|
|
TestContext.WriteLine(string.Join(Environment.NewLine, browser.Log));
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task TheSessionCookieSurvivesACleanRestartOfTheBrowser()
|
|
{
|
|
var profile = Path.Combine(Path.GetTempPath(), "febe-profilo-" + Guid.NewGuid().ToString("N"));
|
|
using var site = new LocalTestSite();
|
|
try
|
|
{
|
|
var first = await RealBrowser.StartAsync(profile, site);
|
|
await first.GoAsync("/cookie");
|
|
var options = new SessionCookieOptions("sessionid", site.Url("/"));
|
|
Assert.IsTrue(await SessionCookieProbe.HasSessionCookieAsync(first.Cdp, options));
|
|
var pid = first.Host.ProcessId!.Value;
|
|
|
|
var watch = Stopwatch.StartNew();
|
|
await first.StopBrowserAsync();
|
|
TestContext.WriteLine($"Arresto ordinato di Chromium in {watch.Elapsed.TotalSeconds:F1} s.");
|
|
Assert.IsFalse(Process.GetProcesses().Any(p => p.Id == pid), "Chromium has exited.");
|
|
Assert.AreEqual(SupervisedState.Stopped, first.Host.State);
|
|
|
|
await using var second = await RealBrowser.StartAsync(profile, site);
|
|
Assert.IsTrue(await SessionCookieProbe.HasSessionCookieAsync(second.Cdp, options), "The cookie written before the stop is still in the profile.");
|
|
Assert.AreEqual("about:blank", await second.Cdp.GetMainFrameUrlAsync(), "A restart opens the rest page, not the last site page.");
|
|
}
|
|
finally
|
|
{
|
|
RealBrowser.TryDelete(profile);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task XvfbIsRestartedWhenItDies()
|
|
{
|
|
var display = XvfbProcess.FindFreeDisplay(100, 199)!;
|
|
await using var xvfb = new XvfbProcess(display, 800, 600, restart: new RestartPolicy(TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), TimeSpan.FromMinutes(1)));
|
|
var restarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
xvfb.Restarted += (_, _) => restarted.TrySetResult();
|
|
await xvfb.StartAsync(CancellationToken.None);
|
|
Assert.IsTrue(File.Exists(xvfb.SocketPath));
|
|
var pid = xvfb.ProcessId!.Value;
|
|
|
|
using (var process = Process.GetProcessById(pid))
|
|
{
|
|
process.Kill();
|
|
}
|
|
|
|
await restarted.Task.WaitAsync(TimeSpan.FromSeconds(20));
|
|
Assert.AreNotEqual(pid, xvfb.ProcessId);
|
|
Assert.AreEqual(SupervisedState.Running, xvfb.State);
|
|
|
|
await xvfb.StopAsync();
|
|
Assert.AreEqual(SupervisedState.Stopped, xvfb.State);
|
|
Assert.IsFalse(File.Exists(xvfb.SocketPath), "A polite stop removes the X socket.");
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task APortAlreadyInUseIsRefusedBeforeLaunching()
|
|
{
|
|
var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
|
|
listener.Start();
|
|
try
|
|
{
|
|
var port = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
|
|
await using var host = new ChromiumProcessHost(new ChromiumLaunchOptions { NoSandbox = RealBrowser.IsRoot });
|
|
var options = new Febe.Core.Abstractions.BrowserOptions(Path.Combine(Path.GetTempPath(), "febe-non-usato"), DebugPort: port, ExecutablePath: RealBrowser.ChromiumPath());
|
|
var ex = await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => host.StartAsync(options, CancellationToken.None));
|
|
StringAssert.Contains(ex.Message, "già occupata");
|
|
}
|
|
finally
|
|
{
|
|
listener.Stop();
|
|
}
|
|
}
|
|
|
|
private sealed class Collector : IResponseConsumer
|
|
{
|
|
public ConcurrentBag<string> Paths { get; } = [];
|
|
|
|
public ValueTask ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct)
|
|
{
|
|
Paths.Add(response.Path);
|
|
return ValueTask.CompletedTask;
|
|
}
|
|
}
|
|
}
|