From 8769f58049565689cb0ac1362eb1695d216e07fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Kondratiuk?= Date: Wed, 4 Nov 2026 18:40:28 -0300 Subject: [PATCH 1/4] Port Playwright's check, wait-for-url, locator-list and selectors-text tests (Refs #1060) The testbed gets the /content route and Playwright's test assets (with its LICENSE and NOTICE), and the first four of upstream's Playwright page test files run against them. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Ls2e1yaZFgZ3FEJkYScfkK --- COMPATIBILITY.md | 1 + tests/E2E.Agent.Tests/PlaywrightRoutes.cs | 72 +++++++ tests/E2E.Agent.Tests/Testbed.cs | 2 +- tests/E2E.NUnit.Tests/Check/PageCheckTests.cs | 160 ++++++++++++++ tests/E2E.NUnit.Tests/E2E.NUnit.Tests.csproj | 2 + tests/E2E.NUnit.Tests/Helpers/Helpers.cs | 69 ++++++ .../LocatorList/LocatorListTests.cs | 27 +++ .../SelectorsText/SelectorsTextTests.cs | 62 ++++++ .../Testbed/playwright/LICENSE | 202 ++++++++++++++++++ .../E2E.NUnit.Tests/Testbed/playwright/NOTICE | 5 + .../Testbed/playwright/assets/empty.html | 0 .../Testbed/playwright/assets/grid.html | 66 ++++++ .../WaitForUrl/PageWaitForUrlTests.cs | 127 +++++++++++ 13 files changed, 794 insertions(+), 1 deletion(-) create mode 100644 tests/E2E.Agent.Tests/PlaywrightRoutes.cs create mode 100644 tests/E2E.NUnit.Tests/Check/PageCheckTests.cs create mode 100644 tests/E2E.NUnit.Tests/Helpers/Helpers.cs create mode 100644 tests/E2E.NUnit.Tests/LocatorList/LocatorListTests.cs create mode 100644 tests/E2E.NUnit.Tests/SelectorsText/SelectorsTextTests.cs create mode 100644 tests/E2E.NUnit.Tests/Testbed/playwright/LICENSE create mode 100644 tests/E2E.NUnit.Tests/Testbed/playwright/NOTICE create mode 100644 tests/E2E.NUnit.Tests/Testbed/playwright/assets/empty.html create mode 100644 tests/E2E.NUnit.Tests/Testbed/playwright/assets/grid.html create mode 100644 tests/E2E.NUnit.Tests/WaitForUrl/PageWaitForUrlTests.cs diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index 7f77ebc47..1bdd8a6c4 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -162,6 +162,7 @@ Differences: - Upstream's docs site pages that have no counterpart in the port: the page objects page (`docs/page-objects.mdx`, moved to `/page-object-model` in `d30114a`), `e2e feedback` and the `docs/reference/cli.mdx` text about its opt-out variables (`4c1e2e8`), and `examples/` with its registry (`b3ae3a4`, `38b802d`, `a29edcb`, `b54646f`). The migration guides (`docs/migrate/*.mdx`, `8537abc`) are ported: see [Migration guides](#migration-guides). The docs site has .NET-only guides for upstream's five example apps of `caf51eb` (tester-army/e2e#1497: i18n, file upload, location, biometrics, deep links), under [Examples](docs-site/src/content/docs/examples/index.mdx). They are not ports: that commit only adds registry entries that link to separate repositories, so there was no guide text. Each page writes C# tests for the upstream app. The self-healing deep dive (`6fa99ea`) is ported as the [Self-healing tests](README.md#self-healing-tests) section of the guide, since the port has no docs pages for the cache, the trace page, or executors to link to. Known gap: only `e2e explore` prints a run summary, since it is the one command that feeds a run to `ListReporter` (see [List reporter](#list-reporter)): the `Cache 4 replayed · 1 handed off · 1 missed` row is `Format.CacheText` over `Format.StepsCacheTally` (`E2E.Cli`, upstream's `cacheText` and `stepsCacheTally` of `report/format.ts`), which an exploration, with its cache off, never fills, and a test run does not print ([#799](https://github.com/hardkoded/e2e-dotnet/issues/799)) - Parallel workers and serial suites - `test.fail` and the `fail` test option (tester-army/e2e#1539, `732ea8a`): a test expected to fail, whose product failure passes and whose pass fails with `UNEXPECTED_PASS`. It lives in upstream's test registry, scheduler, retry, and reporters (`settleExpectedFailure` runs on a finished attempt), and the port has none of them. NUnit and xUnit v3 own the verdict and the retries, and neither has an expected-failure outcome, so a port would need a new public API of its own +- Playwright's page tests in the testbed suite (tester-army/e2e#1505, `bdf769b`) are ported in slices (hardkoded/e2e-dotnet#1060), as the `playwright` category of `tests/E2E.NUnit.Tests`, against the playground's `/content` route and Playwright's test assets (Apache-2.0, `Testbed/playwright/`, with Playwright's `LICENSE` and `NOTICE`). A test upstream marks `{ fail: 'reason' }` keeps its assertions inside the test-only `Helpers.ExpectedToFailAsync`, which passes while the body fails and fails once it passes. Ported so far: `check`, `wait-for-url`, `locator-list`, and `selectors-text` (one test is such a known difference, hardkoded/e2e-dotnet#1062). - Serial groups (upstream tester-army/e2e#1056, #1470): serial runs, group retries, and skipping the rest of a group after a failure belong to the test runner, which is NUnit or xUnit here, so the port keeps no serial groups. The schema has `serialAttempt.cutRetry` and the serial verdict is read from it, but nothing in the port writes a serial attempt: see [Report document](#report-document) - The out-of-process engine protocol (upstream tester-army/e2e#1232, [#873](https://github.com/hardkoded/e2e-dotnet/issues/873)): the port has no runner and no worker pool, so there is no engine process to talk to. An engine is written in .NET against `IEngine` - Diff-only observations for a custom executor's own model turns. The built-in agent has them (#1022): `#id` lines on the opening screen and on `observe`, and a diff after each action (see [MCP server](#mcp-server) for the presenter). `ExecutorObservation.Text`, which an executor reads from `Observe`, keeps the full `[ref=…]` snapshot, cut at the observation byte budget (see [Agents](#agents)), and a node is addressed by its ref there (`new ExecutorTarget("e12")`), so a custom executor has no presenter of its own. Upstream gives every executor the `#id` view. diff --git a/tests/E2E.Agent.Tests/PlaywrightRoutes.cs b/tests/E2E.Agent.Tests/PlaywrightRoutes.cs new file mode 100644 index 000000000..c27600fb8 --- /dev/null +++ b/tests/E2E.Agent.Tests/PlaywrightRoutes.cs @@ -0,0 +1,72 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using System.Net; +using System.Text; + +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 and the assets so far. +/// +internal static class PlaywrightRoutes +{ + private static readonly string Root = Path.Combine(AppContext.BaseDirectory, "Testbed", "playwright", "assets"); + + private static readonly Dictionary Types = new(StringComparer.Ordinal) + { + [".html"] = "text/html", + [".js"] = "text/javascript", + [".css"] = "text/css", + [".json"] = "application/json", + [".png"] = "image/png", + [".pdf"] = "application/pdf", + [".svg"] = "image/svg+xml", + [".txt"] = "text/plain", + }; + + /// 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") + { + var html = context.Request.QueryString["html"] ?? ""; + response.ContentType = "text/html; charset=utf-8"; + await WriteAsync(response, FromBase64Url(html)).ConfigureAwait(false); + return; + } + + var file = Path.GetFullPath(Path.Combine(Root, Uri.UnescapeDataString(path).TrimStart('/'))); + if (!file.StartsWith(Root + Path.DirectorySeparatorChar, StringComparison.Ordinal) || !File.Exists(file)) + { + response.StatusCode = 404; + response.ContentType = "text/plain"; + await WriteAsync(response, Encoding.UTF8.GetBytes("Not found")).ConfigureAwait(false); + return; + } + + response.ContentType = Types.GetValueOrDefault(Path.GetExtension(file), "application/octet-stream"); + response.AddHeader("Cache-Control", "no-store"); + await WriteAsync(response, await File.ReadAllBytesAsync(file).ConfigureAwait(false)).ConfigureAwait(false); + } + + private static byte[] FromBase64Url(string value) + { + var padded = value.Replace('-', '+').Replace('_', '/'); + padded = padded.PadRight(padded.Length + ((4 - (padded.Length % 4)) % 4), '='); + var bytes = new byte[padded.Length]; + return Convert.TryFromBase64String(padded, bytes, out var written) ? bytes[..written] : []; + } + + private static async Task WriteAsync(HttpListenerResponse response, byte[] bytes) + { + response.ContentLength64 = bytes.Length; + await response.OutputStream.WriteAsync(bytes).ConfigureAwait(false); + } +} diff --git a/tests/E2E.Agent.Tests/Testbed.cs b/tests/E2E.Agent.Tests/Testbed.cs index acdb010f7..d2a2336cf 100644 --- a/tests/E2E.Agent.Tests/Testbed.cs +++ b/tests/E2E.Agent.Tests/Testbed.cs @@ -1014,7 +1014,7 @@ await WriteHtmlAsync(response, "Dashboard", """ } else { - response.StatusCode = 404; + await PlaywrightRoutes.HandleAsync(context).ConfigureAwait(false); } response.Close(); diff --git a/tests/E2E.NUnit.Tests/Check/PageCheckTests.cs b/tests/E2E.NUnit.Tests/Check/PageCheckTests.cs new file mode 100644 index 000000000..174b0c70e --- /dev/null +++ b/tests/E2E.NUnit.Tests/Check/PageCheckTests.cs @@ -0,0 +1,160 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using static E2E.NUnit.Tests.Helpers; + +namespace E2E.NUnit.Tests.Check; + +/// +/// test.describe('page check') of upstream's apps/testbed/tests/check.e2e.ts (Playwright's page-check.spec.ts). +/// Not ported, as upstream: should check the label with position (no position), trial run should not check and trial run +/// should not uncheck (no trial), should check the box using setChecked (no setChecked). +/// +public sealed class PageCheckTests : PlaywrightTest +{ + private static readonly string[] AriaRoles = ["checkbox", "menuitemcheckbox", "option", "radio", "switch", "menuitemradio", "treeitem"]; + + [Test] + public async Task Should_check_the_box() + { + await Browser.GotoAsync(Content("")); + await Browser.Locator("input").CheckAsync(); + Assert.That(await Browser.EvaluateAsync("() => window.checkbox.checked"), Is.True); + } + + [Test] + public async Task Should_not_check_the_checked_box() + { + await Browser.GotoAsync(Content("")); + await Browser.Locator("input").CheckAsync(); + Assert.That(await Browser.EvaluateAsync("() => window.checkbox.checked"), Is.True); + } + + [Test] + public async Task Should_uncheck_the_box() + { + await Browser.GotoAsync(Content("")); + await Browser.Locator("input").UncheckAsync(); + Assert.That(await Browser.EvaluateAsync("() => window.checkbox.checked"), Is.False); + } + + [Test] + public async Task Should_not_uncheck_the_unchecked_box() + { + await Browser.GotoAsync(Content("")); + await Browser.Locator("input").UncheckAsync(); + Assert.That(await Browser.EvaluateAsync("() => window.checkbox.checked"), Is.False); + } + + [Test] + public async Task Should_check_radio() + { + await Browser.GotoAsync(Content(""" + one + two + three + """)); + await Browser.Locator("#two").CheckAsync(); + Assert.That(await Browser.EvaluateAsync("() => window.two.checked"), Is.True); + } + + [Test] + public async Task Should_check_radio_by_aria_role() + { + await Browser.GotoAsync(Content(""" + + + """)); + await Browser.Locator("div").CheckAsync(); + Assert.That(await Browser.EvaluateAsync("() => window.checkbox.getAttribute('aria-checked')"), Is.EqualTo("true")); + } + + // Upstream: { fail: '`uncheck` refuses a `role=radio`, where Playwright clicks it and refuses only a native radio' }. + [Test] + public async Task Should_uncheck_radio_by_aria_role() + { + await ExpectedToFailAsync(async () => + { + await Browser.GotoAsync(Content(""" + + + """)); + await Browser.Locator("div").UncheckAsync(); + Equal("false", await Browser.EvaluateAsync("() => window.checkbox.getAttribute('aria-checked')")); + }); + } + + [Test] + public async Task Should_check_the_box_by_aria_role() + { + foreach (var role in AriaRoles) + { + await Browser.GotoAsync(Content($$""" +
CHECKBOX
+ + """)); + await Browser.Locator("div").CheckAsync(); + Assert.That(await Browser.EvaluateAsync("() => window.checkbox.getAttribute('aria-checked')"), Is.EqualTo("true")); + } + } + + // Upstream: { fail: '`uncheck` refuses a `role=radio`, where Playwright clicks it and refuses only a native radio' }. + [Test] + public async Task Should_uncheck_the_box_by_aria_role() + { + await ExpectedToFailAsync(async () => + { + foreach (var role in AriaRoles) + { + await Browser.GotoAsync(Content($$""" +
CHECKBOX
+ + """)); + await Browser.Locator("div").UncheckAsync(); + Equal("false", await Browser.EvaluateAsync("() => window.checkbox.getAttribute('aria-checked')")); + } + }); + } + + [Test] + public async Task Should_throw_when_not_a_checkbox() + { + await Browser.GotoAsync(Content("
Check me
")); + var error = await Assert.CatchAsync(() => Browser.Locator("div").CheckAsync()); + Assert.That(error!.Message, Does.Contain("Not a checkbox or radio button")); + } + + [Test] + public async Task Should_throw_when_not_a_checkbox_2() + { + await Browser.GotoAsync(Content("
Check me
")); + var error = await Assert.CatchAsync(() => Browser.Locator("div").CheckAsync()); + Assert.That(error!.Message, Does.Contain("Not a checkbox or radio button")); + } + + [Test] + public async Task Should_check_the_box_inside_a_button() + { + await Browser.GotoAsync(Content("
")); + await Browser.Locator("input").CheckAsync(); + Assert.That(await Browser.EvaluateAsync("() => document.querySelector('input').checked"), Is.True); + Assert.That(await Browser.Locator("input").IsCheckedAsync(), Is.True); + } + + [Test] + public async Task Should_throw_when_trying_to_uncheck_radio_button() + { + await Browser.GotoAsync(Content("")); + var error = await Assert.CatchAsync(() => Browser.Locator("#radio").UncheckAsync()); + Assert.That(error!.Message, Does.Contain("uncheck cannot clear a radio button")); + } +} diff --git a/tests/E2E.NUnit.Tests/E2E.NUnit.Tests.csproj b/tests/E2E.NUnit.Tests/E2E.NUnit.Tests.csproj index ae5cb97ad..b71222b73 100644 --- a/tests/E2E.NUnit.Tests/E2E.NUnit.Tests.csproj +++ b/tests/E2E.NUnit.Tests/E2E.NUnit.Tests.csproj @@ -16,7 +16,9 @@ + + diff --git a/tests/E2E.NUnit.Tests/Helpers/Helpers.cs b/tests/E2E.NUnit.Tests/Helpers/Helpers.cs new file mode 100644 index 000000000..994ac1351 --- /dev/null +++ b/tests/E2E.NUnit.Tests/Helpers/Helpers.cs @@ -0,0 +1,69 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using System.Text; + +namespace E2E.NUnit.Tests; + +/// +/// The helpers of the tests ported from Playwright, upstream's apps/testbed/tests/helpers.ts: +/// content and PREFIX. is .NET-only (see its summary). +/// +internal static class Helpers +{ + /// The app's origin, Playwright's server.PREFIX in the tests ported from it. + public static string PREFIX => E2E.Playground.Testbed.Url; + + /// A path that serves as a page, for Playwright's page.setContent(html). + public static string Content(string html) => + "/content?html=" + Convert.ToBase64String(Encoding.UTF8.GetBytes(html)).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + /// + /// An equality check for a body run by . It throws: an NUnit assertion inside a test body is + /// recorded as a failure of the test even when the body catches it. + /// + public static void Equal(T expected, T actual) + { + if (!EqualityComparer.Default.Equals(expected, actual)) + { + throw new InvalidOperationException($"Expected {expected}, but was {actual}."); + } + } + + /// + /// Runs the body of a test upstream marks { fail: 'reason' }, a known difference from Playwright: the test passes while + /// still fails, and fails once it passes, so the marker is removed. The port has no fail test option + /// (see COMPATIBILITY.md), and NUnit has no expected-failure outcome. + /// + public static async Task ExpectedToFailAsync(Func body) + { + try + { + await body().ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + return; + } + + Assert.Fail("UNEXPECTED_PASS: the test is marked as a known difference from Playwright, and it passed. Remove the marker."); + } +} + +/// +/// The base of the classes ported from Playwright's page tests: the playground as the base URL, the cache off, and the playwright +/// category (upstream's tags: ['playwright']). +/// +[Category("playwright")] +public abstract class PlaywrightTest : E2ETest +{ + private static readonly E2EConfig FixtureConfig = E2EConfig.Parse( + """{ "cache": { "mode": "off" } }""", + AppContext.BaseDirectory, + _ => null); + + protected override E2EConfig Config => FixtureConfig; + + protected override string? BaseUrl => E2E.Playground.Testbed.Url; +} diff --git a/tests/E2E.NUnit.Tests/LocatorList/LocatorListTests.cs b/tests/E2E.NUnit.Tests/LocatorList/LocatorListTests.cs new file mode 100644 index 000000000..9d25b0898 --- /dev/null +++ b/tests/E2E.NUnit.Tests/LocatorList/LocatorListTests.cs @@ -0,0 +1,27 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using static E2E.NUnit.Tests.Helpers; + +namespace E2E.NUnit.Tests.LocatorList; + +/// +/// test.describe('locator list') of upstream's apps/testbed/tests/locator-list.e2e.ts (Playwright's +/// locator-list.spec.ts). div >> p is the CSS div p. +/// +public sealed class LocatorListTests : PlaywrightTest +{ + [Test] + public async Task Locator_all_should_work() + { + await Browser.GotoAsync(Content("

A

B

C

")); + var texts = new List(); + foreach (var p in await Browser.Locator("div p").AllAsync()) + { + texts.Add(await p.TextContentAsync()); + } + + Assert.That(texts, Is.EqualTo(new[] { "A", "B", "C" })); + } +} diff --git a/tests/E2E.NUnit.Tests/SelectorsText/SelectorsTextTests.cs b/tests/E2E.NUnit.Tests/SelectorsText/SelectorsTextTests.cs new file mode 100644 index 000000000..30eb20b81 --- /dev/null +++ b/tests/E2E.NUnit.Tests/SelectorsText/SelectorsTextTests.cs @@ -0,0 +1,62 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using System.Text.RegularExpressions; +using static E2E.NUnit.Tests.Helpers; + +namespace E2E.NUnit.Tests.SelectorsText; + +/// +/// test.describe('selectors text') of upstream's apps/testbed/tests/selectors-text.e2e.ts (Playwright's +/// selectors-text.spec.ts). locator(css, { hasText }) is a locator Filter(hasText). The 20 other tests are not +/// ported, as upstream: they need Playwright's text= selectors, :text pseudo-classes, >> chains, or element handles. +/// +public sealed partial class SelectorsTextTests : PlaywrightTest +{ + [Test] + public async Task Text_is_should_ignore_comments() + { + await Browser.GotoAsync(Content(""" +
hello + + world
+ """)); + Assert.That(await Browser.Locator("div").Filter(hasText: "hello world").GetAttributeAsync("id"), Is.EqualTo("me")); + Assert.That(await Screen.GetByText("hello world").GetAttributeAsync("id"), Is.EqualTo("me")); + } + + // Known difference, hardkoded/e2e-dotnet#1062: the first getByText('hello') match has no `id`. + [Test] + public async Task HasText_and_internal_text_should_match_full_node_text_in_strict_mode() + { + await ExpectedToFailAsync(async () => + { + await Browser.GotoAsync(Content(""" +
helloworld
+
hello
+ """)); + await Expect.That(Screen.GetByText("helloworld")).ToHaveAttributeAsync("id", "div1"); + await Expect.That(Screen.GetByText("hello")).ToHaveAttributeAsync("id", "div2"); + await Expect.That(Browser.Locator("div").Filter(hasText: HelloWorld())).ToHaveAttributeAsync("id", "div1"); + await Expect.That(Browser.Locator("div").Filter(hasText: Hello())).ToHaveAttributeAsync("id", "div2"); + + await Browser.GotoAsync(Content(""" +
helloworld
+
hello
+ """)); + await Expect.That(Screen.GetByText("helloworld")).ToHaveAttributeAsync("id", "div1"); + Equal("span1", await Screen.GetByText("hello").Nth(0).GetAttributeAsync("id")); + Equal("span2", await Screen.GetByText("hello").Nth(1).GetAttributeAsync("id")); + await Expect.That(Screen.GetByText("hello")).ToHaveCountAsync(2); + await Expect.That(Browser.Locator("div").Filter(hasText: HelloWorld())).ToHaveAttributeAsync("id", "div1"); + await Expect.That(Browser.Locator("div").Filter(hasText: Hello())).ToHaveAttributeAsync("id", "div2"); + }); + } + + [GeneratedRegex(@"^helloworld$")] + private static partial Regex HelloWorld(); + + [GeneratedRegex(@"^hello$")] + private static partial Regex Hello(); +} diff --git a/tests/E2E.NUnit.Tests/Testbed/playwright/LICENSE b/tests/E2E.NUnit.Tests/Testbed/playwright/LICENSE new file mode 100644 index 000000000..4ace03ddb --- /dev/null +++ b/tests/E2E.NUnit.Tests/Testbed/playwright/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Portions Copyright (c) Microsoft Corporation. + Portions Copyright 2017 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tests/E2E.NUnit.Tests/Testbed/playwright/NOTICE b/tests/E2E.NUnit.Tests/Testbed/playwright/NOTICE new file mode 100644 index 000000000..814ec1696 --- /dev/null +++ b/tests/E2E.NUnit.Tests/Testbed/playwright/NOTICE @@ -0,0 +1,5 @@ +Playwright +Copyright (c) Microsoft Corporation + +This software contains code derived from the Puppeteer project (https://github.com/puppeteer/puppeteer), +available under the Apache 2.0 license (https://github.com/puppeteer/puppeteer/blob/master/LICENSE). diff --git a/tests/E2E.NUnit.Tests/Testbed/playwright/assets/empty.html b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/empty.html new file mode 100644 index 000000000..e69de29bb diff --git a/tests/E2E.NUnit.Tests/Testbed/playwright/assets/grid.html b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/grid.html new file mode 100644 index 000000000..8345f429b --- /dev/null +++ b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/grid.html @@ -0,0 +1,66 @@ + + + diff --git a/tests/E2E.NUnit.Tests/WaitForUrl/PageWaitForUrlTests.cs b/tests/E2E.NUnit.Tests/WaitForUrl/PageWaitForUrlTests.cs new file mode 100644 index 000000000..29bb79f45 --- /dev/null +++ b/tests/E2E.NUnit.Tests/WaitForUrl/PageWaitForUrlTests.cs @@ -0,0 +1,127 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using System.Text.RegularExpressions; +using static E2E.NUnit.Tests.Helpers; + +namespace E2E.NUnit.Tests.WaitForUrl; + +/// +/// test.describe('page wait for url') of upstream's apps/testbed/tests/wait-for-url.e2e.ts (Playwright's +/// page-wait-for-url.spec.ts). Not ported, as upstream: should work with both domcontentloaded and load, should work with +/// commit, should work with commit and about:blank (no waitUntil), should work on frame (no frame.waitForURL). +/// +public sealed partial class PageWaitForUrlTests : PlaywrightTest +{ + private static string EmptyPage => $"{PREFIX}/empty.html"; + + [Test] + public async Task Should_work() + { + await Browser.GotoAsync(EmptyPage); + await Browser.EvaluateAsync("(url) => { window.location.href = url; }", $"{PREFIX}/grid.html"); + await Browser.WaitForURLAsync("/grid.html"); + } + + [Test] + public async Task Should_respect_timeout() + { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await Browser.GotoAsync(EmptyPage); + var promise = Assert.CatchAsync(() => Browser.WaitForURLAsync("/frame.html", TimeSpan.FromMilliseconds(2500))); + await Browser.GotoAsync(EmptyPage); + var error = await promise; + Assert.That(error!.Message, Does.Contain("frame.html")); + } + + [Test] + public async Task Should_work_with_clicking_on_anchor_links() + { + await Browser.GotoAsync(EmptyPage); + await Browser.GotoAsync(Content("foobar")); + await Browser.Locator("a").TapAsync(); + await Browser.WaitForURLAsync(FoobarSuffix()); + } + + [Test] + public async Task Should_work_with_history_pushState() + { + await Browser.GotoAsync(EmptyPage); + await Browser.GotoAsync(Content(""" + SPA + + """)); + await Browser.Locator("a").TapAsync(); + await Browser.WaitForURLAsync("/wow.html"); + Assert.That(await Browser.UrlAsync(), Is.EqualTo($"{PREFIX}/wow.html")); + } + + [Test] + public async Task Should_work_with_history_replaceState() + { + await Browser.GotoAsync(EmptyPage); + await Browser.GotoAsync(Content(""" + SPA + + """)); + await Browser.Locator("a").TapAsync(); + await Browser.WaitForURLAsync("/replaced.html"); + Assert.That(await Browser.UrlAsync(), Is.EqualTo($"{PREFIX}/replaced.html")); + } + + [Test] + public async Task Should_work_with_DOM_history_back_history_forward() + { + await Browser.GotoAsync(EmptyPage); + await Browser.GotoAsync(Content(""" + back + forward + + """)); + Assert.That(await Browser.UrlAsync(), Is.EqualTo($"{PREFIX}/second.html")); + + await Browser.Locator("a#back").TapAsync(); + await Browser.WaitForURLAsync("/first.html"); + Assert.That(await Browser.UrlAsync(), Is.EqualTo($"{PREFIX}/first.html")); + + await Browser.Locator("a#forward").TapAsync(); + await Browser.WaitForURLAsync("/second.html"); + Assert.That(await Browser.UrlAsync(), Is.EqualTo($"{PREFIX}/second.html")); + } + + [Test] + public async Task Should_work_with_url_match_for_same_document_navigations() + { + await Browser.GotoAsync(EmptyPage); + var resolved = false; + var waitPromise = Task.Run(async () => + { + await Browser.WaitForURLAsync(ThirdHtml()); + resolved = true; + }); + Assert.That(resolved, Is.False); + await Browser.EvaluateAsync("() => { history.pushState({}, '', '/first.html'); }"); + Assert.That(resolved, Is.False); + await Browser.EvaluateAsync("() => { history.pushState({}, '', '/second.html'); }"); + Assert.That(resolved, Is.False); + await Browser.EvaluateAsync("() => { history.pushState({}, '', '/third.html'); }"); + await waitPromise; + Assert.That(resolved, Is.True); + } + + [GeneratedRegex(@"#foobar$")] + private static partial Regex FoobarSuffix(); + + [GeneratedRegex(@"third\.html")] + private static partial Regex ThirdHtml(); +} From b9f92cf450fe125e214362320fa98dd8fbc18cba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Kondratiuk?= Date: Wed, 4 Nov 2026 18:43:21 -0300 Subject: [PATCH 2/4] Link the routes into the xUnit test project and pin the known difference of expected failures (Refs #1060) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Ls2e1yaZFgZ3FEJkYScfkK --- tests/E2E.NUnit.Tests/Check/PageCheckTests.cs | 4 ++-- tests/E2E.NUnit.Tests/Helpers/Helpers.cs | 5 +++-- tests/E2E.NUnit.Tests/SelectorsText/SelectorsTextTests.cs | 2 +- tests/E2E.XUnit.V3.Tests/E2E.XUnit.V3.Tests.csproj | 1 + 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/tests/E2E.NUnit.Tests/Check/PageCheckTests.cs b/tests/E2E.NUnit.Tests/Check/PageCheckTests.cs index 174b0c70e..0895e69e9 100644 --- a/tests/E2E.NUnit.Tests/Check/PageCheckTests.cs +++ b/tests/E2E.NUnit.Tests/Check/PageCheckTests.cs @@ -76,7 +76,7 @@ await Browser.GotoAsync(Content(""" [Test] public async Task Should_uncheck_radio_by_aria_role() { - await ExpectedToFailAsync(async () => + await ExpectedToFailAsync("uncheck", async () => { await Browser.GotoAsync(Content(""" @@ -109,7 +109,7 @@ await Browser.GotoAsync(Content($$""" [Test] public async Task Should_uncheck_the_box_by_aria_role() { - await ExpectedToFailAsync(async () => + await ExpectedToFailAsync("uncheck", async () => { foreach (var role in AriaRoles) { diff --git a/tests/E2E.NUnit.Tests/Helpers/Helpers.cs b/tests/E2E.NUnit.Tests/Helpers/Helpers.cs index 994ac1351..da38a9b5c 100644 --- a/tests/E2E.NUnit.Tests/Helpers/Helpers.cs +++ b/tests/E2E.NUnit.Tests/Helpers/Helpers.cs @@ -33,10 +33,10 @@ public static void Equal(T expected, T actual) /// /// Runs the body of a test upstream marks { fail: 'reason' }, a known difference from Playwright: the test passes while - /// still fails, and fails once it passes, so the marker is removed. The port has no fail test option + /// still fails with a message that contains , and fails once it passes, so the marker is removed. The port has no fail test option /// (see COMPATIBILITY.md), and NUnit has no expected-failure outcome. /// - public static async Task ExpectedToFailAsync(Func body) + public static async Task ExpectedToFailAsync(string failure, Func body) { try { @@ -44,6 +44,7 @@ public static async Task ExpectedToFailAsync(Func body) } catch (Exception ex) when (ex is not OperationCanceledException) { + Assert.That(ex.Message, Does.Contain(failure), "the body failed, but not with the known difference"); return; } diff --git a/tests/E2E.NUnit.Tests/SelectorsText/SelectorsTextTests.cs b/tests/E2E.NUnit.Tests/SelectorsText/SelectorsTextTests.cs index 30eb20b81..c14218e4a 100644 --- a/tests/E2E.NUnit.Tests/SelectorsText/SelectorsTextTests.cs +++ b/tests/E2E.NUnit.Tests/SelectorsText/SelectorsTextTests.cs @@ -30,7 +30,7 @@ await Browser.GotoAsync(Content(""" [Test] public async Task HasText_and_internal_text_should_match_full_node_text_in_strict_mode() { - await ExpectedToFailAsync(async () => + await ExpectedToFailAsync("Expected span1", async () => { await Browser.GotoAsync(Content("""
helloworld
diff --git a/tests/E2E.XUnit.V3.Tests/E2E.XUnit.V3.Tests.csproj b/tests/E2E.XUnit.V3.Tests/E2E.XUnit.V3.Tests.csproj index 9d764e906..43d87e126 100644 --- a/tests/E2E.XUnit.V3.Tests/E2E.XUnit.V3.Tests.csproj +++ b/tests/E2E.XUnit.V3.Tests/E2E.XUnit.V3.Tests.csproj @@ -19,6 +19,7 @@ + From a21cd423c5137c1ef0d79d995923100e64e597fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Kondratiuk?= Date: Wed, 4 Nov 2026 18:59:25 -0300 Subject: [PATCH 3/4] Port Playwright's route, request-fallback and request-fulfill tests and the rest of routes.mjs (Refs #1060) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Ls2e1yaZFgZ3FEJkYScfkK --- tests/E2E.Agent.Tests/PlaywrightRoutes.cs | 389 ++++++++- tests/E2E.Agent.Tests/Testbed.cs | 18 +- tests/E2E.NUnit.Tests/Helpers/Helpers.cs | 53 ++ .../PageRequestFallbackTests.cs | 112 +++ .../RequestFulfill/PageRequestFulfillTests.cs | 322 +++++++ tests/E2E.NUnit.Tests/Route/PageRouteTests.cs | 800 ++++++++++++++++++ .../Testbed/playwright/assets/global-var.html | 3 + .../Testbed/playwright/assets/one-style.css | 3 + .../Testbed/playwright/assets/one-style.html | 3 + .../Testbed/playwright/assets/pptr.png | Bin 0 -> 6138 bytes .../Testbed/playwright/assets/preload.html | 5 + .../Testbed/playwright/assets/title.html | 2 + 12 files changed, 1701 insertions(+), 9 deletions(-) create mode 100644 tests/E2E.NUnit.Tests/RequestFallback/PageRequestFallbackTests.cs create mode 100644 tests/E2E.NUnit.Tests/RequestFulfill/PageRequestFulfillTests.cs create mode 100644 tests/E2E.NUnit.Tests/Route/PageRouteTests.cs create mode 100644 tests/E2E.NUnit.Tests/Testbed/playwright/assets/global-var.html create mode 100644 tests/E2E.NUnit.Tests/Testbed/playwright/assets/one-style.css create mode 100644 tests/E2E.NUnit.Tests/Testbed/playwright/assets/one-style.html create mode 100644 tests/E2E.NUnit.Tests/Testbed/playwright/assets/pptr.png create mode 100644 tests/E2E.NUnit.Tests/Testbed/playwright/assets/preload.html create mode 100644 tests/E2E.NUnit.Tests/Testbed/playwright/assets/title.html diff --git a/tests/E2E.Agent.Tests/PlaywrightRoutes.cs b/tests/E2E.Agent.Tests/PlaywrightRoutes.cs index c27600fb8..183b3d980 100644 --- a/tests/E2E.Agent.Tests/PlaywrightRoutes.cs +++ b/tests/E2E.Agent.Tests/PlaywrightRoutes.cs @@ -2,8 +2,12 @@ // Modified by Dario Kondratiuk. // SPDX-License-Identifier: Apache-2.0 +using System.Collections.Concurrent; using System.Net; +using System.Net.WebSockets; using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; namespace E2E.Playground; @@ -11,10 +15,17 @@ 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 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 const int MaxDelayMs = 30_000; + private const int MaxBytes = 16 << 20; + + // .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) @@ -29,19 +40,200 @@ 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; } + 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) + { + 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; + } + + 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; + } + + var received = await BodyAsync(request).ConfigureAwait(false); + response.ContentType = "text/plain"; + await WriteAsync(response, Echo(request, received)).ConfigureAwait(false); + return; + } + + case "/bounce": + { + var options = request.HttpMethod == "OPTIONS"; + if (!options) + { + response.RedirectLocation = SameServer(query.GetValueOrDefault("to"), port); + } + + 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("set-cookie", cookie); + } + + response.StatusCode = options ? 204 : Number(query.GetValueOrDefault("status"), 302); + 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; + } + + 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('/'))); if (!file.StartsWith(Root + Path.DirectorySeparatorChar, StringComparison.Ordinal) || !File.Exists(file)) { @@ -56,6 +248,187 @@ public static async Task HandleAsync(HttpListenerContext context) await WriteAsync(response, await File.ReadAllBytesAsync(file).ConfigureAwait(false)).ConfigureAwait(false); } + /// + /// /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) + { + 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(); + } + } + + /// A redirect target on this server (a path, or either origin), else the empty page. + private static string SameServer(string? target, int port) + { + 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")) + { + 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) + { + 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; + } + } + } + } + + /// 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) + { + break; + } + + 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 = 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; + } + + 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 Task HoldAsync() => Task.Delay(HeldRequestLimit); + private static byte[] FromBase64Url(string value) { var padded = value.Replace('-', '+').Replace('_', '/'); diff --git a/tests/E2E.Agent.Tests/Testbed.cs b/tests/E2E.Agent.Tests/Testbed.cs index d2a2336cf..69754630d 100644 --- a/tests/E2E.Agent.Tests/Testbed.cs +++ b/tests/E2E.Agent.Tests/Testbed.cs @@ -929,6 +929,7 @@ private static string Start() url = "http://127.0.0.1:" + port.ToString(CultureInfo.InvariantCulture) + "/"; listener = new HttpListener(); listener.Prefixes.Add(url); + listener.Prefixes.Add("http://localhost:" + port.ToString(CultureInfo.InvariantCulture) + "/"); try { listener.Start(); @@ -1014,13 +1015,28 @@ await WriteHtmlAsync(response, "Dashboard", """ } else { - await PlaywrightRoutes.HandleAsync(context).ConfigureAwait(false); + // The Playwright routes hold requests open (/never, /sse, /ws), so they do not block the loop. + _ = ServePlaywrightRoutesAsync(context); + continue; } response.Close(); } } + private static async Task ServePlaywrightRoutesAsync(HttpListenerContext context) + { + try + { + await PlaywrightRoutes.HandleAsync(context).ConfigureAwait(false); + context.Response.Close(); + } + catch (Exception) + { + context.Response.Abort(); + } + } + private static async Task WriteHtmlAsync(HttpListenerResponse response, string title, string body) { var bytes = Encoding.UTF8.GetBytes(Layout(title, body)); diff --git a/tests/E2E.NUnit.Tests/Helpers/Helpers.cs b/tests/E2E.NUnit.Tests/Helpers/Helpers.cs index da38a9b5c..80d7941cb 100644 --- a/tests/E2E.NUnit.Tests/Helpers/Helpers.cs +++ b/tests/E2E.NUnit.Tests/Helpers/Helpers.cs @@ -15,6 +15,9 @@ internal static class Helpers /// The app's origin, Playwright's server.PREFIX in the tests ported from it. public static string PREFIX => E2E.Playground.Testbed.Url; + /// Another origin on the same app, Playwright's server.CROSS_PROCESS_PREFIX. + 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) => "/content?html=" + Convert.ToBase64String(Encoding.UTF8.GetBytes(html)).TrimEnd('=').Replace('+', '-').Replace('/', '_'); @@ -31,6 +34,56 @@ 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) + { + 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/pptr.png b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/pptr.png new file mode 100644 index 0000000000000000000000000000000000000000..65d87c68e65902c058af18d2a595fc89f423f4ff GIT binary patch literal 6138 zcmZu#cQjmWw;y9L%IID6F3RYg=q(tXsDlyR=)DagT6krUFiIrRiC%*dq6>-MMT<^? zh#Z0{rl~`P72IO2SUP30ssIYdb*mXIH`pju3$pkdn)>_ z6DL5A)eO}DfQC%cTQ~u3&f%hKY6t*C@BsjEi2%TFoGNY)00@Qx00&M0fWiv^fB}i= zG*QBRAapj+(FFYc_bKTve~!}-BXw;80RU2(e+M2QAH#@K5(ViQY7u=Up~B-QgS)T2 z1pw&x^)%JY!S$ZHQO&^aI)0-lv;<>80 zWA#UG$S*B4?TsqlUBshCdEDvPHNcV*OdOyOSy@aH)WgWr#na4aKR#bVDS|H_LulpcHxOMdr_XTVAT!R8 zhP{h>9N8B}El0+vnW!71Xz}AHA^Qa~g_3$0 zM2{yfOO-^-2o%Oog%|oeW7_?Er$4z+&KEfYAyEqZ_(l9LNWkxt8Eyc1uUE%(5$VX=D%> z*~dY;KVcMRNjv^nyx<=5xGrjl-$4Bi>lp{HsFgCI_;%Qhl2+U> zm(l&Sydg~V>~ETryTDi&Svy11NHU(uCG`DjUlzw(A1_1Y;<1EK8SvaGsK0{10qEe~ z8K}cr%WxK%2*zf?V8D+%Kx5gnb6`^)IiJa7Q5_`%M9-gck6S?ads%yw98zrb?gy+e zAhPc%K@pL|fH(6f_Jxs>yrD#-#6>2EzX@o1MQT|1?Hc$ig56tHSfHB>yc*)`Wl~%D zoZH|#(VxtU`W~`z4+xG2DQoF!%7@MYX~tDPcpg)98Z!+wcJ-xQ>RDqh%vS8kBvDM zpJ&{|>UT@LIb|9tPH&A&Er}i9fMrfBkxF))g7jsX=m9NMn%Nj~?g*v=k(ZJCi+|6D z`<`ODPQ1qh%Fl4A$S~1vI)9V<&^NBmpnFyf8*lh%|V7Lv9 zEAZ0gSkfyWP@2G@!Ju^Gti)f7b_;mv<8}mFWA<5&HBKwh{7X}79H2Snp$6Zz%zs{z zn)VPXEnjR*WT=?Pm_>sb%6-XB2q<_A2(J=9m|8zC9T&eUMM+9n_Ayb;lHH>ne)ki* zWDZYwP85X~l^#881tpYVn}FP=u+*KVJcSuQKMC+85%a-Y+S&!5cMI+3MrVhjXAvz3om5A5i$g9^bN4R zyb(p3-qMi*8AOgG_KEb@ca03Ll4xr_Mg22H`evZ`$uG36%*>c_4c&M zo{&`g)%f!GzXOXk{*NgL9=o%*yCyXCkq^C%-_g`4-`$Wx-X|z0L~=>cmZirLC-A}7 zuKz~eUkhJOi^QlDVia{BDRWG9Bu}0Y*{7Uf@o?r|x)}qS)OQI&!0W!Mk%J&RAWr%W z(C !4@^Vx1sD`7N#d=xeNFoPC9oyU-cfsEl&6lomsESF+tG@eQK*Rh_E6^MP|L zo%KhZgeJ4+BV`4()-B z#Ckf_O^nXtPvaSQL8R@8XhW9+>9Po;D5BIdcIJ zb_gd{&^-S;#RkSlET{ExEEXc*B_^Oi36Cr!omp~V2NeNS%I1D}{VX^BIwctUJ2aU| zFZ*Sv!3j7i&k`(})8DEAJ@*Cw!1H4HKx>FyRQfgK*8V8tET})|>OnJ`eZ9B*Q^XB? z`w16JZ~yO-ldH^P+FdvM#!?XsG&SKlY=HirmQi($^)y&4rj3b|ro)m3Sg|weP zd~PH-3;SE`4^?nzgqJ({2uW09W5iqW*zs&cFp=_}u7~LXuP{GRo4(7Oc3wq4t0_s9 zfDbk1HTD?rrfGOz6UMzO?>xxRW{1>R%K5YPEQl`TkrOLhfZ16sDTdZ26L0#DZp>F2 z;dxHezJ-C;nZSNn-8nIGuCHUKWE8)y!nMt!CHR84%{~Xb!D-F|u6mcEqt$x_|B|rB zf_KHQpUr}8=QC-la`iV%-Kg${nLqm5-7C8yX|2`p`D=;SWiI~ZYl{$0?*6-FVbTGnGAf&_W7wTRDsr$m-+;xVxJK0?k+N4NA*T;MB8nG>oS<0q2gCBorvAyaxKELp(B zSEc84wbHG%PYwmpUgobAnr*Pf(Ea|DjDW2a!EFAr3hfR#d2lC>t7~7QA*#2Q{^+4b zSf_JOD5DWYrq&+wTmlo+3$lfNCsZEd? zQ-ng9vg->``!I+x&JvO1qvBYxML!$SH!#sHkhSco_}dDql~Pea6=zs zoJW`=fy-m&xmqG|bBsSZ9oZoM>KdC#OohY}hoZXVd*FO>+fzjgos0CdF6SoVm3R|fSV>xs37S|g*GEi=z zs?%b~Fk28}QTXh%;+X_FYDJ|xNvxloG81@}rh*C{D!L%~c_4AmB2lrg3CzOo5>F_z z+9wRD!|KCW#k}(jvZBrrH>%IGZUe%yV)spZImwcsrWpY;ec1w-n@|g1KcM#bXcwZ;5lYka^TJIF;KV1+R7U8{NY=S1$7-6R$p{;o{5m6;O(Y=95@Y{1O) zymYpbRC`BntLXWU5(s%5&bJ5!$0}=3%0uu=%f33PEb3a@`q8p#Pg7Wf0ir)anh3$t z@Q>QGUpFCH|j;?a!5nS@VjGq%KVAJ6joJ^Hu1uh zxTe656kUgcGo zVuEbUyeVWkrA^6FtCE_j9PB9~3xt1I_QozP&X-7ysH?U_HNbkkC)t&udgFYRLqodC z;+C76uB!8Xaa0xId+fC)0>x&Ebn0C7>>LbXEIFL(?u^eiRx+w)@}w0UTb}J!9XGu_ z_OI80wWJ9-5!aKqRBc$G5zUpzK>QtGx~9cf3D}tApqVNnk~W9tj^}QowW+DXXn}z4 z&${=RyP?qofvU_4Z4tR_fwY%1Unp$5M&Ve-!5 z2HS%C?uuG9rle7w2Tyi$f*x9w65@AJo4idtOxjG$Uv9YiV&&ei`9(xXZwsbE!g%Xa za-l}mQvK9+9q|bD1v(j^ZI4WrKFBReS3``4Al8p^?=%-D*JI$xuk~|$k~aHWl!GQF zd}oc(-B{Zc=J?K%-{UeGOixF}j;hLbI&z+sP#+|33)?OaZE`dQgS0fR3s^iEt6P*G z75cvan3F-m&r|h-&!od_zV*TWvjbzEEZ@jF&3{gY8%ykT+tfxhI;PIbSQHMTb%3EI zz-HwN=K%T9CoAoj+%`HAusMg612JCDZhP?P6U!;5Vc(?(R_5x`pIQ^r1kO8CM?*dL z+XH|RrCdu7X9&oFpYUIMK&uyMM};{DzU=L}&lf32I?KE~Y|Uy+NE8sklu>?YO&Kut z`l|VxSVBUAOmL@3>IH=-_^oWc|CjFPof8GJnI$D0LH0WODR4$G=adwrADU%ax|kcn zlBA|%5fh^#)_qIu7<0X2Geh#-Wvcx(D?20Og3l+6d}4C43nL*D6B8{xeW?dC0)fED z`J?ig>FO}bk+~Smy+lgZpHysYpD>Go>2Yy!im)AmeD#zcS6BQ{U4jM=50Bd)UmY8N ziKSK6)$JCBu7B-IX5*2T&cT_+oU`|S?dX^^ad2>WoXcuxS)Eg|!6CxI0bs^8Ey#<{ ziIiZFss75!3Ye6Xn}-KvKTmu{!J(vdPfSbn0f$%~(D4*{~oCUL#6(R?OKbIJb91l_;?NPW5xqEy(fg&J% zA?-B>A$Xpht?uT=C+RkhotQXwjCoJLI^^82vAa81;MX&9Fk79Hk^=v}`4OWSO5P7W zD3g7IwieFq+^3A(wR!Ytbhi5P3cl1UNtW>Ci)mH$yE~0q+$}~&nT>7V*>~k?rP2HE ze|f82oR^np=HL)Bp;A>tV4v-fSEmj!he@ zPAoLI*mMN&+P3+AoSn^?nKADS+W!zZsXSB<>5R&ay|O$`v8sc#>vU2GQ)zf!`e0h0f7>~ z^`3DYex5!B(~H_YUG(OYlzfi6e6EPCHnM(8D_i7IDkZA1QDS$pc=C0o%ILCRuVGY_ zQlVm~TYnM+qf+a}92gjA(;K6V%PNd~VA9T5Uen`Aw!w5J4IJW+pc^@nBmCN?xCC0-psr_1~xXf7Z3SR z2?_f%l{5xo4`#mSm30ay zTU-5y?|O~Y)qz_>nU6OIQoL6?=?tgA5XjDP+d3Z~Us7Ts$n6tmWOt&#rpXPG1kcLJ zv1nWO>%Gh6FOJIg-x_QPIez32zC(vY@AXmB(jMIiCk|7=I8V1?pso_vSt(%uyocv&&{2y z(4TMS@|7t#)Xy&}D%$IGn2(i{m!A#J#jy*RvpwQcXm)lML_|cxz>r+#p{c1k^;##> ztIQM9Us6_wvZJZ>&|-)rY&WBqSu(?MTkzs2{|!w_EI= zg9|w|k~k7KRyqRTpM4;$vFpfwLdvkYwWVQdN{s^@Egjw0lM^E(6517dI_TMg<67Lg zx4(Tm?;~P|Sz2m4J9AxMUx!6T(oj-jKNTucsY4?!+=J}P8ymB6H37%_!=s}gR##c8 zXP0(Oz0z{2X=yc2*Sf_ESl-2vKp+SlnG4%ACaV6uo+M*cpydReoSZNw#kaM|^78U3 z-5fQwcXWK;OcTq_%EBf=SkBJRw{VA5IvtyY!y(eZQP{JRfB7n|f=&@aHU96?y#w@h@QDj66I%lr%INnwlU|df|=k zt2LL)gIN$Ep+xMTD23nyO;=Z*SFc|ApuWJ^2Zn~mva_i@tPqH|!lI(N^l4f$7Ct_; zO3}ZY$H&LfxO{DFZ?|Sn;>;7a;ljtq--*X3a@E#OdXN07zUqgApcpq7muo~s=R;%T zyzubwjGs1UX57ZbDk9U<)41A&czsGjO1guCh^vQ3CE9fK;J`EdU`8+;N21}l%+p@p z-QFHiW_3vHd-qyD?598)`Ax!npY>Q zhii(8in0NUIBjWZ-Q7FGekd|DG&F2>+%52Rv<$kpSM|@IKf$Mk7z{4Kg4%s_b-|pR zoWZA0C`F#h%r_r*9#_)gqVRQRM+-L9QvIIaxai?KhwihVKYdU8TdS8?^?PIP_U7Le z_n%TzQ|s#LwlDhlTC_E}{%?Iy*i0=bll*&JR2Rx4(3nx2CiADR0_o(?DF} W{|p>bpZvrb0Q9tsH0#uzQ2zrM7gd%3 literal 0 HcmV?d00001 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 From ce17a04b69af53a7c69dcccfd3b62ea99775a0d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Kondratiuk?= Date: Wed, 4 Nov 2026 19:02:29 -0300 Subject: [PATCH 4/4] Fail AllAsync as soon as the action fails (Refs #1060) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Ls2e1yaZFgZ3FEJkYScfkK --- tests/E2E.NUnit.Tests/Helpers/Helpers.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/E2E.NUnit.Tests/Helpers/Helpers.cs b/tests/E2E.NUnit.Tests/Helpers/Helpers.cs index 80d7941cb..fa08888c1 100644 --- a/tests/E2E.NUnit.Tests/Helpers/Helpers.cs +++ b/tests/E2E.NUnit.Tests/Helpers/Helpers.cs @@ -80,6 +80,12 @@ public static Served Parse(string json) => /// 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; }