using System.Collections.Concurrent;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Browser.Capture;
using Febe.Browser.Cdp;
using Febe.Browser.Download;
using Febe.Browser.Gestures;
using Febe.Browser.Hosting;
using Febe.Browser.RemoteView;
using Febe.Browser.WebView2;
using Febe.Browser.Recipes;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.SitoDiProva;
using Febe.Tests.Windows.Support;
namespace Febe.Tests.Windows;
///
/// S1 on a real Windows (docs/prove-dal-vivo.md, C3): the DevTools protocol of WebView2 through the real
/// and its allowlist, against the local test site (never Instagram), from thread-pool
/// threads as the engine sends it, with the window «Browser di Febe» out of view as it always is.
///
[TestClass]
public sealed class WebView2CdpTests
{
public TestContext TestContext { get; set; } = null!;
[TestInitialize]
public void RequireWebView2() => WebView2Runtime.Require();
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task S1TheProtocolWorksOnTheTestSiteWithTheWindowOutOfView()
{
var ct = TestContext.CancellationToken;
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
await using var bed = await BrowserBed.CreateAsync("s1");
await bed.StartAsync(ct);
var cdp = bed.Browser.Cdp;
Assert.IsInstanceOfType(cdp, "the real session of WebView2, with its allowlist");
var clock = new SystemClock();
var testSite = CollectionSite.TestSite(site.SiteHost, site.CdnHost);
await Task.Run(
async () =>
{
// Response bodies: Network.enable and the events are subscribed from this thread, the bodies come
// through Network.getResponseBody.
var bodies = new BodyCollector();
await using var tap = new ResponseTap(cdp, testSite.Hosts, clock);
tap.AddConsumer(bodies);
await tap.StartAsync(ct);
// Navigation.
var navigation = await cdp.NavigateAsync(site.Url("/profilo/luca.prova/"), ct);
Assert.IsTrue(navigation.Succeeded, navigation.ErrorText);
Assert.IsTrue(await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(20), ct), "the profile page loaded");
await WaitUntilAsync(() => bodies.Paths.Contains("/dati/profilo/luca.prova"), TimeSpan.FromSeconds(20), "il corpo JSON del profilo", ct);
var profile = bodies.Json("/dati/profilo/luca.prova");
Assert.AreEqual("luca.prova", profile.GetProperty("profilo").GetProperty("nome").GetString());
Assert.IsTrue(tap.Stats.JsonBodies >= 1);
// Read-only Runtime.evaluate: what the page sees, out of view (S2: visible, never «hidden»).
var seen = await cdp.EvaluateAsync(
"({ visibility: document.visibilityState, hidden: document.hidden, webdriver: navigator.webdriver, width: innerWidth, height: innerHeight, path: location.pathname, tiles: document.querySelectorAll('#griglia a').length })",
ct);
TestContext.WriteLine("La pagina vede: " + seen.GetRawText());
Assert.AreEqual("/profilo/luca.prova/", seen.GetProperty("path").GetString());
Assert.AreEqual("visible", seen.GetProperty("visibility").GetString(), "out of view the page stays visible (S2)");
Assert.IsFalse(seen.GetProperty("hidden").GetBoolean());
Assert.IsFalse(seen.GetProperty("webdriver").GetBoolean(), "an ordinary browser: navigator.webdriver is false");
Assert.AreEqual(1280, seen.GetProperty("width").GetInt32(), "the page has its fixed width");
Assert.IsGreaterThan(0, seen.GetProperty("tiles").GetInt32(), "the page drew the grid from the JSON");
// The session cookie of the site exists (only its name is looked at).
Assert.IsTrue(await SessionCookieProbe.HasSessionCookieAsync(cdp, testSite.SessionCookie, ct));
// Scrolling with Input.dispatchMouseEvent (mouseWheel), as the recipes do.
var height = (await cdp.EvaluateAsync("document.documentElement.scrollHeight", ct)).GetDouble();
Assert.IsGreaterThan(seen.GetProperty("height").GetInt32() + 400.0, height, "a page long enough to scroll");
Assert.AreEqual(0, (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble());
var gestures = new HumanGestures(cdp, clock, new SeededRandom(20261020));
await gestures.MoveToAsync(new PagePoint(640, 450), ct);
var requested = await gestures.ScrollBurstAsync(ct: ct);
await Task.Delay(800, ct);
var scrolled = (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble();
TestContext.WriteLine($"Scorrimento: chiesti {requested} pixel, pagina scesa di {scrolled}.");
Assert.IsGreaterThan(100.0, scrolled, "the wheel really scrolled the page out of view");
// Page.captureScreenshot: a JPEG of the page, out of view (the preview of Attività).
var jpeg = await PagePreview.CaptureAsync(cdp, 60, ct);
TestContext.WriteLine($"Fotogramma: {jpeg.Length} byte.");
Assert.IsGreaterThan(5_000, jpeg.Length, "a real frame, not an empty one");
Assert.AreEqual(0xFF, jpeg[0]);
Assert.AreEqual(0xD8, jpeg[1]);
// A file of the CDN through the browser (Network.loadNetworkResource, IO.read, IO.close).
var media = FirstCdnAddress(profile, site.CdnUrl) ?? throw new AssertFailedException("nessun indirizzo del CDN nel JSON del profilo");
var fetcher = new BrowserFileFetcher(cdp, testSite.Hosts);
using var file = new MemoryStream();
var fetched = await fetcher.FetchAsync(new Uri(media), file, null, ct);
Assert.AreEqual(FetchOutcome.Completed, fetched.Outcome, fetched.Error);
Assert.IsGreaterThan(1_000L, fetched.Bytes);
Assert.AreEqual(0xFF, file.GetBuffer()[0], "a JPEG of the CDN");
var refused = await fetcher.FetchAsync(new Uri(site.Url("/dati/inizio")), Stream.Null, null, ct);
Assert.AreEqual(FetchOutcome.HostNotAllowed, refused.Outcome, "only the CDN is downloaded");
// Forbidden commands are refused before WebView2, and change nothing.
await Assert.ThrowsExactlyAsync(() => cdp.SendAsync("Emulation.setTimezoneOverride", new JsonObject { ["timezoneId"] = "America/New_York" }, ct));
await Assert.ThrowsExactlyAsync(() => cdp.SendAsync("Network.setUserAgentOverride", new JsonObject { ["userAgent"] = "Febe" }, ct));
await Assert.ThrowsExactlyAsync(() => cdp.SendAsync("Page.addScriptToEvaluateOnNewDocument", new JsonObject { ["source"] = "1" }, ct));
await Assert.ThrowsExactlyAsync(() => cdp.SendAsync("Fetch.enable", null, ct));
await Assert.ThrowsExactlyAsync(() => cdp.SendAsync("Target.createTarget", new JsonObject { ["url"] = "about:blank" }, ct));
await Assert.ThrowsExactlyAsync(() => cdp.EvaluateAsync("window.scrollBy(0, 500)", ct));
Assert.AreEqual(scrolled, (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble(), "the refused script did not run");
var zone = (await cdp.EvaluateAsync("Intl.DateTimeFormat().resolvedOptions().timeZone", ct)).GetString();
Assert.AreNotEqual("America/New_York", zone);
// Back to the rest page.
await bed.Browser.RestAsync(ct);
await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(10), ct);
Assert.AreEqual(CdpPageExtensions.RestUrl, await cdp.GetMainFrameUrlAsync(ct));
},
ct);
// The log has actions and outcomes only: no signed address of the CDN, no error.
TestContext.WriteLine(bed.Lines.Text);
Assert.IsFalse(bed.Lines.Any("firma="), "no signed address in the log");
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
}
private static string? FirstCdnAddress(JsonElement element, string cdnUrl)
{
switch (element.ValueKind)
{
case JsonValueKind.Object:
foreach (var property in element.EnumerateObject())
{
if (property.Name == "indirizzo" && property.Value.ValueKind == JsonValueKind.String
&& property.Value.GetString() is { } address && address.StartsWith(cdnUrl, StringComparison.Ordinal) && address.Contains(".jpg", StringComparison.Ordinal))
{
return address;
}
if (FirstCdnAddress(property.Value, cdnUrl) is { } found)
{
return found;
}
}
return null;
case JsonValueKind.Array:
foreach (var item in element.EnumerateArray())
{
if (FirstCdnAddress(item, cdnUrl) is { } found)
{
return found;
}
}
return null;
default:
return null;
}
}
private static async Task WaitUntilAsync(Func condition, TimeSpan timeout, string what, CancellationToken ct)
{
var deadline = DateTime.UtcNow + timeout;
while (!condition())
{
if (DateTime.UtcNow > deadline)
{
Assert.Fail($"Tempo scaduto: {what}.");
}
await Task.Delay(50, ct);
}
}
/// The JSON bodies the page received, by path.
private sealed class BodyCollector : IResponseConsumer
{
private readonly ConcurrentDictionary _bodies = new(StringComparer.Ordinal);
public ICollection Paths => _bodies.Keys;
public JsonElement Json(string path) => JsonDocument.Parse(_bodies[path]).RootElement.Clone();
public ValueTask ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct)
{
_bodies.TryAdd(response.Path, body.RootElement.GetRawText());
return ValueTask.CompletedTask;
}
}
}