Skip to content

Commit 108b3ed

Browse files
kblokclaude
andauthored
Port Playwright's check, wait-for-url, locator-list and selectors-text tests (#1064)
* Port Playwright's check, wait-for-url, locator-list and selectors-text tests (Refs #1060) The testbed gets the /content route and Playwright's test assets (with its LICENSE and NOTICE), and the first four of upstream's Playwright page test files run against them. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ls2e1yaZFgZ3FEJkYScfkK * Link the routes into the xUnit test project and pin the known difference of expected failures (Refs #1060) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ls2e1yaZFgZ3FEJkYScfkK --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent fe81b9d commit 108b3ed

14 files changed

Lines changed: 796 additions & 1 deletion

File tree

‎COMPATIBILITY.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,7 @@ Differences:
162162
- Upstream's docs site pages that have no counterpart in the port: the page objects page (`docs/page-objects.mdx`, moved to `/page-object-model` in `d30114a`), `e2e feedback` and the `docs/reference/cli.mdx` text about its opt-out variables (`4c1e2e8`), and `examples/` with its registry (`b3ae3a4`, `38b802d`, `a29edcb`, `b54646f`). The migration guides (`docs/migrate/*.mdx`, `8537abc`) are ported: see [Migration guides](#migration-guides). The docs site has .NET-only guides for upstream's five example apps of `caf51eb` (tester-army/e2e#1497: i18n, file upload, location, biometrics, deep links), under [Examples](docs-site/src/content/docs/examples/index.mdx). They are not ports: that commit only adds registry entries that link to separate repositories, so there was no guide text. Each page writes C# tests for the upstream app. The self-healing deep dive (`6fa99ea`) is ported as the [Self-healing tests](README.md#self-healing-tests) section of the guide, since the port has no docs pages for the cache, the trace page, or executors to link to. Known gap: only `e2e explore` prints a run summary, since it is the one command that feeds a run to `ListReporter` (see [List reporter](#list-reporter)): the `Cache 4 replayed · 1 handed off · 1 missed` row is `Format.CacheText` over `Format.StepsCacheTally` (`E2E.Cli`, upstream's `cacheText` and `stepsCacheTally` of `report/format.ts`), which an exploration, with its cache off, never fills, and a test run does not print ([#799](https://github.com/hardkoded/e2e-dotnet/issues/799))
163163
- Parallel workers and serial suites
164164
- `test.fail` and the `fail` test option (tester-army/e2e#1539, `732ea8a`): a test expected to fail, whose product failure passes and whose pass fails with `UNEXPECTED_PASS`. It lives in upstream's test registry, scheduler, retry, and reporters (`settleExpectedFailure` runs on a finished attempt), and the port has none of them. NUnit and xUnit v3 own the verdict and the retries, and neither has an expected-failure outcome, so a port would need a new public API of its own
165+
- Playwright's page tests in the testbed suite (tester-army/e2e#1505, `bdf769b`) are ported in slices (hardkoded/e2e-dotnet#1060), as the `playwright` category of `tests/E2E.NUnit.Tests`, against the playground's `/content` route and Playwright's test assets (Apache-2.0, `Testbed/playwright/`, with Playwright's `LICENSE` and `NOTICE`). A test upstream marks `{ fail: 'reason' }` keeps its assertions inside the test-only `Helpers.ExpectedToFailAsync`, which passes while the body fails and fails once it passes. Ported so far: `check`, `wait-for-url`, `locator-list`, and `selectors-text` (one test is such a known difference, hardkoded/e2e-dotnet#1062).
165166
- Serial groups (upstream tester-army/e2e#1056, #1470): serial runs, group retries, and skipping the rest of a group after a failure belong to the test runner, which is NUnit or xUnit here, so the port keeps no serial groups. The schema has `serialAttempt.cutRetry` and the serial verdict is read from it, but nothing in the port writes a serial attempt: see [Report document](#report-document)
166167
- The out-of-process engine protocol (upstream tester-army/e2e#1232, [#873](https://github.com/hardkoded/e2e-dotnet/issues/873)): the port has no runner and no worker pool, so there is no engine process to talk to. An engine is written in .NET against `IEngine`
167168
- Diff-only observations for a custom executor's own model turns. The built-in agent has them (#1022): `#id` lines on the opening screen and on `observe`, and a diff after each action (see [MCP server](#mcp-server) for the presenter). `ExecutorObservation.Text`, which an executor reads from `Observe`, keeps the full `[ref=…]` snapshot, cut at the observation byte budget (see [Agents](#agents)), and a node is addressed by its ref there (`new ExecutorTarget("e12")`), so a custom executor has no presenter of its own. Upstream gives every executor the `#id` view.
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// Copyright 2026 TesterArmy.
2+
// Modified by Dario Kondratiuk.
3+
// SPDX-License-Identifier: Apache-2.0
4+
5+
using System.Net;
6+
using System.Text;
7+
8+
namespace E2E.Playground;
9+
10+
/// <summary>
11+
/// The routes of the tests ported from Playwright, a port of upstream's <c>apps/testbed/app/playwright/routes.mjs</c>:
12+
/// its test assets (copied from microsoft/playwright <c>tests/assets</c> at v1.64.1, Apache-2.0, under
13+
/// <c>Testbed/playwright/assets</c> next to the test assembly) and the dynamic routes its test server sets per test.
14+
/// The playground serves them for any path it has no page for. This port has <c>/content</c> and the assets so far.
15+
/// </summary>
16+
internal static class PlaywrightRoutes
17+
{
18+
private static readonly string Root = Path.Combine(AppContext.BaseDirectory, "Testbed", "playwright", "assets");
19+
20+
private static readonly Dictionary<string, string> Types = new(StringComparer.Ordinal)
21+
{
22+
[".html"] = "text/html",
23+
[".js"] = "text/javascript",
24+
[".css"] = "text/css",
25+
[".json"] = "application/json",
26+
[".png"] = "image/png",
27+
[".pdf"] = "application/pdf",
28+
[".svg"] = "image/svg+xml",
29+
[".txt"] = "text/plain",
30+
};
31+
32+
/// <summary>Serves one request: a dynamic route, else an asset, else a 404.</summary>
33+
public static async Task HandleAsync(HttpListenerContext context)
34+
{
35+
var response = context.Response;
36+
var path = context.Request.Url!.AbsolutePath;
37+
if (path == "/content")
38+
{
39+
var html = context.Request.QueryString["html"] ?? "";
40+
response.ContentType = "text/html; charset=utf-8";
41+
await WriteAsync(response, FromBase64Url(html)).ConfigureAwait(false);
42+
return;
43+
}
44+
45+
var file = Path.GetFullPath(Path.Combine(Root, Uri.UnescapeDataString(path).TrimStart('/')));
46+
if (!file.StartsWith(Root + Path.DirectorySeparatorChar, StringComparison.Ordinal) || !File.Exists(file))
47+
{
48+
response.StatusCode = 404;
49+
response.ContentType = "text/plain";
50+
await WriteAsync(response, Encoding.UTF8.GetBytes("Not found")).ConfigureAwait(false);
51+
return;
52+
}
53+
54+
response.ContentType = Types.GetValueOrDefault(Path.GetExtension(file), "application/octet-stream");
55+
response.AddHeader("Cache-Control", "no-store");
56+
await WriteAsync(response, await File.ReadAllBytesAsync(file).ConfigureAwait(false)).ConfigureAwait(false);
57+
}
58+
59+
private static byte[] FromBase64Url(string value)
60+
{
61+
var padded = value.Replace('-', '+').Replace('_', '/');
62+
padded = padded.PadRight(padded.Length + ((4 - (padded.Length % 4)) % 4), '=');
63+
var bytes = new byte[padded.Length];
64+
return Convert.TryFromBase64String(padded, bytes, out var written) ? bytes[..written] : [];
65+
}
66+
67+
private static async Task WriteAsync(HttpListenerResponse response, byte[] bytes)
68+
{
69+
response.ContentLength64 = bytes.Length;
70+
await response.OutputStream.WriteAsync(bytes).ConfigureAwait(false);
71+
}
72+
}

‎tests/E2E.Agent.Tests/Testbed.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1014,7 +1014,7 @@ await WriteHtmlAsync(response, "Dashboard", """
10141014
}
10151015
else
10161016
{
1017-
response.StatusCode = 404;
1017+
await PlaywrightRoutes.HandleAsync(context).ConfigureAwait(false);
10181018
}
10191019

10201020
response.Close();
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
// Copyright 2026 TesterArmy.
2+
// Modified by Dario Kondratiuk.
3+
// SPDX-License-Identifier: Apache-2.0
4+
5+
using static E2E.NUnit.Tests.Helpers;
6+
7+
namespace E2E.NUnit.Tests.Check;
8+
9+
/// <summary>
10+
/// <c>test.describe('page check')</c> of upstream's <c>apps/testbed/tests/check.e2e.ts</c> (Playwright's <c>page-check.spec.ts</c>).
11+
/// Not ported, as upstream: should check the label with position (no <c>position</c>), trial run should not check and trial run
12+
/// should not uncheck (no <c>trial</c>), should check the box using setChecked (no <c>setChecked</c>).
13+
/// </summary>
14+
public sealed class PageCheckTests : PlaywrightTest
15+
{
16+
private static readonly string[] AriaRoles = ["checkbox", "menuitemcheckbox", "option", "radio", "switch", "menuitemradio", "treeitem"];
17+
18+
[Test]
19+
public async Task Should_check_the_box()
20+
{
21+
await Browser.GotoAsync(Content("<input id='checkbox' type='checkbox'></input>"));
22+
await Browser.Locator("input").CheckAsync();
23+
Assert.That(await Browser.EvaluateAsync<bool>("() => window.checkbox.checked"), Is.True);
24+
}
25+
26+
[Test]
27+
public async Task Should_not_check_the_checked_box()
28+
{
29+
await Browser.GotoAsync(Content("<input id='checkbox' type='checkbox' checked></input>"));
30+
await Browser.Locator("input").CheckAsync();
31+
Assert.That(await Browser.EvaluateAsync<bool>("() => window.checkbox.checked"), Is.True);
32+
}
33+
34+
[Test]
35+
public async Task Should_uncheck_the_box()
36+
{
37+
await Browser.GotoAsync(Content("<input id='checkbox' type='checkbox' checked></input>"));
38+
await Browser.Locator("input").UncheckAsync();
39+
Assert.That(await Browser.EvaluateAsync<bool>("() => window.checkbox.checked"), Is.False);
40+
}
41+
42+
[Test]
43+
public async Task Should_not_uncheck_the_unchecked_box()
44+
{
45+
await Browser.GotoAsync(Content("<input id='checkbox' type='checkbox'></input>"));
46+
await Browser.Locator("input").UncheckAsync();
47+
Assert.That(await Browser.EvaluateAsync<bool>("() => window.checkbox.checked"), Is.False);
48+
}
49+
50+
[Test]
51+
public async Task Should_check_radio()
52+
{
53+
await Browser.GotoAsync(Content("""
54+
<input type='radio'>one</input>
55+
<input id='two' type='radio'>two</input>
56+
<input type='radio'>three</input>
57+
"""));
58+
await Browser.Locator("#two").CheckAsync();
59+
Assert.That(await Browser.EvaluateAsync<bool>("() => window.two.checked"), Is.True);
60+
}
61+
62+
[Test]
63+
public async Task Should_check_radio_by_aria_role()
64+
{
65+
await Browser.GotoAsync(Content("""
66+
<div role='radio' id='checkbox'>CHECKBOX</div>
67+
<script>
68+
checkbox.addEventListener('click', () => checkbox.setAttribute('aria-checked', 'true'));
69+
</script>
70+
"""));
71+
await Browser.Locator("div").CheckAsync();
72+
Assert.That(await Browser.EvaluateAsync<string>("() => window.checkbox.getAttribute('aria-checked')"), Is.EqualTo("true"));
73+
}
74+
75+
// Upstream: { fail: '`uncheck` refuses a `role=radio`, where Playwright clicks it and refuses only a native radio' }.
76+
[Test]
77+
public async Task Should_uncheck_radio_by_aria_role()
78+
{
79+
await ExpectedToFailAsync("uncheck", async () =>
80+
{
81+
await Browser.GotoAsync(Content("""
82+
<div role='radio' id='checkbox' aria-checked="true">CHECKBOX</div>
83+
<script>
84+
checkbox.addEventListener('click', () => checkbox.setAttribute('aria-checked', 'false'));
85+
</script>
86+
"""));
87+
await Browser.Locator("div").UncheckAsync();
88+
Equal("false", await Browser.EvaluateAsync<string>("() => window.checkbox.getAttribute('aria-checked')"));
89+
});
90+
}
91+
92+
[Test]
93+
public async Task Should_check_the_box_by_aria_role()
94+
{
95+
foreach (var role in AriaRoles)
96+
{
97+
await Browser.GotoAsync(Content($$"""
98+
<div role='{{role}}' id='checkbox'>CHECKBOX</div>
99+
<script>
100+
checkbox.addEventListener('click', () => checkbox.setAttribute('aria-checked', 'true'));
101+
</script>
102+
"""));
103+
await Browser.Locator("div").CheckAsync();
104+
Assert.That(await Browser.EvaluateAsync<string>("() => window.checkbox.getAttribute('aria-checked')"), Is.EqualTo("true"));
105+
}
106+
}
107+
108+
// Upstream: { fail: '`uncheck` refuses a `role=radio`, where Playwright clicks it and refuses only a native radio' }.
109+
[Test]
110+
public async Task Should_uncheck_the_box_by_aria_role()
111+
{
112+
await ExpectedToFailAsync("uncheck", async () =>
113+
{
114+
foreach (var role in AriaRoles)
115+
{
116+
await Browser.GotoAsync(Content($$"""
117+
<div role='{{role}}' id='checkbox' aria-checked="true">CHECKBOX</div>
118+
<script>
119+
checkbox.addEventListener('click', () => checkbox.setAttribute('aria-checked', 'false'));
120+
</script>
121+
"""));
122+
await Browser.Locator("div").UncheckAsync();
123+
Equal("false", await Browser.EvaluateAsync<string>("() => window.checkbox.getAttribute('aria-checked')"));
124+
}
125+
});
126+
}
127+
128+
[Test]
129+
public async Task Should_throw_when_not_a_checkbox()
130+
{
131+
await Browser.GotoAsync(Content("<div>Check me</div>"));
132+
var error = await Assert.CatchAsync(() => Browser.Locator("div").CheckAsync());
133+
Assert.That(error!.Message, Does.Contain("Not a checkbox or radio button"));
134+
}
135+
136+
[Test]
137+
public async Task Should_throw_when_not_a_checkbox_2()
138+
{
139+
await Browser.GotoAsync(Content("<div role=button>Check me</div>"));
140+
var error = await Assert.CatchAsync(() => Browser.Locator("div").CheckAsync());
141+
Assert.That(error!.Message, Does.Contain("Not a checkbox or radio button"));
142+
}
143+
144+
[Test]
145+
public async Task Should_check_the_box_inside_a_button()
146+
{
147+
await Browser.GotoAsync(Content("<div role='button'><input type='checkbox'></div>"));
148+
await Browser.Locator("input").CheckAsync();
149+
Assert.That(await Browser.EvaluateAsync<bool>("() => document.querySelector('input').checked"), Is.True);
150+
Assert.That(await Browser.Locator("input").IsCheckedAsync(), Is.True);
151+
}
152+
153+
[Test]
154+
public async Task Should_throw_when_trying_to_uncheck_radio_button()
155+
{
156+
await Browser.GotoAsync(Content("<input type='radio' name='test' checked id='radio'>"));
157+
var error = await Assert.CatchAsync(() => Browser.Locator("#radio").UncheckAsync());
158+
Assert.That(error!.Message, Does.Contain("uncheck cannot clear a radio button"));
159+
}
160+
}

‎tests/E2E.NUnit.Tests/E2E.NUnit.Tests.csproj‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,9 @@
1616
</ItemGroup>
1717
<ItemGroup>
1818
<None Include="Testbed\control-inventory.html" CopyToOutputDirectory="PreserveNewest" />
19+
<None Include="Testbed\playwright\**" CopyToOutputDirectory="PreserveNewest" />
1920
<Compile Include="..\E2E.Agent.Tests\Testbed.cs" Link="Testbed\Playground.cs" />
21+
<Compile Include="..\E2E.Agent.Tests\PlaywrightRoutes.cs" Link="Testbed\PlaywrightRoutes.cs" />
2022
</ItemGroup>
2123
<ItemGroup>
2224
<ProjectReference Include="..\..\src\E2E.NUnit\E2E.NUnit.csproj" />
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// Copyright 2026 TesterArmy.
2+
// Modified by Dario Kondratiuk.
3+
// SPDX-License-Identifier: Apache-2.0
4+
5+
using System.Text;
6+
7+
namespace E2E.NUnit.Tests;
8+
9+
/// <summary>
10+
/// The helpers of the tests ported from Playwright, upstream's <c>apps/testbed/tests/helpers.ts</c>:
11+
/// <c>content</c> and <c>PREFIX</c>. <see cref="ExpectedToFailAsync"/> is .NET-only (see its summary).
12+
/// </summary>
13+
internal static class Helpers
14+
{
15+
/// <summary>The app's origin, Playwright's <c>server.PREFIX</c> in the tests ported from it.</summary>
16+
public static string PREFIX => E2E.Playground.Testbed.Url;
17+
18+
/// <summary>A path that serves <paramref name="html"/> as a page, for Playwright's <c>page.setContent(html)</c>.</summary>
19+
public static string Content(string html) =>
20+
"/content?html=" + Convert.ToBase64String(Encoding.UTF8.GetBytes(html)).TrimEnd('=').Replace('+', '-').Replace('/', '_');
21+
22+
/// <summary>
23+
/// An equality check for a body run by <see cref="ExpectedToFailAsync"/>. It throws: an NUnit assertion inside a test body is
24+
/// recorded as a failure of the test even when the body catches it.
25+
/// </summary>
26+
public static void Equal<T>(T expected, T actual)
27+
{
28+
if (!EqualityComparer<T>.Default.Equals(expected, actual))
29+
{
30+
throw new InvalidOperationException($"Expected {expected}, but was {actual}.");
31+
}
32+
}
33+
34+
/// <summary>
35+
/// Runs the body of a test upstream marks <c>{ fail: 'reason' }</c>, a known difference from Playwright: the test passes while
36+
/// <paramref name="body"/> still fails with a message that contains <paramref name="failure"/>, and fails once it passes, so the marker is removed. The port has no <c>fail</c> test option
37+
/// (see COMPATIBILITY.md), and NUnit has no expected-failure outcome.
38+
/// </summary>
39+
public static async Task ExpectedToFailAsync(string failure, Func<Task> body)
40+
{
41+
try
42+
{
43+
await body().ConfigureAwait(false);
44+
}
45+
catch (Exception ex) when (ex is not OperationCanceledException)
46+
{
47+
Assert.That(ex.Message, Does.Contain(failure), "the body failed, but not with the known difference");
48+
return;
49+
}
50+
51+
Assert.Fail("UNEXPECTED_PASS: the test is marked as a known difference from Playwright, and it passed. Remove the marker.");
52+
}
53+
}
54+
55+
/// <summary>
56+
/// The base of the classes ported from Playwright's page tests: the playground as the base URL, the cache off, and the <c>playwright</c>
57+
/// category (upstream's <c>tags: ['playwright']</c>).
58+
/// </summary>
59+
[Category("playwright")]
60+
public abstract class PlaywrightTest : E2ETest
61+
{
62+
private static readonly E2EConfig FixtureConfig = E2EConfig.Parse(
63+
"""{ "cache": { "mode": "off" } }""",
64+
AppContext.BaseDirectory,
65+
_ => null);
66+
67+
protected override E2EConfig Config => FixtureConfig;
68+
69+
protected override string? BaseUrl => E2E.Playground.Testbed.Url;
70+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Copyright 2026 TesterArmy.
2+
// Modified by Dario Kondratiuk.
3+
// SPDX-License-Identifier: Apache-2.0
4+
5+
using static E2E.NUnit.Tests.Helpers;
6+
7+
namespace E2E.NUnit.Tests.LocatorList;
8+
9+
/// <summary>
10+
/// <c>test.describe('locator list')</c> of upstream's <c>apps/testbed/tests/locator-list.e2e.ts</c> (Playwright's
11+
/// <c>locator-list.spec.ts</c>). <c>div &gt;&gt; p</c> is the CSS <c>div p</c>.
12+
/// </summary>
13+
public sealed class LocatorListTests : PlaywrightTest
14+
{
15+
[Test]
16+
public async Task Locator_all_should_work()
17+
{
18+
await Browser.GotoAsync(Content("<div><p>A</p><p>B</p><p>C</p></div>"));
19+
var texts = new List<string?>();
20+
foreach (var p in await Browser.Locator("div p").AllAsync())
21+
{
22+
texts.Add(await p.TextContentAsync());
23+
}
24+
25+
Assert.That(texts, Is.EqualTo(new[] { "A", "B", "C" }));
26+
}
27+
}

0 commit comments

Comments
 (0)