diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index da500f3cc..0fcf3a13c 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -905,7 +905,7 @@ Differences from upstream: - `Browser.EvaluateAsync` takes the script as a string (an expression, or a function source that is called with the optional argument) and deserializes the JSON result to `T`. A throwing script fails with `EVALUATE_FAILED` and the message it threw, a result that is not JSON (such as `Infinity`) with `INVALID_ARGUMENT`, and a browser that closes under it with `ENGINE_FAILURE`. - `Browser.RouteAsync` takes the same glob string or `Regex` as `WaitForResponseAsync`, and a handler that returns a `Task`. `WebRoute` has `Request`, `FetchAsync` (`WebResponse`: `Url`, `Status`, `Headers`, `TextAsync`, `JsonAsync`; takes no options, adds the configured site headers, runs under the action timeout, never follows a redirect, and does not decide the route; a body the browser could not read fails `TextAsync` and `JsonAsync` with `ACTION_FAILED` naming `route.fetch`), `FulfillAsync` (`RouteFulfillResponse`: `Status`, `Headers`, `ContentType`, `Json`, `Body`, `Path`), `ContinueAsync` (`RouteContinueOverrides`: `Url`, `Method`, `Headers`, `PostData`), `FallbackAsync`, and `AbortAsync`, with upstream's checks, codes, and messages. `UnrouteAsync` removes the routes added with an equal glob, or a `Regex` with the same source and options. `UnrouteAllAsync` removes every route added through the browser and keeps the configured site headers. `Path` resolves against the project root (`E2ESessionOptions.ProjectRoot`, which `E2ETest` sets to the config's directory, else the working directory). Differences: options are typed, so an unknown key, a non-string header value, and an `abort` error code do not compile instead of failing with `INVALID_ARGUMENT`; `Json` is serialized with `System.Text.Json` web defaults, and `null` means no JSON body; a handler error raised after the test's last browser call is collected by `E2ESession.SettleAttemptAsync` (as upstream's `settleAttempt`) and fails the attempt at its end, as for a dialog handler (see the `OnDialogAsync` entry): the settle waits within the cleanup timeout for a handler still running, and one that outlives it fails the attempt with `CLEANUP_TIMEOUT` naming it, after which what it throws is dropped. - `Browser.AddInitScriptAsync` takes source or a `WebInitScript`, and a JSON argument only with `WebInitScript.FromFunction`, the function's JavaScript source. -- Each async `Browser` call is a harness step of kind `resource`, as upstream's `FixtureRecorder` records it, with the api name `browser.goto`, `reload`, `back`, `forward`, `url`, `title`, `waitForURL`, `evaluate`, `addInitScript`, `route`, `unroute`, `unrouteAll`, `waitForResponse`, `cookies`, `setCookies`, `clearCookies`, `setViewport`, `emulateMedia`, `onDialog`, `waitForDownload`, `waitForDownloads`, and `keyboard.*` and `mouse.*`, and upstream's labels (a URL or pattern, the key, ` chars` for typed text, the init script's path or kind, the media features). `browser.waitForURL` verifies, and `expect(browser)` matchers are `assertion` steps nested in it. A pattern label writes a regex as `/source/flags`, since .NET has no `String(RegExp)`. `Browser.Locator` and `FrameLocator` are not async and record nothing, as upstream. Argument checks the type system makes upstream's (a predicate pattern, an unknown option key) do not exist, so upstream's `fails with INVALID_ARGUMENT at %s` and `an option waitForURL does not take is refused` tests have no port. The port does not wrap each call in the action timeout, as `FixtureRecorder.run` does: a call keeps the bound it had. `Browser.ClearCookiesAsync(CookieFilter?)` is upstream's `clearCookies(options)`: a filter field is a `TextMatch` (a string matches exactly, a `Regex` matches the text, run by Playwright as JavaScript), and `Context.ClearCookiesAsync` does the removal. Upstream's `refuses an unknown filter and a value that is not a string or RegExp, clearing nothing` test and `tests/types/clear-cookies.ts` have no port: `CookieFilter` has no `url` member and the compiler refuses a field that is neither, so there is no `INVALID_ARGUMENT` path. +- Each async `Browser` call is a harness step of kind `resource`, as upstream's `FixtureRecorder` records it, with the api name `browser.goto`, `reload`, `back`, `forward`, `url`, `title`, `waitForURL`, `evaluate`, `addInitScript`, `route`, `unroute`, `unrouteAll`, `waitForResponse`, `cookies`, `setCookies`, `clearCookies`, `setViewport`, `emulateMedia`, `onDialog`, `waitForDownload`, `waitForDownloads`, and `keyboard.*` and `mouse.*`, and upstream's labels (a URL or pattern, the key, ` chars` for typed text, the init script's path or kind, the media features). `browser.waitForURL` verifies, and `expect(browser)` matchers are `assertion` steps nested in it. A pattern label (upstream's `patternLabel`) writes a glob string quoted, as `JSON.stringify` does, and a regex as `/source/flags`, since .NET has no `String(RegExp)`. `Browser.Locator` and `FrameLocator` are not async and record nothing, as upstream. Argument checks the type system makes upstream's (a predicate pattern, an unknown option key) do not exist, so upstream's `fails with INVALID_ARGUMENT at %s` and `an option waitForURL does not take is refused` tests have no port. The port does not wrap each call in the action timeout, as `FixtureRecorder.run` does: a call keeps the bound it had. `Browser.ClearCookiesAsync(CookieFilter?)` is upstream's `clearCookies(options)`: a filter field is a `TextMatch` (a string matches exactly, a `Regex` matches the text, run by Playwright as JavaScript), and `Context.ClearCookiesAsync` does the removal. Upstream's `refuses an unknown filter and a value that is not a string or RegExp, clearing nothing` test and `tests/types/clear-cookies.ts` have no port: `CookieFilter` has no `url` member and the compiler refuses a field that is neither, so there is no `INVALID_ARGUMENT` path. - Navigation URLs resolve with `System.Uri`, not WHATWG. As upstream, only `http:`, `https:`, and the exact `about:blank` are admitted. But a tab or newline inside a URL is escaped, not stripped, so `view-\tsource:file:` opens as an http path under the base URL (or fails with `APP_URL_REQUIRED` without one) instead of `POLICY_DENIED`. A percent-encoded unreserved character in the path is decoded (`%66ile:` becomes `file:`). Neither opens a scheme other than http(s). `DocumentEngine` supports `app.back` (it rebuilds the previous route), `app.restart`, and `app.clearState` (both drop the history and reopen the base URL). It has no viewport: `DocumentPage.OnScroll` and `DocumentElement.OnScroll` let a page load more rows when it is scrolled. It has no browser, so every `Browser` member fails with `UNSUPPORTED_CAPABILITY`. A custom engine opts in by implementing `IBrowserSession`, and by overriding the default `BackAsync`, `RestartAsync`, and `ClearStateAsync` on `IEngineSession`, which otherwise fail with `UNSUPPORTED_CAPABILITY`. diff --git a/src/E2E/Internal/Routes.cs b/src/E2E/Internal/Routes.cs index 5a24c9194..8c218179d 100644 --- a/src/E2E/Internal/Routes.cs +++ b/src/E2E/Internal/Routes.cs @@ -3,6 +3,8 @@ // SPDX-License-Identifier: Apache-2.0 using System.Text; +using System.Text.Encodings.Web; +using System.Text.Json; using System.Text.RegularExpressions; namespace E2E.Internal; @@ -147,13 +149,19 @@ public static Func Matcher(object pattern) => _ => false, }; - /// The step label of a URL pattern, as upstream's String(pattern) writes it: a glob as it is, a regex as /source/flags. - public static string Label(object pattern) => pattern switch + /// + /// A URL pattern as steps and errors name it, upstream's patternLabel: a glob string quoted (JSON.stringify), a regex as + /// /source/flags (String(RegExp)). + /// + public static string PatternLabel(object pattern) => pattern switch { + string glob => JsonSerializer.Serialize(glob, QuoteOptions), Regex regex => "/" + regex + "/" + (regex.Options.HasFlag(RegexOptions.IgnoreCase) ? "i" : "") + (regex.Options.HasFlag(RegexOptions.Multiline) ? "m" : "") + (regex.Options.HasFlag(RegexOptions.Singleline) ? "s" : ""), - _ => (string)pattern, + _ => throw new ArgumentException("A URL pattern is a string or a Regex.", nameof(pattern)), }; + private static readonly JsonSerializerOptions QuoteOptions = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; + [GeneratedRegex("^[A-Za-z][A-Za-z0-9+.-]*:")] private static partial Regex SchemePattern(); } diff --git a/src/E2E/Run/Browser.cs b/src/E2E/Run/Browser.cs index 0403ef0b3..1fa832862 100644 --- a/src/E2E/Run/Browser.cs +++ b/src/E2E/Run/Browser.cs @@ -140,7 +140,7 @@ public Task TitleAsync(CancellationToken cancellationToken = default) => public Task WaitForURLAsync(string url, TimeSpan? timeout = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(url); - return RunStepAsync(StepKind.Resource, "browser.waitForURL", url, () => + return RunStepAsync(StepKind.Resource, "browser.waitForURL", Routes.PatternLabel(url), () => { Require("waitForURL"); return new BrowserExpect(this, negated: false).ToHaveURLAsync(url, timeout: timeout, cancellationToken: cancellationToken); @@ -151,7 +151,7 @@ public Task WaitForURLAsync(string url, TimeSpan? timeout = null, CancellationTo public Task WaitForURLAsync(Regex pattern, TimeSpan? timeout = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(pattern); - return RunStepAsync(StepKind.Resource, "browser.waitForURL", Routes.Label(pattern), () => + return RunStepAsync(StepKind.Resource, "browser.waitForURL", Routes.PatternLabel(pattern), () => { Require("waitForURL"); return new BrowserExpect(this, negated: false).ToHaveURLAsync(pattern, timeout: timeout, cancellationToken: cancellationToken); @@ -513,7 +513,7 @@ private async Task AddInitScriptStepAsync(WebInitScript script, object? arg, boo } private Task WaitForResponseCoreAsync(object pattern, Func> matcher, TimeSpan? timeout, CancellationToken cancellationToken) => - RunStepAsync(StepKind.Resource, "browser.waitForResponse", Routes.Label(pattern), async () => + RunStepAsync(StepKind.Resource, "browser.waitForResponse", Routes.PatternLabel(pattern), async () => { var session = Require("waitForResponse"); var response = await session.WaitForResponseAsync(matcher(), timeout ?? _actionTimeout, Token(cancellationToken)).ConfigureAwait(false); @@ -523,7 +523,7 @@ private Task WaitForResponseCoreAsync(object pattern, Func handler, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(handler); - return RunStepAsync(StepKind.Resource, "browser.route", Routes.Label(pattern), () => RouteStepAsync(pattern, handler, cancellationToken)); + return RunStepAsync(StepKind.Resource, "browser.route", Routes.PatternLabel(pattern), () => RouteStepAsync(pattern, handler, cancellationToken)); } private async Task RouteStepAsync(object pattern, Func handler, CancellationToken cancellationToken) @@ -544,7 +544,7 @@ async Task Decide(IBrowserRoute engineRoute) } private Task UnrouteCoreAsync(object pattern, CancellationToken cancellationToken) => - RunStepAsync(StepKind.Resource, "browser.unroute", Routes.Label(pattern), () => + RunStepAsync(StepKind.Resource, "browser.unroute", Routes.PatternLabel(pattern), () => RemoveRoutesAsync("unroute", stored => Routes.PatternsEqual(stored.Pattern, pattern), cancellationToken)); /// Unregisters the stored routes selects, newest first. diff --git a/tests/E2E.Tests/RoutePattern/PatternLabelTests.cs b/tests/E2E.Tests/RoutePattern/PatternLabelTests.cs new file mode 100644 index 000000000..56cf43208 --- /dev/null +++ b/tests/E2E.Tests/RoutePattern/PatternLabelTests.cs @@ -0,0 +1,23 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using System.Text.RegularExpressions; + +namespace E2E.Tests.RoutePattern; + +/// +/// .NET-only: upstream's patternLabel is covered by the wait case of fixture-runtime.test.ts's "maps an EngineError a +/// contributed method throws onto the runner taxonomy" (the label in a timeout message). The port has no FixtureRecorder +/// or translated, so that it cannot be ported and only the label itself is checked here. +/// +public sealed class PatternLabelTests +{ + [Fact] + public void Quotes_a_glob_and_writes_a_regex_as_its_literal() + { + Assert.Equal("\"foo.css\"", E2E.Internal.Routes.PatternLabel("foo.css")); + Assert.Equal("\"**/a \\\"b\\\"\"", E2E.Internal.Routes.PatternLabel("**/a \"b\"")); + Assert.Equal("/api\\/\\w+$/i", E2E.Internal.Routes.PatternLabel(new Regex(@"api\/\w+$", RegexOptions.IgnoreCase))); + } +}