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;
///
/// A real Chromium on a private Xvfb display, driven by , plus a local test site.
/// Integration tests become inconclusive when Chromium or Xvfb is missing.
///
public sealed class RealBrowser : IAsyncDisposable
{
/// Chromium of this development environment; FEBE_CHROMIUM overrides it.
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 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 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;
}
/// Environment of the browser process: Italian language and Rome time zone; no proxy for the test browser.
public static IReadOnlyDictionary BrowserEnvironment => new Dictionary
{
["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 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();
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);
}
/// Opens a page of the test site and waits until it has loaded.
public async Task GoAsync(string path)
{
var result = await Cdp.NavigateAsync(Site.Url(path));
if (!result.Succeeded)
{
throw new InvalidOperationException($"Navigazione fallita: {result.ErrorText}");
}
if (!await Cdp.WaitForLoadAsync(Clock, TimeSpan.FromSeconds(15)))
{
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.
await Task.Delay(SettleAfterLoad);
}
public static TimeSpan SettleAfterLoad { get; } = TimeSpan.FromMilliseconds(500);
public async Task EvalAsync(string expression) =>
(await Cdp.EvaluateAsync(expression)).Deserialize()!;
/// Stops the browser but keeps the profile and the site (for restart tests).
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)
{
}
}
}