using System.Collections.Concurrent; using System.Text.Json; using Febe.Browser.Cdp; using Febe.Browser.Gestures; using Febe.Core.Abstractions; using Febe.Core.Collection; using Febe.Sonda; using Febe.Tests.Collection.Support; using Febe.Tests.Support; namespace Febe.Tests.Collection; /// /// The passive probe (spec §14.5) on the local test site: the test plays Alberto (it navigates and moves the mouse), /// the probe only listens. Then the whole M0 path: raw samples, cleaning, verification. /// [TestClass] [TestCategory(SyntheticSite.Category)] [DoNotParallelize] public sealed class ProbeIntegrationTests { private static SharedChromium? s_chromium; private static string? s_unavailable; public TestContext TestContext { get; set; } = null!; [ClassInitialize] public static async Task StartAsync(TestContext context) { s_unavailable = SharedChromium.UnavailableReason(); if (s_unavailable is null) { s_chromium = await SharedChromium.StartAsync(); } } [ClassCleanup] public static async Task StopAsync() { if (s_chromium is not null) { await s_chromium.DisposeAsync(); s_chromium = null; } } [TestMethod] [Timeout(180_000, CooperativeCancellation = true)] public async Task TheProbeRecordsResponsesAndTargetsWithoutGesturesAndItsSamplesCleanUp() { if (s_unavailable is not null) { Assert.Inconclusive(s_unavailable); } await using var site = await SyntheticSite.StartAsync(); using var temp = new TempFolder("sonda"); var raw = temp.Combine("grezzi"); var hosts = new HostClassifier([site.SiteHost], [site.CdnHost]); var recording = new RecordingCdp(s_chromium!.Cdp); await using (var probe = new ProbeRecorder(recording, hosts, raw, pollEvery: TimeSpan.FromMilliseconds(100))) { await probe.StartAsync(); // Alberto opens a profile and points at the «Reel» tab. var cdp = s_chromium.Cdp; await cdp.NavigateAsync(site.Url("/profilo/marta.prova/")); Assert.IsTrue(await cdp.WaitForLoadAsync(new SystemClock(), TimeSpan.FromSeconds(60)), "Il profilo non ha finito di caricare."); // By condition, not after fixed pauses (#46): the data answer recorded and the tab drawn. await TestWait.UntilAsync( async () => probe.Stats.Responses >= 1 && (await cdp.EvaluateAsync("[...document.querySelectorAll('a[role=tab]')].some((a) => a.textContent === 'Reel')")).ValueKind == JsonValueKind.True, "i dati del profilo registrati e la scheda «Reel» disegnata", ct: TestContext.CancellationToken); var tab = await cdp.EvaluateAsync("(() => { const r = [...document.querySelectorAll('a[role=tab]')].find((a) => a.textContent === 'Reel').getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; })()"); var alberto = new HumanGestures(cdp, new SystemClock(), new SeededRandom(5)); await alberto.MoveToAsync(new PagePoint(tab.GetProperty("x").GetDouble(), tab.GetProperty("y").GetDouble())); await TestWait.UntilAsync(() => HoverRecorded(raw), "il passaggio sulla scheda «Reel» registrato", ct: TestContext.CancellationToken); await probe.StopAsync(); Assert.IsTrue(probe.Stats.Responses >= 1, "The profile data was recorded."); } Assert.IsFalse(recording.Methods.Any(m => m.StartsWith("Input.", StringComparison.Ordinal)), "The probe never performs a gesture."); Assert.IsFalse(recording.Methods.Contains("Page.navigate"), "The probe never opens a page by itself."); Assert.IsTrue(File.Exists(Path.Combine(raw, "LEGGIMI.txt"))); var responses = Directory.EnumerateFiles(Path.Combine(raw, "risposte")).ToList(); Assert.IsTrue(responses.Count >= 1); using (var sample = JsonDocument.Parse(File.ReadAllText(responses[0]))) { var url = sample.RootElement.GetProperty("descrittore").GetProperty("indirizzo").GetString()!; Assert.IsFalse(url.Contains('?', StringComparison.Ordinal), "Never the query string."); Assert.AreEqual("sito", sample.RootElement.GetProperty("descrittore").GetProperty("host").GetString()); Assert.IsTrue(sample.RootElement.GetProperty("corpo").TryGetProperty("profilo", out _)); } var interactions = File.ReadAllLines(Path.Combine(raw, "interazioni.jsonl")); Assert.IsTrue(interactions.Any(IsReelHover), "The hovered tab is described with role and accessible name: " + string.Join(" | ", interactions)); Assert.IsTrue(File.ReadAllText(Path.Combine(raw, "navigazioni.jsonl")).Contains("/profilo/marta.prova/", StringComparison.Ordinal)); // M0 path: clean, then verify. var clean = temp.Combine("ripuliti"); new SampleSanitizer(hosts: hosts).SanitizeFolder(raw, clean); var report = SampleVerifier.Verify(raw, clean); Assert.IsTrue(report.Passed, string.Join("; ", report.Leaks.Select(l => $"{l.CleanFile} {l.Length} {l.Kind}"))); Assert.IsTrue(File.ReadLines(Path.Combine(clean, "interazioni.jsonl")).Any(l => l.Contains("\"role\":\"tab\"", StringComparison.Ordinal)), "Roles survive the cleaning."); } /// Forwards to the browser and records the command names (never parameters). private sealed class RecordingCdp(ICdpSession inner) : ICdpSession { private readonly ConcurrentQueue _methods = new(); public IReadOnlyList Methods => [.. _methods]; public Task SendAsync(string method, object? parameters = null, CancellationToken ct = default) { _methods.Enqueue(method); return inner.SendAsync(method, parameters, ct); } public IDisposable On(string eventName, Action handler) => inner.On(eventName, handler); } private static bool IsReelHover(string line) => line.Contains("\"sopra\"", StringComparison.Ordinal) && line.Contains("\"role\":\"tab\"", StringComparison.Ordinal) && line.Contains("Reel", StringComparison.Ordinal); /// True once the probe has written the hover on «Reel» (the file may be in the middle of a write). private static bool HoverRecorded(string raw) { try { var path = Path.Combine(raw, "interazioni.jsonl"); return File.Exists(path) && File.ReadAllLines(path).Any(IsReelHover); } catch (IOException) { return false; } } }