Strato browser (M0/M2): client CDP con elenco dei comandi ammessi, ChromiumProcessHost e Xvfb sorvegliati, gesti umani, mappa dei bersagli, cattura delle risposte, segnali di arresto, scaricamento dal browser, vista remota, distribuzioni del ritmo; prove unitarie e d'insieme con Chromium su Xvfb; esito locale di S5 e S6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
44 files changed
+8396
No files matched your search
@@ -0,0 +1,192 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Tests.Browser.TestSupport;
|
||||
|
||||
/// <summary>Virtual clock: <see cref="Delay"/> advances time instantly, so timing can be asserted without waiting.</summary>
|
||||
public sealed class VirtualClock(DateTimeOffset? start = null) : IClock
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private DateTimeOffset _now = start ?? new DateTimeOffset(2026, 10, 13, 9, 0, 0, TimeSpan.Zero);
|
||||
|
||||
public DateTimeOffset Now
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public TimeZoneInfo LocalZone => TimeZoneInfo.Utc;
|
||||
|
||||
public List<TimeSpan> Delays { get; } = [];
|
||||
|
||||
public Task Delay(TimeSpan time, CancellationToken ct)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
lock (_gate)
|
||||
{
|
||||
if (time > TimeSpan.Zero)
|
||||
{
|
||||
_now += time;
|
||||
}
|
||||
|
||||
Delays.Add(time);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public void Advance(TimeSpan time)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_now += time;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A command recorded by <see cref="FakeCdpSession"/>.</summary>
|
||||
public sealed record SentCommand(string Method, JsonNode? Parameters, DateTimeOffset At)
|
||||
{
|
||||
public string? Type => Parameters?["type"]?.GetValue<string>();
|
||||
|
||||
public double X => Parameters?["x"]?.GetValue<double>() ?? double.NaN;
|
||||
|
||||
public double Y => Parameters?["y"]?.GetValue<double>() ?? double.NaN;
|
||||
|
||||
public double DeltaY => Parameters?["deltaY"]?.GetValue<double>() ?? 0;
|
||||
}
|
||||
|
||||
/// <summary>Records commands with the virtual time at which they were sent, and answers with canned results.</summary>
|
||||
public sealed class FakeCdpSession(IClock clock) : ICdpSession
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Dictionary<string, List<Action<JsonElement>>> _handlers = new(StringComparer.Ordinal);
|
||||
|
||||
private readonly List<SentCommand> _sent = [];
|
||||
|
||||
/// <summary>Snapshot of the commands sent so far (background pumps may add more concurrently).</summary>
|
||||
public IReadOnlyList<SentCommand> Sent
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return [.. _sent];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void ClearSent()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_sent.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Returns the result for a command; null means an empty object.</summary>
|
||||
public Func<string, JsonNode?, JsonNode?> Responder { get; set; } = (_, _) => null;
|
||||
|
||||
public Task<JsonElement> SendAsync(string method, object? parameters = null, CancellationToken ct = default)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var node = parameters switch
|
||||
{
|
||||
null => null,
|
||||
JsonNode n => JsonNode.Parse(n.ToJsonString()),
|
||||
_ => JsonSerializer.SerializeToNode(parameters, parameters.GetType()),
|
||||
};
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
_sent.Add(new SentCommand(method, node, clock.Now));
|
||||
}
|
||||
|
||||
var result = Responder(method, node) ?? new JsonObject();
|
||||
return Task.FromResult(JsonSerializer.Deserialize<JsonElement>(result.ToJsonString()));
|
||||
}
|
||||
|
||||
public IDisposable On(string eventName, Action<JsonElement> handler)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_handlers.TryGetValue(eventName, out var list))
|
||||
{
|
||||
list = [];
|
||||
_handlers[eventName] = list;
|
||||
}
|
||||
|
||||
list.Add(handler);
|
||||
}
|
||||
|
||||
return new Unsubscribe(() =>
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_handlers[eventName].Remove(handler);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void Raise(string eventName, JsonNode payload)
|
||||
{
|
||||
Action<JsonElement>[] handlers;
|
||||
lock (_gate)
|
||||
{
|
||||
handlers = _handlers.TryGetValue(eventName, out var list) ? [.. list] : [];
|
||||
}
|
||||
|
||||
var element = JsonSerializer.Deserialize<JsonElement>(payload.ToJsonString());
|
||||
foreach (var handler in handlers)
|
||||
{
|
||||
handler(element);
|
||||
}
|
||||
}
|
||||
|
||||
public List<SentCommand> Mouse(string? type = null)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return [.. _sent.Where(c => c.Method == "Input.dispatchMouseEvent" && (type is null || c.Type == type))];
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Unsubscribe(Action action) : IDisposable
|
||||
{
|
||||
public void Dispose() => action();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Circuit breaker that only records what it receives.</summary>
|
||||
public sealed class RecordingBreaker : ICircuitBreaker
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<Signal> _signals = [];
|
||||
|
||||
public BreakerState State => BreakerState.Normal;
|
||||
|
||||
public IReadOnlyList<Signal> Signals
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return [.. _signals];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Report(Signal signal)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_signals.Add(signal);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Tests.Browser.TestSupport;
|
||||
|
||||
/// <summary>
|
||||
/// Tiny local site served by the test itself on 127.0.0.1 (never Instagram): one port plays the site, another the CDN.
|
||||
/// </summary>
|
||||
public sealed class LocalTestSite : IDisposable
|
||||
{
|
||||
public const int BigFileBytes = 24 * 1024 * 1024;
|
||||
|
||||
private static readonly Lazy<(byte[] Bytes, string Sha256)> BigFile = new(() =>
|
||||
{
|
||||
var bytes = new byte[BigFileBytes];
|
||||
new Random(20261013).NextBytes(bytes);
|
||||
return (bytes, Convert.ToHexString(SHA256.HashData(bytes)));
|
||||
});
|
||||
|
||||
private readonly HttpListener _listener = new();
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
|
||||
public LocalTestSite()
|
||||
{
|
||||
SitePort = FreePort();
|
||||
CdnPort = FreePort();
|
||||
_listener.Prefixes.Add($"http://127.0.0.1:{SitePort}/");
|
||||
_listener.Prefixes.Add($"http://127.0.0.1:{CdnPort}/");
|
||||
_listener.Start();
|
||||
_ = Task.Run(LoopAsync);
|
||||
}
|
||||
|
||||
public int SitePort { get; }
|
||||
|
||||
public int CdnPort { get; }
|
||||
|
||||
public string SiteHost => $"127.0.0.1:{SitePort}";
|
||||
|
||||
public string CdnHost => $"127.0.0.1:{CdnPort}";
|
||||
|
||||
public static string BigFileSha256 => BigFile.Value.Sha256;
|
||||
|
||||
public string Url(string path) => $"http://{SiteHost}{path}";
|
||||
|
||||
public string CdnUrl(string path) => $"http://{CdnHost}{path}";
|
||||
|
||||
public static int FreePort()
|
||||
{
|
||||
var probe = new TcpListener(IPAddress.Loopback, 0);
|
||||
probe.Start();
|
||||
var port = ((IPEndPoint)probe.LocalEndpoint).Port;
|
||||
probe.Stop();
|
||||
return port;
|
||||
}
|
||||
|
||||
private int _disposed;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_stop.Cancel();
|
||||
try
|
||||
{
|
||||
_listener.Stop();
|
||||
_listener.Close();
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
|
||||
_stop.Dispose();
|
||||
}
|
||||
|
||||
private async Task LoopAsync()
|
||||
{
|
||||
while (!_stop.IsCancellationRequested)
|
||||
{
|
||||
HttpListenerContext context;
|
||||
try
|
||||
{
|
||||
context = await _listener.GetContextAsync();
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpListenerException or ObjectDisposedException or InvalidOperationException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_ = Task.Run(() => HandleAsync(context));
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleAsync(HttpListenerContext context)
|
||||
{
|
||||
var response = context.Response;
|
||||
try
|
||||
{
|
||||
var path = context.Request.Url!.AbsolutePath;
|
||||
if (context.Request.Url.Port == CdnPort)
|
||||
{
|
||||
if (path == "/file.bin")
|
||||
{
|
||||
response.ContentType = "application/octet-stream";
|
||||
response.ContentLength64 = BigFile.Value.Bytes.Length;
|
||||
await response.OutputStream.WriteAsync(BigFile.Value.Bytes);
|
||||
}
|
||||
else
|
||||
{
|
||||
response.StatusCode = 404;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
switch (path)
|
||||
{
|
||||
case "/api/dati.json":
|
||||
await JsonAsync(response, 200, """{"elementi":[{"id":"1","testo":"ciao"},{"id":"2","testo":"mondo"}]}""");
|
||||
return;
|
||||
case "/api/troppe":
|
||||
await JsonAsync(response, 429, """{"messaggio":"troppe richieste"}""");
|
||||
return;
|
||||
case "/api/attendi.json":
|
||||
await JsonAsync(response, 200, """{"messaggio":"Attendi qualche minuto prima di riprovare."}""");
|
||||
return;
|
||||
case "/vai-a-verifica":
|
||||
response.StatusCode = 302;
|
||||
response.RedirectLocation = "/verifica?da=prova";
|
||||
return;
|
||||
case "/cookie":
|
||||
response.AppendHeader("Set-Cookie", "sessionid=valore-finto-di-prova; Path=/; Max-Age=86400; SameSite=Lax");
|
||||
await HtmlAsync(response, "<p>Cookie impostato</p>");
|
||||
return;
|
||||
default:
|
||||
await HtmlAsync(response, Page(path));
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpListenerException or IOException or ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
response.Close();
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpListenerException or ObjectDisposedException or InvalidOperationException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string Page(string path) => path switch
|
||||
{
|
||||
"/lunga" => string.Concat(Enumerable.Range(1, 300).Select(i => $"<p>Riga {i} di una pagina lunga.</p>"))
|
||||
+ "<script>window.__wheel = { count: 0, trusted: true };"
|
||||
+ "addEventListener('wheel', (e) => { window.__wheel.count++; window.__wheel.trusted = window.__wheel.trusted && e.isTrusted; }, { passive: true });</script>",
|
||||
"/bottoni" => """
|
||||
<div style="height:3000px;position:relative">
|
||||
<button id="b1" aria-label="Indietro" style="position:absolute;left:100px;top:100px;width:120px;height:40px">‹</button>
|
||||
<button id="b2" aria-label="Avanti" style="position:absolute;left:400px;top:300px;width:160px;height:50px">›</button>
|
||||
<button id="b3" aria-label="Avanti" style="display:none">nascosto</button>
|
||||
<a id="l1" href="/profilo/alice/" style="position:absolute;left:100px;top:500px">alice</a>
|
||||
<a id="l2" href="/stories/alice/123/" style="position:absolute;left:300px;top:500px"><span>Storia di alice</span></a>
|
||||
<button id="b4" aria-label="Coperto" style="position:absolute;left:700px;top:100px;width:100px;height:40px">x</button>
|
||||
<div style="position:absolute;left:690px;top:90px;width:140px;height:70px;background:#ddd"></div>
|
||||
<button id="b5" style="position:absolute;left:400px;top:2400px;width:120px;height:40px">Lontano</button>
|
||||
</div>
|
||||
<script>
|
||||
window.__clicks = [];
|
||||
window.__moves = 0;
|
||||
document.addEventListener('mousemove', () => { window.__moves++; });
|
||||
document.addEventListener('click', (e) => {
|
||||
const t = e.target.closest('[id]');
|
||||
window.__clicks.push({ id: t ? t.id : '', x: e.clientX, y: e.clientY, trusted: e.isTrusted });
|
||||
});
|
||||
</script>
|
||||
""",
|
||||
"/cattura" => "<p>Cattura</p><script>addEventListener('load', () => fetch('/api/dati.json').then((r) => r.json()).then(() => { document.title = 'caricato'; }));</script>",
|
||||
"/cattura-429" => "<p>Troppe</p><script>addEventListener('load', () => fetch('/api/troppe').then((r) => r.text()));</script>",
|
||||
"/cattura-attendi" => "<p>Attendi</p><script>addEventListener('load', () => fetch('/api/attendi.json').then((r) => r.json()));</script>",
|
||||
"/animata" => """
|
||||
<style>@keyframes giro { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
|
||||
#q { width: 200px; height: 200px; margin: 100px; background: #c63; animation: giro 1s linear infinite; }</style>
|
||||
<div id="q"></div>
|
||||
""",
|
||||
"/modulo" => """
|
||||
<input id="campo" aria-label="Campo" style="position:absolute;left:200px;top:200px;width:300px;height:30px">
|
||||
<script>
|
||||
window.__keys = 0;
|
||||
window.__clicks = 0;
|
||||
document.addEventListener('keydown', () => { window.__keys++; });
|
||||
document.addEventListener('mousedown', () => { window.__clicks++; });
|
||||
</script>
|
||||
""",
|
||||
"/spa" => "<p>Applicazione</p><script>addEventListener('load', () => setTimeout(() => history.pushState({}, '', '/verifica/interna?x=1'), 300));</script>",
|
||||
"/verifica" => "<h1>Verifica</h1>",
|
||||
"/accesso" => "<h1>Accesso</h1>",
|
||||
_ => "<p>Pagina di prova</p>",
|
||||
};
|
||||
|
||||
private static Task HtmlAsync(HttpListenerResponse response, string body) =>
|
||||
WriteAsync(response, 200, "text/html; charset=utf-8", $"<!doctype html><html lang=\"it\"><head><meta charset=\"utf-8\"><title>Prova</title></head><body>{body}</body></html>");
|
||||
|
||||
private static Task JsonAsync(HttpListenerResponse response, int status, string json) =>
|
||||
WriteAsync(response, status, "application/json; charset=utf-8", json);
|
||||
|
||||
private static async Task WriteAsync(HttpListenerResponse response, int status, string contentType, string body)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(body);
|
||||
response.StatusCode = status;
|
||||
response.ContentType = contentType;
|
||||
response.ContentLength64 = bytes.Length;
|
||||
response.AddHeader("Cache-Control", "no-store");
|
||||
await response.OutputStream.WriteAsync(bytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
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)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user