Files
Febe/tests/Febe.Tests/Browser/TestSupport/RealBrowser.cs
T

199 lines
6.4 KiB
C#
Raw 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}");
}
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<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)
{
}
}
}