From 54248b9f281c901d941f4272c34d867dbbbbf8ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Kondratiuk?= Date: Tue, 3 Nov 2026 15:35:38 -0300 Subject: [PATCH] Extract LocatorEngine so its upstream tests port as written The retries, deadlines, resolve, and the operation context a call carries lived in Screen and Locator. They now live in LocatorEngine (locator/engine.ts upstream), which Screen and Locator hand their query. Behavior is unchanged. The origin test, the missing resolve, and the reads that do not wait now port from locator-engine.test.ts without Partial_ where the port has the call. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Ls2e1yaZFgZ3FEJkYScfkK --- COMPATIBILITY.md | 4 +- src/E2E/Expect/ScreenshotCapture.cs | 6 +- src/E2E/Locator/LocatorEngine.cs | 708 +++++++++++++++++ src/E2E/Locator/Screen.cs | 709 ++---------------- src/E2E/Run/E2ESession.cs | 22 +- .../WebAndDocumentEngineLocateTests.cs | 2 +- ...eSharedBrowserAFreshAttemptPerTestTests.cs | 16 +- .../LocatorEngine/IsNodeVisibleTests.cs | 21 + .../LocatorEnginePerformContractTests.cs | 17 +- .../LocatorEngineReadAllNowContractTests.cs | 40 + .../LocatorEngineReadsThatDoNotWaitTests.cs | 109 +++ .../LocatorEngineResolveRetryContractTests.cs | 86 ++- .../LocatorEngineVisibleQueriesTests.cs | 50 +- .../LocatorEngine/OriginRecordingEngine.cs | 6 +- .../LocatorEngine/ScriptedLocatorEngine.cs | 160 ++++ .../TranslateLocatorErrorMappingTableTests.cs | 11 +- 16 files changed, 1287 insertions(+), 680 deletions(-) create mode 100644 src/E2E/Locator/LocatorEngine.cs create mode 100644 tests/E2E.Tests/LocatorEngine/IsNodeVisibleTests.cs create mode 100644 tests/E2E.Tests/LocatorEngine/LocatorEngineReadAllNowContractTests.cs create mode 100644 tests/E2E.Tests/LocatorEngine/LocatorEngineReadsThatDoNotWaitTests.cs create mode 100644 tests/E2E.Tests/LocatorEngine/ScriptedLocatorEngine.cs diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index 55daf950b..472eb2398 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -38,7 +38,7 @@ Names are C# versions of the JavaScript API: `agent.act` is `ActAsync`, `screen. - Actions: tap, click (an alias of tap), doubleTap (`DblClickAsync` is an alias), fill (a string or a `Secret`), pressSequentially, press, check, uncheck, clear, selectOption, focus, scrollIntoView. They wait up to the action timeout for exactly one enabled, visible match. `selectOption` takes a string that matches an option value or label, or a `SelectOption` with exactly one of `Label`, `Value`, or a nonnegative `Index` (upstream's `{ label }`, `{ value }`, `{ index }`; the document engine refuses `Index`). Upstream's plain string means a label only; the port keeps matching a value or a label. `ActionOptions.Timeout` overrides the wait per action (`PressSequentiallyOptions` adds `Delay`). The web engine's own Playwright wait still uses the configured action timeout - Locator reads: `textContent`, `inputValue`, `getAttribute`, `isVisible`, `isHidden`, `isEnabled`, `isDisabled`, `isChecked`, `boundingBox`, `count`, `all`, `allTextContents`. A read of one node (`textContent`, `inputValue`, `getAttribute`, `isEnabled`, `isDisabled`, `isChecked`, `boundingBox`) waits for its one match until the action timeout, then reads once with no retry for a value; `isVisible`, `isHidden`, `count`, `all`, and `allTextContents` answer from the current screen at once. No read verifies an earlier `act`. `textContent` and `allTextContents` collapse each whitespace run to one space and trim, as upstream. A single-node read fails with `LOCATOR_NOT_FOUND` when nothing matches before the action timeout ends - `screen.tree()` and `screen.debug()` (commit `d7ec0ec`) are `Screen.TreeAsync` and `Screen.DebugAsync`. One observation of the whole screen, rendered by `FailureEvidence.Listing` (the trace's screen at failure, upstream's `prepareObservation`): one node per line, children indented, secrets redacted, cut at the observation byte limit (262144). A node the page does not show is left out. A step of kind `screen`. `DebugAsync` writes the text to `Console.Out`, where a test framework picks it up. Differences: `Timeout` bounds the read with a linked token and fails with `OPERATION_TIMEOUT`, where upstream passes it to the engine operation. A `Locator` has no `TreeAsync`, so upstream's refusal on a locator is a compile error. On a `FrameScreen` they refuse with `INVALID_ARGUMENT`, as upstream's do. The same commit's change to print test output without the `list` reporter, and to keep stdout for `--reporter json`, is not ported: the port has no runner. `screen-tree.test.ts` is `ScreenTree/ScreenTreeTests` and `ScreenDebugTests` (not ported: the refusal on a locator, the unknown option, and `sdk-types.ts`'s checks, which a typed API makes compile errors); `screen-tree-secrets.test.ts` is `ScreenTreeSecrets/ScreenTreeTests` (through a session over a fake engine). `run-user-output.test.ts`'s two new cases are not ported with the runner change. -- The last read of a wait gets grace (`fix: give the last read of a wait the time of the slowest one`, `57f9ed9`, tester-army/e2e#1464). `Locator.WaitForAsync`, a locator `Expect`, and `ToHaveScreenshotAsync` read through a `ReadWindow` (`Internal/Time.cs`, upstream's `ReadWindow` in `internal/time.ts`; `Screen.Reads` is `LocatorEngine.reads`). Each engine locate runs until the wait's deadline plus the slowest read the wait finished (the budget `IEngineSession.LocateAsync` gets), capped by the test timeout (`Screen.BudgetDeadline`, upstream's `budget.deadline`), so a screen that shows up during a slow last read passes. `Time.PollReadsAsync` is `pollReads`, and `PollConditionAsync` is `pollCondition` over a window with no cap. A read the deadline cut off is `ReadWindow.CutOff`: an `OPERATION_TIMEOUT` of a read that started with under one poll tick, or under the slowest read, left (it replaces `cutOffAtDeadline`). A negation counts as held only until the deadline. `Locator.ResolveExactlyOneAsync` and the other waiting resolves end a wait whose last read was cut off after a read that found nothing as `LOCATOR_NOT_FOUND`, not as `ACTION_FAILED`, and a retry the deadline cut off ends on the failure it was retrying (upstream's `resolveCounted` and `resolveOnce`). An action whose deadline passed before it was sent fails with `ACTION_FAILED` (upstream's `lateAction`). A capture of `ToHaveScreenshotAsync` that outlives its budget is an `OPERATION_TIMEOUT` the poll judges as it judges any read; the message of a failure with no capture is `the last screenshot ran past the timeout`. Differences: the port polls every 50 ms in the locator and 100 ms in screenshots where upstream polls every 100 ms. An engine is handed the read's budget by `IEngineSession.LocateAsync`, `ObserveAsync(TimeSpan, CancellationToken)`, and `ScreenshotAsync(TimeSpan, CancellationToken)` (see the operation budget bullet in the mobile section); an engine that does not override the last two (the web and WinApp engines) drops it, so the window only times its read (a screenshot is cancelled at its budget). `Locator.WaitForAsync` fails with `LOCATOR_NOT_FOUND`, as upstream. A positioned tap whose target became visible past the deadline is `ACTION_FAILED` too (`Locator.PerformWithinAsync`, upstream's `performWithin`). Tests: `Time/PollConditionTests` (the five `pollReads` and `ReadWindow` its), `LocatorWaitFor/ASlowLastReadTests`, `LocatorEngine/LocatorEngineResolveRetryContractTests` (four its) and `LocatorEnginePerformContractTests` ('never sends an action whose target resolved past the deadline'), and `ScreenshotAssertions/ToHaveScreenshotTests` (the two capture-timeout its). +- The last read of a wait gets grace (`fix: give the last read of a wait the time of the slowest one`, `57f9ed9`, tester-army/e2e#1464). `Locator.WaitForAsync`, a locator `Expect`, and `ToHaveScreenshotAsync` read through a `ReadWindow` (`Internal/Time.cs`, upstream's `ReadWindow` in `internal/time.ts`; `LocatorEngine.Reads` is upstream's `LocatorEngine.reads`; `Screen.Reads` forwards to it). Each engine locate runs until the wait's deadline plus the slowest read the wait finished (the budget `IEngineSession.LocateAsync` gets), capped by the test timeout (`Screen.BudgetDeadline`, upstream's `budget.deadline`), so a screen that shows up during a slow last read passes. `Time.PollReadsAsync` is `pollReads`, and `PollConditionAsync` is `pollCondition` over a window with no cap. A read the deadline cut off is `ReadWindow.CutOff`: an `OPERATION_TIMEOUT` of a read that started with under one poll tick, or under the slowest read, left (it replaces `cutOffAtDeadline`). A negation counts as held only until the deadline. `LocatorEngine.ResolveExactlyOneAsync` and the other waiting resolves end a wait whose last read was cut off after a read that found nothing as `LOCATOR_NOT_FOUND`, not as `ACTION_FAILED`, and a retry the deadline cut off ends on the failure it was retrying (upstream's `resolveCounted` and `resolveOnce`). An action whose deadline passed before it was sent fails with `ACTION_FAILED` (upstream's `lateAction`). A capture of `ToHaveScreenshotAsync` that outlives its budget is an `OPERATION_TIMEOUT` the poll judges as it judges any read; the message of a failure with no capture is `the last screenshot ran past the timeout`. Differences: the port polls every 50 ms in the locator and 100 ms in screenshots where upstream polls every 100 ms. An engine is handed the read's budget by `IEngineSession.LocateAsync`, `ObserveAsync(TimeSpan, CancellationToken)`, and `ScreenshotAsync(TimeSpan, CancellationToken)` (see the operation budget bullet in the mobile section); an engine that does not override the last two (the web and WinApp engines) drops it, so the window only times its read (a screenshot is cancelled at its budget). `Locator.WaitForAsync` fails with `LOCATOR_NOT_FOUND`, as upstream. A positioned tap whose target became visible past the deadline is `ACTION_FAILED` too (`LocatorEngine.PerformWithinAsync`, upstream's `performWithin`). Tests: `Time/PollConditionTests` (the five `pollReads` and `ReadWindow` its), `LocatorWaitFor/ASlowLastReadTests`, `LocatorEngine/LocatorEngineResolveRetryContractTests` and `LocatorEnginePerformContractTests` ('never sends an action whose target resolved past the deadline'), and `ScreenshotAssertions/ToHaveScreenshotTests` (the two capture-timeout its). - `locator.waitFor` with `attached`, `detached`, `visible` (default), and `hidden`, as `WaitForAsync(new LocatorWaitForOptions { State, Timeout })`. The timeout defaults to the action timeout. `LocatorWaitForOptions` is named apart from `agent.waitFor`'s `WaitForOptions`. A timeout fails with `LOCATOR_NOT_FOUND` (`locator did not become : `), and a passing `waitFor` verifies an earlier `act`, as upstream (`verifies: true` is `Screen.NotifyVerified`). The timeout carries `Details` as upstream's does (the locator, what it asked for, and how long it waited; see [Trace page](#trace-page)) - Locator expectations: visible, hidden, attached, enabled, disabled, checked, selected, expanded, focused, text, contained text, value, attribute, accessible name, and count. They poll until the assertion timeout, or the matcher's own `timeout`. `Not` inverts a matcher, which then passes after 1000 ms of continuous truth (or the whole budget when it is shorter). Text matchers take the same `TextMatch` as queries, `ignoreCase`, and a list form. The boolean flags are `visible`, `attached`, `enabled`, and `isChecked` (`checked` is a C# keyword) - `toHaveScreenshot` as `Expect.That(Screen).ToHaveScreenshotAsync(name, options)` and the same on a locator, with `Not` and `Expect.Soft(locator)`; see [Visual comparison](#visual-comparison) @@ -120,7 +120,7 @@ Names are C# versions of the JavaScript API: `agent.act` is `ActAsync`, `screen. ## Error codes that differ -A locator reports an engine failure as upstream's `translateLocatorError` (`LocatorResolver.TranslateLocatorError`, over `ErrorSerializer.TranslateEngineError`, upstream's `translateEngineError`, `internal/errors.ts`) does, with the engine error as `InnerException` and the locator's description added to the message (#846): `NOT_ACTIONABLE` and `ACTION_MAY_HAVE_COMMITTED` are `ACTION_FAILED`, `OPERATION_TIMEOUT` is `ACTION_FAILED` (`operation timed out: `), `NODE_STALE` and `FRAME_NOT_FOUND` are `LOCATOR_NOT_FOUND`, `FRAME_AMBIGUOUS` is `LOCATOR_AMBIGUOUS`, and `INVALID_STATE` is `APP_NOT_OPEN`. `CANCELLED` is an `EngineException` of that code (`operation cancelled`), `UNSUPPORTED_CAPABILITY` is a `ConfigurationException` (category `configuration`), and `ENGINE_FAILURE`, any other engine code, and an error that is no e2e error are an `EngineException` `ENGINE_FAILURE` (category `infrastructure`), each with the original error as `InnerException`, as upstream's `translateEngineError` wraps them (#885). Differences: an `OperationCanceledException` is returned as it is, so a caller's cancel stays a cancel. The port applies the translation to the locator's resolve (including the resolve over an observation) and to its actions; it has no read by reference to translate. An action whose engine call finds a retryable stale node resolves the locator again and repeats the action while its deadline remains, as upstream's `performUntil` does; an action that may have committed is never repeated. An action whose deadline passed before it was sent is not sent: it fails with `ACTION_FAILED` (`operation timed out before the tap was sent: `), as upstream's `lateAction` (#869). Tests: `LocatorEngine/TranslateLocatorErrorMappingTableTests` (the `translateLocatorError mapping table` describe; the seven rows with the port's codes are `Partial_`) and the perform `it`s of `LocatorEngine/LocatorEnginePerformContractTests`. All six perform `it`s are ported; `marks every action it performs with the test origin` is `Partial_`: the port has no `LocatorEngine` class, so it checks the origin at the session a `Screen` step reaches (`OriginRecordingEngine`) and not at the `LocatorEngine` that adds it. +A locator reports an engine failure as upstream's `translateLocatorError` (`LocatorEngine.TranslateLocatorError`, over `ErrorSerializer.TranslateEngineError`, upstream's `translateEngineError`, `internal/errors.ts`) does, with the engine error as `InnerException` and the locator's description added to the message (#846): `NOT_ACTIONABLE` and `ACTION_MAY_HAVE_COMMITTED` are `ACTION_FAILED`, `OPERATION_TIMEOUT` is `ACTION_FAILED` (`operation timed out: `), `NODE_STALE` and `FRAME_NOT_FOUND` are `LOCATOR_NOT_FOUND`, `FRAME_AMBIGUOUS` is `LOCATOR_AMBIGUOUS`, and `INVALID_STATE` is `APP_NOT_OPEN`. `CANCELLED` is an `EngineException` of that code (`operation cancelled`), `UNSUPPORTED_CAPABILITY` is a `ConfigurationException` (category `configuration`), and `ENGINE_FAILURE`, any other engine code, and an error that is no e2e error are an `EngineException` `ENGINE_FAILURE` (category `infrastructure`), each with the original error as `InnerException`, as upstream's `translateEngineError` wraps them (#885). Differences: an `OperationCanceledException` is returned as it is, so a caller's cancel stays a cancel. The port applies the translation to the locator's resolve (including the resolve over an observation) and to its actions; it has no read by reference to translate. `LocatorEngine` (`Locator/LocatorEngine.cs`, upstream's `locator/engine.ts`, #994) owns the resolve, the retries, the deadlines, the engine events, and the operation context a call carries (`OperationContext.Test`); `Screen` and `Locator` pass it their query. Differences: its session is the set of calls in `LocatorEngineOptions` (.NET-only: the attempt reads the screen through its scope), a locate answers the nodes themselves so `read`, `readNow`, `readAllNow`, and `tryRead` read a resolve and have no `session.read` to go stale, `fillSecret` and `pressSequentially` are not engine methods (a secret fill and a typed text are engine actions), and `DeadlineFor` is upstream's `deadline` (`Deadline` is the type's name). `LocatorEngine/` ports the `read retry`, `resolve retry`, `perform`, `readAllNow`, `reads that do not wait`, `translateLocatorError`, `visible queries`, and `isNodeVisible` describes; not ported: the its that need `session.read` to go stale (read retry 1 to 3, read contract, readAllNow stale and failure, readNow stale between resolve and read), `secret fill` (no engine `fillSecret`), `AttemptBudget.capped` (no `AttemptBudget`), the cross-realm describe (no second module registry in .NET), and the `locator failure candidate counts` describe (#1001). An action whose engine call finds a retryable stale node resolves the locator again and repeats the action while its deadline remains, as upstream's `performUntil` does; an action that may have committed is never repeated. An action whose deadline passed before it was sent is not sent: it fails with `ACTION_FAILED` (`operation timed out before the tap was sent: `), as upstream's `lateAction` (#869). Tests: `LocatorEngine/TranslateLocatorErrorMappingTableTests` (the `translateLocatorError mapping table` describe; the seven rows with the port's codes are `Partial_`) and the perform `it`s of `LocatorEngine/LocatorEnginePerformContractTests`. All six perform `it`s are ported; `marks every action it performs with the test origin` runs on the `LocatorEngine` itself (`ScriptedLocatorEngine`, upstream's `makeEngine`), and a .NET-only test checks that `E2ESession` wires that origin to the engine a test's step reaches (`OriginRecordingEngine`). ## Locator actions diff --git a/src/E2E/Expect/ScreenshotCapture.cs b/src/E2E/Expect/ScreenshotCapture.cs index 272e53847..506f1e529 100644 --- a/src/E2E/Expect/ScreenshotCapture.cs +++ b/src/E2E/Expect/ScreenshotCapture.cs @@ -42,11 +42,11 @@ private Task ReadAsync(Func> read, Ca catch (Exception ex) when (bounded.IsCancellationRequested && !cancellationToken.IsCancellationRequested && (ex is OperationCanceledException || ex is EngineException { Code: EngineErrorCodes.OperationTimeout or EngineErrorCodes.Cancelled } || ex.InnerException is OperationCanceledException)) { - throw LocatorResolver.TranslateLocatorError(new EngineException(EngineErrorCodes.OperationTimeout, "the screenshot outlived its budget", retryable: false, ex)); + throw LocatorEngine.TranslateLocatorError(new EngineException(EngineErrorCodes.OperationTimeout, "the screenshot outlived its budget", retryable: false, ex)); } catch (EngineException ex) when (ex.Code == EngineErrorCodes.OperationTimeout) { - throw LocatorResolver.TranslateLocatorError(ex); + throw LocatorEngine.TranslateLocatorError(ex); } }); @@ -62,7 +62,7 @@ public async Task CaptureAsync(CancellationToken cancellationToken) { try { - await screen.PerformAsync(node, new LocatorAction.ScrollIntoView(), cancellationToken).ConfigureAwait(false); + await screen.Engine.SessionPerformAsync(node, new LocatorAction.ScrollIntoView(), cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (ex is EngineException { Code: EngineErrorCodes.NodeStale } or TestException { Code: "LOCATOR_NOT_FOUND" }) { diff --git a/src/E2E/Locator/LocatorEngine.cs b/src/E2E/Locator/LocatorEngine.cs new file mode 100644 index 000000000..a98dbacbb --- /dev/null +++ b/src/E2E/Locator/LocatorEngine.cs @@ -0,0 +1,708 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using System.Diagnostics; +using System.Globalization; +using E2E.Engine; +using E2E.Internal; + +namespace E2E; + +/// +/// What a frame the engine reports missing means to a resolve (upstream's MissingFrame). +/// +internal enum MissingFrame +{ + /// Treated like a node that is not there yet: the resolve keeps polling for it. + Wait, + + /// Answers zero matches. + Empty, +} + +/// +/// What a runs over (upstream's LocatorEngineOptions). Upstream hands the engine a TargetSession; +/// the port hands it the session's calls (.NET-only): the attempt reads the screen through its scope, and a test builds an engine from +/// bare functions. +/// +internal sealed class LocatorEngineOptions +{ + /// One observation of the screen. + public required Func> Observe { get; init; } + + /// One observation within a budget the engine bounds its reads by (upstream's operation.timeoutMs); null answers with . + public Func>? ObserveWithin { get; init; } + + /// The engine's own resolve (upstream's session.locate); null resolves over . + public Func>>? Locate { get; init; } + + /// One action on a node (upstream's session.perform), with the context that says who acts. + public required Func Perform { get; init; } + + /// One pointer action at a viewport point (upstream's session.performAt); null when the engine has none. + public Func? PerformAt { get; init; } + + /// The running phase's token (upstream's budget.signal), read per operation. + public required Func Cancellation { get; init; } + + /// How long an action waits for its node. + public required TimeSpan ActionTimeout { get; init; } + + /// How long an assertion waits. + public required TimeSpan AssertionTimeout { get; init; } + + /// The clock every deadline reads. + public TimeProvider Clock { get; init; } = TimeProvider.System; +} + +/// Per-attempt locator execution engine: runner-owned query polling, strictness, and action retry (upstream's LocatorEngine, locator/engine.ts). +internal sealed class LocatorEngine(LocatorEngineOptions options) +{ + /// How long an action waits for its node. + internal TimeSpan ActionTimeout { get; } = options.ActionTimeout; + + /// How long an assertion waits (upstream's assertionTimeout). + internal TimeSpan AssertionTimeout { get; } = options.AssertionTimeout; + + internal TimeProvider Clock { get; } = options.Clock; + + internal TimeSpan PollInterval { get; } = TimeSpan.FromMilliseconds(50); + + /// The end of the attempt's test timeout, which no read may outlast (upstream's budget.deadline); null outside a session or with no test timeout. + internal Deadline? BudgetDeadline { get; set; } + + /// What the attempt's engine declares; none outside a session. Upstream's session.tapModifiers is . + internal EngineCapabilities Capabilities { get; set; } + + /// + /// The locator action kinds the engine declared (upstream's session.actions). Null declares every kind, as an engine built over + /// bare functions does; a session sets it from . + /// + internal IReadOnlyCollection? ActionKinds { get; set; } + + /// The pointer action kinds the engine declared (upstream's session.pointerActions). Null declares none. + internal IReadOnlyCollection? PointerActionKinds { get; set; } + + /// Records what an action did under the running step (upstream's recordEvent); null where no step records. + internal StepRecorder? Steps { get; set; } + + /// Replaces secret values in text an event quotes from the screen, before it is clipped (upstream's redact); identity outside a session. + internal Func Redact { get; set; } = static text => text; + + /// + /// Whether the engine resolves a locator itself. Upstream's engines all do; a port engine that does not has its locator resolved + /// over (.NET-only), until it implements . + /// + internal bool LocatesInEngine => options.Locate is not null; + + /// Canonical visibility predicate over a semantic node snapshot (upstream's isNodeVisible). + internal static bool IsNodeVisible(SemanticNode? node) => node is { States.Hidden: false }; + + /// + /// Denies reading a value, text, or attribute when any node is a secure field: the engine withholds them there, so what reads as + /// missing is redacted, not empty or absent (upstream's denySecureRead). + /// + internal static void DenySecureRead(IReadOnlyList nodes, string label) + { + if (nodes.Any(node => node.States.Secure)) + { + throw new TestException("POLICY_DENIED", "reading values from a secure field is denied: " + label); + } + } + + /// + /// The facts of a locator failure an error keeps beside the message (upstream's locatorDetails): the locator as written, + /// what it asked for, and how long it waited, when it waited. + /// + internal static ErrorDetails LocatorDetails(LocatorExpression expression, TimeSpan? waited = null) => + expression.ExpressionHints() with { Locator = expression.Describe(), WaitedMs = waited is { } elapsed ? (long)elapsed.TotalMilliseconds : null }; + + /// + /// Translates an engine error into the runner-owned public taxonomy (upstream's translateLocatorError), naming + /// in the message when one is given. A missing or ambiguous frame also carries the locator's details. + /// + internal static Exception TranslateLocatorError(Exception cause, LocatorExpression? expression = null) + { + var translated = ErrorSerializer.TranslateEngineError(cause, expression is null ? "" : ": " + expression.Describe()); + return expression is not null && translated is TestException { Code: "LOCATOR_NOT_FOUND" or "LOCATOR_AMBIGUOUS" } frame && cause is EngineException { Code: EngineErrorCodes.FrameNotFound or EngineErrorCodes.FrameAmbiguous } + ? new TestException(frame.Code, frame.Message, frame.InnerException!) { Details = LocatorDetails(expression) } + : translated; + } + + /// The method a test called, as upstream names the action: tap, doubleTap, fill, selectOption. + internal static string ApiName(LocatorAction action) => action switch + { + LocatorAction.Tap => "tap", + LocatorAction.DoubleTap => "doubleTap", + LocatorAction.Fill => "fill", + LocatorAction.Press => "press", + LocatorAction.PressSequentially => "pressSequentially", + LocatorAction.Select => "selectOption", + LocatorAction.SetInputFiles => "setInputFiles", + LocatorAction.Check => "check", + LocatorAction.Uncheck => "uncheck", + LocatorAction.Clear => "clear", + LocatorAction.Focus => "focus", + LocatorAction.ScrollIntoView => "scrollIntoView", + LocatorAction.Swipe => "swipe", + LocatorAction.SecondaryTap => "secondaryTap", + LocatorAction.LongPress => "longPress", + LocatorAction.Hover => "hover", + LocatorAction.DragTo => "dragTo", + _ => throw new ArgumentOutOfRangeException(nameof(action), action, "unknown locator action"), + }; + + /// + /// The failure of an action whose deadline passed before it was sent. A read may finish past its deadline so its result is classed + /// right; an action never starts past it (upstream's lateAction). + /// + internal static TestException LateAction(string kind, string target) => + new("ACTION_FAILED", "operation timed out before the " + kind + " was sent: " + target); + + /// The token an operation runs under: the caller's, ending with the running phase's too (upstream's signal). + internal CancellationToken Token(CancellationToken cancellationToken) => Time.Link(cancellationToken, options.Cancellation()); + + /// The reads of one wait on : the last may run past it, up to the test timeout (upstream's reads). + internal ReadWindow Reads(Deadline deadline) => new(deadline, Clock, BudgetDeadline ?? new Deadline(DateTimeOffset.MaxValue)); + + /// + /// The timeout of one action-family operation: when given, the action timeout otherwise. Upstream's + /// deadline(timeoutMs) builds the deadline itself; is also this type's name here (.NET-only name). + /// + internal TimeSpan TimeoutOf(TimeSpan? timeout) + { + if (timeout is TimeSpan chosen) + { + ArgumentOutOfRangeException.ThrowIfLessThan(chosen, TimeSpan.Zero, "timeout"); + return chosen; + } + + return ActionTimeout; + } + + /// Deadline for one action-family operation (upstream's deadline; .NET-only name, as Deadline is the type). + internal Deadline DeadlineFor(TimeSpan? timeout = null) => new(TimeoutOf(timeout), Clock); + + /// One observation of the screen, an unopened app reported as APP_NOT_OPEN. + internal async Task ObserveAsync(CancellationToken cancellationToken) + { + return await AppNotOpen.GuardAsync(() => options.Observe(cancellationToken == default ? options.Cancellation() : cancellationToken)).ConfigureAwait(false); + } + + /// within , the budget the engine bounds its reads by (upstream's operation.timeoutMs). + internal async Task ObserveAsync(TimeSpan timeout, CancellationToken cancellationToken) + { + var token = cancellationToken == default ? options.Cancellation() : cancellationToken; + return await AppNotOpen.GuardAsync(() => options.ObserveWithin is { } within ? within(timeout, token) : options.Observe(token)).ConfigureAwait(false); + } + + /// One immediate engine resolve: the nodes the query matches now, within of the engine's own work. Upstream's session.locate. + private async Task> SessionLocateAsync(LocatorExpression expression, TimeSpan timeout, CancellationToken cancellationToken) + { + return await AppNotOpen.GuardAsync(() => options.Locate!(expression, timeout, cancellationToken == default ? options.Cancellation() : cancellationToken)).ConfigureAwait(false); + } + + /// Carries out one action on a node (upstream's session.perform, marked with the test origin: the engine may act without settling). + internal async Task SessionPerformAsync(SemanticNode node, LocatorAction action, CancellationToken cancellationToken) + { + // The session adapter's own guard (upstream's `session.ts`): an action built per attempt, such as a drag, is checked when it is sent. + CheckAction(action); + await AppNotOpen.GuardAsync(() => options.Perform(node, action, OperationContext.Test, cancellationToken == default ? options.Cancellation() : cancellationToken)).ConfigureAwait(false); + } + + /// Carries out one pointer action at a viewport point, with no node behind it. Upstream's session.performAt. + internal async Task SessionPerformAtAsync(Point point, PointerAction action, CancellationToken cancellationToken) + { + CheckPointerAction(action); + var perform = options.PerformAt ?? throw new EngineException(EngineErrorCodes.UnsupportedCapability, "the pointer actions are not supported by this engine."); + await AppNotOpen.GuardAsync(() => perform(point, action, OperationContext.Test, cancellationToken == default ? options.Cancellation() : cancellationToken)).ConfigureAwait(false); + } + + /// + /// Refuses an action the engine did not declare, before the node is resolved: UNSUPPORTED_CAPABILITY. Upstream's + /// checkAction; its modifiers check is the tap family's own (ActionDispatcher.RequireClickModifiers). + /// + internal void CheckAction(LocatorAction action) + { + var kind = EngineActionKinds.Of(action); + if (ActionKinds is { } declared && !declared.Contains(kind)) + { + throw new EngineException( + EngineErrorCodes.UnsupportedCapability, + $"the \"{kind}\" action is not available on this target: its engine declares {(declared.Count == 0 ? "no actions" : string.Join(", ", declared))}"); + } + } + + /// Refuses a pointer action the engine did not declare: UNSUPPORTED_CAPABILITY. Upstream's checkPointerAction. + internal void CheckPointerAction(PointerAction action) + { + var kind = EngineActionKinds.Of(action); + var declared = PointerActionKinds ?? []; + if (!declared.Contains(kind)) + { + throw new EngineException( + EngineErrorCodes.UnsupportedCapability, + $"the \"{kind}\" action at a point is not available on this target: its engine declares {(declared.Count == 0 ? "no pointer actions" : string.Join(", ", declared))}"); + } + } + + /// + /// One immediate resolve, retrying a retryable engine error within the deadline (upstream's resolveOnce). The engine answers it + /// when it resolves locators, and a role query of its skips a hidden node unless asks for it; any + /// other engine is resolved over its observation. bounds the retries and the budget of each read, and defaults + /// to a window of the action timeout. With a retryable FRAME_NOT_FOUND is zero matches instead: + /// nothing under a frame that is not in the document matches, and a read that promised not to wait must not wait for it. + /// + internal async Task> ResolveOnceAsync(LocatorExpression expression, CancellationToken token, bool includeHidden = false, ReadWindow? reads = null, MissingFrame missingFrame = MissingFrame.Wait) + { + reads ??= Reads(new Deadline(ActionTimeout, Clock)); + if (!LocatesInEngine) + { + Observation observation; + try + { + observation = await reads.ReadAsync(budget => ObserveAsync(budget, token)).ConfigureAwait(false); + } + catch (EngineException ex) when (!token.IsCancellationRequested) + { + var translated = TranslateLocatorError(ex, expression); + if (ReferenceEquals(translated, ex)) + { + throw; + } + + throw translated; + } + + return LocatorResolver.Resolve(observation, expression, includeHidden); + } + + var query = includeHidden ? expression with { IncludeHidden = true } : expression; + EngineException? retried = null; + while (true) + { + try + { + var nodes = await reads.ReadAsync(budget => SessionLocateAsync(query, budget, token)).ConfigureAwait(false); + + // An engine answers `visible` inside scopes, filters, and indices, where only it can. A direct query is held to the same + // predicate here, so it never resolves to a node its own state calls hidden. + return expression.Visible && expression.Kind is not ("filter" or "index" or "selector") ? nodes.Where(node => !node.States.Hidden).ToList() : nodes; + } + catch (EngineException ex) when (retried is not null && !token.IsCancellationRequested && reads.CutOff(ex)) + { + // A retry the deadline cut off saw nothing new: the wait ends on the failure it was retrying. + throw TranslateLocatorError(retried, expression); + } + catch (EngineException ex) when (missingFrame == MissingFrame.Empty && ex is { Code: EngineErrorCodes.FrameNotFound, Retryable: true }) + { + return []; + } + catch (EngineException ex) when (ex.Retryable && !reads.Deadline.Expired(Clock.GetUtcNow()) && !token.IsCancellationRequested) + { + retried = ex; + await Task.Delay(PollInterval, token).ConfigureAwait(false); + } + catch (EngineException ex) when (!token.IsCancellationRequested) + { + var translated = TranslateLocatorError(ex, expression); + if (ReferenceEquals(translated, ex)) + { + throw; + } + + throw translated; + } + } + } + + /// + /// Resolves every current match at once, without waiting for one. A frame the engine reports missing is zero matches, since nothing + /// under it is in the document. A stale resolve is still retried within the deadline, as every resolve does. + /// + internal Task> ResolveNowAsync(LocatorExpression expression, CancellationToken token, ReadWindow? reads = null) => + ResolveOnceAsync(expression, token, reads: reads, missingFrame: MissingFrame.Empty); + + /// + /// Reads every current match at once, in document order: a missing frame reads as no matches. A locate answers the nodes themselves, + /// so there is no separate read to go stale between a resolve and a read (upstream's session.read). + /// + internal Task> ReadAllNowAsync(LocatorExpression expression, CancellationToken token, ReadWindow? reads = null) => + ResolveNowAsync(expression, token, reads); + + /// + /// Reads the one current match at once, for isVisible and isHidden: null for zero matches or a missing frame; two matches + /// are LOCATOR_AMBIGUOUS. + /// + internal Task ReadNowAsync(LocatorExpression expression, CancellationToken token) => + TryReadAsync(expression, token, missingFrame: MissingFrame.Empty); + + /// + /// Reads one node for polling surfaces; null while zero matches. A poll that waits for absence passes : + /// nothing under a frame that is not in the document is attached, so the sample is zero matches rather than a wait for the frame. + /// + internal async Task TryReadAsync(LocatorExpression expression, CancellationToken token, ReadWindow? reads = null, MissingFrame missingFrame = MissingFrame.Wait) + { + var matches = await ResolveOnceAsync(expression, token, reads: reads, missingFrame: missingFrame).ConfigureAwait(false); + return matches.Count > 1 ? throw Ambiguous(expression, matches.Count) : matches.Count == 1 ? matches[0] : null; + } + + /// + /// Waits up to the action timeout for the one match of a read. Zero matches poll until the action timeout, as an action's resolve + /// does, so a read of a node the app is still rendering answers once it is there. More than one match fails at once. Upstream's read. + /// + internal async Task ReadAsync(LocatorExpression expression, CancellationToken token) + { + var started = Clock.GetUtcNow(); + var deadline = started + ActionTimeout; + var reads = Reads(new Deadline(deadline)); + var stamp = Stopwatch.GetTimestamp(); + var sampled = false; + while (true) + { + var node = await ResolveCountedAsync(expression, token, reads, sampled, () => Stopwatch.GetElapsedTime(stamp)).ConfigureAwait(false); + sampled = true; + if (node is not null) + { + return node; + } + + if (Clock.GetUtcNow() >= deadline) + { + throw NotFound(expression, Clock.GetUtcNow() - started); + } + + await Task.Delay(PollInterval, token).ConfigureAwait(false); + } + } + + /// + /// Waits until for the one match. Zero matches poll until the deadline; more than one match fails at once. + /// Upstream's resolveExactlyOne, which a drag uses for the node it drops on. + /// + internal async Task ResolveExactlyOneAsync(LocatorExpression expression, Deadline deadline, CancellationToken token) + { + var started = Clock.GetTimestamp(); + var reads = Reads(deadline); + var sampled = false; + while (true) + { + var node = await ResolveCountedAsync(expression, token, reads, sampled, () => Clock.GetElapsedTime(started)).ConfigureAwait(false); + sampled = true; + if (node is not null) + { + return node; + } + + if (deadline.Expired(Clock.GetUtcNow())) + { + throw NotFound(expression, Clock.GetElapsedTime(started)); + } + + await Task.Delay(PollInterval, token).ConfigureAwait(false); + } + } + + /// + /// for a wait: a resolve the deadline cut off, after one that matched nothing, is the wait running out + /// (upstream's resolveCounted), reported as not found rather than as the timeout of the read. + /// + private async Task ResolveCountedAsync(LocatorExpression expression, CancellationToken token, ReadWindow reads, bool sampled, Func elapsed) + { + try + { + return await TryReadAsync(expression, token, reads).ConfigureAwait(false); + } + catch (Exception ex) when (sampled && !token.IsCancellationRequested && reads.CutOff(ex)) + { + throw new TestException("LOCATOR_NOT_FOUND", expression.Describe() + " matched 0 nodes.", ex) { Details = LocatorDetails(expression, elapsed()) }; + } + } + + /// + /// Performs exactly one action against exactly one enabled match. Stale nodes are re-resolved while the deadline remains; a possibly + /// committed action is never repeated. An action that itself names other nodes (dragTo) is built per attempt, so its nodes are + /// re-resolved together with the source. + /// + internal async Task PerformAsync(LocatorExpression expression, Func> build, TimeSpan? timeout, CancellationToken token) + { + var started = Clock.GetUtcNow(); + var deadline = started + TimeoutOf(timeout); + var startedAt = DateTimeOffset.UtcNow; + var stamp = Stopwatch.GetTimestamp(); + // Each resolve counts its own rounds and wait, as upstream's resolveCounted does: a stale retry starts them over. + var resolveStamp = stamp; + var rounds = 0; + var stale = 0; + var window = new Deadline(deadline); + var reads = Reads(window); + while (true) + { + var node = await ResolveCountedAsync(expression, token, reads, sampled: rounds > 0, () => Stopwatch.GetElapsedTime(resolveStamp)).ConfigureAwait(false); + rounds++; + if (node is { States.Disabled: false, States.Hidden: false }) + { + var waitedMs = rounds > 1 ? (long)Stopwatch.GetElapsedTime(resolveStamp).TotalMilliseconds : 0; + var action = await build(window, token).ConfigureAwait(false); + if (window.Expired(Clock.GetUtcNow())) + { + var late = LateAction(KindOf(action), expression.Describe()); + RecordAction(node, action, startedAt, stamp, waitedMs, stale, StepEventStatus.Failed, late.Code); + throw late; + } + + try + { + await SessionPerformAsync(node, action, token).ConfigureAwait(false); + } + catch (EngineException ex) when (ex is { Code: EngineErrorCodes.NodeStale, Retryable: true } && !token.IsCancellationRequested && !window.Expired(Clock.GetUtcNow())) + { + // The node went stale under the action: look again, within the deadline. + stale++; + rounds = 0; + resolveStamp = Stopwatch.GetTimestamp(); + continue; + } + catch (Exception ex) + { + var failure = token.IsCancellationRequested ? ex : TranslateLocatorError(ex, expression); + RecordAction(node, action, startedAt, stamp, waitedMs, stale, token.IsCancellationRequested ? StepEventStatus.Cancelled : StepEventStatus.Failed, ErrorSerializer.Classify(failure).Code); + if (ReferenceEquals(failure, ex)) + { + throw; + } + + throw failure; + } + + RecordAction(node, action, startedAt, stamp, waitedMs, stale, StepEventStatus.Passed, null); + return; + } + + if (Clock.GetUtcNow() >= deadline) + { + throw node is null + ? NotFound(expression, Clock.GetUtcNow() - started) + : new TestException("NOT_ACTIONABLE", expression.Describe() + (node.States.Hidden ? " is hidden." : " is disabled.")); + } + + await Task.Delay(PollInterval, token).ConfigureAwait(false); + } + } + + /// + /// Performs one action on the one enabled match, waiting for it until a caller shares across steps (upstream's + /// performUntil). With a hidden or disabled match is acted on too, as upstream's resolve does not look at the state. + /// + internal async Task PerformUntilAsync(LocatorExpression expression, LocatorAction action, Deadline deadline, CancellationToken token, bool anyState = false) + { + var started = Clock.GetTimestamp(); + var reads = Reads(deadline); + var sampled = false; + while (true) + { + var node = await ResolveCountedAsync(expression, token, reads, sampled, () => Clock.GetElapsedTime(started)).ConfigureAwait(false); + sampled = true; + if (node is not null && (anyState || node is { States.Disabled: false, States.Hidden: false })) + { + if (deadline.Expired(Clock.GetUtcNow())) + { + throw LateAction(KindOf(action), expression.Describe()); + } + + try + { + await SessionPerformAsync(node, action, token).ConfigureAwait(false); + } + catch (EngineException ex) when (ex is { Code: EngineErrorCodes.NodeStale, Retryable: true } && !token.IsCancellationRequested && !deadline.Expired(Clock.GetUtcNow())) + { + // The node went stale under the action: look again, within the deadline. + continue; + } + catch (Exception ex) when (!token.IsCancellationRequested) + { + var translated = TranslateLocatorError(ex, expression); + if (ReferenceEquals(translated, ex)) + { + throw; + } + + throw translated; + } + + return; + } + + if (deadline.Expired(Clock.GetUtcNow())) + { + throw node is null + ? NotFound(expression, Clock.GetElapsedTime(started)) + : new TestException("NOT_ACTIONABLE", expression.Describe() + (node.States.Hidden ? " is hidden." : " is disabled.")); + } + + await Task.Delay(PollInterval, token).ConfigureAwait(false); + } + } + + /// Performs one pointer action at a viewport point, with no node behind it. Upstream's performAt. + internal async Task PerformAtAsync(Point point, PointerAction action, TimeSpan? timeout, CancellationToken token) + { + CheckPointerAction(action); + await DispatchAtAsync(point, action, new Deadline(TimeoutOf(timeout), Clock), token).ConfigureAwait(false); + } + + /// + /// Performs one pointer action at an offset from the top-left corner of exactly one match: the node is scrolled into view when the engine + /// can, then its box is read and the pointer dispatched at the point, with no node behind the gesture. The node has to be visible with a + /// box within the deadline; one that never is fails as LOCATOR_NOT_FOUND, as WaitForAsync does. Upstream's performWithin. + /// + internal async Task PerformWithinAsync(LocatorExpression expression, Point offset, PointerAction action, TimeSpan? timeout, CancellationToken token) + { + CheckPointerAction(action); + var deadline = new Deadline(TimeoutOf(timeout), Clock); + var started = Clock.GetTimestamp(); + if (ActionKinds is not { } declared || declared.Contains("scrollIntoView")) + { + await PerformUntilAsync(expression, new LocatorAction.ScrollIntoView(), deadline, token, anyState: true).ConfigureAwait(false); + } + + TestException NotVisible(Exception? cause) + { + var message = "locator did not become visible with a box to act within: " + expression.Describe(); + var details = LocatorDetails(expression, Clock.GetElapsedTime(started)); + return cause is null ? new TestException("LOCATOR_NOT_FOUND", message) { Details = details } : new TestException("LOCATOR_NOT_FOUND", message, cause) { Details = details }; + } + + var reads = Reads(deadline); + var sampled = false; + while (true) + { + SemanticNode? node; + try + { + node = await TryReadAsync(expression, token, reads).ConfigureAwait(false); + } + catch (Exception ex) when (sampled && !token.IsCancellationRequested && reads.CutOff(ex)) + { + throw NotVisible(ex); + } + + sampled = true; + if (node is { States.Hidden: false, Rect: { } rect }) + { + await DispatchAtAsync(new Point(rect.X + offset.X, rect.Y + offset.Y), action, deadline, token).ConfigureAwait(false); + return; + } + + if (deadline.Expired(Clock.GetUtcNow())) + { + throw NotVisible(null); + } + + await Task.Delay(PollInterval, token).ConfigureAwait(false); + } + } + + /// One pointer dispatch within a deadline, its engine error translated to the public taxonomy. Upstream's dispatchAt. + private async Task DispatchAtAsync(Point point, PointerAction action, Deadline deadline, CancellationToken token) + { + var startedAt = DateTimeOffset.UtcNow; + var stamp = Stopwatch.GetTimestamp(); + var kind = EngineActionKinds.Of(action); + var at = string.Create(CultureInfo.InvariantCulture, $"({Math.Round(point.X, MidpointRounding.AwayFromZero)}, {Math.Round(point.Y, MidpointRounding.AwayFromZero)})"); + void Record(StepEventStatus status, string? code) => Steps?.RecordEvent(new StepEvent + { + Kind = StepEventKind.Engine, + Name = kind, + StartedAt = startedAt, + DurationMs = (long)Stopwatch.GetElapsedTime(stamp).TotalMilliseconds, + Status = status, + Code = code, + Detail = kind + " at " + at, + }); + + if (deadline.Expired(Clock.GetUtcNow())) + { + var late = LateAction(kind, at); + Record(StepEventStatus.Failed, late.Code); + throw late; + } + + try + { + await SessionPerformAtAsync(point, action, token).ConfigureAwait(false); + } + catch (Exception ex) + { + var failure = token.IsCancellationRequested ? ex : TranslateLocatorError(ex); + Record(token.IsCancellationRequested ? StepEventStatus.Cancelled : StepEventStatus.Failed, ErrorSerializer.Classify(failure).Code); + if (ReferenceEquals(failure, ex)) + { + throw; + } + + throw failure; + } + + Record(StepEventStatus.Passed, null); + } + + /// The action kind an event names: the method's name but for selectOption, which the engine contract calls select. + private static string KindOf(LocatorAction action) => action is LocatorAction.Select ? "select" : ApiName(action); + + /// + /// Records one performed action as an engine event of the running step (upstream's recordAction): the node it landed on as + /// the resolve read it, how long the node took to appear, and how many times it went stale under the action. + /// + private void RecordAction(SemanticNode node, LocatorAction action, DateTimeOffset startedAt, long started, long waitedMs, int stale, StepEventStatus status, string? code) + { + if (Steps is null) + { + return; + } + + string? Field(string? value) + { + var text = value is null ? "" : Redact(TextRules.Normalize(value)); + return text.Length == 0 ? null : text; + } + + var target = RecordedTarget.TargetLabel(new RecordedTarget + { + Role = node.Role, + Name = Field(node.Name), + Text = Field(node.Text), + Placeholder = Field(node.AttributeOf("placeholder")), + TestId = Field(node.TestId), + }); + var kind = KindOf(action); + List notes = []; + if (waitedMs > 0) + { + notes.Add("appeared after " + waitedMs.ToString(CultureInfo.InvariantCulture) + "ms"); + } + + if (stale > 0) + { + notes.Add("went stale " + stale.ToString(CultureInfo.InvariantCulture) + "x"); + } + + Steps.RecordEvent(new StepEvent + { + Kind = StepEventKind.Engine, + Name = kind, + StartedAt = startedAt, + DurationMs = (long)Stopwatch.GetElapsedTime(started).TotalMilliseconds, + Status = status, + Code = code, + Detail = kind + " " + target + (notes.Count == 0 ? "" : " (" + string.Join(", ", notes) + ")"), + }); + } + + internal static TestException Ambiguous(LocatorExpression expression, int count) => + new("LOCATOR_AMBIGUOUS", expression.Describe() + " matched " + count.ToString(CultureInfo.InvariantCulture) + " nodes.") { Details = LocatorDetails(expression) with { Matches = count } }; + + private static TestException NotFound(LocatorExpression expression, TimeSpan waited) => + new("LOCATOR_NOT_FOUND", expression.Describe() + " matched 0 nodes.") { Details = LocatorDetails(expression, waited) }; +} diff --git a/src/E2E/Locator/Screen.cs b/src/E2E/Locator/Screen.cs index 7ca19270a..9b39675be 100644 --- a/src/E2E/Locator/Screen.cs +++ b/src/E2E/Locator/Screen.cs @@ -2,7 +2,6 @@ // Modified by Dario Kondratiuk. // SPDX-License-Identifier: Apache-2.0 -using System.Diagnostics; using E2E.Engine; using E2E.Internal; @@ -15,27 +14,15 @@ namespace E2E; /// public class Screen { - private readonly Func> _observe; - private readonly Func>? _observeWithin; - private readonly Func _perform; - private readonly Func>>? _locate; - private readonly Func _cancellation; private readonly Action _verified; private readonly Func? _swipe; - private readonly Func? _performAt; private readonly Screen? _scopeOf; private readonly Func? _wrap; private ScreenshotContext? _screenshots; - private Deadline? _budgetDeadline; private Action? _rememberSecret; - private Func _redact = static text => text; private Func? _renderTree; - private StepRecorder? _steps; private string? _projectRoot; private Action _failed = static () => { }; - private EngineCapabilities _capabilities; - private IReadOnlyCollection? _actionKinds; - private IReadOnlyCollection? _pointerActionKinds; internal Screen( Func> observe, @@ -50,19 +37,32 @@ internal Screen( Func? swipe = null, Func>? observeWithin = null, Func? performAt = null) - { + : this( + new LocatorEngine(new LocatorEngineOptions + { + Observe = observe, + ObserveWithin = observeWithin, + Locate = locate, + Perform = (node, action, _, token) => perform(node, action, token), + PerformAt = performAt is null ? null : (point, action, _, token) => performAt(point, action, token), + Cancellation = cancellation, + ActionTimeout = actionTimeout, + AssertionTimeout = assertionTimeout, + Clock = clock ?? TimeProvider.System, + }), + verified, + softFailures, + swipe) + { + } + + /// A screen over the locator engine of an attempt. + internal Screen(LocatorEngine engine, Action verified, SoftFailures? softFailures = null, Func? swipe = null) + { + Engine = engine; + _verified = verified; _swipe = swipe; - _performAt = performAt; - _observeWithin = observeWithin; SoftFailures = softFailures ?? new SoftFailures(); - _observe = observe; - _perform = perform; - _locate = locate; - _cancellation = cancellation; - _verified = verified; - ActionTimeout = actionTimeout; - AssertionTimeout = assertionTimeout; - Clock = clock ?? TimeProvider.System; } /// @@ -74,20 +74,15 @@ internal Screen(Screen screen, Func wrap) var root = screen.Root; _scopeOf = root; _wrap = wrap; - _observe = root._observe; - _observeWithin = root._observeWithin; - _perform = root._perform; - _locate = root._locate; - _cancellation = root._cancellation; + Engine = root.Engine; _verified = root._verified; _swipe = root._swipe; - _performAt = root._performAt; SoftFailures = root.SoftFailures; - ActionTimeout = root.ActionTimeout; - AssertionTimeout = root.AssertionTimeout; - Clock = root.Clock; } + /// The attempt's locator engine, which the screen and every locator of it share (upstream's engine). + internal LocatorEngine Engine { get; } + /// The screen this one scopes, or this screen when it is not a scope: the one an attempt's state lives on. internal Screen Root => _scopeOf ?? this; @@ -96,33 +91,33 @@ internal Screen(Screen screen, Func wrap) private LocatorExpression Scoped(LocatorExpression expression) => _wrap is null ? expression : _wrap(expression); - internal TimeSpan ActionTimeout { get; } + internal TimeSpan ActionTimeout => Engine.ActionTimeout; - internal TimeSpan AssertionTimeout { get; } + internal TimeSpan AssertionTimeout => Engine.AssertionTimeout; - internal TimeProvider Clock { get; } + internal TimeProvider Clock => Engine.Clock; /// The end of the attempt's test timeout, which no read may outlast (upstream's budget.deadline); null outside a session or with no test timeout. - internal Deadline? BudgetDeadline { get => Root._budgetDeadline; set => Root._budgetDeadline = value; } + internal Deadline? BudgetDeadline { get => Engine.BudgetDeadline; set => Engine.BudgetDeadline = value; } /// The reads of one wait on : the last may run past it, up to the test timeout (upstream's reads). - internal ReadWindow Reads(Deadline deadline) => new(deadline, Clock, BudgetDeadline ?? new Deadline(DateTimeOffset.MaxValue)); + internal ReadWindow Reads(Deadline deadline) => Engine.Reads(deadline); /// What the attempt's engine declares; none for a screen outside a session. The locator reads , upstream's session.tapModifiers. - internal EngineCapabilities Capabilities { get => Root._capabilities; set => Root._capabilities = value; } + internal EngineCapabilities Capabilities { get => Engine.Capabilities; set => Engine.Capabilities = value; } /// /// The locator action kinds the engine declared (upstream's session.actions). Null declares every kind, as a screen built over /// bare functions does; a session sets it from . /// - internal IReadOnlyCollection? ActionKinds { get => Root._actionKinds; set => Root._actionKinds = value; } + internal IReadOnlyCollection? ActionKinds { get => Engine.ActionKinds; set => Engine.ActionKinds = value; } /// The pointer action kinds the engine declared (upstream's session.pointerActions). Null declares none. - internal IReadOnlyCollection? PointerActionKinds { get => Root._pointerActionKinds; set => Root._pointerActionKinds = value; } + internal IReadOnlyCollection? PointerActionKinds { get => Engine.PointerActionKinds; set => Engine.PointerActionKinds = value; } internal SoftFailures SoftFailures { get; } - internal TimeSpan PollInterval { get; } = TimeSpan.FromMilliseconds(50); + internal TimeSpan PollInterval => Engine.PollInterval; /// Where ToHaveScreenshotAsync keeps screenshots; null for a screen outside a session. internal ScreenshotContext? Screenshots { get => Root._screenshots; set => Root._screenshots = value; } @@ -133,7 +128,7 @@ internal Screen(Screen screen, Func wrap) internal Action? RememberSecret { get => Root._rememberSecret; set => Root._rememberSecret = value; } /// Replaces the secrets the attempt knows in text a failure quotes from the screen; the text as it is for a screen outside a session. - internal Func Redact { get => Root._redact; set => Root._redact = value; } + internal Func Redact { get => Engine.Redact; set => Engine.Redact = value; } /// Creates a lazy role query. img is read as image. A role query never matches a hidden node. public Locator GetByRole(string role, TextMatch? name = null, bool exact = true) @@ -223,7 +218,7 @@ public async Task DebugAsync(ActionOptions? options = null, CancellationToken ca public Task TapAtAsync(Point point, ActionOptions? options = null, CancellationToken cancellationToken = default) { var at = RequirePoint(point, "tapAt"); - return RunStepAsync(StepKind.Screen, "screen.tapAt", DescribePoint(at), () => PerformAtAsync(at, new PointerAction.Tap(), options?.Timeout, cancellationToken)); + return RunStepAsync(StepKind.Screen, "screen.tapAt", DescribePoint(at), () => Engine.PerformAtAsync(at, new PointerAction.Tap(), options?.Timeout, Token(cancellationToken))); } /// @@ -262,7 +257,7 @@ public Task SwipeAsync(SwipePathOptions options, CancellationToken cancellationT var from = RequirePoint(options.From, "swipe from"); var to = RequirePoint(options.To, "swipe to"); var duration = ValidateSwipeDuration(options.Duration); - return RunStepAsync(StepKind.Screen, "screen.swipe", DescribePoint(from) + " → " + DescribePoint(to), () => PerformAtAsync(from, new PointerAction.SwipeTo(to, duration), null, cancellationToken)); + return RunStepAsync(StepKind.Screen, "screen.swipe", DescribePoint(from) + " → " + DescribePoint(to), () => Engine.PerformAtAsync(from, new PointerAction.SwipeTo(to, duration), null, Token(cancellationToken))); } /// Validates a point a test names: finite, and never off the plane. Upstream's requirePoint. @@ -302,76 +297,6 @@ internal static string DescribePoint(Point point) => _ => "right", }; - /// Performs one pointer action at a viewport point, with no node behind it. Upstream's performAt. - internal async Task PerformAtAsync(Point point, PointerAction action, TimeSpan? timeout, CancellationToken cancellationToken) - { - CheckPointerAction(action); - var token = Token(cancellationToken); - await DispatchAtAsync(point, action, new Deadline(TimeoutOf(timeout), Clock), token).ConfigureAwait(false); - } - - internal TimeSpan TimeoutOf(TimeSpan? timeout) - { - if (timeout is TimeSpan chosen) - { - ArgumentOutOfRangeException.ThrowIfLessThan(chosen, TimeSpan.Zero, "timeout"); - return chosen; - } - - return ActionTimeout; - } - - /// One pointer dispatch within a deadline, its engine error translated to the public taxonomy. Upstream's dispatchAt. - internal async Task DispatchAtAsync(Point point, PointerAction action, Deadline deadline, CancellationToken token) - { - var startedAt = DateTimeOffset.UtcNow; - var stamp = Stopwatch.GetTimestamp(); - var kind = EngineActionKinds.Of(action); - var at = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"({Math.Round(point.X, MidpointRounding.AwayFromZero)}, {Math.Round(point.Y, MidpointRounding.AwayFromZero)})"); - void Record(StepEventStatus status, string? code) => RecordEvent(new StepEvent - { - Kind = StepEventKind.Engine, - Name = kind, - StartedAt = startedAt, - DurationMs = (long)Stopwatch.GetElapsedTime(stamp).TotalMilliseconds, - Status = status, - Code = code, - Detail = kind + " at " + at, - }); - - if (deadline.Expired(Clock.GetUtcNow())) - { - var late = LateAction(kind, at); - Record(StepEventStatus.Failed, late.Code); - throw late; - } - - try - { - await PerformAtAsync(point, action, token).ConfigureAwait(false); - } - catch (Exception ex) - { - var failure = token.IsCancellationRequested ? ex : LocatorResolver.TranslateLocatorError(ex); - Record(token.IsCancellationRequested ? StepEventStatus.Cancelled : StepEventStatus.Failed, ErrorSerializer.Classify(failure).Code); - if (ReferenceEquals(failure, ex)) - { - throw; - } - - throw failure; - } - - Record(StepEventStatus.Passed, null); - } - - /// - /// The failure of an action whose deadline passed before it was sent. A read may finish past its deadline so its result is classed - /// right; an action never starts past it (upstream's lateAction). - /// - internal static TestException LateAction(string kind, string target) => - new("ACTION_FAILED", "operation timed out before the " + kind + " was sent: " + target); - /// /// Scrolls the viewport until is visible: polls the target and swipes between polls, down and slowly /// unless say otherwise. Every swipe is bounded by the scroll's own deadline, not the @@ -399,7 +324,7 @@ await RunStepAsync(StepKind.Screen, "screen.scrollUntilVisible", label, async () TestException NotVisible(Exception? cause) { var message = "target did not become visible while scrolling: " + label; - return new TestException("LOCATOR_NOT_FOUND", message, cause!) { Details = LocatorResolver.LocatorDetails(target.Query, Clock.GetElapsedTime(startedAt)) }; + return new TestException("LOCATOR_NOT_FOUND", message, cause!) { Details = LocatorEngine.LocatorDetails(target.Query, Clock.GetElapsedTime(startedAt)) }; } var reads = Reads(deadline); @@ -515,77 +440,12 @@ async Task Read() return Steps is null ? await Read().ConfigureAwait(false) : await Steps.RunAsync(StepKind.Screen, api, "whole screen", Read).ConfigureAwait(false); } - internal async Task ObserveAsync(CancellationToken cancellationToken) - { - return await AppNotOpen.GuardAsync(() => _observe(cancellationToken == default ? _cancellation() : cancellationToken)).ConfigureAwait(false); - } - - /// within , the budget the engine bounds its reads by (upstream's operation.timeoutMs). - internal async Task ObserveAsync(TimeSpan timeout, CancellationToken cancellationToken) - { - var token = cancellationToken == default ? _cancellation() : cancellationToken; - return await AppNotOpen.GuardAsync(() => _observeWithin is { } within ? within(timeout, token) : _observe(token)).ConfigureAwait(false); - } - - /// - /// Whether the engine resolves a locator itself. Upstream's engines all do; a port engine that does not has its locator resolved - /// here over , until it implements (.NET-only). - /// - internal bool LocatesInEngine => _locate is not null; - - /// One immediate engine resolve: the nodes the query matches now, within of the engine's own work. - internal async Task> LocateAsync(LocatorExpression query, TimeSpan timeout, CancellationToken cancellationToken) - { - return await AppNotOpen.GuardAsync(() => _locate!(query, timeout, cancellationToken == default ? _cancellation() : cancellationToken)).ConfigureAwait(false); - } - - internal async Task PerformAsync(SemanticNode node, LocatorAction action, CancellationToken cancellationToken) - { - // The session adapter's own guard (upstream's `session.ts`): an action built per attempt, such as a drag, is checked when it is sent. - CheckAction(action); - await AppNotOpen.GuardAsync(() => _perform(node, action, cancellationToken == default ? _cancellation() : cancellationToken)).ConfigureAwait(false); - } - - /// Carries out one pointer action at a viewport point, with no node behind it. Upstream's session.performAt. - internal async Task PerformAtAsync(Point point, PointerAction action, CancellationToken cancellationToken) - { - CheckPointerAction(action); - var perform = _performAt ?? throw new EngineException(EngineErrorCodes.UnsupportedCapability, "the pointer actions are not supported by this engine."); - await AppNotOpen.GuardAsync(() => perform(point, action, cancellationToken == default ? _cancellation() : cancellationToken)).ConfigureAwait(false); - } + internal Task ObserveAsync(CancellationToken cancellationToken) => Engine.ObserveAsync(cancellationToken); - /// - /// Refuses an action the engine did not declare, before the node is resolved: UNSUPPORTED_CAPABILITY. Upstream's - /// checkAction; its modifiers check is the tap family's own (ActionDispatcher.RequireClickModifiers). - /// - internal void CheckAction(LocatorAction action) - { - var kind = EngineActionKinds.Of(action); - if (ActionKinds is { } declared && !declared.Contains(kind)) - { - throw new EngineException( - EngineErrorCodes.UnsupportedCapability, - $"the \"{kind}\" action is not available on this target: its engine declares {(declared.Count == 0 ? "no actions" : string.Join(", ", declared))}"); - } - } + /// The observation within , the budget the engine bounds its reads by (upstream's operation.timeoutMs). + internal Task ObserveAsync(TimeSpan timeout, CancellationToken cancellationToken) => Engine.ObserveAsync(timeout, cancellationToken); - /// Refuses a pointer action the engine did not declare: UNSUPPORTED_CAPABILITY. Upstream's checkPointerAction. - internal void CheckPointerAction(PointerAction action) - { - var kind = EngineActionKinds.Of(action); - var declared = PointerActionKinds ?? []; - if (!declared.Contains(kind)) - { - throw new EngineException( - EngineErrorCodes.UnsupportedCapability, - $"the \"{kind}\" action at a point is not available on this target: its engine declares {(declared.Count == 0 ? "no pointer actions" : string.Join(", ", declared))}"); - } - } - - internal CancellationToken Token(CancellationToken cancellationToken) - { - return Time.Link(cancellationToken, _cancellation()); - } + internal CancellationToken Token(CancellationToken cancellationToken) => Engine.Token(cancellationToken); internal void NotifyVerified() => _verified(); @@ -593,7 +453,7 @@ internal CancellationToken Token(CancellationToken cancellationToken) internal string? ProjectRoot { get => Root._projectRoot; set => Root._projectRoot = value; } /// The attempt's step timeline; null for a screen outside a session, whose calls then run unrecorded. - internal StepRecorder? Steps { get => Root._steps; set => Root._steps = value; } + internal StepRecorder? Steps { get => Engine.Steps; set => Engine.Steps = value; } /// Runs one call that touches the app as a recorded step of the attempt, or as it is without a timeline. internal Task RunStepAsync(StepKind kind, string api, string label, Func body, bool verifies = false) => @@ -967,7 +827,7 @@ public async Task InputValueAsync(CancellationToken cancellationToken = /// Reads current visibility: true when exactly one visible node matches. More than one match fails. public async Task IsVisibleAsync(CancellationToken cancellationToken = default) { - return await ResolveSingleAsync(_screen.Token(cancellationToken), missingFrame: MissingFrame.Empty).ConfigureAwait(false) is { States.Hidden: false }; + return LocatorEngine.IsNodeVisible(await _screen.Engine.ReadNowAsync(Query, _screen.Token(cancellationToken)).ConfigureAwait(false)); } /// Reads current hidden or absent state, the negation of . @@ -979,7 +839,7 @@ public async Task IsHiddenAsync(CancellationToken cancellationToken = defa /// Waits up to the action timeout for one match, then reads its enabled state once. public async Task IsEnabledAsync(CancellationToken cancellationToken = default) { - var node = await ResolveStrictAsync(cancellationToken).ConfigureAwait(false); + var node = await _screen.Engine.ReadAsync(Query, _screen.Token(cancellationToken)).ConfigureAwait(false); return !node.States.Disabled; } @@ -992,7 +852,7 @@ public async Task IsDisabledAsync(CancellationToken cancellationToken = de /// Waits up to the action timeout for one match, then reads its checked state once. public async Task IsCheckedAsync(CancellationToken cancellationToken = default) { - var node = await ResolveStrictAsync(cancellationToken).ConfigureAwait(false); + var node = await _screen.Engine.ReadAsync(Query, _screen.Token(cancellationToken)).ConfigureAwait(false); return node.States.Checked; } @@ -1002,14 +862,14 @@ public async Task IsCheckedAsync(CancellationToken cancellationToken = def /// public async Task BoundingBoxAsync(CancellationToken cancellationToken = default) { - var node = await ResolveStrictAsync(cancellationToken).ConfigureAwait(false); + var node = await _screen.Engine.ReadAsync(Query, _screen.Token(cancellationToken)).ConfigureAwait(false); return node.Rect; } /// Counts current matches without waiting. public async Task CountAsync(CancellationToken cancellationToken = default) { - var matches = await ResolveAsync(_screen.Token(cancellationToken), missingFrame: MissingFrame.Empty).ConfigureAwait(false); + var matches = await _screen.Engine.ReadAllNowAsync(Query, _screen.Token(cancellationToken)).ConfigureAwait(false); return matches.Count; } @@ -1032,7 +892,7 @@ public async Task> AllAsync(CancellationToken cancellatio /// public async Task> AllTextContentsAsync(CancellationToken cancellationToken = default) { - var matches = await ResolveAsync(_screen.Token(cancellationToken), missingFrame: MissingFrame.Empty).ConfigureAwait(false); + var matches = await _screen.Engine.ReadAllNowAsync(Query, _screen.Token(cancellationToken)).ConfigureAwait(false); DenySecureRead(matches); return matches.Select(node => TextRules.Normalize(node.Text ?? "")).ToList(); } @@ -1074,7 +934,7 @@ await samples.RecordAsync(_screen.Steps, token, () => Time.PollReadsAsync(new Po var matches = await ResolveAsync(token, includeHidden: true, reads, state is WaitForState.Detached or WaitForState.Hidden ? MissingFrame.Empty : MissingFrame.Wait).ConfigureAwait(false); if (matches.Count > 1) { - throw Ambiguous(matches.Count); + throw LocatorEngine.Ambiguous(Query, matches.Count); } samples.Add(matches.Count == 0 ? "absent" : matches[0].States.Hidden ? "hidden" : "visible"); @@ -1091,85 +951,18 @@ await samples.RecordAsync(_screen.Steps, token, () => Time.PollReadsAsync(new Po "locator did not become " + StateName(state) + ": " + Query.Describe(), cause, _screen.Redact, - LocatorResolver.LocatorDetails(Query, clock.GetElapsedTime(startedAt))), + LocatorEngine.LocatorDetails(Query, clock.GetElapsedTime(startedAt))), })).ConfigureAwait(false); _screen.NotifyVerified(); } /// - /// The nodes the locator matches now. An engine that resolves locators answers it, and a role query of its skips a hidden node unless - /// asks for it; any other engine is resolved over its observation. bounds the retries of an engine - /// that asks for one and the budget of each read, and defaults to a window of the action timeout. says what a frame the engine reports missing means. + /// The nodes the locator matches now (upstream's resolveOnce, ). A role query of an engine that + /// resolves locators skips a hidden node unless asks for it. bounds the retries and the budget + /// of each read, and defaults to a window of the action timeout. says what a frame the engine reports missing means. /// - internal async Task> ResolveAsync(CancellationToken cancellationToken, bool includeHidden = false, ReadWindow? reads = null, MissingFrame missingFrame = MissingFrame.Wait) - { - reads ??= _screen.Reads(new Deadline(_screen.ActionTimeout, _screen.Clock)); - if (_screen.LocatesInEngine) - { - return await LocateAsync(reads, includeHidden, missingFrame, cancellationToken).ConfigureAwait(false); - } - - Observation observation; - try - { - observation = await reads.ReadAsync(budget => _screen.ObserveAsync(budget, cancellationToken)).ConfigureAwait(false); - } - catch (EngineException ex) when (!cancellationToken.IsCancellationRequested) - { - var translated = LocatorResolver.TranslateLocatorError(ex, Query); - if (ReferenceEquals(translated, ex)) - { - throw; - } - - throw translated; - } - - return LocatorResolver.Resolve(observation, Query, includeHidden); - } - - /// One immediate engine resolve, retrying a retryable engine error until the deadline (upstream's resolveOnce). - private async Task> LocateAsync(ReadWindow reads, bool includeHidden, MissingFrame missingFrame, CancellationToken cancellationToken) - { - var expression = includeHidden ? Query with { IncludeHidden = true } : Query; - EngineException? retried = null; - while (true) - { - try - { - var nodes = await reads.ReadAsync(budget => _screen.LocateAsync(expression, budget, cancellationToken)).ConfigureAwait(false); - - // An engine answers `visible` inside scopes, filters, and indices, where only it can. A direct query is held to the same - // predicate here, so it never resolves to a node its own state calls hidden. - return Query.Visible && Query.Kind is not ("filter" or "index" or "selector") ? nodes.Where(node => !node.States.Hidden).ToList() : nodes; - } - catch (EngineException ex) when (retried is not null && !cancellationToken.IsCancellationRequested && reads.CutOff(ex)) - { - // A retry the deadline cut off saw nothing new: the wait ends on the failure it was retrying. - throw LocatorResolver.TranslateLocatorError(retried, Query); - } - catch (EngineException ex) when (missingFrame == MissingFrame.Empty && ex is { Code: EngineErrorCodes.FrameNotFound, Retryable: true }) - { - // Nothing under a frame that is not in the document matches, and a read that promised not to wait must not wait for it. - return []; - } - catch (EngineException ex) when (ex.Retryable && !reads.Deadline.Expired(_screen.Clock.GetUtcNow()) && !cancellationToken.IsCancellationRequested) - { - retried = ex; - await Task.Delay(_screen.PollInterval, cancellationToken).ConfigureAwait(false); - } - catch (EngineException ex) when (!cancellationToken.IsCancellationRequested) - { - var translated = LocatorResolver.TranslateLocatorError(ex, Query); - if (ReferenceEquals(translated, ex)) - { - throw; - } - - throw translated; - } - } - } + internal Task> ResolveAsync(CancellationToken cancellationToken, bool includeHidden = false, ReadWindow? reads = null, MissingFrame missingFrame = MissingFrame.Wait) => + _screen.Engine.ResolveOnceAsync(Query, cancellationToken, includeHidden, reads, missingFrame); internal Screen Screen => _screen; @@ -1180,7 +973,7 @@ private async Task> LocateAsync(ReadWindow reads, bo /// More than one match fails at once. /// private Task ActAsync(LocatorAction action, ActionOptions? options, CancellationToken cancellationToken) => - ActAsync("locator." + ApiName(action), (_, _) => Task.FromResult(action), options, null, () => _screen.CheckAction(action), cancellationToken); + ActAsync("locator." + LocatorEngine.ApiName(action), (_, _) => Task.FromResult(action), options, null, () => _screen.Engine.CheckAction(action), cancellationToken); /// /// for an action built once the node is found, with the step's @@ -1190,7 +983,7 @@ private Task ActAsync(string api, Func { check?.Invoke(); - return PerformAsync(build, options, cancellationToken); + return _screen.Engine.PerformAsync(Query, build, options?.Timeout, _screen.Token(cancellationToken)); }); /// @@ -1215,7 +1008,7 @@ private Task ClickWithAsync(string api, Func?, Locato label, () => { - _screen.CheckAction(action); + _screen.Engine.CheckAction(action); if (modifiers is not null) { ActionDispatcher.RequireClickModifiers(options, api, _screen.Capabilities); @@ -1262,96 +1055,6 @@ private Task TapWithAsync(string api, ClickOptions? options, CancellationToken c return hold; } - // The method the test called, as upstream names it: tap, doubleTap, fill, selectOption. - private static string ApiName(LocatorAction action) => action switch - { - LocatorAction.Tap => "tap", - LocatorAction.DoubleTap => "doubleTap", - LocatorAction.Fill => "fill", - LocatorAction.Press => "press", - LocatorAction.PressSequentially => "pressSequentially", - LocatorAction.Select => "selectOption", - LocatorAction.SetInputFiles => "setInputFiles", - LocatorAction.Check => "check", - LocatorAction.Uncheck => "uncheck", - LocatorAction.Clear => "clear", - LocatorAction.Focus => "focus", - LocatorAction.ScrollIntoView => "scrollIntoView", - LocatorAction.Swipe => "swipe", - LocatorAction.SecondaryTap => "secondaryTap", - LocatorAction.LongPress => "longPress", - LocatorAction.Hover => "hover", - LocatorAction.DragTo => "dragTo", - _ => throw new ArgumentOutOfRangeException(nameof(action), action, "unknown locator action"), - }; - - private async Task PerformAsync(Func> build, ActionOptions? options, CancellationToken cancellationToken) - { - var token = _screen.Token(cancellationToken); - var started = _screen.Clock.GetUtcNow(); - var deadline = started + TimeoutOf(options?.Timeout); - var startedAt = DateTimeOffset.UtcNow; - var stamp = Stopwatch.GetTimestamp(); - // Each resolve counts its own rounds and wait, as upstream's resolveCounted does: a stale retry starts them over. - var resolveStamp = stamp; - var rounds = 0; - var stale = 0; - var window = new Deadline(deadline); - var reads = _screen.Reads(window); - while (true) - { - var node = await ResolveCountedAsync(token, reads, sampled: rounds > 0, () => Stopwatch.GetElapsedTime(resolveStamp)).ConfigureAwait(false); - rounds++; - if (node is { States.Disabled: false, States.Hidden: false }) - { - var waitedMs = rounds > 1 ? (long)Stopwatch.GetElapsedTime(resolveStamp).TotalMilliseconds : 0; - var action = await build(window, token).ConfigureAwait(false); - if (window.Expired(_screen.Clock.GetUtcNow())) - { - var late = LateAction(action); - RecordAction(node, action, startedAt, stamp, waitedMs, stale, StepEventStatus.Failed, late.Code); - throw late; - } - - try - { - await _screen.PerformAsync(node, action, token).ConfigureAwait(false); - } - catch (EngineException ex) when (ex is { Code: EngineErrorCodes.NodeStale, Retryable: true } && !token.IsCancellationRequested && !window.Expired(_screen.Clock.GetUtcNow())) - { - // The node went stale under the action: look again, within the deadline. - stale++; - rounds = 0; - resolveStamp = Stopwatch.GetTimestamp(); - continue; - } - catch (Exception ex) - { - var failure = token.IsCancellationRequested ? ex : LocatorResolver.TranslateLocatorError(ex, Query); - RecordAction(node, action, startedAt, stamp, waitedMs, stale, token.IsCancellationRequested ? StepEventStatus.Cancelled : StepEventStatus.Failed, ErrorSerializer.Classify(failure).Code); - if (ReferenceEquals(failure, ex)) - { - throw; - } - - throw failure; - } - - RecordAction(node, action, startedAt, stamp, waitedMs, stale, StepEventStatus.Passed, null); - return; - } - - if (_screen.Clock.GetUtcNow() >= deadline) - { - throw node is null - ? NotFound(_screen.Clock.GetUtcNow() - started) - : new TestException("NOT_ACTIONABLE", Query.Describe() + (node.States.Hidden ? " is hidden." : " is disabled.")); - } - - await Task.Delay(_screen.PollInterval, token).ConfigureAwait(false); - } - } - /// /// Scrolls this locator's node until is visible: the node itself swipes, so a scroll container pages /// without the pointer having to hover it first. Both locators must come from the same screen. Upstream's locator.scrollUntilVisible. @@ -1364,263 +1067,35 @@ public Task ScrollUntilVisibleAsync(Locator target, ScrollUntilVisibleOptions? o /// can, then its box is read and the pointer dispatched at the point, with no node behind the gesture. The node has to be visible with a /// box within the deadline; one that never is fails as LOCATOR_NOT_FOUND, as WaitForAsync does. Upstream's performWithin. /// - internal async Task PerformWithinAsync(Point offset, PointerAction action, TimeSpan? timeout, CancellationToken cancellationToken) - { - _screen.CheckPointerAction(action); - var token = _screen.Token(cancellationToken); - var clock = _screen.Clock; - var deadline = new Deadline(TimeoutOf(timeout), clock); - var started = clock.GetTimestamp(); - if (_screen.ActionKinds is not { } declared || declared.Contains("scrollIntoView")) - { - await PerformUntilAsync(new LocatorAction.ScrollIntoView(), deadline, token, anyState: true).ConfigureAwait(false); - } - - TestException NotVisible(Exception? cause) - { - var message = "locator did not become visible with a box to act within: " + Query.Describe(); - var details = LocatorResolver.LocatorDetails(Query, clock.GetElapsedTime(started)); - return cause is null ? new TestException("LOCATOR_NOT_FOUND", message) { Details = details } : new TestException("LOCATOR_NOT_FOUND", message, cause) { Details = details }; - } - - var reads = _screen.Reads(deadline); - var sampled = false; - while (true) - { - SemanticNode? node; - try - { - node = await ResolveSingleAsync(token, reads).ConfigureAwait(false); - } - catch (Exception ex) when (sampled && !token.IsCancellationRequested && reads.CutOff(ex)) - { - throw NotVisible(ex); - } - - sampled = true; - if (node is { States.Hidden: false, Rect: { } rect }) - { - await _screen.DispatchAtAsync(new Point(rect.X + offset.X, rect.Y + offset.Y), action, deadline, token).ConfigureAwait(false); - return; - } - - if (deadline.Expired(clock.GetUtcNow())) - { - throw NotVisible(null); - } - - await Task.Delay(_screen.PollInterval, token).ConfigureAwait(false); - } - } - - /// Performs one action on the one enabled match, waiting for it until (upstream's performUntil). With a hidden or disabled match is acted on too, as upstream's resolve does not look at the state. - internal async Task PerformUntilAsync(LocatorAction action, Deadline deadline, CancellationToken token, bool anyState = false) - { - var started = _screen.Clock.GetTimestamp(); - var reads = _screen.Reads(deadline); - var sampled = false; - while (true) - { - var node = await ResolveCountedAsync(token, reads, sampled, () => _screen.Clock.GetElapsedTime(started)).ConfigureAwait(false); - sampled = true; - if (node is not null && (anyState || node is { States.Disabled: false, States.Hidden: false })) - { - if (deadline.Expired(_screen.Clock.GetUtcNow())) - { - throw LateAction(action); - } - - try - { - await _screen.PerformAsync(node, action, token).ConfigureAwait(false); - } - catch (EngineException ex) when (ex is { Code: EngineErrorCodes.NodeStale, Retryable: true } && !token.IsCancellationRequested && !deadline.Expired(_screen.Clock.GetUtcNow())) - { - // The node went stale under the action: look again, within the deadline. - continue; - } - catch (Exception ex) when (!token.IsCancellationRequested) - { - var translated = LocatorResolver.TranslateLocatorError(ex, Query); - if (ReferenceEquals(translated, ex)) - { - throw; - } - - throw translated; - } - - return; - } - - if (deadline.Expired(_screen.Clock.GetUtcNow())) - { - throw node is null - ? NotFound(_screen.Clock.GetElapsedTime(started)) - : new TestException("NOT_ACTIONABLE", Query.Describe() + (node.States.Hidden ? " is hidden." : " is disabled.")); - } - - await Task.Delay(_screen.PollInterval, token).ConfigureAwait(false); - } - } - - /// - /// Records one performed action as an engine event of the running step (upstream's recordAction, locator/engine.ts): - /// the node it landed on as the resolve read it, how long the node took to appear, and how many times it went stale under the action. - /// - private void RecordAction(SemanticNode node, LocatorAction action, DateTimeOffset startedAt, long started, long waitedMs, int stale, StepEventStatus status, string? code) - { - if (_screen.Steps is null) - { - return; - } - - string? Field(string? value) - { - var text = value is null ? "" : _screen.Redact(TextRules.Normalize(value)); - return text.Length == 0 ? null : text; - } - - var target = RecordedTarget.TargetLabel(new RecordedTarget - { - Role = node.Role, - Name = Field(node.Name), - Text = Field(node.Text), - Placeholder = Field(node.AttributeOf("placeholder")), - TestId = Field(node.TestId), - }); - // The action kind the engine contract names, which is the method's name but for selectOption. - var kind = action is LocatorAction.Select ? "select" : ApiName(action); - List notes = []; - if (waitedMs > 0) - { - notes.Add("appeared after " + waitedMs.ToString(System.Globalization.CultureInfo.InvariantCulture) + "ms"); - } + internal Task PerformWithinAsync(Point offset, PointerAction action, TimeSpan? timeout, CancellationToken cancellationToken) => + _screen.Engine.PerformWithinAsync(Query, offset, action, timeout, _screen.Token(cancellationToken)); - if (stale > 0) - { - notes.Add("went stale " + stale.ToString(System.Globalization.CultureInfo.InvariantCulture) + "x"); - } - - _screen.RecordEvent(new StepEvent - { - Kind = StepEventKind.Engine, - Name = kind, - StartedAt = startedAt, - DurationMs = (long)Stopwatch.GetElapsedTime(started).TotalMilliseconds, - Status = status, - Code = code, - Detail = kind + " " + target + (notes.Count == 0 ? "" : " (" + string.Join(", ", notes) + ")"), - }); - } + /// Performs one action on the one enabled match, waiting for it until (upstream's performUntil, ). + internal Task PerformUntilAsync(LocatorAction action, Deadline deadline, CancellationToken token, bool anyState = false) => + _screen.Engine.PerformUntilAsync(Query, action, deadline, token, anyState); /// A secure field's text, value, and attributes are withheld, so reading them is denied rather than read as empty. - internal void DenySecureRead(IReadOnlyList nodes) - { - if (nodes.Any(node => node.States.Secure)) - { - throw new TestException("POLICY_DENIED", "reading values from a secure field is denied: " + Query.Describe()); - } - } + internal void DenySecureRead(IReadOnlyList nodes) => LocatorEngine.DenySecureRead(nodes, Query.Describe()); /// Returns the one match for a text or value read. A secure match fails with POLICY_DENIED. private async Task ResolveReadableAsync(CancellationToken cancellationToken) { - var node = await ResolveStrictAsync(cancellationToken).ConfigureAwait(false); + var node = await _screen.Engine.ReadAsync(Query, _screen.Token(cancellationToken)).ConfigureAwait(false); DenySecureRead([node]); return node; } - /// Waits up to the action timeout for the one match of a read. More than one match fails at once. - private async Task ResolveStrictAsync(CancellationToken cancellationToken) - { - var token = _screen.Token(cancellationToken); - var started = _screen.Clock.GetUtcNow(); - var deadline = started + _screen.ActionTimeout; - var reads = _screen.Reads(new Deadline(deadline)); - var stamp = Stopwatch.GetTimestamp(); - var sampled = false; - while (true) - { - var node = await ResolveCountedAsync(token, reads, sampled, () => Stopwatch.GetElapsedTime(stamp)).ConfigureAwait(false); - sampled = true; - if (node is not null) - { - return node; - } - - if (_screen.Clock.GetUtcNow() >= deadline) - { - throw NotFound(_screen.Clock.GetUtcNow() - started); - } - - await Task.Delay(_screen.PollInterval, token).ConfigureAwait(false); - } - } - - /// - /// Waits until for the one match. More than one match fails at once. Upstream's resolveExactlyOne, - /// which a drag uses for the node it drops on. - /// - internal async Task ResolveExactlyOneAsync(Deadline deadline, CancellationToken token) - { - var started = _screen.Clock.GetTimestamp(); - var reads = _screen.Reads(deadline); - var sampled = false; - while (true) - { - var node = await ResolveCountedAsync(token, reads, sampled, () => _screen.Clock.GetElapsedTime(started)).ConfigureAwait(false); - sampled = true; - if (node is not null) - { - return node; - } - - if (deadline.Expired(_screen.Clock.GetUtcNow())) - { - throw NotFound(_screen.Clock.GetElapsedTime(started)); - } - - await Task.Delay(_screen.PollInterval, token).ConfigureAwait(false); - } - } - /// Returns the one match, or null when nothing matches. More than one match fails. - internal async Task ResolveSingleAsync(CancellationToken token, ReadWindow? reads = null, MissingFrame missingFrame = MissingFrame.Wait) - { - var matches = await ResolveAsync(token, reads: reads, missingFrame: missingFrame).ConfigureAwait(false); - if (matches.Count > 1) - { - throw Ambiguous(matches.Count); - } - - return matches.Count == 1 ? matches[0] : null; - } + internal Task ResolveSingleAsync(CancellationToken token, ReadWindow? reads = null, MissingFrame missingFrame = MissingFrame.Wait) => + _screen.Engine.TryReadAsync(Query, token, reads, missingFrame); /// - /// for a wait: a resolve the deadline cut off, after one that matched nothing, is the wait running out - /// (upstream's resolveCounted), reported as not found rather than as the timeout of the read. + /// Waits until for the one match. Upstream's resolveExactlyOne, which a drag uses for the node it drops on. /// - private async Task ResolveCountedAsync(CancellationToken token, ReadWindow reads, bool sampled, Func elapsed) - { - try - { - return await ResolveSingleAsync(token, reads).ConfigureAwait(false); - } - catch (Exception ex) when (sampled && !token.IsCancellationRequested && reads.CutOff(ex)) - { - throw new TestException("LOCATOR_NOT_FOUND", Query.Describe() + " matched 0 nodes.", ex) { Details = LocatorResolver.LocatorDetails(Query, elapsed()) }; - } - } + internal Task ResolveExactlyOneAsync(Deadline deadline, CancellationToken token) => + _screen.Engine.ResolveExactlyOneAsync(Query, deadline, token); - /// - /// The failure of an action whose deadline passed before it was sent. A read may finish past its deadline so its result is classed - /// right; an action never starts past it (upstream's lateAction). - /// - private TestException LateAction(LocatorAction action) => - new("ACTION_FAILED", "operation timed out before the " + (action is LocatorAction.Select ? "select" : ApiName(action)) + " was sent: " + Query.Describe()); - - private TimeSpan TimeoutOf(TimeSpan? timeout) => _screen.TimeoutOf(timeout); + private TimeSpan TimeoutOf(TimeSpan? timeout) => _screen.Engine.TimeoutOf(timeout); private static string StateName(WaitForState state) => state switch { @@ -1629,21 +1104,6 @@ private TestException LateAction(LocatorAction action) => WaitForState.Hidden => "hidden", _ => "visible", }; - - private TestException Ambiguous(int count) => - new("LOCATOR_AMBIGUOUS", Query.Describe() + " matched " + count.ToString(System.Globalization.CultureInfo.InvariantCulture) + " nodes.") { Details = LocatorResolver.LocatorDetails(Query) with { Matches = count } }; - - private TestException NotFound(TimeSpan waited) => new("LOCATOR_NOT_FOUND", Query.Describe() + " matched 0 nodes.") { Details = LocatorResolver.LocatorDetails(Query, waited) }; -} - -/// What a frame the engine reports missing means to a resolve (upstream's MissingFrame). -internal enum MissingFrame -{ - /// Treated like a node that is not there yet: the resolve keeps polling for it. - Wait, - - /// Answers zero matches. - Empty, } /// Options for one locator action. @@ -1990,25 +1450,6 @@ void Add(string key, bool? state) /// internal static class LocatorResolver { - /// - /// The facts of a locator failure an error keeps beside the message (upstream's locatorDetails): the locator as written, - /// what it asked for, and how long it waited, when it waited. - /// - public static ErrorDetails LocatorDetails(LocatorExpression query, TimeSpan? waited = null) => - query.ExpressionHints() with { Locator = query.Describe(), WaitedMs = waited is { } elapsed ? (long)elapsed.TotalMilliseconds : null }; - - /// - /// Translates an engine error into the runner-owned public taxonomy (upstream's translateLocatorError, locator/engine.ts), - /// naming in the message when one is given. A missing or ambiguous frame also carries the locator's details. - /// - public static Exception TranslateLocatorError(Exception cause, LocatorExpression? query = null) - { - var translated = ErrorSerializer.TranslateEngineError(cause, query is null ? "" : ": " + query.Describe()); - return query is not null && translated is TestException { Code: "LOCATOR_NOT_FOUND" or "LOCATOR_AMBIGUOUS" } frame && cause is EngineException { Code: EngineErrorCodes.FrameNotFound or EngineErrorCodes.FrameAmbiguous } - ? new TestException(frame.Code, frame.Message, frame.InnerException!) { Details = LocatorDetails(query) } - : translated; - } - /// /// Returns the nodes names. /// asks for every attached node, so role queries match hidden nodes too. diff --git a/src/E2E/Run/E2ESession.cs b/src/E2E/Run/E2ESession.cs index 259fcdc0d..bc720ed65 100644 --- a/src/E2E/Run/E2ESession.cs +++ b/src/E2E/Run/E2ESession.cs @@ -348,18 +348,22 @@ internal static async Task LaunchAsync(E2ESessionOptions options, IR browser.Failed = scope.Implicate; browser.Attach = scope.AttachArtifact; var agent = new Agent(scope); + var locatorEngine = new LocatorEngine(new LocatorEngineOptions + { + Observe = scope.ObserveAsync, + ObserveWithin = scope.ObserveAsync, + Locate = engine.CanLocate ? engine.LocateAsync : null, + Perform = engine.PerformAsync, + PerformAt = engine.PerformAtAsync, + Cancellation = () => timeout.Token, + ActionTimeout = options.ActionTimeout, + AssertionTimeout = options.AssertionTimeout, + }); var screen = new Screen( - scope.ObserveAsync, - (node, action, token) => engine.PerformAsync(node, action, OperationContext.Test, token), - () => timeout.Token, + locatorEngine, scope.MarkVerified, - options.ActionTimeout, - options.AssertionTimeout, softFailures, - locate: engine.CanLocate ? engine.LocateAsync : null, - swipe: (direction, momentum, token) => engine.SwipeAsync(direction, momentum, OperationContext.Test, token), - observeWithin: scope.ObserveAsync, - performAt: (point, action, token) => engine.PerformAtAsync(point, action, OperationContext.Test, token)); + (direction, momentum, token) => engine.SwipeAsync(direction, momentum, OperationContext.Test, token)); var fixtureContext = new EngineFixtureContext(screen); browser.Context = fixtureContext; (engine as IEngineFixtureHost)?.CreateFixtures(fixtureContext); diff --git a/tests/E2E.Tests/EngineLocate/WebAndDocumentEngineLocateTests.cs b/tests/E2E.Tests/EngineLocate/WebAndDocumentEngineLocateTests.cs index 1677a6d23..235799481 100644 --- a/tests/E2E.Tests/EngineLocate/WebAndDocumentEngineLocateTests.cs +++ b/tests/E2E.Tests/EngineLocate/WebAndDocumentEngineLocateTests.cs @@ -156,7 +156,7 @@ public async Task A_locator_waits_for_a_hidden_role_node_to_be_attached_through_ await WebEngineTests.RunAsync(session, async () => { await session.App.OpenAsync("/"); - Assert.True(session.Screen.LocatesInEngine); + Assert.True(session.Screen.Engine.LocatesInEngine); Assert.Equal(0, await session.Screen.GetByRole("status").CountAsync()); await Expect.That(session.Screen.GetByRole("status")).ToBeAttachedAsync(); await session.Screen.GetByRole("status").WaitForAsync(new LocatorWaitForOptions { State = WaitForState.Hidden }); diff --git a/tests/E2E.Tests/Lifecycle/OnOneSharedBrowserAFreshAttemptPerTestTests.cs b/tests/E2E.Tests/Lifecycle/OnOneSharedBrowserAFreshAttemptPerTestTests.cs index 9fc6ddee8..07588fe1a 100644 --- a/tests/E2E.Tests/Lifecycle/OnOneSharedBrowserAFreshAttemptPerTestTests.cs +++ b/tests/E2E.Tests/Lifecycle/OnOneSharedBrowserAFreshAttemptPerTestTests.cs @@ -69,15 +69,15 @@ await WebSemanticsTests.RunAsync(session, async () => // Every pointer kind at a bare point, read back from the page's event log. Assert.Equal(["tap", "doubleTap", "secondaryTap", "longPress", "hover", "dragTo", "swipe", "swipeTo"], session.Screen.PointerActionKinds); - await session.Screen.PerformAtAsync(new Point(150, 350), new PointerAction.Tap(), CancellationToken.None); - await session.Screen.PerformAtAsync(new Point(160, 360), new PointerAction.DoubleTap(), CancellationToken.None); - await session.Screen.PerformAtAsync(new Point(170, 370), new PointerAction.SecondaryTap(), CancellationToken.None); - await session.Screen.PerformAtAsync(new Point(180, 380), new PointerAction.LongPress(TimeSpan.FromMilliseconds(120)), CancellationToken.None); - await session.Screen.PerformAtAsync(new Point(190, 390), new PointerAction.Hover(), CancellationToken.None); - await session.Screen.PerformAtAsync(new Point(200, 400), new PointerAction.DragTo(new Point(300, 450)), CancellationToken.None); - await session.Screen.PerformAtAsync(new Point(210, 410), new PointerAction.Swipe(ScrollDirection.Down), CancellationToken.None); + await session.Screen.Engine.SessionPerformAtAsync(new Point(150, 350), new PointerAction.Tap(), CancellationToken.None); + await session.Screen.Engine.SessionPerformAtAsync(new Point(160, 360), new PointerAction.DoubleTap(), CancellationToken.None); + await session.Screen.Engine.SessionPerformAtAsync(new Point(170, 370), new PointerAction.SecondaryTap(), CancellationToken.None); + await session.Screen.Engine.SessionPerformAtAsync(new Point(180, 380), new PointerAction.LongPress(TimeSpan.FromMilliseconds(120)), CancellationToken.None); + await session.Screen.Engine.SessionPerformAtAsync(new Point(190, 390), new PointerAction.Hover(), CancellationToken.None); + await session.Screen.Engine.SessionPerformAtAsync(new Point(200, 400), new PointerAction.DragTo(new Point(300, 450)), CancellationToken.None); + await session.Screen.Engine.SessionPerformAtAsync(new Point(210, 410), new PointerAction.Swipe(ScrollDirection.Down), CancellationToken.None); // A fractional path lands on whole pixels: the browser would truncate it a pixel early. - await session.Screen.PerformAtAsync(new Point(220.6, 420.4), new PointerAction.SwipeTo(new Point(320.5, 460.5)), CancellationToken.None); + await session.Screen.Engine.SessionPerformAtAsync(new Point(220.6, 420.4), new PointerAction.SwipeTo(new Point(320.5, 460.5)), CancellationToken.None); // The port's text read folds the log's line breaks into spaces; no entry holds one. var lines = ((await screen.GetByTestId("log").TextContentAsync()) ?? "").Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList(); Assert.Contains("click:150,350", lines); diff --git a/tests/E2E.Tests/LocatorEngine/IsNodeVisibleTests.cs b/tests/E2E.Tests/LocatorEngine/IsNodeVisibleTests.cs new file mode 100644 index 000000000..c452561db --- /dev/null +++ b/tests/E2E.Tests/LocatorEngine/IsNodeVisibleTests.cs @@ -0,0 +1,21 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using E2E.Engine; +using Locators = global::E2E.LocatorEngine; + +namespace E2E.Tests.LocatorEngine; + +/// Upstream's isNodeVisible. +public sealed class IsNodeVisibleTests +{ + [Fact] + public void Treats_missing_nodes_and_hidden_state_correctly() + { + Assert.False(Locators.IsNodeVisible(null)); + Assert.False(Locators.IsNodeVisible(new SemanticNode { Ref = "node-1", Role = "button", Name = "Submit", States = new NodeStates { Hidden = true } })); + Assert.True(Locators.IsNodeVisible(new SemanticNode { Ref = "node-1", Role = "button", Name = "Submit", States = new NodeStates { Hidden = false } })); + Assert.True(Locators.IsNodeVisible(new SemanticNode { Ref = "node-1", Role = "button" })); + } +} diff --git a/tests/E2E.Tests/LocatorEngine/LocatorEnginePerformContractTests.cs b/tests/E2E.Tests/LocatorEngine/LocatorEnginePerformContractTests.cs index 2eb927c66..0122b51e3 100644 --- a/tests/E2E.Tests/LocatorEngine/LocatorEnginePerformContractTests.cs +++ b/tests/E2E.Tests/LocatorEngine/LocatorEnginePerformContractTests.cs @@ -9,9 +9,8 @@ namespace E2E.Tests.LocatorEngine; /// -/// Upstream's LocatorEngine perform contract. The port has no LocatorEngine class: Screen and Locator hold its -/// retries, so these run through them. 'marks every action it performs with the test origin' is partial for that reason: it reads the origin -/// at the session the test's step reaches, not at the LocatorEngine that adds it. +/// Upstream's LocatorEngine perform contract. The retry tests run through Screen and Locator, which hand the +/// their query; the origin test runs on the engine itself. /// public sealed class LocatorEnginePerformContractTests { @@ -162,7 +161,17 @@ public async Task Never_sends_a_positioned_tap_whose_target_became_visible_past_ } [Fact] - public async Task Partial_Marks_every_action_it_performs_with_the_test_origin_so_an_engine_can_act_without_settling() + public async Task Marks_every_action_it_performs_with_the_test_origin_so_an_engine_can_act_without_settling() + { + var scripted = ScriptedLocatorEngine.Make(); + + await scripted.Engine.PerformAsync(ScriptedLocatorEngine.Expression, (_, _) => Task.FromResult(new LocatorAction.Tap()), null, CancellationToken.None); + + Assert.Equal([OperationOrigin.Test], scripted.Origins); + } + + [Fact] + public async Task NET_only_a_session_wires_the_test_origin_to_the_engine_a_test_acts_on() { var engine = new OriginRecordingEngine(new DocumentEngine(BillingWorld.Create())); await using var session = await E2ESession.StartAsync(new E2ESessionOptions diff --git a/tests/E2E.Tests/LocatorEngine/LocatorEngineReadAllNowContractTests.cs b/tests/E2E.Tests/LocatorEngine/LocatorEngineReadAllNowContractTests.cs new file mode 100644 index 000000000..a82436f50 --- /dev/null +++ b/tests/E2E.Tests/LocatorEngine/LocatorEngineReadAllNowContractTests.cs @@ -0,0 +1,40 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using E2E.Engine; + +namespace E2E.Tests.LocatorEngine; + +/// +/// Upstream's LocatorEngine readAllNow contract. The port's locate answers the nodes themselves, so there is no session.read to +/// go stale between a resolve and a read: the 're-resolves the whole set when one member went stale between resolve and read', 'gives up on +/// a set that stays stale at the deadline as LOCATOR_NOT_FOUND' and 'translates non-stale read failures' its have nothing to run and are not +/// ported, and the first it, which counts reads, is Partial_: it checks the resolve and the order, not a read call. +/// +public sealed class LocatorEngineReadAllNowContractTests +{ + private static readonly SemanticNode Other = new() { Ref = "node-2", Role = "button", Name = "Cancel" }; + + [Fact] + public async Task Partial_Reads_every_current_match_in_the_order_the_engine_resolved_them() + { + var scripted = ScriptedLocatorEngine.Make([ScriptedLocatorEngine.Nodes(ScriptedLocatorEngine.Node, Other)]); + var engine = scripted.Engine; + + var nodes = await engine.ReadAllNowAsync(ScriptedLocatorEngine.Expression, CancellationToken.None, engine.Reads(engine.DeadlineFor())); + + Assert.Equal([ScriptedLocatorEngine.Node.Ref, Other.Ref], nodes.Select(node => node.Ref)); + Assert.Equal(1, scripted.Resolves); + } + + [Fact] + public async Task Answers_zero_matches_with_an_empty_list_without_waiting() + { + var scripted = ScriptedLocatorEngine.Make([ScriptedLocatorEngine.Nodes()]); + var engine = scripted.Engine; + + Assert.Empty(await engine.ReadAllNowAsync(ScriptedLocatorEngine.Expression, CancellationToken.None, engine.Reads(engine.DeadlineFor()))); + Assert.Equal(1, scripted.Resolves); + } +} diff --git a/tests/E2E.Tests/LocatorEngine/LocatorEngineReadsThatDoNotWaitTests.cs b/tests/E2E.Tests/LocatorEngine/LocatorEngineReadsThatDoNotWaitTests.cs new file mode 100644 index 000000000..51d621bd6 --- /dev/null +++ b/tests/E2E.Tests/LocatorEngine/LocatorEngineReadsThatDoNotWaitTests.cs @@ -0,0 +1,109 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using System.Diagnostics; +using E2E.Engine; + +namespace E2E.Tests.LocatorEngine; + +/// +/// Upstream's LocatorEngine reads that do not wait. The port's locate answers the nodes themselves, so there is no separate +/// session.read call: the 'readNow answers null for a node that went stale between resolve and read, without a second read' it has +/// nothing to run and is not ported, and the 'readNow re-resolves after a stale resolve' it, which counts a read, is Partial_: it +/// checks the resolves and the node, not a read call. +/// +public sealed class LocatorEngineReadsThatDoNotWaitTests +{ + private static readonly SemanticNode Node = ScriptedLocatorEngine.Node; + + private static readonly LocatorExpression Expression = ScriptedLocatorEngine.Expression; + + [Fact] + public async Task ResolveNow_answers_a_missing_frame_with_zero_matches_at_once() + { + var scripted = ScriptedLocatorEngine.Make([ScriptedLocatorEngine.Frame, ScriptedLocatorEngine.Nodes(Node)], actionTimeout: TimeSpan.FromMilliseconds(5_000)); + var watch = Stopwatch.StartNew(); + + var matches = await scripted.Engine.ResolveNowAsync(Expression, CancellationToken.None); + + Assert.Empty(matches); + Assert.Equal(1, scripted.Resolves); + Assert.True(watch.Elapsed < TimeSpan.FromMilliseconds(1_000), "took " + watch.Elapsed); + } + + [Fact] + public async Task ResolveNow_still_re_resolves_after_a_stale_resolve_a_race_not_a_wait() + { + var scripted = ScriptedLocatorEngine.Make([ScriptedLocatorEngine.Stale, ScriptedLocatorEngine.Nodes(Node)]); + + var matches = await scripted.Engine.ResolveNowAsync(Expression, CancellationToken.None); + + Assert.Equal([Node.Ref], matches.Select(match => match.Ref)); + Assert.Equal(2, scripted.Resolves); + } + + [Fact] + public async Task ResolveNow_translates_a_non_retryable_failure_without_retrying() + { + var scripted = ScriptedLocatorEngine.Make([ScriptedLocatorEngine.Failure]); + + var error = await Assert.ThrowsAnyAsync(() => scripted.Engine.ResolveNowAsync(Expression, CancellationToken.None)); + + Assert.Equal("ENGINE_FAILURE", ErrorSerializer.Classify(error).Code); + Assert.Equal(1, scripted.Resolves); + } + + [Fact] + public async Task ReadNow_answers_null_for_a_missing_frame_without_reading() + { + var scripted = ScriptedLocatorEngine.Make([ScriptedLocatorEngine.Frame], actionTimeout: TimeSpan.FromMilliseconds(5_000)); + + Assert.Null(await scripted.Engine.ReadNowAsync(Expression, CancellationToken.None)); + Assert.Equal(1, scripted.Resolves); + } + + [Fact] + public async Task Partial_ReadNow_re_resolves_after_a_stale_resolve_as_a_poll_would_then_reads_the_node() + { + var scripted = ScriptedLocatorEngine.Make([ScriptedLocatorEngine.Stale, ScriptedLocatorEngine.Nodes(Node)]); + + var node = await scripted.Engine.ReadNowAsync(Expression, CancellationToken.None); + + Assert.Equal(Node.Ref, node?.Ref); + Assert.Equal(2, scripted.Resolves); + } + + [Fact] + public async Task ReadNow_gives_a_resolve_that_stays_stale_the_action_timeout_then_LOCATOR_NOT_FOUND() + { + var scripted = ScriptedLocatorEngine.Make(Enumerable.Repeat(ScriptedLocatorEngine.Stale, 50), actionTimeout: TimeSpan.FromMilliseconds(350)); + var watch = Stopwatch.StartNew(); + + var error = await Assert.ThrowsAnyAsync(() => scripted.Engine.ReadNowAsync(Expression, CancellationToken.None)); + + Assert.Equal("LOCATOR_NOT_FOUND", ErrorSerializer.Classify(error).Code); + Assert.True(watch.Elapsed >= TimeSpan.FromMilliseconds(300), "failed after " + watch.Elapsed); + Assert.True(scripted.Resolves > 1); + } + + [Fact] + public async Task ReadNow_reads_the_one_match_and_refuses_two_with_LOCATOR_AMBIGUOUS() + { + Assert.Equal(Node.Ref, (await ScriptedLocatorEngine.Make().Engine.ReadNowAsync(Expression, CancellationToken.None))?.Ref); + var twins = ScriptedLocatorEngine.Make([ScriptedLocatorEngine.Nodes(Node, new SemanticNode { Ref = "node-2", Role = "button", Name = "Submit" })]); + + var error = await Assert.ThrowsAsync(() => twins.Engine.ReadNowAsync(Expression, CancellationToken.None)); + + Assert.Equal("LOCATOR_AMBIGUOUS", error.Code); + } + + [Fact] + public async Task ReadAllNow_answers_a_missing_frame_with_no_nodes_without_reading() + { + var scripted = ScriptedLocatorEngine.Make([ScriptedLocatorEngine.Frame], actionTimeout: TimeSpan.FromMilliseconds(5_000)); + + Assert.Empty(await scripted.Engine.ReadAllNowAsync(Expression, CancellationToken.None)); + Assert.Equal(1, scripted.Resolves); + } +} diff --git a/tests/E2E.Tests/LocatorEngine/LocatorEngineResolveRetryContractTests.cs b/tests/E2E.Tests/LocatorEngine/LocatorEngineResolveRetryContractTests.cs index 5111daed8..6ac252592 100644 --- a/tests/E2E.Tests/LocatorEngine/LocatorEngineResolveRetryContractTests.cs +++ b/tests/E2E.Tests/LocatorEngine/LocatorEngineResolveRetryContractTests.cs @@ -8,12 +8,10 @@ namespace E2E.Tests.LocatorEngine; /// -/// The port resolves a locator over one observation per try and has no engine locate to retry, so the count of -/// resolves is the count of observations. The other upstream its of this file are not ported: the retry on a stale or frame miss, the deadline cut of a -/// resolve, the stale read contract, and readAll and readNow by reference, all of which need the engine reference API the -/// port does not have. The reads that take time run through a screen whose engine resolves locators itself, which is how the budget of -/// a read reaches the engine; the port polls every 50 ms where upstream polls every 100 ms, so the budgets differ by that. The perform contract is in , and translateLocatorError in -/// . +/// Upstream's LocatorEngine resolve retry contract. The tests that run on the use a +/// , upstream's makeEngine; the port polls every 50 ms where upstream polls every 100 ms, so the +/// budgets of the retries differ by that. The perform contract is in , and +/// translateLocatorError in . /// public sealed class LocatorEngineResolveRetryContractTests { @@ -159,4 +157,80 @@ public async Task Gives_each_retry_of_a_resolve_what_is_left_of_its_budget_not_t Assert.True(budgets[1] < budgets[0] - TimeSpan.FromMilliseconds(40), string.Join(", ", budgets)); Assert.True(budgets[2] < budgets[1] - TimeSpan.FromMilliseconds(40), string.Join(", ", budgets)); } + + [Fact] + public async Task Retries_retryable_frame_misses_until_the_engine_recovers() + { + var scripted = ScriptedLocatorEngine.Make([ScriptedLocatorEngine.Frame, ScriptedLocatorEngine.Stale, ScriptedLocatorEngine.Nodes(ScriptedLocatorEngine.Node)]); + + var node = await scripted.Engine.ResolveExactlyOneAsync(ScriptedLocatorEngine.Expression, scripted.Engine.DeadlineFor(), CancellationToken.None); + + Assert.Equal(ScriptedLocatorEngine.Node.Ref, node.Ref); + Assert.Equal(3, scripted.Resolves); + } + + [Fact] + public async Task Translates_a_non_retryable_resolve_failure_immediately_without_retrying() + { + var scripted = ScriptedLocatorEngine.Make([ScriptedLocatorEngine.Failure]); + var engine = scripted.Engine; + + var error = await Assert.ThrowsAnyAsync(() => engine.ResolveNowAsync(ScriptedLocatorEngine.Expression, CancellationToken.None, engine.Reads(engine.DeadlineFor()))); + + var classified = ErrorSerializer.Classify(error); + Assert.Equal("infrastructure", classified.Category); + Assert.Equal("ENGINE_FAILURE", classified.Code); + Assert.Equal(1, scripted.Resolves); + } + + [Fact] + public async Task Gives_up_on_persistent_retryable_errors_at_the_deadline_with_the_translated_error() + { + var scripted = ScriptedLocatorEngine.Make(Enumerable.Repeat(ScriptedLocatorEngine.Stale, 50), actionTimeout: TimeSpan.FromMilliseconds(350)); + var engine = scripted.Engine; + + var error = await Assert.ThrowsAnyAsync(() => engine.ResolveNowAsync(ScriptedLocatorEngine.Expression, CancellationToken.None, engine.Reads(engine.DeadlineFor()))); + + var classified = ErrorSerializer.Classify(error); + Assert.Equal("test", classified.Category); + Assert.Equal("LOCATOR_NOT_FOUND", classified.Code); + } + + [Fact] + public async Task Reports_a_resolve_the_deadline_cut_off_after_one_that_matched_nothing_as_LOCATOR_NOT_FOUND() + { + var deadline = new Deadline(TimeSpan.FromMilliseconds(350), TimeProvider.System); + ResolveStep cut = _ => deadline.Remaining(DateTimeOffset.UtcNow) < TimeSpan.FromMilliseconds(50) ? ScriptedLocatorEngine.TimedOut(_) : ScriptedLocatorEngine.Nodes()(_); + var scripted = ScriptedLocatorEngine.Make(Enumerable.Repeat(cut, 50)); + + var error = await Assert.ThrowsAsync(() => scripted.Engine.ResolveExactlyOneAsync(ScriptedLocatorEngine.Expression, deadline, CancellationToken.None)); + + Assert.Equal("LOCATOR_NOT_FOUND", error.Code); + var cause = Assert.IsType(error.InnerException); + Assert.Equal("ACTION_FAILED", cause.Code); + Assert.Contains("operation timed out", cause.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task Ends_a_frame_wait_the_deadline_cut_off_on_the_missing_frame_as_LOCATOR_NOT_FOUND() + { + var deadline = new Deadline(TimeSpan.FromMilliseconds(350), TimeProvider.System); + ResolveStep cut = _ => deadline.Remaining(DateTimeOffset.UtcNow) < TimeSpan.FromMilliseconds(50) ? ScriptedLocatorEngine.TimedOut(_) : ScriptedLocatorEngine.Frame(_); + var scripted = ScriptedLocatorEngine.Make(Enumerable.Repeat(cut, 50)); + + var error = await Assert.ThrowsAsync(() => scripted.Engine.ResolveExactlyOneAsync(ScriptedLocatorEngine.Expression, deadline, CancellationToken.None)); + + Assert.Equal("LOCATOR_NOT_FOUND", error.Code); + Assert.Contains("frame missing", error.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task Keeps_a_first_resolve_the_deadline_cut_off_a_timeout_because_nothing_was_ever_seen_missing() + { + var scripted = ScriptedLocatorEngine.Make([ScriptedLocatorEngine.TimedOut]); + + var error = await Assert.ThrowsAsync(() => scripted.Engine.ResolveExactlyOneAsync(ScriptedLocatorEngine.Expression, new Deadline(TimeSpan.Zero, TimeProvider.System), CancellationToken.None)); + + Assert.Equal("ACTION_FAILED", error.Code); + } } diff --git a/tests/E2E.Tests/LocatorEngine/LocatorEngineVisibleQueriesTests.cs b/tests/E2E.Tests/LocatorEngine/LocatorEngineVisibleQueriesTests.cs index b36905b08..c974a68e3 100644 --- a/tests/E2E.Tests/LocatorEngine/LocatorEngineVisibleQueriesTests.cs +++ b/tests/E2E.Tests/LocatorEngine/LocatorEngineVisibleQueriesTests.cs @@ -3,15 +3,14 @@ // SPDX-License-Identifier: Apache-2.0 using E2E.Engine; +using E2E.Internal; namespace E2E.Tests.LocatorEngine; /// -/// The port resolves a query over the observed tree, so a node that reports no visibility is shown and a visible query -/// under an index is not handed to an engine. So the upstream its "keeps nodes whose engine reports no visibility at all" -/// and "hands a visible query under an index to the engine unchanged: only it can filter before nth" are not ported. And -/// a role query never matches a hidden node, so the getByRole row of "without visible keeps the hidden twin, so the pair -/// is LOCATOR_AMBIGUOUS" is not ported (COMPATIBILITY, Locators). +/// A role query never matches a hidden node, so the getByRole row of "without visible keeps the hidden twin, so the pair +/// is LOCATOR_AMBIGUOUS" is not ported (COMPATIBILITY, Locators). The two tests that hand the query to an engine of its own run on a +/// over a locate, as upstream's makeLocatorEngineOverEngine does. /// public sealed class LocatorEngineVisibleQueriesTests { @@ -95,4 +94,45 @@ public async Task Names_the_predicate_in_the_ambiguity_message_when_two_visible_ Assert.Equal("LOCATOR_AMBIGUOUS", error.Code); Assert.Contains("getByText(\"Save\", visible: true)", error.Message, StringComparison.Ordinal); } + + /// A locator engine over an engine that answers every locate with , and keeps the expressions it was asked. + private static E2E.LocatorEngine EngineAnswering(IReadOnlyList nodes, List expressions) => new(new LocatorEngineOptions + { + Observe = _ => Task.FromResult(new Observation { Route = "/", Roots = [] }), + Locate = (expression, _, _) => + { + expressions.Add(expression); + return Task.FromResult(nodes); + }, + Perform = (_, _, _, _) => Task.CompletedTask, + Cancellation = () => CancellationToken.None, + ActionTimeout = TimeSpan.FromMilliseconds(1_000), + AssertionTimeout = TimeSpan.FromMilliseconds(1_000), + }); + + [Fact] + public async Task Keeps_nodes_whose_engine_reports_no_visibility_at_all() + { + var engine = EngineAnswering([new SemanticNode { Ref = "unknown", Role = "button", Name = "Save" }], []); + var query = ScreenOver([], []).GetByRole("button", new RoleOptions { Name = "Save", Visible = true }).Query; + + var node = await engine.ResolveExactlyOneAsync(query, new Deadline(TimeSpan.FromMilliseconds(5_000), TimeProvider.System), CancellationToken.None); + + Assert.Equal("unknown", node.Ref); + } + + [Fact] + public async Task Hands_a_visible_query_under_an_index_to_the_engine_unchanged_only_it_can_filter_before_nth() + { + var expressions = new List(); + var engine = EngineAnswering(Twins, expressions); + var indexed = ScreenOver([], []).GetByText("Save", new TextMatchOptions { Visible = true }).First().Query; + + // The adapter cannot know which of the engine's answers came first, so it must not second-guess them; the engine applied + // `visible` before `first`. + var matches = await engine.ResolveNowAsync(indexed, CancellationToken.None, engine.Reads(engine.DeadlineFor())); + + Assert.Equal(2, matches.Count); + Assert.Equal(indexed, expressions[0]); + } } diff --git a/tests/E2E.Tests/LocatorEngine/OriginRecordingEngine.cs b/tests/E2E.Tests/LocatorEngine/OriginRecordingEngine.cs index 2060c1d7d..be0b8c79f 100644 --- a/tests/E2E.Tests/LocatorEngine/OriginRecordingEngine.cs +++ b/tests/E2E.Tests/LocatorEngine/OriginRecordingEngine.cs @@ -7,9 +7,9 @@ namespace E2E.Tests.LocatorEngine; /// -/// Wraps an engine and records the origin of every action it is asked to perform: the origins list of makeEngine in -/// upstream's locator-engine.test.ts, whose perform pushes operation.origin. An action that reaches the session -/// without a context is not recorded, so a caller that never says who acts fails the test. +/// Wraps an engine and records the origin of every action it is asked to perform (.NET-only): what makeEngine in upstream's +/// locator-engine.test.ts records at its fake session, here at the real session a test's step reaches. An action that reaches the +/// session without a context is not recorded, so a caller that never says who acts fails the test. /// internal sealed class OriginRecordingEngine(IEngine inner) : IEngine { diff --git a/tests/E2E.Tests/LocatorEngine/ScriptedLocatorEngine.cs b/tests/E2E.Tests/LocatorEngine/ScriptedLocatorEngine.cs new file mode 100644 index 000000000..fc467fe4b --- /dev/null +++ b/tests/E2E.Tests/LocatorEngine/ScriptedLocatorEngine.cs @@ -0,0 +1,160 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using E2E.Engine; + +namespace E2E.Tests.LocatorEngine; + +/// One scripted answer of a fake locate: what it resolves, given the budget of that locate. +internal delegate Task> ResolveStep(TimeSpan budget); + +/// +/// The makeEngine of upstream's locator-engine.test.ts: a over a fake session whose locate and +/// perform answer the next entry of a script, and a default past its end (the one match, an action that succeeds). The port's locate answers +/// the nodes themselves, so there is no read script: a node is read as it is resolved. +/// +internal sealed class ScriptedLocatorEngine +{ + /// The one node a default locate answers, upstream's NODE. + public static readonly SemanticNode Node = new() { Ref = "node-1", Role = "button", Name = "Submit" }; + + /// The expression every test resolves, upstream's EXPRESSION: a role query for a button. + public static readonly LocatorExpression Expression = new Screen( + _ => Task.FromResult(new Observation { Route = "/", Roots = [] }), + (_, _, _) => Task.CompletedTask, + () => CancellationToken.None, + () => { }, + TimeSpan.FromMilliseconds(300), + TimeSpan.FromMilliseconds(300)).GetByRole("button").Query; + + private readonly List _resolve; + private readonly List> _perform; + private readonly List _resolveTimeouts = []; + private readonly List _origins = []; + private readonly List _performed = []; + private readonly List<(Point Point, PointerAction Action)> _performedAt = []; + private readonly object _gate = new(); + private int _resolves; + private int _performs; + + private ScriptedLocatorEngine(List resolve, List> perform, TimeSpan actionTimeout, TimeProvider? clock) + { + _resolve = resolve; + _perform = perform; + Engine = new E2E.LocatorEngine(new LocatorEngineOptions + { + Observe = _ => Task.FromResult(new Observation { Route = "/", Roots = [] }), + Locate = (_, budget, _) => LocateAsync(budget), + Perform = (_, action, context, _) => PerformAsync(action, context), + PerformAt = (point, action, _, _) => + { + lock (_gate) + { + _performedAt.Add((point, action)); + } + + return Task.CompletedTask; + }, + Cancellation = () => CancellationToken.None, + ActionTimeout = actionTimeout, + AssertionTimeout = TimeSpan.FromMilliseconds(1_000), + Clock = clock ?? TimeProvider.System, + }); + } + + /// The engine under test. + public E2E.LocatorEngine Engine { get; } + + /// How many locates, and how many performs, the session has answered. + public int Resolves => Locked(() => _resolves); + + /// + public int Performs => Locked(() => _performs); + + /// The budget each locate was given, in order (upstream's resolveTimeouts). + public IReadOnlyList ResolveTimeouts => Locked(() => (IReadOnlyList)[.. _resolveTimeouts]); + + /// The origin each perform was marked with (upstream's origins). + public IReadOnlyList Origins => Locked(() => (IReadOnlyList)[.. _origins]); + + /// The actions the session performed, in order (upstream's performed). + public IReadOnlyList Performed => Locked(() => (IReadOnlyList)[.. _performed]); + + /// The pointer actions the session performed at a point, in order. + public IReadOnlyList<(Point Point, PointerAction Action)> PerformedAt => Locked(() => (IReadOnlyList<(Point Point, PointerAction Action)>)[.. _performedAt]); + + /// A resolve that answers , as a default locate does. + public static ResolveStep Nodes(params SemanticNode[] nodes) => _ => Task.FromResult>(nodes); + + /// A resolve that answers after , ended at its budget (upstream's slowResolve). + public static ResolveStep Slow(TimeSpan after, params SemanticNode[] nodes) => budget => SlowLocate.AnswerAsync(after, nodes, budget); + + /// A resolve that never answers on its own, ended at its budget. + public static ResolveStep Hang => SlowLocate.HangAsync; + + /// A resolve that fails with a retryable NODE_STALE. + public static ResolveStep Stale => Fail(new EngineException(EngineErrorCodes.NodeStale, "stale", retryable: true)); + + /// A resolve that fails with a retryable FRAME_NOT_FOUND. + public static ResolveStep Frame => Fail(new EngineException(EngineErrorCodes.FrameNotFound, "frame missing", retryable: true)); + + /// A resolve that fails with a non-retryable ENGINE_FAILURE. + public static ResolveStep Failure => Fail(new EngineException(EngineErrorCodes.EngineFailure, "engine died", retryable: false)); + + /// A resolve that fails with a non-retryable OPERATION_TIMEOUT, as an engine does at the end of its budget. + public static ResolveStep TimedOut => Fail(new EngineException(EngineErrorCodes.OperationTimeout, "locate timed out", retryable: false)); + + /// A perform that fails with a retryable NODE_STALE. + public static Func PerformStale { get; } = () => Task.FromException(new EngineException(EngineErrorCodes.NodeStale, "stale", retryable: true)); + + /// A perform that fails with a non-retryable ACTION_MAY_HAVE_COMMITTED. + public static Func Committed { get; } = () => Task.FromException(new EngineException(EngineErrorCodes.ActionMayHaveCommitted, "maybe committed", retryable: false)); + + /// A perform that fails with a non-retryable NOT_ACTIONABLE. + public static Func NotActionable { get; } = () => Task.FromException(new EngineException(EngineErrorCodes.NotActionable, "covered by overlay", retryable: false)); + + /// A perform that succeeds. + public static Func Succeeds { get; } = () => Task.CompletedTask; + + /// Builds the engine over a script, 1 s of action timeout unless says otherwise. + public static ScriptedLocatorEngine Make(IEnumerable? resolve = null, IEnumerable>? perform = null, TimeSpan? actionTimeout = null, TimeProvider? clock = null) => + new([.. resolve ?? []], [.. perform ?? []], actionTimeout ?? TimeSpan.FromMilliseconds(1_000), clock); + + private T Locked(Func read) + { + lock (_gate) + { + return read(); + } + } + + private static ResolveStep Fail(Exception failure) => _ => Task.FromException>(failure); + + private Task> LocateAsync(TimeSpan budget) + { + ResolveStep? step; + lock (_gate) + { + _resolveTimeouts.Add(budget); + step = _resolves < _resolve.Count ? _resolve[_resolves] : null; + _resolves++; + } + + return (step ?? Nodes(Node))(budget); + } + + private Task PerformAsync(LocatorAction action, OperationContext context) + { + Func? step; + lock (_gate) + { + _origins.Add(context.Origin); + _performed.Add(action); + step = _performs < _perform.Count ? _perform[_performs] : null; + _performs++; + } + + return (step ?? Succeeds)(); + } +} diff --git a/tests/E2E.Tests/LocatorEngine/TranslateLocatorErrorMappingTableTests.cs b/tests/E2E.Tests/LocatorEngine/TranslateLocatorErrorMappingTableTests.cs index 2200bbf12..0f5ef2e29 100644 --- a/tests/E2E.Tests/LocatorEngine/TranslateLocatorErrorMappingTableTests.cs +++ b/tests/E2E.Tests/LocatorEngine/TranslateLocatorErrorMappingTableTests.cs @@ -3,6 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 using E2E.Engine; +using Locators = global::E2E.LocatorEngine; namespace E2E.Tests.LocatorEngine; @@ -35,7 +36,7 @@ public void Engine_code_maps_to_category_and_code(string engineCode, string cate { var engineError = new EngineException(engineCode, "boom", retryable: false); - var translated = LocatorResolver.TranslateLocatorError(engineError); + var translated = Locators.TranslateLocatorError(engineError); var classified = ErrorSerializer.Classify(translated); Assert.Equal(category, classified.Category); @@ -48,13 +49,13 @@ public void Passes_existing_E2EErrors_through_unchanged() { var original = new ConfigurationException("INVALID_CONFIG", "bad config"); - Assert.Same(original, LocatorResolver.TranslateLocatorError(original)); + Assert.Same(original, Locators.TranslateLocatorError(original)); } [Fact] public void Wraps_unknown_errors_as_infrastructure_ENGINE_FAILURE() { - var translated = LocatorResolver.TranslateLocatorError(new InvalidOperationException("socket hangup")); + var translated = Locators.TranslateLocatorError(new InvalidOperationException("socket hangup")); var classified = ErrorSerializer.Classify(translated); Assert.Equal("infrastructure", classified.Category); @@ -65,7 +66,7 @@ public void Wraps_unknown_errors_as_infrastructure_ENGINE_FAILURE() [Fact] public void Appends_the_locator_description_when_an_expression_is_provided() { - var translated = LocatorResolver.TranslateLocatorError(new EngineException(EngineErrorCodes.NodeStale, "stale", retryable: false), Button); + var translated = Locators.TranslateLocatorError(new EngineException(EngineErrorCodes.NodeStale, "stale", retryable: false), Button); Assert.Contains("stale", translated.Message, StringComparison.Ordinal); Assert.EndsWith(": getByRole(\"button\")", translated.Message, StringComparison.Ordinal); @@ -76,7 +77,7 @@ public void NET_only_a_cancel_passes_through_as_a_cancel() { var cancel = new OperationCanceledException(); - Assert.Same(cancel, LocatorResolver.TranslateLocatorError(cancel, Button)); + Assert.Same(cancel, Locators.TranslateLocatorError(cancel, Button)); } [Fact]