diff --git a/tests/E2E.Agent.Tests/PlaywrightRoutes.cs b/tests/E2E.Agent.Tests/PlaywrightRoutes.cs index 3cf9a77bf..183b3d980 100644 --- a/tests/E2E.Agent.Tests/PlaywrightRoutes.cs +++ b/tests/E2E.Agent.Tests/PlaywrightRoutes.cs @@ -2,8 +2,9 @@ // Modified by Dario Kondratiuk. // SPDX-License-Identifier: Apache-2.0 -using System.Globalization; +using System.Collections.Concurrent; using System.Net; +using System.Net.WebSockets; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; @@ -14,14 +15,18 @@ namespace E2E.Playground; /// The routes of the tests ported from Playwright, a port of upstream's apps/testbed/app/playwright/routes.mjs: /// its test assets (copied from microsoft/playwright tests/assets at v1.64.1, Apache-2.0, under /// Testbed/playwright/assets next to the test assembly) and the dynamic routes its test server sets per test. -/// The playground serves them for any path it has no page for. This port has /content, /never and the assets so far. +/// The playground serves them for any path it has no page for. 127.0.0.1 and localhost on the playground's +/// port are the two origins of the cross-origin cases, and the only ones trusted. /// -internal static class PlaywrightRoutes +internal static partial class PlaywrightRoutes { - private static readonly string Root = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "Testbed", "playwright", "assets")); + private const int MaxDelayMs = 30_000; + private const int MaxBytes = 16 << 20; - /// Cancelled when the process exits, which releases the requests a route holds. - private static readonly CancellationTokenSource Shutdown = CreateShutdown(); + // .NET-only: HttpListener has no close event for a request, so a held request is released after this long. + private static readonly TimeSpan HeldRequestLimit = TimeSpan.FromMinutes(2); + + private static readonly string Root = Path.Combine(AppContext.BaseDirectory, "Testbed", "playwright", "assets"); private static readonly Dictionary Types = new(StringComparer.Ordinal) { @@ -35,63 +40,198 @@ internal static class PlaywrightRoutes [".txt"] = "text/plain", }; + private static readonly ConcurrentDictionary Counts = new(StringComparer.Ordinal); + private static readonly ConcurrentDictionary> Logs = new(StringComparer.Ordinal); + /// Serves one request: a dynamic route, else an asset, else a 404. public static async Task HandleAsync(HttpListenerContext context) { - var response = context.Response; - var path = context.Request.Url!.AbsolutePath; - if (path == "/content") + if (context.Request.IsWebSocketRequest) { - var html = context.Request.QueryString["html"] ?? ""; - response.ContentType = "text/html; charset=utf-8"; - await WriteAsync(response, FromBase64Url(html)).ConfigureAwait(false); + await UpgradeAsync(context).ConfigureAwait(false); return; } - if (path == "/never") + var request = context.Request; + var response = context.Response; + var port = request.LocalEndPoint.Port; + var path = request.Url!.AbsolutePath; + var query = ParseQuery(request.Url.Query); + switch (path) { - // Holds the response and never answers, as upstream's /never. It ends when the run ends (the testbed never stops before that) - // or after upstream's longest delay, so a held request cannot outlive the run. - try - { - await Task.Delay(TimeSpan.FromSeconds(30), Shutdown.Token).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - // The run is ending. - } + case "/content": + response.ContentType = "text/html; charset=utf-8"; + await WriteAsync(response, FromBase64Url(query.GetValueOrDefault("html") ?? "")).ConfigureAwait(false); + return; + case "/echo": + { + var received = await BodyAsync(request).ConfigureAwait(false); + response.ContentType = "application/json"; + response.AddHeader("access-control-allow-origin", "*"); + await WriteAsync(response, Echo(request, received)).ConfigureAwait(false); + return; + } - response.Abort(); - return; - } + case "/status": + response.StatusCode = Number(query.GetValueOrDefault("code"), 200); + response.ContentType = "text/plain"; + await WriteAsync(response, Encoding.UTF8.GetBytes(query.GetValueOrDefault("body") ?? "")).ConfigureAwait(false); + return; + case "/slow": + await Task.Delay(Bounded(query.GetValueOrDefault("ms"), 1000, MaxDelayMs)).ConfigureAwait(false); + response.ContentType = query.GetValueOrDefault("type") ?? "text/plain"; + response.AddHeader("access-control-allow-origin", "*"); + await WriteAsync(response, Encoding.UTF8.GetBytes(query.GetValueOrDefault("body") ?? "slow")).ConfigureAwait(false); + return; + case "/never": + await HoldAsync().ConfigureAwait(false); + response.Abort(); + return; + case "/redirect": + response.StatusCode = 302; + response.RedirectLocation = SameServer(query.GetValueOrDefault("to"), port); + return; + case "/download": + response.ContentType = "application/octet-stream"; + response.AddHeader("content-disposition", $"attachment{(query.TryGetValue("name", out var name) ? $"; filename={name}" : "")}"); + await WriteAsync(response, Encoding.UTF8.GetBytes(query.GetValueOrDefault("body") ?? "Hello world")).ConfigureAwait(false); + return; + case "/set-cookie": + response.AddHeader("set-cookie", query.GetValueOrDefault("cookie") ?? "name=value"); + response.ContentType = "text/html"; + await WriteAsync(response, Encoding.UTF8.GetBytes("cookie")).ConfigureAwait(false); + return; + case "/respond": + response.StatusCode = Number(query.GetValueOrDefault("status"), 200); + AddHeaders(response, query.GetValueOrDefault("headers") ?? "{}"); + await WriteAsync(response, Encoding.UTF8.GetBytes(query.GetValueOrDefault("body") ?? "")).ConfigureAwait(false); + return; + case "/cors-echo": + { + response.AddHeader("access-control-allow-origin", TrustedOrigin(request, port)); + response.AddHeader("access-control-allow-credentials", "true"); + response.AddHeader("access-control-allow-methods", "POST, GET, OPTIONS, DELETE"); + response.AddHeader("access-control-allow-headers", request.Headers["access-control-request-headers"] ?? "*"); + if (request.HttpMethod == "OPTIONS" && query.ContainsKey("preflight")) + { + response.StatusCode = 204; + return; + } - if (path == "/respond") - { - var query = context.Request.QueryString; - response.StatusCode = int.TryParse(query["status"], CultureInfo.InvariantCulture, out var status) ? status : 200; - if (query["headers"] is { } headers) - { - foreach (var (name, value) in JsonSerializer.Deserialize>(headers)!) + var received = await BodyAsync(request).ConfigureAwait(false); + response.ContentType = "text/plain"; + await WriteAsync(response, Echo(request, received)).ConfigureAwait(false); + return; + } + + case "/bounce": { - if (name.Equals("content-type", StringComparison.OrdinalIgnoreCase)) + var options = request.HttpMethod == "OPTIONS"; + if (!options) { - response.ContentType = value; + response.RedirectLocation = SameServer(query.GetValueOrDefault("to"), port); } - else + + response.AddHeader("access-control-allow-origin", TrustedOrigin(request, port)); + response.AddHeader("access-control-allow-credentials", "true"); + response.AddHeader("access-control-allow-headers", request.Headers["access-control-request-headers"] ?? "*"); + if (query.TryGetValue("cookie", out var cookie)) { - response.AddHeader(name, value); + response.AddHeader("set-cookie", cookie); } + + response.StatusCode = options ? 204 : Number(query.GetValueOrDefault("status"), 302); + return; } - } - await WriteAsync(response, Encoding.UTF8.GetBytes(query["body"] ?? "")).ConfigureAwait(false); - return; - } + case "/count": + { + var count = Counts.AddOrUpdate(query.GetValueOrDefault("key") ?? "", 1, (_, current) => current + 1); + response.ContentType = "text/plain"; + await WriteAsync(response, Encoding.UTF8.GetBytes((count * 11).ToString(System.Globalization.CultureInfo.InvariantCulture))).ConfigureAwait(false); + return; + } - if (path == "/upload") - { - await UploadAsync(context).ConfigureAwait(false); - return; + case "/options": + { + var log = Logs.GetOrAdd(query.GetValueOrDefault("key") ?? "", _ => []); + lock (log) + { + log.Add($"{request.HttpMethod}:{path}"); + } + + var options = request.HttpMethod == "OPTIONS"; + response.AddHeader("access-control-allow-origin", "*"); + if (options) + { + response.AddHeader("access-control-allow-methods", "POST, GET, OPTIONS, DELETE"); + response.AddHeader("access-control-allow-headers", "*"); + response.AddHeader("cache-control", "no-cache"); + } + + await WriteAsync(response, Encoding.UTF8.GetBytes(options ? "Hello" : "World")).ConfigureAwait(false); + return; + } + + case "/options-log": + { + response.ContentType = "application/json"; + var log = Logs.GetValueOrDefault(query.GetValueOrDefault("key") ?? "") ?? []; + string[] entries; + lock (log) + { + entries = [.. log]; + } + + await WriteAsync(response, JsonSerializer.SerializeToUtf8Bytes(entries)).ConfigureAwait(false); + return; + } + + case "/upload": + { + var received = await BodyAsync(request).ConfigureAwait(false); + response.ContentType = "text/plain"; + response.AddHeader("access-control-allow-origin", "*"); + await WriteAsync(response, JsonSerializer.SerializeToUtf8Bytes(Files(received, request.ContentType ?? ""))).ConfigureAwait(false); + return; + } + + case "/binary": + { + var data = new byte[Bounded(query.GetValueOrDefault("bytes"), 1 << 20, MaxBytes)]; + for (var i = 0; i < data.Length; i++) + { + data[i] = (byte)(unchecked((uint)((i + 1) * 2654435761L)) >> 24); + } + + response.ContentType = "application/zip"; + await WriteAsync(response, data).ConfigureAwait(false); + return; + } + + case "/download-stall": + { + response.ContentType = "application/octet-stream"; + response.AddHeader("content-disposition", "attachment; filename=file.txt"); + response.SendChunked = true; + await response.OutputStream.WriteAsync(Encoding.ASCII.GetBytes(new string('a', 4096) + "foo")).ConfigureAwait(false); + await response.OutputStream.FlushAsync().ConfigureAwait(false); + await HoldAsync().ConfigureAwait(false); + response.Abort(); + return; + } + + case "/sse": + { + response.ContentType = "text/event-stream"; + response.AddHeader("cache-control", "no-cache"); + response.SendChunked = true; + await response.OutputStream.WriteAsync(Encoding.ASCII.GetBytes("data: hello\n\n")).ConfigureAwait(false); + await response.OutputStream.FlushAsync().ConfigureAwait(false); + await HoldAsync().ConfigureAwait(false); + response.Abort(); + return; + } } var file = Path.GetFullPath(Path.Combine(Root, Uri.UnescapeDataString(path).TrimStart('/'))); @@ -108,62 +248,186 @@ public static async Task HandleAsync(HttpListenerContext context) await WriteAsync(response, await File.ReadAllBytesAsync(file).ConfigureAwait(false)).ConfigureAwait(false); } - private static CancellationTokenSource CreateShutdown() + /// + /// /ws accepts the handshake and holds the socket open, as Playwright's server does, so an open WebSocket is in the + /// page during network-idle tests. Any other path is refused. + /// + private static async Task UpgradeAsync(HttpListenerContext context) { - var source = new CancellationTokenSource(); - AppDomain.CurrentDomain.ProcessExit += (_, _) => source.Cancel(); - return source; + if (context.Request.Url!.AbsolutePath != "/ws") + { + context.Response.Abort(); + return; + } + + var socket = (await context.AcceptWebSocketAsync(null).ConfigureAwait(false)).WebSocket; + using var limit = new CancellationTokenSource(HeldRequestLimit); + var buffer = new byte[256]; + try + { + while (socket.State == WebSocketState.Open) + { + var received = await socket.ReceiveAsync(buffer, limit.Token).ConfigureAwait(false); + if (received.MessageType == WebSocketMessageType.Close) + { + break; + } + } + } + catch (Exception ex) when (ex is WebSocketException or OperationCanceledException) + { + } + finally + { + socket.Abort(); + socket.Dispose(); + } } - /// Answers a multipart form with the files it carried as JSON, as upstream's /upload: name, filename, mimetype, size, and the bytes (base64) of a file up to 64 KB. - private static async Task UploadAsync(HttpListenerContext context) + /// A redirect target on this server (a path, or either origin), else the empty page. + private static string SameServer(string? target, int port) { - using var received = new MemoryStream(); - await context.Request.InputStream.CopyToAsync(received).ConfigureAwait(false); - var data = received.GetBuffer().AsMemory(0, (int)received.Length); - var type = context.Request.ContentType ?? ""; - var marker = type.IndexOf("boundary=", StringComparison.Ordinal); - var boundary = Encoding.UTF8.GetBytes("--" + (marker < 0 ? "" : type[(marker + "boundary=".Length)..])); - var files = new List>(); - var start = data.Span.IndexOf(boundary); - while (start >= 0) + if (target is null) + { + return "/empty.html"; + } + + var origin = new Uri($"http://127.0.0.1:{port}"); + if (!Uri.TryCreate(origin, target, out var resolved) || resolved.Scheme != "http" || resolved.Port != port || resolved.Host is not ("127.0.0.1" or "localhost")) { - var afterStart = start + boundary.Length; - var relative = data.Span[afterStart..].IndexOf(boundary); - if (relative < 0) + return "/empty.html"; + } + + return target.StartsWith('/') ? resolved.PathAndQuery + resolved.Fragment : resolved.AbsoluteUri; + } + + /// + /// The request's origin when it is one of the server's own, the only ones granted credentials, or null, + /// the origin a cross-origin redirect leaves. + /// + private static string TrustedOrigin(HttpListenerRequest request, int port) + { + var origin = request.Headers["origin"]; + if (origin == "null") + { + return "null"; + } + + return origin is not null && (origin == $"http://127.0.0.1:{port}" || origin == $"http://localhost:{port}") ? origin : $"http://127.0.0.1:{port}"; + } + + /// The request as JSON: { method, headers, body, url }. + private static byte[] Echo(HttpListenerRequest request, byte[] body) + { + var headers = new Dictionary(StringComparer.Ordinal); + foreach (var name in request.Headers.AllKeys) + { + if (name is not null) { - break; + headers[name.ToLowerInvariant()] = request.Headers[name]!; + } + } + + return JsonSerializer.SerializeToUtf8Bytes(new { method = request.HttpMethod, headers, body = Encoding.UTF8.GetString(body), url = request.RawUrl }); + } + + /// The headers of a JSON object, a header with an array value sent once for each item. + private static void AddHeaders(HttpListenerResponse response, string json) + { + using var headers = JsonDocument.Parse(json); + foreach (var header in headers.RootElement.EnumerateObject()) + { + JsonElement[] values = header.Value.ValueKind == JsonValueKind.Array ? [.. header.Value.EnumerateArray()] : [header.Value]; + foreach (var value in values) + { + var text = value.ToString(); + switch (header.Name.ToLowerInvariant()) + { + case "content-type": + response.ContentType = text; + break; + case "location": + response.RedirectLocation = text; + break; + default: + response.AppendHeader(header.Name, text); + break; + } } + } + } - var next = afterStart + relative; - var part = data[(afterStart + 2)..(next - 2)]; - var split = part.Span.IndexOf("\r\n\r\n"u8); - if (split < 0) + /// The parts of a multipart body, as /upload answers with them. + private static List Files(byte[] received, string type) + { + var files = new List(); + var at = type.IndexOf("boundary=", StringComparison.Ordinal); + var boundary = Encoding.UTF8.GetBytes("--" + (at >= 0 ? type[(at + "boundary=".Length)..] : "")); + for (var start = IndexOf(received, boundary, 0); start != -1;) + { + var next = IndexOf(received, boundary, start + boundary.Length); + if (next == -1) { - start = next; - continue; + break; } - var head = Encoding.UTF8.GetString(part.Span[..split]); - var body = part[(split + 4)..]; - files.Add(new Dictionary + var part = received.AsSpan(start + boundary.Length + 2, next - 2 - (start + boundary.Length + 2)); + var split = part.IndexOf("\r\n\r\n"u8); + var head = Encoding.UTF8.GetString(part[..split]); + var data = part[(split + 4)..]; + files.Add(new { - ["name"] = Capture(head, "name=\"([^\"]*)\""), - ["filename"] = Capture(head, "filename=\"([^\"]*)\""), - ["mimetype"] = Capture(head, "content-type: ([^\r\n]+)"), - ["size"] = body.Length, - ["base64"] = body.Length <= 65536 ? Convert.ToBase64String(body.Span) : null, + name = PartName().Match(head) is { Success: true } named ? named.Groups[1].Value : null, + filename = PartFilename().Match(head) is { Success: true } filename ? filename.Groups[1].Value : null, + mimetype = PartMimetype().Match(head) is { Success: true } mimetype ? mimetype.Groups[1].Value.Trim() : null, + size = data.Length, + base64 = data.Length <= 65536 ? Convert.ToBase64String(data) : null, }); start = next; } - context.Response.ContentType = "text/plain"; - context.Response.AddHeader("Access-Control-Allow-Origin", "*"); - await WriteAsync(context.Response, JsonSerializer.SerializeToUtf8Bytes(files)).ConfigureAwait(false); + return files; + } + + private static int IndexOf(byte[] haystack, byte[] needle, int from) => + from > haystack.Length ? -1 : haystack.AsSpan(from).IndexOf(needle) is var at and >= 0 ? from + at : -1; + + [GeneratedRegex("name=\"([^\"]*)\"")] + private static partial Regex PartName(); + + [GeneratedRegex("filename=\"([^\"]*)\"")] + private static partial Regex PartFilename(); + + [GeneratedRegex("content-type: (.+)", RegexOptions.IgnoreCase)] + private static partial Regex PartMimetype(); + + /// as a number in [0, ], when absent. + private static int Bounded(string? value, int fallback, int max) => + Math.Min(Math.Max(Number(value, fallback), 0), max); + + private static int Number(string? value, int fallback) => + value is null ? fallback : int.TryParse(value, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var number) ? number : 0; + + private static Dictionary ParseQuery(string query) + { + var values = new Dictionary(StringComparer.Ordinal); + foreach (var pair in query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var parts = pair.Split('=', 2); + values.TryAdd(Uri.UnescapeDataString(parts[0].Replace('+', ' ')), parts.Length > 1 ? Uri.UnescapeDataString(parts[1].Replace('+', ' ')) : ""); + } + + return values; + } + + private static async Task BodyAsync(HttpListenerRequest request) + { + using var body = new MemoryStream(); + await request.InputStream.CopyToAsync(body).ConfigureAwait(false); + return body.ToArray(); } - private static string? Capture(string text, string pattern) => - Regex.Match(text, pattern, RegexOptions.IgnoreCase) is { Success: true } match ? match.Groups[1].Value : null; + private static Task HoldAsync() => Task.Delay(HeldRequestLimit); private static byte[] FromBase64Url(string value) { diff --git a/tests/E2E.NUnit.Tests/Helpers/Helpers.cs b/tests/E2E.NUnit.Tests/Helpers/Helpers.cs index 1112f1d7a..eb30bd386 100644 --- a/tests/E2E.NUnit.Tests/Helpers/Helpers.cs +++ b/tests/E2E.NUnit.Tests/Helpers/Helpers.cs @@ -37,10 +37,7 @@ public static async Task After(int milliseconds, Func next) } /// Another origin on the same app, Playwright's server.CROSS_PROCESS_PREFIX. - public static string CROSS => PREFIX.Replace("127.0.0.1", "localhost", StringComparison.Ordinal); - - /// The absolute path of one of Playwright's test assets. - public static string Asset(string name) => Path.Combine(AppContext.BaseDirectory, "Testbed", "playwright", "assets", name); + public static string CROSS => E2E.Playground.Testbed.Url.Replace("127.0.0.1", "localhost", StringComparison.Ordinal); /// A path that serves as a page, for Playwright's page.setContent(html). public static string Content(string html) => @@ -58,6 +55,62 @@ public static void Equal(T expected, T actual) } } + /// A check that contains , for a body run by . It throws, as does. + public static void Contain(string expected, string actual) + { + if (!actual.Contains(expected, StringComparison.Ordinal)) + { + throw new InvalidOperationException($"Expected the text to contain {expected}, but was {actual}."); + } + } + + /// The absolute path of one of Playwright's test assets. + public static string Asset(string name) => Path.Combine(AppContext.BaseDirectory, "Testbed", "playwright", "assets", name); + + /// A promise with its resolver, for a route handler the test holds open. .NET-only, a test helper. + public static TaskCompletionSource Deferred() => new(TaskCreationOptions.RunContinuationsAsynchronously); + + /// A with no value. + public static TaskCompletionSource Deferred() => new(TaskCreationOptions.RunContinuationsAsynchronously); + + /// The request headers with added or replaced, for { ...route.request.headers, name: value }. .NET-only, a test helper. + public static Dictionary WithHeaders(IReadOnlyDictionary headers, params (string Name, string Value)[] set) + { + var copy = new Dictionary(headers, StringComparer.Ordinal); + foreach (var (name, value) in set) + { + copy[name] = value; + } + + return copy; + } + + /// The request the server received, which /cors-echo and /echo answer with. .NET-only, a test helper. + public sealed record Served(string Method, Dictionary Headers, string Body, string Url) + { + /// The header named , or when the request had none. + public string? Header(string name) => Headers.GetValueOrDefault(name); + + public static Served Parse(string json) => + System.Text.Json.JsonSerializer.Deserialize(json, new System.Text.Json.JsonSerializerOptions(System.Text.Json.JsonSerializerDefaults.Web))!; + } + + /// + /// Playwright's Promise.all([wait, action]) for a wait whose result the test reads: waits for both and returns the result of . + /// .NET-only, a test helper. + /// + public static async Task AllAsync(Task wait, Task action) + { + var first = await Task.WhenAny(wait, action).ConfigureAwait(false); + if (first.IsFaulted) + { + await first.ConfigureAwait(false); + } + + await Task.WhenAll(wait, action).ConfigureAwait(false); + return wait.Result; + } + /// /// Runs the body of a test upstream marks { fail: 'reason' }, a known difference from Playwright: the test passes while /// still fails with a message that contains , and fails once it passes, so the marker is removed. The port has no fail test option diff --git a/tests/E2E.NUnit.Tests/RequestFallback/PageRequestFallbackTests.cs b/tests/E2E.NUnit.Tests/RequestFallback/PageRequestFallbackTests.cs new file mode 100644 index 000000000..cf2b61f8a --- /dev/null +++ b/tests/E2E.NUnit.Tests/RequestFallback/PageRequestFallbackTests.cs @@ -0,0 +1,112 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using E2E.Engine; +using static E2E.NUnit.Tests.Helpers; + +namespace E2E.NUnit.Tests.RequestFallback; + +/// +/// test.describe('page request fallback') of upstream's apps/testbed/tests/request-fallback.e2e.ts (Playwright's +/// page-request-fallback.spec.ts). Not ported, as upstream: should chain once (no times), should amend HTTP headers, +/// should delete header with undefined value, should amend method, should override request url, and the post data tests +/// (no options on fallback). +/// +public sealed class PageRequestFallbackTests : PlaywrightTest +{ + private static string EmptyPage => $"{PREFIX}/empty.html"; + + [Test] + public async Task Should_work() + { + await Browser.RouteAsync("**/*", route => route.FallbackAsync()); + await Browser.GotoAsync(EmptyPage); + } + + [Test] + public async Task Should_fall_back() + { + var intercepted = new List(); + foreach (var index in new[] { 1, 2, 3 }) + { + await Browser.RouteAsync("**/empty.html", async route => + { + intercepted.Add(index); + await route.FallbackAsync(); + }); + } + + await Browser.GotoAsync(EmptyPage); + Assert.That(intercepted, Is.EqualTo(new[] { 3, 2, 1 })); + } + + [Test] + public async Task Should_fall_back_async() + { + var intercepted = new List(); + foreach (var index in new[] { 1, 2, 3 }) + { + await Browser.RouteAsync("**/empty.html", async route => + { + intercepted.Add(index); + await Task.Delay(100); + await route.FallbackAsync(); + }); + } + + await Browser.GotoAsync(EmptyPage); + Assert.That(intercepted, Is.EqualTo(new[] { 3, 2, 1 })); + } + + [Test] + public async Task Should_not_chain_fulfill() + { + var failed = false; + await Browser.RouteAsync("**/empty.html", async route => + { + failed = true; + await route.ContinueAsync(); + }); + await Browser.RouteAsync("**/empty.html", route => route.FulfillAsync(new RouteFulfillResponse { Status = 200, Body = "fulfilled" })); + await Browser.RouteAsync("**/empty.html", route => route.FallbackAsync()); + var response = await AllAsync(Browser.WaitForResponseAsync("**/empty.html"), Browser.GotoAsync(EmptyPage)); + Assert.That(await response.TextAsync(), Is.EqualTo("fulfilled")); + Assert.That(failed, Is.False); + } + + [Test] + public async Task Should_not_chain_abort() + { + var failed = false; + await Browser.RouteAsync("**/empty.html", async route => + { + failed = true; + await route.ContinueAsync(); + }); + await Browser.RouteAsync("**/empty.html", route => route.AbortAsync()); + await Browser.RouteAsync("**/empty.html", route => route.FallbackAsync()); + var e = await Assert.CatchAsync(() => Browser.GotoAsync(EmptyPage)); + Assert.That(e, Is.Not.Null); + Assert.That(failed, Is.False); + } + + [Test] + public async Task Should_fall_back_after_exception() + { + await Browser.RouteAsync("**/empty.html", route => route.ContinueAsync()); + await Browser.RouteAsync("**/empty.html", async route => + { + try + { + // Upstream passes an unknown option; here a body and a json together, which fulfill refuses before it decides. + await route.FulfillAsync(new RouteFulfillResponse { Body = "", Json = new { } }); + } + catch + { + await route.FallbackAsync(); + } + }); + await Browser.GotoAsync(EmptyPage); + } +} diff --git a/tests/E2E.NUnit.Tests/RequestFulfill/PageRequestFulfillTests.cs b/tests/E2E.NUnit.Tests/RequestFulfill/PageRequestFulfillTests.cs new file mode 100644 index 000000000..e4279e6d9 --- /dev/null +++ b/tests/E2E.NUnit.Tests/RequestFulfill/PageRequestFulfillTests.cs @@ -0,0 +1,322 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using System.Text.Json; +using E2E.Engine; +using static E2E.NUnit.Tests.Helpers; + +namespace E2E.NUnit.Tests.RequestFulfill; + +/// +/// test.describe('page request fulfill') of upstream's apps/testbed/tests/request-fulfill.e2e.ts (Playwright's +/// page-request-fulfill.spec.ts). Not ported, as upstream: should work with buffer as body (a string body only), should allow +/// mocking binary responses, should fulfill with global fetch result, should fulfill with fetch result, should fulfill with fetch +/// result and overrides (no fulfill({ response })), headerValue should return set-cookie from intercepted response (Playwright +/// expects it to fail on Chromium), should fulfill with har response (HAR), should fulfill with gzip and readback. +/// +public sealed class PageRequestFulfillTests : PlaywrightTest +{ + private const string SkipMultipleSetCookie = + "`route.fulfill` refuses a header value with a newline, so the request is aborted and the navigation fails as an engine failure, which `fail` does not cover"; + + private static string EmptyPage => $"{PREFIX}/empty.html"; + + /// Polls the page until is truthy, Playwright's page.waitForFunction. + private static string WaitForFunction(string expression) => + $"() => new Promise((resolve) => {{ const check = () => ({expression}) ? resolve(true) : setTimeout(check, 20); check(); }})"; + + [Test] + public async Task Should_work() + { + await Browser.RouteAsync("**/*", route => route.FulfillAsync(new RouteFulfillResponse + { + Status = 201, + Headers = new Dictionary { ["foo"] = "bar" }, + ContentType = "text/html", + Body = "Yo, page!", + })); + var response = await AllAsync(Browser.WaitForResponseAsync("**/empty.html"), Browser.GotoAsync(EmptyPage)); + Assert.That(response.Status, Is.EqualTo(201)); + Assert.That(response.Headers["foo"], Is.EqualTo("bar")); + Assert.That(await Browser.EvaluateAsync("() => document.body.textContent"), Is.EqualTo("Yo, page!")); + } + + [Test] + public async Task Should_work_with_status_code_422() + { + await Browser.RouteAsync("**/*", route => route.FulfillAsync(new RouteFulfillResponse { Status = 422, Body = "Yo, page!" })); + var response = await AllAsync(Browser.WaitForResponseAsync("**/empty.html"), Browser.GotoAsync(EmptyPage)); + Assert.That(response.Status, Is.EqualTo(422)); + Assert.That(await Browser.EvaluateAsync("() => document.body.textContent"), Is.EqualTo("Yo, page!")); + } + + [Test] + public async Task Should_fulfill_with_unuassigned_status_codes() + { + var fulfilled = Deferred(); + await Browser.RouteAsync("**/data.json", async route => + { + try + { + await route.FulfillAsync(new RouteFulfillResponse { Status = 430, Body = "Yo, page!" }); + fulfilled.TrySetResult(null); + } + catch (Exception caught) + { + fulfilled.TrySetResult(caught); + } + }); + await Browser.GotoAsync(EmptyPage); + var response = await Browser.EvaluateAsync( + "async (url) => { const { status, statusText } = await fetch(url); return { status, statusText }; }", + $"{PREFIX}/data.json"); + var error = await fulfilled.Task; + Assert.That(error, Is.Null); + Assert.That(response.GetProperty("status").GetInt32(), Is.EqualTo(430)); + Assert.That(response.GetProperty("statusText").GetString(), Is.EqualTo("Unknown")); + } + + [Test] + public async Task Should_not_throw_if_request_was_cancelled_by_the_page() + { + var routed = Deferred(); + var release = Deferred(); + await Browser.RouteAsync("**/data.json", async route => + { + routed.TrySetResult(); + await release.Task; + await route.FulfillAsync(new RouteFulfillResponse { Status = 200 }); + }); + await Browser.GotoAsync(EmptyPage); + await Browser.EvaluateAsync(""" + (url) => { + globalThis.controller = new AbortController(); + globalThis.failure = fetch(url, { signal: globalThis.controller.signal }).then(() => 'loaded', (error) => error.name); + } + """, $"{PREFIX}/data.json"); + await routed.Task; + Assert.That(await Browser.EvaluateAsync("() => { globalThis.controller.abort(); return globalThis.failure; }"), Is.EqualTo("AbortError")); + release.TrySetResult(); + await Browser.EvaluateAsync("() => new Promise((resolve) => setTimeout(resolve, 100))"); + } + + [Test] + public async Task Should_allow_mocking_svg_with_charset() + { + await Browser.GotoAsync(EmptyPage); + await Browser.RouteAsync("**/*", route => route.FulfillAsync(new RouteFulfillResponse + { + ContentType = "image/svg+xml ; charset=utf-8", + Body = """""", + })); + var size = await Browser.EvaluateAsync(""" + (PREFIX) => { + const img = document.createElement('img'); + img.src = PREFIX + '/does-not-exist.svg'; + document.body.appendChild(img); + return new Promise((resolve, reject) => { img.onload = () => resolve([img.naturalWidth, img.naturalHeight]); img.onerror = reject; }); + } + """, PREFIX); + Assert.That(size, Is.EqualTo(new[] { 50, 50 })); + } + + [Test] + public async Task Should_work_with_file_path() + { + await Browser.GotoAsync(EmptyPage); + await Browser.RouteAsync("**/*", route => route.FulfillAsync(new RouteFulfillResponse { ContentType = "shouldBeIgnored", Path = Asset("pptr.png") })); + var size = await Browser.EvaluateAsync(""" + (PREFIX) => { + const img = document.createElement('img'); + img.src = PREFIX + '/does-not-exist.png'; + document.body.appendChild(img); + return new Promise((resolve) => { img.onload = () => resolve([img.naturalWidth, img.naturalHeight]); }); + } + """, PREFIX); + Assert.That(size, Is.EqualTo(new[] { 69, 100 })); + } + + [Test] + public async Task Should_stringify_intercepted_request_response_headers() + { + await Browser.RouteAsync("**/*", route => route.FulfillAsync(new RouteFulfillResponse + { + Status = 200, + Headers = new Dictionary { ["foo"] = "true" }, + Body = "Yo, page!", + })); + var response = await AllAsync(Browser.WaitForResponseAsync("**/empty.html"), Browser.GotoAsync(EmptyPage)); + Assert.That(response.Status, Is.EqualTo(200)); + Assert.That(response.Headers["foo"], Is.EqualTo("true")); + Assert.That(await Browser.EvaluateAsync("() => document.body.textContent"), Is.EqualTo("Yo, page!")); + } + + [Test] + public async Task Should_not_modify_the_headers_sent_to_the_server() + { + await Browser.GotoAsync("/empty.html"); + await Browser.RouteAsync($"{PREFIX}/unused", route => route.ContinueAsync()); + const string fetchServed = "async (url) => { const data = await fetch(url); return data.text(); }"; + var before = Served.Parse((await Browser.EvaluateAsync(fetchServed, $"{CROSS}/cors-echo"))!); + Assert.That(before.Method, Is.EqualTo("GET")); + + await Browser.RouteAsync($"{CROSS}/cors-echo", route => route.ContinueAsync(new RouteContinueOverrides { Headers = WithHeaders(route.Request.Headers) })); + var after = Served.Parse((await Browser.EvaluateAsync(fetchServed, $"{CROSS}/cors-echo"))!); + Assert.That(after.Method, Is.EqualTo("GET")); + Assert.That(after.Headers, Is.EqualTo(before.Headers)); + } + + [Test] + public async Task Should_include_the_origin_header() + { + await Browser.GotoAsync("/empty.html"); + string? origin = null; + await Browser.RouteAsync($"{CROSS}/something", async route => + { + origin = route.Request.Headers.GetValueOrDefault("origin"); + await route.FulfillAsync(new RouteFulfillResponse + { + Headers = new Dictionary { ["Access-Control-Allow-Origin"] = "*" }, + ContentType = "text/plain", + Body = "done", + }); + }); + var text = await Browser.EvaluateAsync("async (url) => { const data = await fetch(url); return data.text(); }", $"{CROSS}/something"); + Assert.That(text, Is.EqualTo("done")); + Assert.That(origin, Is.EqualTo(PREFIX)); + } + + [Test] + public async Task Should_fetch_original_request_and_fulfill() + { + await Browser.RouteAsync("**/*", async route => + { + var response = await route.FetchAsync(); + await route.FulfillAsync(new RouteFulfillResponse + { + Status = response.Status, + Headers = new Dictionary(response.Headers), + Body = await response.TextAsync(), + }); + }); + var response = await AllAsync(Browser.WaitForResponseAsync("**/title.html"), Browser.GotoAsync("/title.html")); + Assert.That(response.Status, Is.EqualTo(200)); + Assert.That(await Browser.TitleAsync(), Is.EqualTo("Woof-Woof")); + } + + [Test] + [Ignore(SkipMultipleSetCookie)] + public async Task Should_fulfill_with_multiple_set_cookie() + { + string[] cookies = ["a=b", "c=d"]; + await Browser.RouteAsync("**/multiple-set-cookie.html", route => route.FulfillAsync(new RouteFulfillResponse + { + Status = 200, + Headers = new Dictionary + { + ["X-Header-1"] = "v1", + ["Set-Cookie"] = string.Join('\n', cookies), + ["X-Header-2"] = "v2", + }, + Body = "", + })); + var response = await AllAsync(Browser.WaitForResponseAsync("**/multiple-set-cookie.html"), Browser.GotoAsync("/multiple-set-cookie.html")); + var cookie = await Browser.EvaluateAsync("() => document.cookie"); + Assert.That(cookie!.Split(';').Select(s => s.Trim()).Order(), Is.EqualTo(cookies)); + Assert.That(response.Headers["x-header-1"], Is.EqualTo("v1")); + Assert.That(response.Headers["x-header-2"], Is.EqualTo("v2")); + } + + [Test] + [Ignore(SkipMultipleSetCookie)] + public async Task Should_fulfill_with_fetch_response_that_has_multiple_set_cookie() + { + await Browser.RouteAsync("**/respond?*", async route => + { + var response = await route.FetchAsync(); + await route.FulfillAsync(new RouteFulfillResponse + { + Status = response.Status, + Headers = new Dictionary(response.Headers), + Body = await response.TextAsync(), + }); + }); + var headers = JsonSerializer.Serialize(new Dictionary { ["set-cookie"] = new[] { "a=b", "c=d" }, ["content-type"] = "text/html" }); + await Browser.GotoAsync($"/respond?headers={Uri.EscapeDataString(headers)}"); + var cookie = await Browser.EvaluateAsync("() => document.cookie"); + Assert.That(cookie!.Split(';').Select(s => s.Trim()).Order(), Is.EqualTo(new[] { "a=b", "c=d" })); + } + + [Test] + public async Task Should_fulfill_preload_link_requests() + { + var intercepted = false; + await Browser.RouteAsync("**/one-style.css", async route => + { + intercepted = true; + await route.FulfillAsync(new RouteFulfillResponse + { + Status = 200, + Headers = new Dictionary + { + ["content-type"] = "text/css; charset=utf-8", + ["cache-control"] = "no-cache, no-store", + ["custom"] = "value", + }, + Body = "body { background-color: green; }", + }); + }); + var response = await AllAsync(Browser.WaitForResponseAsync("**/one-style.css"), Browser.GotoAsync("/preload.html")); + Assert.That(response.Headers["custom"], Is.EqualTo("value")); + await Browser.EvaluateAsync(WaitForFunction("window.preloadedStyles")); + Assert.That(intercepted, Is.True); + // preload.html sets the flag before switching the link to a stylesheet, which applies a task later. + await Expect.Poll(() => Browser.EvaluateAsync("() => window.getComputedStyle(document.body).backgroundColor")).ToMatchAsync(Is.EqualTo("rgb(0, 128, 0)")); + } + + [Test] + public async Task Should_fulfill_json() + { + await Browser.GotoAsync(EmptyPage); + await Browser.RouteAsync("**/data.json", route => route.FulfillAsync(new RouteFulfillResponse + { + Status = 201, + Headers = new Dictionary { ["foo"] = "bar" }, + Json = new { bar = "baz" }, + })); + var waiting = Browser.WaitForResponseAsync("**/*"); + var body = await Browser.EvaluateAsync("() => fetch('./data.json').then((r) => r.text())"); + var response = await waiting; + Assert.That(response.Status, Is.EqualTo(201)); + Assert.That(response.Headers["content-type"], Is.EqualTo("application/json")); + Assert.That(body, Is.EqualTo("""{"bar":"baz"}""")); + } + + [Test] + public async Task Should_not_go_to_the_network_for_fulfilled_requests_body() + { + var key = $"fulfilled-{DateTime.UtcNow.Ticks}-{Random.Shared.NextDouble()}"; + await Browser.RouteAsync($"**/count?key={key}", route => route.FulfillAsync(new RouteFulfillResponse { Status = 404, ContentType = "text/plain", Body = "Not Found! (mocked)" })); + var response = await AllAsync( + Browser.WaitForResponseAsync($"**/count?key={key}"), + Browser.GotoAsync(Content($"""
hello, world!
"""))); + Assert.That(await response.TextAsync(), Is.EqualTo("Not Found! (mocked)")); + await Browser.UnrouteAllAsync(); + var serverHits = await Browser.EvaluateAsync("(key) => fetch('/count?key=' + key).then((r) => r.text())", key); + Assert.That(serverHits, Is.EqualTo("11")); + } + + [Test] + public async Task Should_return_body_for_fulfilled_responses() + { + foreach (var status in new[] { 100, 200, 404, 500 }) + { + var bodyOverride = $"Custom body {status}"; + await Browser.RouteAsync("**/one-style.css", route => route.FulfillAsync(new RouteFulfillResponse { Status = status, ContentType = "text/plain", Body = bodyOverride })); + var response = await AllAsync(Browser.WaitForResponseAsync("**/one-style.css"), Browser.GotoAsync("/one-style.html")); + Assert.That(await response.TextAsync(), Is.EqualTo(bodyOverride)); + await Browser.UnrouteAllAsync(); + } + } +} diff --git a/tests/E2E.NUnit.Tests/Route/PageRouteTests.cs b/tests/E2E.NUnit.Tests/Route/PageRouteTests.cs new file mode 100644 index 000000000..697bf91a7 --- /dev/null +++ b/tests/E2E.NUnit.Tests/Route/PageRouteTests.cs @@ -0,0 +1,800 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using System.Collections.Concurrent; +using System.Text.RegularExpressions; +using E2E.Engine; +using static E2E.NUnit.Tests.Helpers; + +namespace E2E.NUnit.Tests.Route; + +/// +/// test.describe('page route') of upstream's apps/testbed/tests/route.e2e.ts (Playwright's page-route.spec.ts). +/// Not ported, as upstream: should navigate to dataURL and not fire dataURL requests (goto refuses data: URLs), +/// should show custom HTTP headers, should work with custom referer headers and should send referer (no setExtraHTTPHeaders), +/// should be abortable with custom error codes (no abort(errorCode)), should chain fallback w/ dynamic URL (no fallback({ url })), +/// should not fulfill with redirect status (WebKit only), the four tests with the times parameter (no times), +/// should contain sec-fetch headers in route (no allHeaders()), should contain raw response header and +/// should contain raw response header after fulfill (no request.response()), should be able to intercept every navigation +/// to a page controlled by service worker (service workers), should respect URLPattern ignoreCase (no URLPattern). +/// +public sealed class PageRouteTests : PlaywrightTest +{ + private static string EmptyPage => $"{PREFIX}/empty.html"; + + private Task TextContentAsync() => Browser.EvaluateAsync("document.body.textContent")!; + + [Test] + public async Task Should_intercept_smoke() + { + var intercepted = false; + await Browser.RouteAsync("**/empty.html", async route => + { + Assert.That(route.Request.Url, Does.Contain("empty.html")); + Assert.That(route.Request.Headers["user-agent"], Is.Not.Empty); + Assert.That(route.Request.Method, Is.EqualTo("GET")); + Assert.That(route.Request.PostData, Is.Null); + await route.ContinueAsync(); + intercepted = true; + }); + var response = await AllAsync(Browser.WaitForResponseAsync("**/empty.html"), Browser.GotoAsync(EmptyPage)); + Assert.That(response.Status, Is.EqualTo(200)); + Assert.That(intercepted, Is.True); + } + + [Test] + public async Task Should_unroute() + { + var intercepted = new List(); + await Browser.RouteAsync("**/*", async route => + { + intercepted.Add(1); + await route.FallbackAsync(); + }); + await Browser.RouteAsync("**/empty.html", async route => + { + intercepted.Add(2); + await route.FallbackAsync(); + }); + await Browser.RouteAsync("**/empty.html", async route => + { + intercepted.Add(3); + await route.FallbackAsync(); + }); + await Browser.RouteAsync(new Regex("empty.html"), async route => + { + intercepted.Add(4); + await route.FallbackAsync(); + }); + await Browser.GotoAsync(EmptyPage); + Assert.That(intercepted, Is.EqualTo(new[] { 4, 3, 2, 1 })); + + intercepted.Clear(); + await Browser.UnrouteAsync(new Regex("empty.html")); + await Browser.GotoAsync(EmptyPage); + Assert.That(intercepted, Is.EqualTo(new[] { 3, 2, 1 })); + + intercepted.Clear(); + await Browser.UnrouteAsync("**/empty.html"); + await Browser.GotoAsync(EmptyPage); + Assert.That(intercepted, Is.EqualTo(new[] { 1 })); + } + + [Test] + public async Task Should_not_support_question_mark_in_glob_pattern() + { + await ExpectedToFailAsync("index1hello", async () => + { + await Browser.RouteAsync(new Regex(@"/index"), async route => + { + var url = new Uri(route.Request.Url); + var body = url.AbsolutePath switch + { + "/index" => "index-no-hello", + "/index123hello" => "index123hello", + "/index1hello" => "index1hello", + _ => url.AbsolutePath[1..] + url.Query, + }; + await route.FulfillAsync(new RouteFulfillResponse { Body = body, ContentType = "text/html" }); + }); + await Browser.RouteAsync("**/index?hello", route => route.FulfillAsync(new RouteFulfillResponse { Body = "intercepted any character" })); + await Browser.RouteAsync(@"**/index\?hello", route => route.FulfillAsync(new RouteFulfillResponse { Body = "intercepted question mark" })); + + await Browser.GotoAsync($"{PREFIX}/index?hello"); + Contain("intercepted question mark", (await Browser.EvaluateAsync("document.documentElement.outerHTML"))!); + + await Browser.GotoAsync($"{PREFIX}/index"); + Contain("index-no-hello", (await Browser.EvaluateAsync("document.documentElement.outerHTML"))!); + + await Browser.GotoAsync($"{PREFIX}/index1hello"); + Contain("index1hello", (await Browser.EvaluateAsync("document.documentElement.outerHTML"))!); + + await Browser.GotoAsync($"{PREFIX}/index123hello"); + Contain("index123hello", (await Browser.EvaluateAsync("document.documentElement.outerHTML"))!); + }); + } + + [Test] + public async Task Should_work_when_POST_is_redirected_with_302() + { + await Browser.GotoAsync(EmptyPage); + await Browser.RouteAsync("**/*", route => route.ContinueAsync()); + await Browser.GotoAsync(Content(""" +
+ +
+ """)); + var navigation = Browser.WaitForURLAsync("/empty.html"); + await Browser.EvaluateAsync("() => { document.querySelector('form').submit(); }"); + await navigation; + } + + [Test] + public async Task Should_work_when_header_manipulation_headers_with_redirect() + { + await Browser.RouteAsync("**/*", route => route.ContinueAsync(new RouteContinueOverrides { Headers = WithHeaders(route.Request.Headers, ("foo", "bar")) })); + await Browser.GotoAsync("/redirect?to=/empty.html"); + } + + [Test] + public async Task Should_be_able_to_remove_headers() + { + await Browser.GotoAsync(EmptyPage); + await Browser.RouteAsync("**/*", async route => + { + var headers = WithHeaders(route.Request.Headers); + headers.Remove("foo"); + await route.ContinueAsync(new RouteContinueOverrides { Headers = headers }); + }); + var served = Served.Parse((await Browser.EvaluateAsync( + "(url) => fetch(url, { headers: { foo: 'bar' } }).then((response) => response.text())", + $"{PREFIX}/cors-echo"))!); + Assert.That(served.Header("foo"), Is.Null); + } + + [Test] + public async Task Should_contain_referer_header() + { + var requests = new ConcurrentQueue(); + await Browser.RouteAsync("**/*", async route => + { + requests.Enqueue(route.Request); + await route.ContinueAsync(); + }); + await Browser.GotoAsync("/one-style.html"); + var seen = requests.ToArray(); + Assert.That(seen[1].Url, Does.Contain("/one-style.css")); + Assert.That(seen[1].Headers["referer"], Does.Contain("/one-style.html")); + } + + [Test] + public async Task Should_properly_return_navigation_response_when_URL_has_cookies() + { + await Browser.GotoAsync(EmptyPage); + await Browser.SetCookiesAsync([new BrowserCookie { Url = EmptyPage, Name = "foo", Value = "bar" }]); + await Browser.RouteAsync("**/*", route => route.ContinueAsync()); + var response = await AllAsync(Browser.WaitForResponseAsync("**/empty.html"), Browser.ReloadAsync()); + Assert.That(response.Status, Is.EqualTo(200)); + } + + [Test] + public async Task Should_not_override_cookie_header() + { + await Browser.GotoAsync(EmptyPage); + await Browser.EvaluateAsync("() => { document.cookie = 'original=value'; }"); + string? cookieValueInRoute = null; + await Browser.RouteAsync("**", async route => + { + cookieValueInRoute = route.Request.Headers.GetValueOrDefault("cookie"); + await route.ContinueAsync(new RouteContinueOverrides { Headers = WithHeaders(route.Request.Headers, ("cookie", "overridden=value")) }); + }); + await Browser.GotoAsync("/cors-echo"); + var served = Served.Parse((await TextContentAsync())!); + Assert.That(cookieValueInRoute, Is.EqualTo("original=value")); + Assert.That(served.Header("cookie"), Is.EqualTo("original=value")); + } + + [Test] + public async Task Should_work_with_redirect_inside_sync_XHR() + { + await Browser.GotoAsync(EmptyPage); + var continued = false; + await Browser.RouteAsync("**/*", async route => + { + await route.ContinueAsync(); + continued = true; + }); + var status = await Browser.EvaluateAsync(""" + () => { + const request = new XMLHttpRequest(); + request.open('GET', '/redirect?to=/pptr.png', false); + request.send(null); + return request.status; + } + """); + Assert.That(status, Is.EqualTo(200)); + Assert.That(continued, Is.True); + } + + [Test] + public async Task Should_pause_intercepted_XHR_until_continue() + { + await Browser.GotoAsync(EmptyPage); + var routed = Deferred(); + var release = Deferred(); + await Browser.RouteAsync("**/global-var.html", async route => + { + routed.TrySetResult(); + await release.Task; + await route.ContinueAsync(); + }); + var xhrFinished = false; + var statusPromise = Task.Run(async () => + { + var status = await Browser.EvaluateAsync(""" + () => { + const request = new XMLHttpRequest(); + request.open('GET', '/global-var.html', false); + request.send(null); + return request.status; + } + """); + xhrFinished = true; + return status; + }); + await routed.Task; + await Task.Delay(500); + Assert.That(xhrFinished, Is.False); + release.TrySetResult(); + Assert.That(await statusPromise, Is.EqualTo(200)); + } + + [Test] + public async Task Should_pause_intercepted_fetch_request_until_continue() + { + await Browser.GotoAsync(EmptyPage); + var routed = Deferred(); + var release = Deferred(); + await Browser.RouteAsync("**/global-var.html", async route => + { + routed.TrySetResult(); + await release.Task; + await route.ContinueAsync(); + }); + var fetchFinished = false; + var statusPromise = Task.Run(async () => + { + var status = await Browser.EvaluateAsync("async () => (await fetch('/global-var.html')).status"); + fetchFinished = true; + return status; + }); + await routed.Task; + await Task.Delay(500); + Assert.That(fetchFinished, Is.False); + release.TrySetResult(); + Assert.That(await statusPromise, Is.EqualTo(200)); + } + + [Test] + public async Task Should_be_abortable() + { + await Browser.RouteAsync(new Regex(@"\.css$"), route => route.AbortAsync()); + var response = await AllAsync(Browser.WaitForResponseAsync("**/one-style.html"), Browser.GotoAsync("/one-style.html")); + Assert.That(response.Status, Is.EqualTo(200)); + Assert.That(await Browser.EvaluateAsync("getComputedStyle(document.body).backgroundColor"), Is.Not.EqualTo("rgb(255, 192, 203)")); + } + + [Test] + public async Task Should_not_throw_if_request_was_cancelled_by_the_page() + { + var routed = Deferred(); + var release = Deferred(); + await Browser.RouteAsync("**/data.json", async route => + { + routed.TrySetResult(); + await release.Task; + await route.AbortAsync(); + }); + await Browser.GotoAsync(EmptyPage); + await Browser.EvaluateAsync(""" + (url) => { + globalThis.controller = new AbortController(); + globalThis.failure = fetch(url, { signal: globalThis.controller.signal }).then(() => 'loaded', (error) => error.name); + } + """, $"{PREFIX}/data.json"); + await routed.Task; + Assert.That(await Browser.EvaluateAsync("() => { globalThis.controller.abort(); return globalThis.failure; }"), Is.EqualTo("AbortError")); + release.TrySetResult(); + await Browser.EvaluateAsync("() => new Promise((resolve) => setTimeout(resolve, 100))"); + } + + [Test] + public async Task Should_fail_navigation_when_aborting_main_resource() + { + await Browser.RouteAsync("**/*", route => route.AbortAsync()); + var error = await Assert.CatchAsync(() => Browser.GotoAsync(EmptyPage)); + Assert.That(error!.Message, Does.Contain("net::ERR_FAILED")); + } + + [Test] + public async Task Should_not_work_with_redirects() + { + var intercepted = new ConcurrentQueue(); + await Browser.RouteAsync("**/*", async route => + { + await route.ContinueAsync(); + intercepted.Enqueue(route.Request); + }); + string[] chain = ["/non-existing-page.html", "/non-existing-page-2.html", "/non-existing-page-3.html", "/non-existing-page-4.html"]; + var start = "/empty.html"; + foreach (var from in chain.Reverse()) + { + start = $"/redirect?from={from}&to={Uri.EscapeDataString(start)}"; + } + + var response = await AllAsync(Browser.WaitForResponseAsync("**/empty.html"), Browser.GotoAsync(start)); + Assert.That(response.Status, Is.EqualTo(200)); + Assert.That(response.Url, Does.Contain("empty.html")); + + var seen = intercepted.ToArray(); + Assert.That(seen, Has.Length.EqualTo(1)); + Assert.That(seen[0].Url, Does.Contain("/non-existing-page.html")); + } + + [Test] + public async Task Should_work_with_redirects_for_subresources() + { + var intercepted = new ConcurrentQueue(); + await Browser.RouteAsync("**/*", async route => + { + await route.ContinueAsync(); + intercepted.Enqueue(route.Request); + }); + string[] chain = ["/one-style.css", "/two-style.css", "/three-style.css"]; + var stylesheet = "/one-style.css"; + foreach (var from in chain.Reverse()) + { + stylesheet = $"/redirect?from={from}&to={Uri.EscapeDataString(stylesheet)}"; + } + + var page = Content($"""
hello, world!
"""); + var response = await AllAsync(Browser.WaitForResponseAsync("**/content?**"), Browser.GotoAsync(page)); + Assert.That(response.Status, Is.EqualTo(200)); + Assert.That(response.Url, Does.Contain("/content?")); + + var seen = intercepted.ToArray(); + Assert.That(seen, Has.Length.EqualTo(2)); + Assert.That(seen[0].Url, Does.Contain("/content?")); + Assert.That(seen[1].Url, Does.Contain("/one-style.css")); + } + + [Test] + public async Task Should_work_with_equal_requests() + { + await Browser.GotoAsync(EmptyPage); + var key = $"equal-{DateTime.UtcNow.Ticks}-{Random.Shared.NextDouble()}"; + var spinner = false; + await Browser.RouteAsync("**/*", async route => + { + await (spinner ? route.AbortAsync() : route.ContinueAsync()); + spinner = !spinner; + }); + var results = new List(); + for (var i = 0; i < 3; i++) + { + results.Add(await Browser.EvaluateAsync("(key) => fetch('/count?key=' + key).then((response) => response.text()).catch(() => 'FAILED')", key)); + } + + Assert.That(results, Is.EqualTo(new[] { "11", "FAILED", "22" })); + } + + [Test] + public async Task Should_be_able_to_fetch_dataURL_and_not_fire_dataURL_requests() + { + await Browser.GotoAsync(EmptyPage); + var requests = new ConcurrentQueue(); + await Browser.RouteAsync("**/*", async route => + { + requests.Enqueue(route.Request); + await route.ContinueAsync(); + }); + var text = await Browser.EvaluateAsync("(url) => fetch(url).then((response) => response.text())", "data:text/html,
yo
"); + Assert.That(text, Is.EqualTo("
yo
")); + Assert.That(requests, Is.Empty); + } + + [Test] + public async Task Should_navigate_to_URL_with_hash_and_and_fire_requests_without_hash() + { + var requests = new ConcurrentQueue(); + await Browser.RouteAsync("**/*", async route => + { + requests.Enqueue(route.Request); + await route.ContinueAsync(); + }); + var response = await AllAsync(Browser.WaitForResponseAsync("**/empty.html"), Browser.GotoAsync($"{EmptyPage}#hash")); + Assert.That(response.Status, Is.EqualTo(200)); + Assert.That(response.Url, Is.EqualTo(EmptyPage)); + var seen = requests.ToArray(); + Assert.That(seen, Has.Length.EqualTo(1)); + Assert.That(seen[0].Url, Is.EqualTo(EmptyPage)); + } + + [Test] + public async Task Should_work_with_encoded_server() + { + await Browser.RouteAsync("**/*", route => route.ContinueAsync()); + var response = await AllAsync(Browser.WaitForResponseAsync(new Regex("nonexisting")), Browser.GotoAsync($"{PREFIX}/some nonexisting page")); + Assert.That(response.Status, Is.EqualTo(404)); + } + + [Test] + public async Task Should_work_with_badly_encoded_server() + { + await Browser.RouteAsync("**/*", route => route.ContinueAsync()); + var response = await AllAsync(Browser.WaitForResponseAsync(new Regex("rnd=")), Browser.GotoAsync($"{PREFIX}/status?rnd=%911")); + Assert.That(response.Status, Is.EqualTo(200)); + } + + [Test] + public async Task Should_work_with_encoded_server_2() + { + await Browser.GotoAsync(EmptyPage); + var requests = new ConcurrentQueue(); + await Browser.RouteAsync("**/*", async route => + { + await route.ContinueAsync(); + if (!route.Request.Url.Contains("/content?", StringComparison.Ordinal)) + { + requests.Enqueue(route.Request); + } + }); + var response = await AllAsync( + Browser.WaitForResponseAsync(new Regex(@"/fonts\?")), + Browser.GotoAsync(Content($""""""))); + Assert.That(requests, Has.Count.EqualTo(1)); + Assert.That(response.Status, Is.EqualTo(404)); + } + + [Test] + public async Task Should_not_throw_Invalid_Interception_Id_if_the_request_was_cancelled() + { + await Browser.GotoAsync(Content("")); + var routed = Deferred(); + var release = Deferred(); + await Browser.RouteAsync("**/*", async route => + { + routed.TrySetResult(); + await release.Task; + await route.ContinueAsync(); + }); + await Browser.EvaluateAsync("(url) => { document.querySelector('iframe').src = url; }", EmptyPage); + await routed.Task; + await Browser.EvaluateAsync("() => document.querySelector('iframe').remove()"); + release.TrySetResult(); + await Browser.EvaluateAsync("() => new Promise((resolve) => setTimeout(resolve, 100))"); + } + + [Test] + public async Task Should_intercept_main_resource_during_cross_process_navigation() + { + await Browser.GotoAsync(EmptyPage); + var intercepted = false; + await Browser.RouteAsync($"{CROSS}/empty.html", async route => + { + intercepted = true; + await route.ContinueAsync(); + }); + var response = await AllAsync(Browser.WaitForResponseAsync($"{CROSS}/empty.html"), Browser.GotoAsync($"{CROSS}/empty.html")); + Assert.That(response.Status, Is.EqualTo(200)); + Assert.That(intercepted, Is.True); + } + + [Test] + public async Task Should_fulfill_with_redirect_status() + { + await Browser.GotoAsync("/title.html"); + await Browser.RouteAsync("**/*", async route => + { + if (route.Request.Url != $"{PREFIX}/redirect_this") + { + await route.ContinueAsync(); + return; + } + + await route.FulfillAsync(new RouteFulfillResponse { Status = 301, Headers = new Dictionary { ["location"] = "/status?body=foo" } }); + }); + var text = await Browser.EvaluateAsync("async (url) => (await fetch(url)).text()", $"{PREFIX}/redirect_this"); + Assert.That(text, Is.EqualTo("foo")); + } + + [Test] + public async Task Should_support_cors_with_GET() + { + await Browser.GotoAsync(EmptyPage); + await Browser.RouteAsync("**/cars*", async route => + { + var headers = new Dictionary { ["access-control-allow-origin"] = route.Request.Url.EndsWith("allow", StringComparison.Ordinal) ? "*" : "none" }; + await route.FulfillAsync(new RouteFulfillResponse { ContentType = "application/json", Headers = headers, Status = 200, Body = """["electric","gas"]""" }); + }); + var resp = await Browser.EvaluateAsync("async () => (await fetch('https://example.com/cars?allow', { mode: 'cors' })).json()"); + Assert.That(resp, Is.EqualTo(new[] { "electric", "gas" })); + var error = await Assert.CatchAsync(() => Browser.EvaluateAsync("async () => (await fetch('https://example.com/cars?reject', { mode: 'cors' })).json()")); + Assert.That(error!.Message, Does.Contain("Failed")); + } + + [Test] + public async Task Should_add_Access_Control_Allow_Origin_by_default_when_fulfill() + { + await Browser.GotoAsync(EmptyPage); + await Browser.RouteAsync("**/cars", route => route.FulfillAsync(new RouteFulfillResponse { ContentType = "application/json", Status = 200, Body = """["electric","gas"]""" })); + var waiting = Browser.WaitForResponseAsync("https://example.com/cars"); + var result = await Browser.EvaluateAsync(""" + async () => { + const response = await fetch('https://example.com/cars', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + mode: 'cors', + body: JSON.stringify({ number: 1 }), + }); + return response.json(); + } + """); + var response = await waiting; + Assert.That(result, Is.EqualTo(new[] { "electric", "gas" })); + Assert.That(response.Headers["access-control-allow-origin"], Is.EqualTo(PREFIX)); + } + + [Test] + public async Task Should_allow_null_origin_for_about_blank() + { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await Browser.GotoAsync("about:blank"); + await Browser.RouteAsync("**/something", route => route.FulfillAsync(new RouteFulfillResponse { ContentType = "text/plain", Status = 200, Body = "done" })); + var waiting = Browser.WaitForResponseAsync($"{CROSS}/something"); + var text = await Browser.EvaluateAsync(""" + async (url) => { + const data = await fetch(url, { method: 'GET', headers: { 'X-PINGOTHER': 'pingpong' } }); + return data.text(); + } + """, $"{CROSS}/something"); + var response = await waiting; + Assert.That(text, Is.EqualTo("done")); + Assert.That(response.Headers["access-control-allow-origin"], Is.EqualTo("null")); + } + + [Test] + public async Task Should_respect_cors_overrides() + { + await Browser.GotoAsync(EmptyPage); + await Browser.RouteAsync("**/something", route => route.FulfillAsync(new RouteFulfillResponse + { + ContentType = "text/plain", + Status = 200, + Headers = new Dictionary { ["Access-Control-Allow-Origin"] = "http://non-existent" }, + Body = "done", + })); + var error = await Assert.CatchAsync(() => Browser.EvaluateAsync(""" + async (url) => { + const data = await fetch(url, { method: 'GET', headers: { 'X-PINGOTHER': 'pingpong' } }); + return data.text(); + } + """, $"{CROSS}/something")); + Assert.That(error!.Message, Does.Contain("Failed to fetch")); + } + + [Test] + public async Task Should_not_auto_intercept_non_preflight_OPTIONS_without_network_interception() + { + await Browser.GotoAsync(EmptyPage); + var key = $"options-{DateTime.UtcNow.Ticks}-{Random.Shared.NextDouble()}"; + var texts = await Browser.EvaluateAsync(OptionsRequests, $"{CROSS}/options?key={key}"); + Assert.That(texts![0], Is.EqualTo("Hello")); + Assert.That(texts[1], Is.EqualTo("World")); + Assert.That( + await Browser.EvaluateAsync("(key) => fetch(`/options-log?key=${key}`).then((response) => response.json())", key), + Is.EqualTo(new[] { "OPTIONS:/options", "OPTIONS:/options", "GET:/options" })); + } + + [Test] + public async Task Should_not_auto_intercept_non_preflight_OPTIONS_with_network_interception() + { + await Browser.GotoAsync(EmptyPage); + var key = $"options-{DateTime.UtcNow.Ticks}-{Random.Shared.NextDouble()}"; + await Browser.RouteAsync("**/options?*", route => route.ContinueAsync()); + var texts = await Browser.EvaluateAsync(OptionsRequests, $"{CROSS}/options?key={key}"); + Assert.That(texts![0], Is.EqualTo("Hello")); + Assert.That(texts[1], Is.EqualTo("World")); + var requests = await Browser.EvaluateAsync("(key) => fetch(`/options-log?key=${key}`).then((response) => response.json())", key); + Assert.That(requests, Is.EqualTo(new[] { "OPTIONS:/options", "GET:/options" })); + } + + private const string OptionsRequests = """ + async (url) => { + const response1 = await fetch(url, { method: 'OPTIONS' }); + const text1 = await response1.text(); + const response2 = await fetch(url, { method: 'GET' }); + const text2 = await response2.text(); + return [text1, text2]; + } + """; + + private const string PostCars = """ + async () => { + const response = await fetch('https://example.com/cars', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + mode: 'cors', + body: JSON.stringify({ number: 1 }), + }); + return response.json(); + } + """; + + [Test] + public async Task Should_support_cors_with_POST() + { + await Browser.GotoAsync(EmptyPage); + await Browser.RouteAsync("**/cars", route => route.FulfillAsync(new RouteFulfillResponse + { + ContentType = "application/json", + Headers = new Dictionary { ["Access-Control-Allow-Origin"] = "*" }, + Status = 200, + Body = """["electric","gas"]""", + })); + var resp = await Browser.EvaluateAsync(PostCars); + Assert.That(resp, Is.EqualTo(new[] { "electric", "gas" })); + } + + [Test] + public async Task Should_support_cors_with_credentials() + { + await Browser.GotoAsync(EmptyPage); + await Browser.RouteAsync("**/cars", route => route.FulfillAsync(new RouteFulfillResponse + { + ContentType = "application/json", + Headers = new Dictionary { ["Access-Control-Allow-Origin"] = PREFIX, ["Access-Control-Allow-Credentials"] = "true" }, + Status = 200, + Body = """["electric","gas"]""", + })); + var resp = await Browser.EvaluateAsync(""" + async () => { + const response = await fetch('https://example.com/cars', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + mode: 'cors', + body: JSON.stringify({ number: 1 }), + credentials: 'include', + }); + return response.json(); + } + """); + Assert.That(resp, Is.EqualTo(new[] { "electric", "gas" })); + } + + [Test] + public async Task Should_not_abort_preflighted_cross_origin_redirect_when_a_route_is_registered() + { + await Browser.GotoAsync(EmptyPage); + await Browser.RouteAsync("**/never-matches", route => route.ContinueAsync()); + var result = await Browser.EvaluateAsync(""" + async (url) => { + const response = await fetch(url, { credentials: 'include', headers: { 'X-App-Version': '1.2.3' } }); + const served = await response.json(); + return response.status + ' ' + served.method + ' ' + served.headers['x-app-version']; + } + """, $"{CROSS}/bounce?to={Uri.EscapeDataString($"{PREFIX}/cors-echo?preflight")}"); + Assert.That(result, Is.EqualTo("200 GET 1.2.3")); + } + + [Test] + public async Task Should_reject_cors_with_disallowed_credentials() + { + await Browser.GotoAsync(EmptyPage); + await Browser.RouteAsync("**/cars", route => route.FulfillAsync(new RouteFulfillResponse + { + ContentType = "application/json", + Headers = new Dictionary { ["Access-Control-Allow-Origin"] = PREFIX }, + Status = 200, + Body = """["electric","gas"]""", + })); + var error = await Assert.CatchAsync(() => Browser.EvaluateAsync(""" + async () => { + const response = await fetch('https://example.com/cars', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + mode: 'cors', + body: JSON.stringify({ number: 1 }), + credentials: 'include', + }); + return response.json(); + } + """)); + Assert.That(error, Is.Not.Null); + } + + [Test] + public async Task Should_support_cors_for_different_methods() + { + await Browser.GotoAsync(EmptyPage); + await Browser.RouteAsync("**/cars", route => route.FulfillAsync(new RouteFulfillResponse + { + ContentType = "application/json", + Headers = new Dictionary { ["Access-Control-Allow-Origin"] = "*" }, + Status = 200, + Json = new[] { route.Request.Method, "electric", "gas" }, + })); + var post = await Browser.EvaluateAsync(PostCars); + Assert.That(post, Is.EqualTo(new[] { "POST", "electric", "gas" })); + var remove = await Browser.EvaluateAsync(""" + async () => { + const response = await fetch('https://example.com/cars', { method: 'DELETE', headers: {}, mode: 'cors', body: '' }); + return response.json(); + } + """); + Assert.That(remove, Is.EqualTo(new[] { "DELETE", "electric", "gas" })); + } + + [Test] + public async Task Should_contain_raw_request_header() + { + IReadOnlyDictionary? headers = null; + await Browser.RouteAsync("**/*", async route => + { + headers = route.Request.Headers; + await route.ContinueAsync(); + }); + await Browser.GotoAsync("/empty.html"); + Assert.That(headers!["accept"], Is.Not.Empty); + } + + [TestCase("fulfill", TestName = "Route_fulfill_should_throw_if_called_twice")] + [TestCase("continue", TestName = "Route_continue_should_throw_if_called_twice")] + [TestCase("fallback", TestName = "Route_fallback_should_throw_if_called_twice")] + [TestCase("abort", TestName = "Route_abort_should_throw_if_called_twice")] + public async Task Route_method_should_throw_if_called_twice(string method) + { + var handled = Deferred(); + await Browser.RouteAsync("**/*", async route => + { + Task Decide() => method switch + { + "fulfill" => route.FulfillAsync(new RouteFulfillResponse()), + "continue" => route.ContinueAsync(), + "fallback" => route.FallbackAsync(), + _ => route.AbortAsync(), + }; + + await Decide(); + try + { + await Decide(); + handled.TrySetResult(new InvalidOperationException("decided twice")); + } + catch (Exception caught) + { + handled.TrySetResult(caught); + } + }); + var navigation = Browser.GotoAsync("/empty.html").ContinueWith(_ => { }, TaskScheduler.Default); + var e = await handled.Task; + Assert.That(e.Message, Does.Contain("called twice")); + await navigation; + } + + [Test] + public async Task Should_intercept_when_postData_is_more_than_1MB() + { + await Browser.GotoAsync(EmptyPage); + var intercepted = Deferred(); + var postBody = new string('0', 2 * 1024 * 1024); + await Browser.RouteAsync("**/404.html", async route => + { + await route.AbortAsync(); + intercepted.TrySetResult(route.Request.PostData); + }); + await Browser.EvaluateAsync("(body) => fetch('/404.html', { method: 'POST', body }).then(() => null, () => null)", postBody); + Assert.That(await intercepted.Task, Is.EqualTo(postBody)); + } +} diff --git a/tests/E2E.NUnit.Tests/Testbed/playwright/assets/global-var.html b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/global-var.html new file mode 100644 index 000000000..b6be97503 --- /dev/null +++ b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/global-var.html @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/tests/E2E.NUnit.Tests/Testbed/playwright/assets/one-style.css b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/one-style.css new file mode 100644 index 000000000..7b26410d8 --- /dev/null +++ b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/one-style.css @@ -0,0 +1,3 @@ +body { + background-color: pink; +} diff --git a/tests/E2E.NUnit.Tests/Testbed/playwright/assets/one-style.html b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/one-style.html new file mode 100644 index 000000000..b3a6eeeeb --- /dev/null +++ b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/one-style.html @@ -0,0 +1,3 @@ + + +
hello, world!
diff --git a/tests/E2E.NUnit.Tests/Testbed/playwright/assets/preload.html b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/preload.html new file mode 100644 index 000000000..dc10ff6d6 --- /dev/null +++ b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/preload.html @@ -0,0 +1,5 @@ + + +
hello, world!
diff --git a/tests/E2E.NUnit.Tests/Testbed/playwright/assets/title.html b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/title.html new file mode 100644 index 000000000..6e81f4091 --- /dev/null +++ b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/title.html @@ -0,0 +1,2 @@ + +Woof-Woof