From e8a2bab42d4632a82662fb699d6ab925482fe615 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oskar=20Kwas=CC=81niewski?= Date: Sun, 1 Nov 2026 17:54:41 +0100 Subject: [PATCH 1/9] fix(e2e): fixture timeouts name the call label; url patterns quoted in steps --- .changeset/timeout-names-pattern.md | 6 ++++++ packages/e2e/src/run/fixture-recording.ts | 9 +++++---- packages/e2e/tests/unit/fixture-runtime.test.ts | 6 ++++-- packages/web/src/browser.ts | 13 +++++++++---- 4 files changed, 24 insertions(+), 10 deletions(-) create mode 100644 .changeset/timeout-names-pattern.md diff --git a/.changeset/timeout-names-pattern.md b/.changeset/timeout-names-pattern.md new file mode 100644 index 0000000000..ba011f4470 --- /dev/null +++ b/.changeset/timeout-names-pattern.md @@ -0,0 +1,6 @@ +--- +"e2e": patch +"@e2e-dev/web": patch +--- + +A fixture call that times out names what it waited for: `browser.waitForResponse('foo.css')` fails with `operation timed out in browser.waitForResponse "foo.css"`. Steps for `waitForURL`, `waitForResponse`, `route`, and `unroute` show a string pattern in quotes and a RegExp as its literal. diff --git a/packages/e2e/src/run/fixture-recording.ts b/packages/e2e/src/run/fixture-recording.ts index 45d3f31f88..1557b680c2 100644 --- a/packages/e2e/src/run/fixture-recording.ts +++ b/packages/e2e/src/run/fixture-recording.ts @@ -75,7 +75,7 @@ export class FixtureRecorder { if (timeout !== false && timeout !== undefined && (!Number.isFinite(timeout) || timeout <= 0)) { throw new TestError('INVALID_ARGUMENT', `${api} timeout must be positive and finite`); } - const pending = withAbort(() => translated(api, body), environment.budget.signal, () => new TestError('CANCELLED', `${api} cancelled`)); + const pending = withAbort(() => translated(label === '' ? api : `${api} ${label}`, body), environment.budget.signal, () => new TestError('CANCELLED', `${api} cancelled`)); if (timeout === false) return pending; const timeoutMs = timeout ?? environment.config.actionTimeout; return withTimeout(pending, timeoutMs, () => new TestError('ACTION_FAILED', `${api} exceeded its timeout of ${timeoutMs}ms`)); @@ -87,13 +87,14 @@ export class FixtureRecorder { * Runs one operation and maps an `EngineError` it rejects with onto the runner * taxonomy, as every other engine surface is mapped: a contributed fixture * that lost its session throws `INVALID_STATE`, which a test reads as - * `APP_NOT_OPEN`. Anything else is rethrown as the fixture threw it. + * `APP_NOT_OPEN`. Anything else is rethrown as the fixture threw it. `call` + * names the operation and its label, so a timeout says what it waited for. */ -async function translated(api: string, body: () => Promise): Promise { +async function translated(call: string, body: () => Promise): Promise { try { return await body(); } catch (cause) { - throw asEngineError(cause) === undefined ? cause : translateEngineError(cause, ` in ${api}`); + throw asEngineError(cause) === undefined ? cause : translateEngineError(cause, ` in ${call}`); } } diff --git a/packages/e2e/tests/unit/fixture-runtime.test.ts b/packages/e2e/tests/unit/fixture-runtime.test.ts index 8a0efa0a35..617a84d654 100644 --- a/packages/e2e/tests/unit/fixture-runtime.test.ts +++ b/packages/e2e/tests/unit/fixture-runtime.test.ts @@ -299,15 +299,17 @@ describe('explicit fixture operations', () => { gadget: (context) => context.fixture('gadget', { async lost(): Promise { throw new EngineError('INVALID_STATE', 'appstate requires an active session', { retryable: false }); }, async slow(): Promise { throw new EngineError('OPERATION_TIMEOUT', 'appstate timed out', { retryable: false }); }, + async wait(_pattern: string): Promise { throw new EngineError('OPERATION_TIMEOUT', 'wait timed out', { retryable: false }); }, async denied(): Promise { throw new TestError('POLICY_DENIED', 'no'); }, async plain(): Promise { throw new Error('plain failure'); }, - }, { lost: { kind: 'resource' }, slow: { kind: 'resource' }, denied: { kind: 'resource' }, plain: { kind: 'resource' } }), + }, { lost: { kind: 'resource' }, slow: { kind: 'resource' }, wait: { kind: 'resource', label: (pattern) => JSON.stringify(pattern) }, denied: { kind: 'resource' }, plain: { kind: 'resource' } }), }, }); const { fixtures } = runtime(engine); - const gadget = (fixtures as unknown as { gadget: Record<'lost' | 'slow' | 'denied' | 'plain', () => Promise> }).gadget; + const gadget = (fixtures as unknown as { gadget: Record<'lost' | 'slow' | 'denied' | 'plain', () => Promise> & { wait(pattern: string): Promise } }).gadget; await expect(gadget.lost()).rejects.toMatchObject({ code: 'APP_NOT_OPEN', category: 'test', message: 'appstate requires an active session' }); await expect(gadget.slow()).rejects.toMatchObject({ code: 'ACTION_FAILED', message: 'operation timed out in gadget.slow' }); + await expect(gadget.wait('foo.css')).rejects.toMatchObject({ code: 'ACTION_FAILED', message: 'operation timed out in gadget.wait "foo.css"' }); await expect(gadget.denied()).rejects.toMatchObject({ code: 'POLICY_DENIED' }); await expect(gadget.plain()).rejects.toThrow('plain failure'); }); diff --git a/packages/web/src/browser.ts b/packages/web/src/browser.ts index 1983fe55d1..d1c8f67816 100644 --- a/packages/web/src/browser.ts +++ b/packages/web/src/browser.ts @@ -797,13 +797,13 @@ export function createBrowserFixture(surface: PlaywrightSurface, context: Engine forward: navigationCall, url: action, title: action, - waitForURL: { ...navigationCall, verifies: true, label: (url) => String(url) }, + waitForURL: { ...navigationCall, verifies: true, label: patternLabel }, evaluate: action, addInitScript: { ...action, label: (script) => initScriptLabel(script) }, - route: { ...action, label: (pattern) => String(pattern) }, - unroute: { ...action, label: (pattern) => String(pattern) }, + route: { ...action, label: patternLabel }, + unroute: { ...action, label: patternLabel }, unrouteAll: action, - waitForResponse: { ...action, timeout: (_pattern, options) => options?.timeout, label: (pattern) => String(pattern) }, + waitForResponse: { ...action, timeout: (_pattern, options) => options?.timeout, label: patternLabel }, cookies: action, setCookies: action, clearCookies: action, @@ -949,6 +949,11 @@ function requireSelector(method: string, selector: unknown): string { return selector; } +/** A URL pattern as steps and errors name it: a string quoted, a RegExp as its literal. */ +function patternLabel(pattern: string | RegExp): string { + return typeof pattern === 'string' ? JSON.stringify(pattern) : String(pattern); +} + /** * The scope for the innermost of `frames` (outermost first). Every query and * both escape hatches compile through the same `frame` chain, so a `locator` From a29dc03c230c2a31da1b360d5438b97a641b3dc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oskar=20Kwas=CC=81niewski?= Date: Sun, 1 Nov 2026 17:54:41 +0100 Subject: [PATCH 2/9] test(web): Playwright parity suite, page tests at v1.64.1 ported to the public API --- .fallowrc.json | 5 + .oxlintrc.json | 2 + packages/web/tests/parity/.gitignore | 1 + packages/web/tests/parity/LICENSE | 202 +++++ packages/web/tests/parity/NOTICE | 5 + packages/web/tests/parity/README.md | 29 + .../parity/assets/button-overlay-oopif.html | 39 + .../tests/parity/assets/chromium-linux.zip | Bin 0 -> 325 bytes .../web/tests/parity/assets/consolelog.html | 11 + packages/web/tests/parity/assets/counter.html | 10 + .../tests/parity/assets/css-transition.html | 21 + packages/web/tests/parity/assets/digits/0.png | Bin 0 -> 434 bytes packages/web/tests/parity/assets/digits/1.png | Bin 0 -> 346 bytes packages/web/tests/parity/assets/digits/2.png | Bin 0 -> 413 bytes packages/web/tests/parity/assets/digits/3.png | Bin 0 -> 434 bytes packages/web/tests/parity/assets/digits/4.png | Bin 0 -> 403 bytes packages/web/tests/parity/assets/digits/5.png | Bin 0 -> 422 bytes packages/web/tests/parity/assets/digits/6.png | Bin 0 -> 445 bytes packages/web/tests/parity/assets/digits/7.png | Bin 0 -> 387 bytes packages/web/tests/parity/assets/digits/8.png | Bin 0 -> 447 bytes packages/web/tests/parity/assets/digits/9.png | Bin 0 -> 437 bytes packages/web/tests/parity/assets/dom.html | 5 + .../tests/parity/assets/download-blob.html | 29 + packages/web/tests/parity/assets/empty.html | 0 packages/web/tests/parity/assets/empty.pdf | Bin 0 -> 857 bytes .../tests/parity/assets/file to upload.txt | 1 + .../tests/parity/assets/file-to-upload-2.txt | 1 + .../tests/parity/assets/file-to-upload.txt | 1 + .../parity/assets/frames/child-redirect.html | 1 + .../web/tests/parity/assets/frames/frame.html | 19 + .../tests/parity/assets/frames/frameset.html | 8 + .../parity/assets/frames/lazy-frame.html | 6 + .../parity/assets/frames/nested-frames.html | 30 + .../tests/parity/assets/frames/one-frame.html | 1 + .../assets/frames/redirect-my-parent.html | 3 + .../web/tests/parity/assets/frames/script.js | 1 + .../web/tests/parity/assets/frames/style.css | 3 + .../parity/assets/frames/two-frames.html | 16 + .../web/tests/parity/assets/global-var.html | 3 + .../parity/assets/grid-iframe-in-shadow.html | 16 + packages/web/tests/parity/assets/grid.html | 66 ++ .../web/tests/parity/assets/historyapi.html | 5 + .../web/tests/parity/assets/injectedstyle.css | 3 + .../parity/assets/input/animating-button.html | 42 ++ .../parity/assets/input/background-fixed.html | 16 + .../web/tests/parity/assets/input/button.html | 32 + .../tests/parity/assets/input/checkbox.html | 42 ++ .../assets/input/drag-n-drop-manual.html | 44 ++ .../parity/assets/input/fileupload-multi.html | 12 + .../tests/parity/assets/input/fileupload.html | 12 + .../parity/assets/input/folderupload.html | 12 + .../parity/assets/input/handle-locator.html | 91 +++ .../tests/parity/assets/input/keyboard.html | 51 ++ .../tests/parity/assets/input/mouse-helper.js | 62 ++ .../parity/assets/input/rotatedButton.html | 21 + .../tests/parity/assets/input/scrollable.html | 23 + .../parity/assets/input/scrollable2.html | 23 + .../web/tests/parity/assets/input/select.html | 70 ++ .../tests/parity/assets/input/textarea.html | 20 + .../tests/parity/assets/input/touches.html | 35 + .../parity/assets/networkidle-frame.html | 1 + .../web/tests/parity/assets/networkidle.html | 1 + .../web/tests/parity/assets/networkidle.js | 12 + .../tests/parity/assets/offscreenbuttons.html | 55 ++ .../web/tests/parity/assets/one-style.css | 3 + .../web/tests/parity/assets/one-style.html | 3 + .../web/tests/parity/assets/playground.html | 15 + packages/web/tests/parity/assets/pptr.png | Bin 0 -> 6138 bytes packages/web/tests/parity/assets/preload.html | 5 + .../tests/parity/assets/redirectloop1.html | 10 + .../tests/parity/assets/redirectloop2.html | 5 + .../tests/parity/assets/rotate-pseudo.html | 32 + .../parity/assets/rotate-z-shadow-dom.html | 31 + .../web/tests/parity/assets/rotate-z.html | 26 + .../parity/assets/screenshots/canvas.html | 13 + .../parity/assets/screenshots/translateZ.html | 4 + .../parity/assets/sectionselectorengine.js | 8 + .../web/tests/parity/assets/self-request.html | 5 + packages/web/tests/parity/assets/shadow.html | 17 + packages/web/tests/parity/assets/simple.json | 1 + packages/web/tests/parity/assets/title.html | 2 + .../web/tests/parity/assets/wrappedlink.html | 32 + packages/web/tests/parity/e2e.config.ts | 25 + packages/web/tests/parity/server.mjs | 178 +++++ .../web/tests/parity/tests/download.e2e.ts | 218 ++++++ .../elementhandle-scroll-into-view.e2e.ts | 107 +++ .../web/tests/parity/tests/frame-goto.e2e.ts | 26 + .../tests/parity/tests/frame-hierarchy.e2e.ts | 53 ++ packages/web/tests/parity/tests/helpers.ts | 27 + .../parity/tests/locator-convenience.e2e.ts | 107 +++ .../tests/parity/tests/locator-frame.e2e.ts | 232 ++++++ .../parity/tests/locator-is-visible.e2e.ts | 137 ++++ .../tests/parity/tests/locator-list.e2e.ts | 19 + .../tests/parity/tests/locator-misc-2.e2e.ts | 135 ++++ .../tests/parity/tests/locator-query.e2e.ts | 186 +++++ .../web/tests/parity/tests/page-check.e2e.ts | 119 +++ .../parity/tests/page-click-scroll.e2e.ts | 116 +++ .../web/tests/parity/tests/page-click.e2e.ts | 559 ++++++++++++++ .../web/tests/parity/tests/page-dialog.e2e.ts | 124 +++ .../parity/tests/page-filechooser.e2e.ts | 128 ++++ .../web/tests/parity/tests/page-fill.e2e.ts | 375 +++++++++ .../tests/parity/tests/page-keyboard.e2e.ts | 709 ++++++++++++++++++ .../parity/tests/page-network-idle.e2e.ts | 165 ++++ .../parity/tests/page-request-continue.e2e.ts | 429 +++++++++++ .../parity/tests/page-request-fallback.e2e.ts | 93 +++ .../parity/tests/page-request-fulfill.e2e.ts | 241 ++++++ .../web/tests/parity/tests/page-route.e2e.ts | 655 ++++++++++++++++ .../tests/parity/tests/page-screenshot.e2e.ts | 454 +++++++++++ .../parity/tests/page-select-option.e2e.ts | 284 +++++++ .../parity/tests/page-set-input-files.e2e.ts | 279 +++++++ .../tests/page-wait-for-navigation.e2e.ts | 168 +++++ .../tests/page-wait-for-response.e2e.ts | 57 ++ .../parity/tests/page-wait-for-url.e2e.ts | 106 +++ .../tests/parity/tests/selectors-frame.e2e.ts | 164 ++++ .../parity/tests/selectors-get-by.e2e.ts | 217 ++++++ .../tests/parity/tests/selectors-role.e2e.ts | 325 ++++++++ .../tests/parity/tests/selectors-text.e2e.ts | 64 ++ 117 files changed, 8713 insertions(+) create mode 100644 packages/web/tests/parity/.gitignore create mode 100644 packages/web/tests/parity/LICENSE create mode 100644 packages/web/tests/parity/NOTICE create mode 100644 packages/web/tests/parity/README.md create mode 100644 packages/web/tests/parity/assets/button-overlay-oopif.html create mode 100644 packages/web/tests/parity/assets/chromium-linux.zip create mode 100644 packages/web/tests/parity/assets/consolelog.html create mode 100644 packages/web/tests/parity/assets/counter.html create mode 100644 packages/web/tests/parity/assets/css-transition.html create mode 100644 packages/web/tests/parity/assets/digits/0.png create mode 100644 packages/web/tests/parity/assets/digits/1.png create mode 100644 packages/web/tests/parity/assets/digits/2.png create mode 100644 packages/web/tests/parity/assets/digits/3.png create mode 100644 packages/web/tests/parity/assets/digits/4.png create mode 100644 packages/web/tests/parity/assets/digits/5.png create mode 100644 packages/web/tests/parity/assets/digits/6.png create mode 100644 packages/web/tests/parity/assets/digits/7.png create mode 100644 packages/web/tests/parity/assets/digits/8.png create mode 100644 packages/web/tests/parity/assets/digits/9.png create mode 100644 packages/web/tests/parity/assets/dom.html create mode 100644 packages/web/tests/parity/assets/download-blob.html create mode 100644 packages/web/tests/parity/assets/empty.html create mode 100644 packages/web/tests/parity/assets/empty.pdf create mode 100644 packages/web/tests/parity/assets/file to upload.txt create mode 100644 packages/web/tests/parity/assets/file-to-upload-2.txt create mode 100644 packages/web/tests/parity/assets/file-to-upload.txt create mode 100644 packages/web/tests/parity/assets/frames/child-redirect.html create mode 100644 packages/web/tests/parity/assets/frames/frame.html create mode 100644 packages/web/tests/parity/assets/frames/frameset.html create mode 100644 packages/web/tests/parity/assets/frames/lazy-frame.html create mode 100644 packages/web/tests/parity/assets/frames/nested-frames.html create mode 100644 packages/web/tests/parity/assets/frames/one-frame.html create mode 100644 packages/web/tests/parity/assets/frames/redirect-my-parent.html create mode 100644 packages/web/tests/parity/assets/frames/script.js create mode 100644 packages/web/tests/parity/assets/frames/style.css create mode 100644 packages/web/tests/parity/assets/frames/two-frames.html create mode 100644 packages/web/tests/parity/assets/global-var.html create mode 100644 packages/web/tests/parity/assets/grid-iframe-in-shadow.html create mode 100644 packages/web/tests/parity/assets/grid.html create mode 100644 packages/web/tests/parity/assets/historyapi.html create mode 100644 packages/web/tests/parity/assets/injectedstyle.css create mode 100644 packages/web/tests/parity/assets/input/animating-button.html create mode 100644 packages/web/tests/parity/assets/input/background-fixed.html create mode 100644 packages/web/tests/parity/assets/input/button.html create mode 100644 packages/web/tests/parity/assets/input/checkbox.html create mode 100644 packages/web/tests/parity/assets/input/drag-n-drop-manual.html create mode 100644 packages/web/tests/parity/assets/input/fileupload-multi.html create mode 100644 packages/web/tests/parity/assets/input/fileupload.html create mode 100644 packages/web/tests/parity/assets/input/folderupload.html create mode 100644 packages/web/tests/parity/assets/input/handle-locator.html create mode 100644 packages/web/tests/parity/assets/input/keyboard.html create mode 100644 packages/web/tests/parity/assets/input/mouse-helper.js create mode 100644 packages/web/tests/parity/assets/input/rotatedButton.html create mode 100644 packages/web/tests/parity/assets/input/scrollable.html create mode 100644 packages/web/tests/parity/assets/input/scrollable2.html create mode 100644 packages/web/tests/parity/assets/input/select.html create mode 100644 packages/web/tests/parity/assets/input/textarea.html create mode 100644 packages/web/tests/parity/assets/input/touches.html create mode 100644 packages/web/tests/parity/assets/networkidle-frame.html create mode 100644 packages/web/tests/parity/assets/networkidle.html create mode 100644 packages/web/tests/parity/assets/networkidle.js create mode 100644 packages/web/tests/parity/assets/offscreenbuttons.html create mode 100644 packages/web/tests/parity/assets/one-style.css create mode 100644 packages/web/tests/parity/assets/one-style.html create mode 100644 packages/web/tests/parity/assets/playground.html create mode 100644 packages/web/tests/parity/assets/pptr.png create mode 100644 packages/web/tests/parity/assets/preload.html create mode 100644 packages/web/tests/parity/assets/redirectloop1.html create mode 100644 packages/web/tests/parity/assets/redirectloop2.html create mode 100644 packages/web/tests/parity/assets/rotate-pseudo.html create mode 100644 packages/web/tests/parity/assets/rotate-z-shadow-dom.html create mode 100644 packages/web/tests/parity/assets/rotate-z.html create mode 100644 packages/web/tests/parity/assets/screenshots/canvas.html create mode 100644 packages/web/tests/parity/assets/screenshots/translateZ.html create mode 100644 packages/web/tests/parity/assets/sectionselectorengine.js create mode 100644 packages/web/tests/parity/assets/self-request.html create mode 100644 packages/web/tests/parity/assets/shadow.html create mode 100644 packages/web/tests/parity/assets/simple.json create mode 100644 packages/web/tests/parity/assets/title.html create mode 100644 packages/web/tests/parity/assets/wrappedlink.html create mode 100644 packages/web/tests/parity/e2e.config.ts create mode 100644 packages/web/tests/parity/server.mjs create mode 100644 packages/web/tests/parity/tests/download.e2e.ts create mode 100644 packages/web/tests/parity/tests/elementhandle-scroll-into-view.e2e.ts create mode 100644 packages/web/tests/parity/tests/frame-goto.e2e.ts create mode 100644 packages/web/tests/parity/tests/frame-hierarchy.e2e.ts create mode 100644 packages/web/tests/parity/tests/helpers.ts create mode 100644 packages/web/tests/parity/tests/locator-convenience.e2e.ts create mode 100644 packages/web/tests/parity/tests/locator-frame.e2e.ts create mode 100644 packages/web/tests/parity/tests/locator-is-visible.e2e.ts create mode 100644 packages/web/tests/parity/tests/locator-list.e2e.ts create mode 100644 packages/web/tests/parity/tests/locator-misc-2.e2e.ts create mode 100644 packages/web/tests/parity/tests/locator-query.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-check.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-click-scroll.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-click.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-dialog.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-filechooser.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-fill.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-keyboard.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-network-idle.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-request-continue.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-request-fallback.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-request-fulfill.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-route.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-screenshot.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-select-option.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-set-input-files.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-wait-for-navigation.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-wait-for-response.e2e.ts create mode 100644 packages/web/tests/parity/tests/page-wait-for-url.e2e.ts create mode 100644 packages/web/tests/parity/tests/selectors-frame.e2e.ts create mode 100644 packages/web/tests/parity/tests/selectors-get-by.e2e.ts create mode 100644 packages/web/tests/parity/tests/selectors-role.e2e.ts create mode 100644 packages/web/tests/parity/tests/selectors-text.e2e.ts diff --git a/.fallowrc.json b/.fallowrc.json index 7751fab329..1e78610637 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -14,6 +14,9 @@ "apps/mobile-benchmark/e2e.*.config.ts", "apps/mobile-benchmark/tests*/**/*.ts", "apps/mobile-benchmark/index.ts", + "packages/web/tests/parity/e2e.config.ts", + "packages/web/tests/parity/server.mjs", + "packages/web/tests/parity/tests/**/*.ts", "packages/e2e/tests/types/sdk-types.ts", "packages/web/tests/types/connection.ts", "packages/web/tests/types/init-scripts.ts", @@ -35,6 +38,8 @@ "examples/**", "**/next-env.d.ts", "**/.e2e/**", + "packages/web/tests/parity/assets/**", + "packages/web/tests/parity/.e2e-*/**", "packages/e2e/tests/tmp-projects/**" ], "ignoreDependencies": [ diff --git a/.oxlintrc.json b/.oxlintrc.json index e257a33c61..b08c00cdb1 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -16,6 +16,8 @@ "packages/*/tests/fixtures/**", // Vendored conformance data, kept byte for byte. "packages/*/tests/conformance/*/**", + // Playwright's test assets, kept byte for byte. + "packages/web/tests/parity/assets/**", "packages/*/tests/tmp-projects/**", // Standalone user-facing projects with their own installs; nothing here builds them. "examples/**", diff --git a/packages/web/tests/parity/.gitignore b/packages/web/tests/parity/.gitignore new file mode 100644 index 0000000000..c91580c936 --- /dev/null +++ b/packages/web/tests/parity/.gitignore @@ -0,0 +1 @@ +.e2e*/ diff --git a/packages/web/tests/parity/LICENSE b/packages/web/tests/parity/LICENSE new file mode 100644 index 0000000000..4ace03ddb6 --- /dev/null +++ b/packages/web/tests/parity/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Portions Copyright (c) Microsoft Corporation. + Portions Copyright 2017 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/web/tests/parity/NOTICE b/packages/web/tests/parity/NOTICE new file mode 100644 index 0000000000..814ec1696f --- /dev/null +++ b/packages/web/tests/parity/NOTICE @@ -0,0 +1,5 @@ +Playwright +Copyright (c) Microsoft Corporation + +This software contains code derived from the Puppeteer project (https://github.com/puppeteer/puppeteer), +available under the Apache 2.0 license (https://github.com/puppeteer/puppeteer/blob/master/LICENSE). diff --git a/packages/web/tests/parity/README.md b/packages/web/tests/parity/README.md new file mode 100644 index 0000000000..84000287a6 --- /dev/null +++ b/packages/web/tests/parity/README.md @@ -0,0 +1,29 @@ +# Behavior parity + +Playwright's own page tests, rewritten against the e2e public API, so +`web()` is held to Playwright's behavior. Adapted from microsoft/playwright +`tests/page` (and `tests/library/download.spec.ts`) at `v1.64.1`, the version +`playwright-core` is pinned to. Copyright Microsoft Corporation, Apache +License 2.0: see `LICENSE` and `NOTICE`. + +- `tests/*.e2e.ts`: one file per Playwright spec. Each keeps the original + test's title, inputs, and assertions; `page.click(selector)` becomes a + locator tap, `page.setContent(html)` a page the server serves (`content()`). + A test whose API e2e does not expose is left out; the file header lists them. +- `assets/`: Playwright's `tests/assets` files the tests load, unchanged. +- `server.mjs`: serves `assets/`, plus the routes Playwright's test server sets + per test as fixed paths. `127.0.0.1` and `localhost` on its port are the two + origins of the cross-origin cases. + +A test that hits a place where e2e differs from Playwright on purpose or +by a known gap is skipped with `e2eGap(reason)`. + +```sh +pnpm build +cd packages/web/tests/parity +BROWSER=chromium node ../../node_modules/e2e/dist/cli/bin.js run +BROWSER=firefox node ../../node_modules/e2e/dist/cli/bin.js run +``` + +`PARITY_PORT` (default 4311) moves the server; `--output .e2e-` keeps +parallel runs apart. diff --git a/packages/web/tests/parity/assets/button-overlay-oopif.html b/packages/web/tests/parity/assets/button-overlay-oopif.html new file mode 100644 index 0000000000..7e1f136fcd --- /dev/null +++ b/packages/web/tests/parity/assets/button-overlay-oopif.html @@ -0,0 +1,39 @@ + + diff --git a/packages/web/tests/parity/assets/chromium-linux.zip b/packages/web/tests/parity/assets/chromium-linux.zip new file mode 100644 index 0000000000000000000000000000000000000000..9c00ec080d0e9ef688dca5442a75f1095c02f0e3 GIT binary patch literal 325 zcmWIWW@h1H0D;A=Za!cJl;C9$U`Wm=%Fj*J&B@FwtZxSQYgUh!>sg5Doxp z6=C22LUgUd=vpD>fDCwqWWeW-U$}b%3O;=)=IMIE#1P=k&SB2ywUr;}0A3&t@MdHZ zWya+=9++Dl-a3MqXinvTI~8IK!lB4k2s0pzS<+~YZVb%X9B^j`c(byBY-0k#DL{HQ Hh{FH?_oYdx literal 0 HcmV?d00001 diff --git a/packages/web/tests/parity/assets/consolelog.html b/packages/web/tests/parity/assets/consolelog.html new file mode 100644 index 0000000000..9ef271812d --- /dev/null +++ b/packages/web/tests/parity/assets/consolelog.html @@ -0,0 +1,11 @@ + + + + console.log test + + + + + diff --git a/packages/web/tests/parity/assets/counter.html b/packages/web/tests/parity/assets/counter.html new file mode 100644 index 0000000000..1e90289577 --- /dev/null +++ b/packages/web/tests/parity/assets/counter.html @@ -0,0 +1,10 @@ + + +

count: 0

+ diff --git a/packages/web/tests/parity/assets/css-transition.html b/packages/web/tests/parity/assets/css-transition.html new file mode 100644 index 0000000000..449c1548df --- /dev/null +++ b/packages/web/tests/parity/assets/css-transition.html @@ -0,0 +1,21 @@ + + +
+ diff --git a/packages/web/tests/parity/assets/digits/0.png b/packages/web/tests/parity/assets/digits/0.png new file mode 100644 index 0000000000000000000000000000000000000000..ac3c4768edfbe7bd47c436b1451938fa83483a0c GIT binary patch literal 434 zcmeAS@N?(olHy`uVBq!ia0vp^Ahr+(3y?gqul)d!Vo7)Ob!1@J*w6hZkrl{SNcITw zWnidMV_;}#VPN<`%l_%+p4TGxUM+vVxv7$R|b>IB0qra%Ul`~MX*b+&Ovv2B|q(!_F5JEB7P zed0v5sZ%E?Yh1hbjAP{`Rxy#BDWWlty*FwfV(a#?G%)Vx{1iU1`q`mv2gSp$&p2~* z-}_~cq6GO$WM?Q#u2eqHG5>*&;LICE?MK)yaHod0^GXWrZw)prU@KA-JFv3vi--cJ zxiY6feZzXKeM^rjA81T>7dtU=-Ac=*J)Oz+GF_*I;`H`Ro8h-tLFm*jTUKAWRU1F- zfBotg>*8DSc8V=VKyNdsmbgZgq$HN4S|t~y0x1R~14DCN12bJivk*g5D-%O2V@q8F mb1MUbn=hryP&DM`r(~v8;?}TY%i>c&4Gf;HelF{r5}E+JGmpjq literal 0 HcmV?d00001 diff --git a/packages/web/tests/parity/assets/digits/1.png b/packages/web/tests/parity/assets/digits/1.png new file mode 100644 index 0000000000000000000000000000000000000000..6768222729b7a487d338fdd7691e44ca4604b216 GIT binary patch literal 346 zcmeAS@N?(olHy`uVBq!ia0vp^Ahr+(3y?gqul)d!Vo7)Ob!1@J*w6hZkrl{SNcITw zWnidMV_;}#VPN<`%l_%+p4TGxUMOY(Ga43W5;{O5cF=M0GtoN~YQ|NXb^`8@xj{o(qyZXTZh zNB`|_{xm~E;-A5pf9w0RzSOs614Wzvrz@>Y`EmY3PvY_a|9PY*vP4Qqs7R_vN=noT zzEz3h*rdQ|G)c~jg_Tj2N2{sHz90fFVdQ&MBb@0M_4YL;wH) literal 0 HcmV?d00001 diff --git a/packages/web/tests/parity/assets/digits/2.png b/packages/web/tests/parity/assets/digits/2.png new file mode 100644 index 0000000000000000000000000000000000000000..b1daa4735d8a8c8dcce6be0fc2db02beb265860b GIT binary patch literal 413 zcmeAS@N?(olHy`uVBq!ia0vp^Ahr+(3y?gqul)d!Vo7)Ob!1@J*w6hZkrl{SNcITw zWnidMV_;}#VPN<`%l_%$`QSZ$aB6k6)(;us=vdFljxE~Y{OxBK}UC0Lr@F!n?rT`(_E{}JO6 z<{7z73T*rf7DVR9aWl3E8iRZQbg$2f$a-VDO8#vl&KeD#DWG<1jqwYkJ(8lLS zB4RWT1dM<5ebWu_3N}u7Cea|(Ea3RP_Gw+vkLTX@hooODEC@-v@oNsy!Kx*$5hW>! zC8<`)MX5lF!N|bST-U%%*U&7)(A3Jr(8|O>*TCG$z`$)w_#PAux%nxXX_dG&n7@1v QRL{WR>FVdQ&MBb@0Eyv<`%l_%$`QSZ$aB6x!wK;us=vdFq6XS%(-TTK3zgoV~U1u8i>$)?1-gCGWI< z@aS2U3)ZwcEm*ubc;$ti-mV3rF6`=#s{>A4SDeUI_Oe&LoV{Fey4Mfsycbe!vf}Dh z3k0h9j%Z)+Fc6$CIUO_QmvAUQh^kMk%6JPu7R1Zp;?Hbsg;SLm5G6_ nfw`4|f!mhwJt!J-^HVa@DsgKtfB7D$o`J#B)z4*}Q$iB}nZcB~ literal 0 HcmV?d00001 diff --git a/packages/web/tests/parity/assets/digits/4.png b/packages/web/tests/parity/assets/digits/4.png new file mode 100644 index 0000000000000000000000000000000000000000..a721071e2cc4f4d3aeb9a939fb353bee19a655b5 GIT binary patch literal 403 zcmeAS@N?(olHy`uVBq!ia0vp^Ahr+(3y?gqul)d!Vo7)Ob!1@J*w6hZkrl{SNcITw zWnidMV_;}#VPN<`%l_%$^T+cq!(g=TxYIEF}Eo;tyhk1Daqt63f# z{2;4qbecI;$g&|gJoK~I{dMMIqQ-q^Z?t=`WG!sjc4tSKLf;*&Y1X25Kle?TG^sF6 z>D=BYXVM%qnde@pu;0vgB#G~T{mbP)S=PRcF1)|-gago-swJ)wB`Jv|saDBFsX&Us z$iUEC*T78I&@9Bz)XKyVh;$9itqcqv9FE~Y(U6;;l9^VCTf@Y8PqqLxFnGH9xvX<`%l_%$^T+cq!(h1PkxIEF}E?wz22-my@kZT1K|fI9blJ2l{+r3^|)} z*8RfYYV*z8_c%_x;UgqEd!^9Poh`*TW`=*TdCT>^*4BT*|H;1(oM7&m8^G|u$3Da% zDeBX$-lmw9w+s(E_C1K%nffs5$fStkT(0({CkN(r>}Jt>Q{|STYPMH+)2ATwXX;N9 zUY^;$J4woIp1{qfw?{sQ>->K1(PN|HYUInB{Z4ScYq_3-VJ}bo{&&hX4DrV0Symw> zhk!0uEpd$~Nl7e8wMs5Z1yT$~28QOk24=d3W+8^ARwjl(q-$VqWnl2&a0~~EhTQy= Z%(P0}8Ya$rvIVGt!PC{xWt~$(69C)6lY0OF literal 0 HcmV?d00001 diff --git a/packages/web/tests/parity/assets/digits/6.png b/packages/web/tests/parity/assets/digits/6.png new file mode 100644 index 0000000000000000000000000000000000000000..639f38439d94e856e41a6750952b6e06c418cf3f GIT binary patch literal 445 zcmeAS@N?(olHy`uVBq!ia0vp^Ahr+(3y?gqul)d!Vo7)Ob!1@J*w6hZkrl{SNcITw zWnidMV_;}#VPN<`%l_%*enOfK#K3LW)yaSV~TJavMh*Wm;PxBK(YEu72bwVdZ}kbt`XgDKWG zHhQxkJbRS+g$`@}15O#2T~i(@MY241a<;z7)g=_)Zn4zjOK<*{ z^|H0Og+AWm-uT?SDW)^nHSdUci~p}UEv0yy-ENEcy{zt3Kiarmu2tfJsEduUXmP#3 zy#q&>em;$vqY=pZB*h^?VgbV<=ODgW9}Ojw!x+xA)XDx=DXab9=X3YU$4?nbk5(4D zIQzm0Xkxq!^4049#^7%ybRS xLJUo5~f0{rI44$rjF6*2UngAmjmB9c2 literal 0 HcmV?d00001 diff --git a/packages/web/tests/parity/assets/digits/7.png b/packages/web/tests/parity/assets/digits/7.png new file mode 100644 index 0000000000000000000000000000000000000000..5c1150b005a9fe3c2b970617dcb8801d98408fe7 GIT binary patch literal 387 zcmeAS@N?(olHy`uVBq!ia0vp^Ahr+(3y?gqul)d!Vo7)Ob!1@J*w6hZkrl{SNcITw zWnidMV_;}#VPN<`%l_%*enOfK#K3UzzBIEF}E?!B;(m&sAU?cw&>o3As9E-=s#a$@F?F}=VL zyP)8Tqo9h03QMC?e9=i(rpg_=V;%1F{Qf6sEc|5qBl*P@8;rI@9-ZW>@#KW&%vnq~ zzOl}^kHZ9KZ=-wR{MdtU&MofI@cqgkb+dDrc!nov}_HpAKo1^uZt{iyr``c~- z=k|r)r~i7)zL771W73?7Q-RJ>Epd$~Nl7e8wMs5Z1yT$~28QOk24=d3W+8^ARwjm4 pCPumj=2iv<7q#6`HRR@}WTsW(*07-LpC-@-22WQ%mvv4FO#tK!e`o*z literal 0 HcmV?d00001 diff --git a/packages/web/tests/parity/assets/digits/8.png b/packages/web/tests/parity/assets/digits/8.png new file mode 100644 index 0000000000000000000000000000000000000000..abb8b48b0b1e5ac8aabb667265d9469d48b7fa24 GIT binary patch literal 447 zcmeAS@N?(olHy`uVBq!ia0vp^Ahr+(3y?gqul)d!Vo7)Ob!1@J*w6hZkrl{SNcITw zWnidMV_;}#VPN<`%l_%*e4jUVa(g^qi=IEF}Eo;pF-zbR3qZT<755iFO44ID4;ZXsr|G6Z-3AQ~YMF#9yB;s?AMz zKS@rU5cTWfbfKwA)i>7f%FSiSf0jRY%Pf;;KrgA5xJHzuB$lLFB^RXvDF!10LvvjN zGhIWo5JOWd6GJN#V_gGtD+7b_7+*yc4Y~O#nQ4`{HLx*$oeR{!;OXk;vd$@?2>`+@ BpQr!; literal 0 HcmV?d00001 diff --git a/packages/web/tests/parity/assets/digits/9.png b/packages/web/tests/parity/assets/digits/9.png new file mode 100644 index 0000000000000000000000000000000000000000..6a40a21c6f58545cab61ea346f1b6bb8b9300c6d GIT binary patch literal 437 zcmeAS@N?(olHy`uVBq!ia0vp^Ahr+(3y?gqul)d!Vo7)Ob!1@J*w6hZkrl{SNcITw zWnidMV_;}#VPN<`%l_%*e4jUVa(h4y;7IEF}Eo;pD>k10`t_4)k-!5MN3m>MJ651DFC-ODU@ zpZg1!gh!athOH(nj7nKY-017|7X(lneSP5`X2ea_zN%F?Q`q4 z_N=>MvQe>5^dWanr4!!~yIt-xI*MIYJ|5&1TI#UWB`1>;t5@F(qUrTrX|{*Mm$Cl}5-eYz`MaCM!?KE?X)(klhI z7Jr!kGOw6X)u&2!`$KOxphr|oTq8
Text, +more text
+ + + diff --git a/packages/web/tests/parity/assets/download-blob.html b/packages/web/tests/parity/assets/download-blob.html new file mode 100644 index 0000000000..3c4a3d8133 --- /dev/null +++ b/packages/web/tests/parity/assets/download-blob.html @@ -0,0 +1,29 @@ + + + + Blob Download Example + + + +
Download + + diff --git a/packages/web/tests/parity/assets/empty.html b/packages/web/tests/parity/assets/empty.html new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/web/tests/parity/assets/empty.pdf b/packages/web/tests/parity/assets/empty.pdf new file mode 100644 index 0000000000000000000000000000000000000000..ed845a63727e0a03b754a73e0f050e49d4e0f0a2 GIT binary patch literal 857 zcmaJ=L2DC17?sva8IoHR_4Ek_TdU4)Hk)>(gpy5Cf{BJrZ?VvIcapAVcXW0Fu^=dd z2dRHR^dN};K%rN`+=1MML!QK`;4Eo_Bp-sX4zQ+)3-3wfbwGdhb{4gR1JSw}A!9w|Z zPRr?$eWUBVlA4etM+QY;b{`AUM3Nby|I2`x2%-sB>5dkHC@kg7pXqB2_T zp@uT^xX%c!v#2Y#!7__Qh$T7-$>7z2k^69Rc5W6vf3Xi=w$CqK{3cF|C;o1|k-qPCH%F*p#KZfM!(^h;XwVz3)>-%fN zw-4rKE}VFM`P^?Mf4tJzNG{R1@$fza+H|`p&0#U`3y;NsVPmjfi%DpYGNl`AAc59G zB$mdrJ)UcugjNP}y(LxDSh{Y2ipnYCz<`+_xFtS-wuWFq&%v^l!xEcEl0`BGm6$_l zONzcHo30pv8n$-y2j5Nm~ljWwtBb9`CAU zy6AXnm4RR#qQNrJCIbqlX_(M~38rI_8W2q|!#s}ZCOVwr=@#zmDa_1cYSWmtl3-G} rL5~S_6k5R!Lv_^QT!Qk30oI}p2X$O9coIuj$dQXe-Xz&< diff --git a/packages/web/tests/parity/assets/frames/frame.html b/packages/web/tests/parity/assets/frames/frame.html new file mode 100644 index 0000000000..3d3b943431 --- /dev/null +++ b/packages/web/tests/parity/assets/frames/frame.html @@ -0,0 +1,19 @@ + + + + + +
Hi, I'm frame
diff --git a/packages/web/tests/parity/assets/frames/frameset.html b/packages/web/tests/parity/assets/frames/frameset.html new file mode 100644 index 0000000000..4d56f88839 --- /dev/null +++ b/packages/web/tests/parity/assets/frames/frameset.html @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/packages/web/tests/parity/assets/frames/lazy-frame.html b/packages/web/tests/parity/assets/frames/lazy-frame.html new file mode 100644 index 0000000000..f5e0e0914d --- /dev/null +++ b/packages/web/tests/parity/assets/frames/lazy-frame.html @@ -0,0 +1,6 @@ +
One
+
Two
+
Three
+
Four
+
Five
+ diff --git a/packages/web/tests/parity/assets/frames/nested-frames.html b/packages/web/tests/parity/assets/frames/nested-frames.html new file mode 100644 index 0000000000..d858d3285b --- /dev/null +++ b/packages/web/tests/parity/assets/frames/nested-frames.html @@ -0,0 +1,30 @@ + + + + diff --git a/packages/web/tests/parity/assets/frames/one-frame.html b/packages/web/tests/parity/assets/frames/one-frame.html new file mode 100644 index 0000000000..e941d795a2 --- /dev/null +++ b/packages/web/tests/parity/assets/frames/one-frame.html @@ -0,0 +1 @@ + diff --git a/packages/web/tests/parity/assets/frames/redirect-my-parent.html b/packages/web/tests/parity/assets/frames/redirect-my-parent.html new file mode 100644 index 0000000000..3beb0aac1a --- /dev/null +++ b/packages/web/tests/parity/assets/frames/redirect-my-parent.html @@ -0,0 +1,3 @@ + diff --git a/packages/web/tests/parity/assets/frames/script.js b/packages/web/tests/parity/assets/frames/script.js new file mode 100644 index 0000000000..be22256d16 --- /dev/null +++ b/packages/web/tests/parity/assets/frames/script.js @@ -0,0 +1 @@ +console.log('Cheers!'); diff --git a/packages/web/tests/parity/assets/frames/style.css b/packages/web/tests/parity/assets/frames/style.css new file mode 100644 index 0000000000..5b5436e874 --- /dev/null +++ b/packages/web/tests/parity/assets/frames/style.css @@ -0,0 +1,3 @@ +div { + color: blue; +} diff --git a/packages/web/tests/parity/assets/frames/two-frames.html b/packages/web/tests/parity/assets/frames/two-frames.html new file mode 100644 index 0000000000..00324f0845 --- /dev/null +++ b/packages/web/tests/parity/assets/frames/two-frames.html @@ -0,0 +1,16 @@ + + + diff --git a/packages/web/tests/parity/assets/global-var.html b/packages/web/tests/parity/assets/global-var.html new file mode 100644 index 0000000000..b6be975038 --- /dev/null +++ b/packages/web/tests/parity/assets/global-var.html @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/packages/web/tests/parity/assets/grid-iframe-in-shadow.html b/packages/web/tests/parity/assets/grid-iframe-in-shadow.html new file mode 100644 index 0000000000..4649b27227 --- /dev/null +++ b/packages/web/tests/parity/assets/grid-iframe-in-shadow.html @@ -0,0 +1,16 @@ + + diff --git a/packages/web/tests/parity/assets/grid.html b/packages/web/tests/parity/assets/grid.html new file mode 100644 index 0000000000..8345f429bd --- /dev/null +++ b/packages/web/tests/parity/assets/grid.html @@ -0,0 +1,66 @@ + + + diff --git a/packages/web/tests/parity/assets/historyapi.html b/packages/web/tests/parity/assets/historyapi.html new file mode 100644 index 0000000000..bacaf9e9a0 --- /dev/null +++ b/packages/web/tests/parity/assets/historyapi.html @@ -0,0 +1,5 @@ + diff --git a/packages/web/tests/parity/assets/injectedstyle.css b/packages/web/tests/parity/assets/injectedstyle.css new file mode 100644 index 0000000000..aa1634c255 --- /dev/null +++ b/packages/web/tests/parity/assets/injectedstyle.css @@ -0,0 +1,3 @@ +body { + background-color: red; +} diff --git a/packages/web/tests/parity/assets/input/animating-button.html b/packages/web/tests/parity/assets/input/animating-button.html new file mode 100644 index 0000000000..2946f2e89f --- /dev/null +++ b/packages/web/tests/parity/assets/input/animating-button.html @@ -0,0 +1,42 @@ + + diff --git a/packages/web/tests/parity/assets/input/background-fixed.html b/packages/web/tests/parity/assets/input/background-fixed.html new file mode 100644 index 0000000000..5093939a5b --- /dev/null +++ b/packages/web/tests/parity/assets/input/background-fixed.html @@ -0,0 +1,16 @@ + + + + + +
tall
+ + diff --git a/packages/web/tests/parity/assets/input/button.html b/packages/web/tests/parity/assets/input/button.html new file mode 100644 index 0000000000..bfce25ee00 --- /dev/null +++ b/packages/web/tests/parity/assets/input/button.html @@ -0,0 +1,32 @@ + + + + Button test + + + + + + + \ No newline at end of file diff --git a/packages/web/tests/parity/assets/input/checkbox.html b/packages/web/tests/parity/assets/input/checkbox.html new file mode 100644 index 0000000000..ca56762e2b --- /dev/null +++ b/packages/web/tests/parity/assets/input/checkbox.html @@ -0,0 +1,42 @@ + + + + Selection Test + + + + + + + diff --git a/packages/web/tests/parity/assets/input/drag-n-drop-manual.html b/packages/web/tests/parity/assets/input/drag-n-drop-manual.html new file mode 100644 index 0000000000..ee67aeb4d6 --- /dev/null +++ b/packages/web/tests/parity/assets/input/drag-n-drop-manual.html @@ -0,0 +1,44 @@ + + +
+
+ Drop here +
+
+ Drag me +
+
+ + diff --git a/packages/web/tests/parity/assets/input/fileupload-multi.html b/packages/web/tests/parity/assets/input/fileupload-multi.html new file mode 100644 index 0000000000..05dd5a2237 --- /dev/null +++ b/packages/web/tests/parity/assets/input/fileupload-multi.html @@ -0,0 +1,12 @@ + + + + File upload test + + +
+ + +
+ + diff --git a/packages/web/tests/parity/assets/input/fileupload.html b/packages/web/tests/parity/assets/input/fileupload.html new file mode 100644 index 0000000000..6486e5c288 --- /dev/null +++ b/packages/web/tests/parity/assets/input/fileupload.html @@ -0,0 +1,12 @@ + + + + File upload test + + +
+ + +
+ + \ No newline at end of file diff --git a/packages/web/tests/parity/assets/input/folderupload.html b/packages/web/tests/parity/assets/input/folderupload.html new file mode 100644 index 0000000000..16c7e2c3e9 --- /dev/null +++ b/packages/web/tests/parity/assets/input/folderupload.html @@ -0,0 +1,12 @@ + + + + Folder upload test + + +
+ + +
+ + \ No newline at end of file diff --git a/packages/web/tests/parity/assets/input/handle-locator.html b/packages/web/tests/parity/assets/input/handle-locator.html new file mode 100644 index 0000000000..5b164d5c7a --- /dev/null +++ b/packages/web/tests/parity/assets/input/handle-locator.html @@ -0,0 +1,91 @@ + + + + Interstitial test + + + +
+
A place on the side to hover
+
+
This interstitial covers the button
+ +
+ + + diff --git a/packages/web/tests/parity/assets/input/keyboard.html b/packages/web/tests/parity/assets/input/keyboard.html new file mode 100644 index 0000000000..049ed439be --- /dev/null +++ b/packages/web/tests/parity/assets/input/keyboard.html @@ -0,0 +1,51 @@ + + + + Keyboard test + + + + + + \ No newline at end of file diff --git a/packages/web/tests/parity/assets/input/mouse-helper.js b/packages/web/tests/parity/assets/input/mouse-helper.js new file mode 100644 index 0000000000..3c4d57033c --- /dev/null +++ b/packages/web/tests/parity/assets/input/mouse-helper.js @@ -0,0 +1,62 @@ +// This injects a box into the page that moves with the mouse; +// Useful for debugging +(function(){ + const box = document.createElement('div'); + box.classList.add('mouse-helper'); + const styleElement = document.createElement('style'); + styleElement.innerHTML = ` + .mouse-helper { + pointer-events: none; + position: absolute; + top: 0; + left: 0; + width: 20px; + height: 20px; + background: rgba(0,0,0,.4); + border: 1px solid white; + border-radius: 10px; + margin-left: -10px; + margin-top: -10px; + transition: background .2s, border-radius .2s, border-color .2s; + } + .mouse-helper.button-1 { + transition: none; + background: rgba(0,0,0,0.9); + } + .mouse-helper.button-2 { + transition: none; + border-color: rgba(0,0,255,0.9); + } + .mouse-helper.button-3 { + transition: none; + border-radius: 4px; + } + .mouse-helper.button-4 { + transition: none; + border-color: rgba(255,0,0,0.9); + } + .mouse-helper.button-5 { + transition: none; + border-color: rgba(0,255,0,0.9); + } + `; + document.head.appendChild(styleElement); + document.body.appendChild(box); + document.addEventListener('mousemove', event => { + box.style.left = event.pageX + 'px'; + box.style.top = event.pageY + 'px'; + updateButtons(event.buttons); + }, true); + document.addEventListener('mousedown', event => { + updateButtons(event.buttons); + box.classList.add('button-' + event.which); + }, true); + document.addEventListener('mouseup', event => { + updateButtons(event.buttons); + box.classList.remove('button-' + event.which); + }, true); + function updateButtons(buttons) { + for (let i = 0; i < 5; i++) + box.classList.toggle('button-' + i, buttons & (1 << i)); + } +})(); diff --git a/packages/web/tests/parity/assets/input/rotatedButton.html b/packages/web/tests/parity/assets/input/rotatedButton.html new file mode 100644 index 0000000000..1bce66cf5e --- /dev/null +++ b/packages/web/tests/parity/assets/input/rotatedButton.html @@ -0,0 +1,21 @@ + + + + Rotated button test + + + + + + + + diff --git a/packages/web/tests/parity/assets/input/scrollable.html b/packages/web/tests/parity/assets/input/scrollable.html new file mode 100644 index 0000000000..885d3739d5 --- /dev/null +++ b/packages/web/tests/parity/assets/input/scrollable.html @@ -0,0 +1,23 @@ + + + + Scrollable test + + + + + + \ No newline at end of file diff --git a/packages/web/tests/parity/assets/input/scrollable2.html b/packages/web/tests/parity/assets/input/scrollable2.html new file mode 100644 index 0000000000..885d3739d5 --- /dev/null +++ b/packages/web/tests/parity/assets/input/scrollable2.html @@ -0,0 +1,23 @@ + + + + Scrollable test + + + + + + \ No newline at end of file diff --git a/packages/web/tests/parity/assets/input/select.html b/packages/web/tests/parity/assets/input/select.html new file mode 100644 index 0000000000..42784c28f3 --- /dev/null +++ b/packages/web/tests/parity/assets/input/select.html @@ -0,0 +1,70 @@ + + + + Selection Test + + + + + + diff --git a/packages/web/tests/parity/assets/input/textarea.html b/packages/web/tests/parity/assets/input/textarea.html new file mode 100644 index 0000000000..11da79882e --- /dev/null +++ b/packages/web/tests/parity/assets/input/textarea.html @@ -0,0 +1,20 @@ + + + + Textarea test + + + + +
+
Plain div
+ + + + \ No newline at end of file diff --git a/packages/web/tests/parity/assets/input/touches.html b/packages/web/tests/parity/assets/input/touches.html new file mode 100644 index 0000000000..4392cfacbd --- /dev/null +++ b/packages/web/tests/parity/assets/input/touches.html @@ -0,0 +1,35 @@ + + + + Touch test + + + + + + + \ No newline at end of file diff --git a/packages/web/tests/parity/assets/networkidle-frame.html b/packages/web/tests/parity/assets/networkidle-frame.html new file mode 100644 index 0000000000..3bf7ad4feb --- /dev/null +++ b/packages/web/tests/parity/assets/networkidle-frame.html @@ -0,0 +1 @@ + diff --git a/packages/web/tests/parity/assets/networkidle.html b/packages/web/tests/parity/assets/networkidle.html new file mode 100644 index 0000000000..ab10c97967 --- /dev/null +++ b/packages/web/tests/parity/assets/networkidle.html @@ -0,0 +1 @@ + diff --git a/packages/web/tests/parity/assets/networkidle.js b/packages/web/tests/parity/assets/networkidle.js new file mode 100644 index 0000000000..9d8998458a --- /dev/null +++ b/packages/web/tests/parity/assets/networkidle.js @@ -0,0 +1,12 @@ +async function main() { + window.ws = new WebSocket('ws://localhost:' + window.location.port + '/ws'); + window.ws.addEventListener('message', message => {}); + + fetch('fetch-request-a.js'); + window.top.fetchSecond = () => { + // Do not return the promise here. + fetch('fetch-request-b.js'); + }; +} + +main(); diff --git a/packages/web/tests/parity/assets/offscreenbuttons.html b/packages/web/tests/parity/assets/offscreenbuttons.html new file mode 100644 index 0000000000..b7f381decd --- /dev/null +++ b/packages/web/tests/parity/assets/offscreenbuttons.html @@ -0,0 +1,55 @@ + +
+ + + + + + + + + + + +
+ diff --git a/packages/web/tests/parity/assets/one-style.css b/packages/web/tests/parity/assets/one-style.css new file mode 100644 index 0000000000..7b26410d8a --- /dev/null +++ b/packages/web/tests/parity/assets/one-style.css @@ -0,0 +1,3 @@ +body { + background-color: pink; +} diff --git a/packages/web/tests/parity/assets/one-style.html b/packages/web/tests/parity/assets/one-style.html new file mode 100644 index 0000000000..b3a6eeeebe --- /dev/null +++ b/packages/web/tests/parity/assets/one-style.html @@ -0,0 +1,3 @@ + + +
hello, world!
diff --git a/packages/web/tests/parity/assets/playground.html b/packages/web/tests/parity/assets/playground.html new file mode 100644 index 0000000000..828cfb1c70 --- /dev/null +++ b/packages/web/tests/parity/assets/playground.html @@ -0,0 +1,15 @@ + + + + Playground + + + + +
First div
+
+ Second div + Inner span +
+ + \ No newline at end of file diff --git a/packages/web/tests/parity/assets/pptr.png b/packages/web/tests/parity/assets/pptr.png new file mode 100644 index 0000000000000000000000000000000000000000..65d87c68e65902c058af18d2a595fc89f423f4ff GIT binary patch literal 6138 zcmZu#cQjmWw;y9L%IID6F3RYg=q(tXsDlyR=)DagT6krUFiIrRiC%*dq6>-MMT<^? zh#Z0{rl~`P72IO2SUP30ssIYdb*mXIH`pju3$pkdn)>_ z6DL5A)eO}DfQC%cTQ~u3&f%hKY6t*C@BsjEi2%TFoGNY)00@Qx00&M0fWiv^fB}i= zG*QBRAapj+(FFYc_bKTve~!}-BXw;80RU2(e+M2QAH#@K5(ViQY7u=Up~B-QgS)T2 z1pw&x^)%JY!S$ZHQO&^aI)0-lv;<>80 zWA#UG$S*B4?TsqlUBshCdEDvPHNcV*OdOyOSy@aH)WgWr#na4aKR#bVDS|H_LulpcHxOMdr_XTVAT!R8 zhP{h>9N8B}El0+vnW!71Xz}AHA^Qa~g_3$0 zM2{yfOO-^-2o%Oog%|oeW7_?Er$4z+&KEfYAyEqZ_(l9LNWkxt8Eyc1uUE%(5$VX=D%> z*~dY;KVcMRNjv^nyx<=5xGrjl-$4Bi>lp{HsFgCI_;%Qhl2+U> zm(l&Sydg~V>~ETryTDi&Svy11NHU(uCG`DjUlzw(A1_1Y;<1EK8SvaGsK0{10qEe~ z8K}cr%WxK%2*zf?V8D+%Kx5gnb6`^)IiJa7Q5_`%M9-gck6S?ads%yw98zrb?gy+e zAhPc%K@pL|fH(6f_Jxs>yrD#-#6>2EzX@o1MQT|1?Hc$ig56tHSfHB>yc*)`Wl~%D zoZH|#(VxtU`W~`z4+xG2DQoF!%7@MYX~tDPcpg)98Z!+wcJ-xQ>RDqh%vS8kBvDM zpJ&{|>UT@LIb|9tPH&A&Er}i9fMrfBkxF))g7jsX=m9NMn%Nj~?g*v=k(ZJCi+|6D z`<`ODPQ1qh%Fl4A$S~1vI)9V<&^NBmpnFyf8*lh%|V7Lv9 zEAZ0gSkfyWP@2G@!Ju^Gti)f7b_;mv<8}mFWA<5&HBKwh{7X}79H2Snp$6Zz%zs{z zn)VPXEnjR*WT=?Pm_>sb%6-XB2q<_A2(J=9m|8zC9T&eUMM+9n_Ayb;lHH>ne)ki* zWDZYwP85X~l^#881tpYVn}FP=u+*KVJcSuQKMC+85%a-Y+S&!5cMI+3MrVhjXAvz3om5A5i$g9^bN4R zyb(p3-qMi*8AOgG_KEb@ca03Ll4xr_Mg22H`evZ`$uG36%*>c_4c&M zo{&`g)%f!GzXOXk{*NgL9=o%*yCyXCkq^C%-_g`4-`$Wx-X|z0L~=>cmZirLC-A}7 zuKz~eUkhJOi^QlDVia{BDRWG9Bu}0Y*{7Uf@o?r|x)}qS)OQI&!0W!Mk%J&RAWr%W z(C !4@^Vx1sD`7N#d=xeNFoPC9oyU-cfsEl&6lomsESF+tG@eQK*Rh_E6^MP|L zo%KhZgeJ4+BV`4()-B z#Ckf_O^nXtPvaSQL8R@8XhW9+>9Po;D5BIdcIJ zb_gd{&^-S;#RkSlET{ExEEXc*B_^Oi36Cr!omp~V2NeNS%I1D}{VX^BIwctUJ2aU| zFZ*Sv!3j7i&k`(})8DEAJ@*Cw!1H4HKx>FyRQfgK*8V8tET})|>OnJ`eZ9B*Q^XB? z`w16JZ~yO-ldH^P+FdvM#!?XsG&SKlY=HirmQi($^)y&4rj3b|ro)m3Sg|weP zd~PH-3;SE`4^?nzgqJ({2uW09W5iqW*zs&cFp=_}u7~LXuP{GRo4(7Oc3wq4t0_s9 zfDbk1HTD?rrfGOz6UMzO?>xxRW{1>R%K5YPEQl`TkrOLhfZ16sDTdZ26L0#DZp>F2 z;dxHezJ-C;nZSNn-8nIGuCHUKWE8)y!nMt!CHR84%{~Xb!D-F|u6mcEqt$x_|B|rB zf_KHQpUr}8=QC-la`iV%-Kg${nLqm5-7C8yX|2`p`D=;SWiI~ZYl{$0?*6-FVbTGnGAf&_W7wTRDsr$m-+;xVxJK0?k+N4NA*T;MB8nG>oS<0q2gCBorvAyaxKELp(B zSEc84wbHG%PYwmpUgobAnr*Pf(Ea|DjDW2a!EFAr3hfR#d2lC>t7~7QA*#2Q{^+4b zSf_JOD5DWYrq&+wTmlo+3$lfNCsZEd? zQ-ng9vg->``!I+x&JvO1qvBYxML!$SH!#sHkhSco_}dDql~Pea6=zs zoJW`=fy-m&xmqG|bBsSZ9oZoM>KdC#OohY}hoZXVd*FO>+fzjgos0CdF6SoVm3R|fSV>xs37S|g*GEi=z zs?%b~Fk28}QTXh%;+X_FYDJ|xNvxloG81@}rh*C{D!L%~c_4AmB2lrg3CzOo5>F_z z+9wRD!|KCW#k}(jvZBrrH>%IGZUe%yV)spZImwcsrWpY;ec1w-n@|g1KcM#bXcwZ;5lYka^TJIF;KV1+R7U8{NY=S1$7-6R$p{;o{5m6;O(Y=95@Y{1O) zymYpbRC`BntLXWU5(s%5&bJ5!$0}=3%0uu=%f33PEb3a@`q8p#Pg7Wf0ir)anh3$t z@Q>QGUpFCH|j;?a!5nS@VjGq%KVAJ6joJ^Hu1uh zxTe656kUgcGo zVuEbUyeVWkrA^6FtCE_j9PB9~3xt1I_QozP&X-7ysH?U_HNbkkC)t&udgFYRLqodC z;+C76uB!8Xaa0xId+fC)0>x&Ebn0C7>>LbXEIFL(?u^eiRx+w)@}w0UTb}J!9XGu_ z_OI80wWJ9-5!aKqRBc$G5zUpzK>QtGx~9cf3D}tApqVNnk~W9tj^}QowW+DXXn}z4 z&${=RyP?qofvU_4Z4tR_fwY%1Unp$5M&Ve-!5 z2HS%C?uuG9rle7w2Tyi$f*x9w65@AJo4idtOxjG$Uv9YiV&&ei`9(xXZwsbE!g%Xa za-l}mQvK9+9q|bD1v(j^ZI4WrKFBReS3``4Al8p^?=%-D*JI$xuk~|$k~aHWl!GQF zd}oc(-B{Zc=J?K%-{UeGOixF}j;hLbI&z+sP#+|33)?OaZE`dQgS0fR3s^iEt6P*G z75cvan3F-m&r|h-&!od_zV*TWvjbzEEZ@jF&3{gY8%ykT+tfxhI;PIbSQHMTb%3EI zz-HwN=K%T9CoAoj+%`HAusMg612JCDZhP?P6U!;5Vc(?(R_5x`pIQ^r1kO8CM?*dL z+XH|RrCdu7X9&oFpYUIMK&uyMM};{DzU=L}&lf32I?KE~Y|Uy+NE8sklu>?YO&Kut z`l|VxSVBUAOmL@3>IH=-_^oWc|CjFPof8GJnI$D0LH0WODR4$G=adwrADU%ax|kcn zlBA|%5fh^#)_qIu7<0X2Geh#-Wvcx(D?20Og3l+6d}4C43nL*D6B8{xeW?dC0)fED z`J?ig>FO}bk+~Smy+lgZpHysYpD>Go>2Yy!im)AmeD#zcS6BQ{U4jM=50Bd)UmY8N ziKSK6)$JCBu7B-IX5*2T&cT_+oU`|S?dX^^ad2>WoXcuxS)Eg|!6CxI0bs^8Ey#<{ ziIiZFss75!3Ye6Xn}-KvKTmu{!J(vdPfSbn0f$%~(D4*{~oCUL#6(R?OKbIJb91l_;?NPW5xqEy(fg&J% zA?-B>A$Xpht?uT=C+RkhotQXwjCoJLI^^82vAa81;MX&9Fk79Hk^=v}`4OWSO5P7W zD3g7IwieFq+^3A(wR!Ytbhi5P3cl1UNtW>Ci)mH$yE~0q+$}~&nT>7V*>~k?rP2HE ze|f82oR^np=HL)Bp;A>tV4v-fSEmj!he@ zPAoLI*mMN&+P3+AoSn^?nKADS+W!zZsXSB<>5R&ay|O$`v8sc#>vU2GQ)zf!`e0h0f7>~ z^`3DYex5!B(~H_YUG(OYlzfi6e6EPCHnM(8D_i7IDkZA1QDS$pc=C0o%ILCRuVGY_ zQlVm~TYnM+qf+a}92gjA(;K6V%PNd~VA9T5Uen`Aw!w5J4IJW+pc^@nBmCN?xCC0-psr_1~xXf7Z3SR z2?_f%l{5xo4`#mSm30ay zTU-5y?|O~Y)qz_>nU6OIQoL6?=?tgA5XjDP+d3Z~Us7Ts$n6tmWOt&#rpXPG1kcLJ zv1nWO>%Gh6FOJIg-x_QPIez32zC(vY@AXmB(jMIiCk|7=I8V1?pso_vSt(%uyocv&&{2y z(4TMS@|7t#)Xy&}D%$IGn2(i{m!A#J#jy*RvpwQcXm)lML_|cxz>r+#p{c1k^;##> ztIQM9Us6_wvZJZ>&|-)rY&WBqSu(?MTkzs2{|!w_EI= zg9|w|k~k7KRyqRTpM4;$vFpfwLdvkYwWVQdN{s^@Egjw0lM^E(6517dI_TMg<67Lg zx4(Tm?;~P|Sz2m4J9AxMUx!6T(oj-jKNTucsY4?!+=J}P8ymB6H37%_!=s}gR##c8 zXP0(Oz0z{2X=yc2*Sf_ESl-2vKp+SlnG4%ACaV6uo+M*cpydReoSZNw#kaM|^78U3 z-5fQwcXWK;OcTq_%EBf=SkBJRw{VA5IvtyY!y(eZQP{JRfB7n|f=&@aHU96?y#w@h@QDj66I%lr%INnwlU|df|=k zt2LL)gIN$Ep+xMTD23nyO;=Z*SFc|ApuWJ^2Zn~mva_i@tPqH|!lI(N^l4f$7Ct_; zO3}ZY$H&LfxO{DFZ?|Sn;>;7a;ljtq--*X3a@E#OdXN07zUqgApcpq7muo~s=R;%T zyzubwjGs1UX57ZbDk9U<)41A&czsGjO1guCh^vQ3CE9fK;J`EdU`8+;N21}l%+p@p z-QFHiW_3vHd-qyD?598)`Ax!npY>Q zhii(8in0NUIBjWZ-Q7FGekd|DG&F2>+%52Rv<$kpSM|@IKf$Mk7z{4Kg4%s_b-|pR zoWZA0C`F#h%r_r*9#_)gqVRQRM+-L9QvIIaxai?KhwihVKYdU8TdS8?^?PIP_U7Le z_n%TzQ|s#LwlDhlTC_E}{%?Iy*i0=bll*&JR2Rx4(3nx2CiADR0_o(?DF} W{|p>bpZvrb0Q9tsH0#uzQ2zrM7gd%3 literal 0 HcmV?d00001 diff --git a/packages/web/tests/parity/assets/preload.html b/packages/web/tests/parity/assets/preload.html new file mode 100644 index 0000000000..dc10ff6d69 --- /dev/null +++ b/packages/web/tests/parity/assets/preload.html @@ -0,0 +1,5 @@ + + +
hello, world!
diff --git a/packages/web/tests/parity/assets/redirectloop1.html b/packages/web/tests/parity/assets/redirectloop1.html new file mode 100644 index 0000000000..d542c4e9e4 --- /dev/null +++ b/packages/web/tests/parity/assets/redirectloop1.html @@ -0,0 +1,10 @@ +> diff --git a/packages/web/tests/parity/assets/redirectloop2.html b/packages/web/tests/parity/assets/redirectloop2.html new file mode 100644 index 0000000000..87c7194798 --- /dev/null +++ b/packages/web/tests/parity/assets/redirectloop2.html @@ -0,0 +1,5 @@ + diff --git a/packages/web/tests/parity/assets/rotate-pseudo.html b/packages/web/tests/parity/assets/rotate-pseudo.html new file mode 100644 index 0000000000..dca33ecdea --- /dev/null +++ b/packages/web/tests/parity/assets/rotate-pseudo.html @@ -0,0 +1,32 @@ + + + + + +
+ + diff --git a/packages/web/tests/parity/assets/rotate-z-shadow-dom.html b/packages/web/tests/parity/assets/rotate-z-shadow-dom.html new file mode 100644 index 0000000000..0a6e3f723e --- /dev/null +++ b/packages/web/tests/parity/assets/rotate-z-shadow-dom.html @@ -0,0 +1,31 @@ + + + + + diff --git a/packages/web/tests/parity/assets/rotate-z.html b/packages/web/tests/parity/assets/rotate-z.html new file mode 100644 index 0000000000..5397789419 --- /dev/null +++ b/packages/web/tests/parity/assets/rotate-z.html @@ -0,0 +1,26 @@ + + + + + +
+ + diff --git a/packages/web/tests/parity/assets/screenshots/canvas.html b/packages/web/tests/parity/assets/screenshots/canvas.html new file mode 100644 index 0000000000..a0ebc55829 --- /dev/null +++ b/packages/web/tests/parity/assets/screenshots/canvas.html @@ -0,0 +1,13 @@ + + + + diff --git a/packages/web/tests/parity/assets/screenshots/translateZ.html b/packages/web/tests/parity/assets/screenshots/translateZ.html new file mode 100644 index 0000000000..2b4aae8c09 --- /dev/null +++ b/packages/web/tests/parity/assets/screenshots/translateZ.html @@ -0,0 +1,4 @@ +
+
+
+
\ No newline at end of file diff --git a/packages/web/tests/parity/assets/sectionselectorengine.js b/packages/web/tests/parity/assets/sectionselectorengine.js new file mode 100644 index 0000000000..e83b187a95 --- /dev/null +++ b/packages/web/tests/parity/assets/sectionselectorengine.js @@ -0,0 +1,8 @@ +({ + query(root, selector) { + return root.querySelector('section'); + }, + queryAll(root, selector) { + return Array.from(root.querySelectorAll('section')); + } +}) \ No newline at end of file diff --git a/packages/web/tests/parity/assets/self-request.html b/packages/web/tests/parity/assets/self-request.html new file mode 100644 index 0000000000..88aff620ff --- /dev/null +++ b/packages/web/tests/parity/assets/self-request.html @@ -0,0 +1,5 @@ + diff --git a/packages/web/tests/parity/assets/shadow.html b/packages/web/tests/parity/assets/shadow.html new file mode 100644 index 0000000000..d1fd331eb2 --- /dev/null +++ b/packages/web/tests/parity/assets/shadow.html @@ -0,0 +1,17 @@ + diff --git a/packages/web/tests/parity/assets/simple.json b/packages/web/tests/parity/assets/simple.json new file mode 100644 index 0000000000..6d95903051 --- /dev/null +++ b/packages/web/tests/parity/assets/simple.json @@ -0,0 +1 @@ +{"foo": "bar"} diff --git a/packages/web/tests/parity/assets/title.html b/packages/web/tests/parity/assets/title.html new file mode 100644 index 0000000000..6e81f4091a --- /dev/null +++ b/packages/web/tests/parity/assets/title.html @@ -0,0 +1,2 @@ + +Woof-Woof diff --git a/packages/web/tests/parity/assets/wrappedlink.html b/packages/web/tests/parity/assets/wrappedlink.html new file mode 100644 index 0000000000..429b6e9156 --- /dev/null +++ b/packages/web/tests/parity/assets/wrappedlink.html @@ -0,0 +1,32 @@ + +
+ 123321 +
+ diff --git a/packages/web/tests/parity/e2e.config.ts b/packages/web/tests/parity/e2e.config.ts new file mode 100644 index 0000000000..2830b0007c --- /dev/null +++ b/packages/web/tests/parity/e2e.config.ts @@ -0,0 +1,25 @@ +import type { E2EConfig } from 'e2e'; +import { web } from '@e2e-dev/web'; + +/** + * Behavior parity: Playwright's own page tests (microsoft/playwright + * `tests/page` at v1.64.1, Apache-2.0), rewritten against the public API. + * Run it on both browsers (`BROWSER=chromium|firefox`); see README.md. + */ +const port = Number(process.env['PARITY_PORT'] ?? 4311); + +export default { + projectId: 'dev.e2e.web-parity', + tests: 'tests/**/*.e2e.ts', + targets: [ + { + name: 'web', + engine: web({ browser: (process.env['BROWSER'] ?? 'chromium') as 'chromium' | 'firefox' }), + app: { + url: `http://127.0.0.1:${port}`, + command: { executable: 'node', args: ['server.mjs'], env: { PORT: String(port) } }, + }, + }, + ], + reporters: ['list'], +} satisfies E2EConfig; diff --git a/packages/web/tests/parity/server.mjs b/packages/web/tests/parity/server.mjs new file mode 100644 index 0000000000..855c15919e --- /dev/null +++ b/packages/web/tests/parity/server.mjs @@ -0,0 +1,178 @@ +/** + * The parity suite's app: Playwright's test assets (`assets/`, copied from + * microsoft/playwright `tests/assets` at v1.64.1, Apache-2.0) plus the few + * dynamic routes Playwright's test server sets per test, fixed here as paths. + * Serves every interface, so `127.0.0.1` and `localhost` on one port are two + * origins for the cross-origin cases. + */ + +import { createReadStream, existsSync, statSync } from 'node:fs'; +import { createServer } from 'node:http'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), 'assets'); +const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.svg': 'image/svg+xml', '.txt': 'text/plain' }; + +/** The request body, read whole. */ +function body(request) { + return new Promise((resolve) => { + const chunks = []; + request.on('data', (chunk) => chunks.push(chunk)); + request.on('end', () => resolve(Buffer.concat(chunks))); + }); +} + +const counts = new Map(); +const logs = new Map(); + +const server = createServer(async (request, response) => { + const url = new URL(request.url, 'http://localhost'); + const query = url.searchParams; + switch (url.pathname) { + case '/content': + response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); + response.end(Buffer.from(query.get('html') ?? '', 'base64url')); + return; + case '/echo': { + const received = await body(request); + response.writeHead(200, { 'content-type': 'application/json', 'access-control-allow-origin': '*' }); + response.end(JSON.stringify({ method: request.method, headers: request.headers, body: received.toString(), url: request.url })); + return; + } + case '/status': + response.writeHead(Number(query.get('code') ?? 200), { 'content-type': 'text/plain' }); + response.end(query.get('body') ?? ''); + return; + case '/slow': + setTimeout(() => { + response.writeHead(200, { 'content-type': query.get('type') ?? 'text/plain', 'access-control-allow-origin': '*' }); + response.end(query.get('body') ?? 'slow'); + }, Number(query.get('ms') ?? 1000)); + return; + case '/never': + request.on('close', () => response.destroy()); + return; + case '/redirect': + response.writeHead(302, { location: query.get('to') ?? '/empty.html' }); + response.end(); + return; + case '/download': + response.writeHead(200, { + 'content-type': 'application/octet-stream', + 'content-disposition': `attachment${query.has('name') ? `; filename=${query.get('name')}` : ''}`, + }); + response.end(query.get('body') ?? 'Hello world'); + return; + case '/set-cookie': + response.writeHead(200, { 'set-cookie': query.get('cookie') ?? 'name=value', 'content-type': 'text/html' }); + response.end('cookie'); + return; + case '/respond': + response.writeHead(Number(query.get('status') ?? 200), JSON.parse(query.get('headers') ?? '{}')); + response.end(query.get('body') ?? ''); + return; + case '/cors-echo': { + const allow = { + 'access-control-allow-origin': request.headers.origin ?? '*', + 'access-control-allow-credentials': 'true', + 'access-control-allow-methods': 'POST, GET, OPTIONS, DELETE', + 'access-control-allow-headers': request.headers['access-control-request-headers'] ?? '*', + }; + if (request.method === 'OPTIONS' && query.has('preflight')) { + response.writeHead(204, allow); + response.end(); + return; + } + const received = await body(request); + response.writeHead(200, { 'content-type': 'text/plain', ...allow }); + response.end(JSON.stringify({ method: request.method, headers: request.headers, body: received.toString(), url: request.url })); + return; + } + case '/bounce': { + const headers = { + location: query.get('to') ?? '/empty.html', + 'access-control-allow-origin': request.headers.origin ?? '*', + 'access-control-allow-credentials': 'true', + 'access-control-allow-headers': request.headers['access-control-request-headers'] ?? '*', + ...(query.has('cookie') ? { 'set-cookie': query.get('cookie') } : {}), + }; + if (request.method === 'OPTIONS') delete headers.location; + response.writeHead(request.method === 'OPTIONS' ? 204 : Number(query.get('status') ?? 302), headers); + response.end(); + return; + } + case '/count': { + const key = query.get('key') ?? ''; + counts.set(key, (counts.get(key) ?? 0) + 1); + response.writeHead(200, { 'content-type': 'text/plain' }); + response.end(String(counts.get(key) * 11)); + return; + } + case '/options': { + const key = query.get('key') ?? ''; + logs.set(key, [...(logs.get(key) ?? []), `${request.method}:${url.pathname}`]); + response.writeHead(200, request.method === 'OPTIONS' + ? { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'POST, GET, OPTIONS, DELETE', 'access-control-allow-headers': '*', 'cache-control': 'no-cache' } + : { 'access-control-allow-origin': '*' }); + response.end(request.method === 'OPTIONS' ? 'Hello' : 'World'); + return; + } + case '/options-log': + response.writeHead(200, { 'content-type': 'application/json' }); + response.end(JSON.stringify(logs.get(query.get('key') ?? '') ?? [])); + return; + case '/upload': { + const received = await body(request); + const boundary = Buffer.from(`--${/boundary=(.+)$/.exec(request.headers['content-type'] ?? '')?.[1] ?? ''}`); + const files = []; + for (let start = received.indexOf(boundary); start !== -1;) { + const next = received.indexOf(boundary, start + boundary.length); + if (next === -1) break; + const part = received.subarray(start + boundary.length + 2, next - 2); + const split = part.indexOf('\r\n\r\n'); + const head = part.subarray(0, split).toString(); + const data = part.subarray(split + 4); + files.push({ + name: /name="([^"]*)"/.exec(head)?.[1], + filename: /filename="([^"]*)"/.exec(head)?.[1], + mimetype: /content-type: (.+)/i.exec(head)?.[1], + size: data.length, + base64: data.length <= 65536 ? data.toString('base64') : undefined, + }); + start = next; + } + response.writeHead(200, { 'content-type': 'text/plain', 'access-control-allow-origin': '*' }); + response.end(JSON.stringify(files)); + return; + } + case '/binary': { + const data = Buffer.alloc(Number(query.get('bytes') ?? 1 << 20)); + for (let i = 0; i < data.length; i++) data[i] = Math.imul(i + 1, 2654435761) >>> 24; + response.writeHead(200, { 'content-type': 'application/zip', 'content-length': data.length }); + response.end(data); + return; + } + case '/download-stall': + response.writeHead(200, { 'content-type': 'application/octet-stream', 'content-disposition': 'attachment; filename=file.txt' }); + response.write('a'.repeat(4096)); + response.write('foo'); + request.on('close', () => response.destroy()); + return; + case '/sse': + response.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive', 'cache-control': 'no-cache' }); + response.write('data: hello\n\n'); + request.on('close', () => response.destroy()); + return; + } + const file = path.join(ROOT, path.normalize(decodeURIComponent(url.pathname)).replace(/^(\.\.[/\\])+/, '')); + if (!file.startsWith(ROOT) || !existsSync(file) || statSync(file).isDirectory()) { + response.writeHead(404, { 'content-type': 'text/plain' }); + response.end('Not found'); + return; + } + response.writeHead(200, { 'content-type': TYPES[path.extname(file)] ?? 'application/octet-stream', 'cache-control': 'no-store' }); + createReadStream(file).pipe(response); +}); + +server.listen(Number(process.env.PORT ?? 4311)); diff --git a/packages/web/tests/parity/tests/download.e2e.ts b/packages/web/tests/parity/tests/download.e2e.ts new file mode 100644 index 0000000000..2ed2dad2cb --- /dev/null +++ b/packages/web/tests/parity/tests/download.e2e.ts @@ -0,0 +1,218 @@ +/** + * Adapted from microsoft/playwright tests/library/download.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `page.waitForEvent('download')` is `browser.waitForDownload(trigger)`, + * which saves the file, and `download.path()` is the saved file's `absolutePath`. + */ + +/* + * Not ported: + * - should report downloads with acceptDownloads: false: e2e always accepts downloads. + * - should report proper download url when download is from download attribute: needs `download.url()`. + * - should save to user-specified path without updating original path: needs `download.saveAs`. + * - should save to two different paths with multiple saveAs calls: needs `download.saveAs`. + * - should save to overwritten filepath: needs `download.saveAs`. + * - should create subdirectories when saving to non-existent user-specified path: needs `download.saveAs`. + * - should error when saving with downloads disabled: needs `acceptDownloads: false` and `download.saveAs`. + * - should error when saving after deletion: needs `download.delete` and `download.saveAs`. + * - should delete file: needs `download.delete`. + * - should expose stream: needs `download.createReadStream`. + * - should delete downloads on context destruction: needs `context.close` from the test. + * - should delete downloads on browser gone: needs `browserType.launch` from the test. + * - should save downloads to artifactsDir: needs `browserType.launch({ artifactsDir })`. + * - should close the context without awaiting the failed download: needs `context.close` and an HTTPS server. + * - should close the context without awaiting the download: needs `context.close` and `download.failure`. + * - should throw if browser dies: needs `browser.close` from the test. + * - should be able to cancel pending downloads: needs `download.cancel` and `download.failure`. + * - should not fail explicitly to cancel a download even if that is already finished: needs `download.cancel`. + * - should save to user-specified path: needs `download.saveAs`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import fs from 'node:fs'; +import path from 'node:path'; +import { browserName, content, PREFIX, e2eGap } from './helpers.ts'; + +/** `/respond` answering with `headers` and `body`. */ +function respond(headers: Record, body = 'Hello world'): string { + return `/respond?headers=${encodeURIComponent(JSON.stringify(headers))}&body=${encodeURIComponent(body)}`; +} + +/** Checks a saved download is `asset` byte for byte, PDF magic first, Playwright's `assertDownloadToPDF`. */ +function assertDownloadToPDF(download: { absolutePath: string; suggestedFilename: string }, asset: string): void { + expect(download.suggestedFilename).toBe(path.basename(asset)); + const data = fs.readFileSync(download.absolutePath); + const expectedPrefix = '%PDF'; + for (let i = 0; i < expectedPrefix.length; i++) expect(data[i]).toBe(expectedPrefix.charCodeAt(i)); + expect(data.equals(fs.readFileSync(asset))).toBe(true); +} + +test.describe('download event', { requires: ['browser'] }, () => { + test('should report download when navigation turns into download @smoke', async ({ browser }) => { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await browser.goto('/empty.html'); + let responseOrError: unknown; + const download = await browser.waitForDownload(async () => { + responseOrError = await browser.goto(`${PREFIX}/download`).catch((caught: Error) => caught); + }); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + expect(responseOrError instanceof Error).toBeTruthy(); + expect((responseOrError as Error).message).toContain('Download is starting'); + expect(await browser.url()).toBe(`${PREFIX}/empty.html`); + }); + + test('should work with Cross-Origin-Opener-Policy', async ({ browser }) => { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await browser.goto('/empty.html'); + let responseOrError: unknown; + const url = respond({ 'content-type': 'application/octet-stream', 'content-disposition': 'attachment', 'cross-origin-opener-policy': 'same-origin' }); + const download = await browser.waitForDownload(async () => { + responseOrError = await browser.goto(url).catch((caught: Error) => caught); + }); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + expect(responseOrError instanceof Error).toBeTruthy(); + expect((responseOrError as Error).message).toContain('Download is starting'); + expect(await browser.url()).toBe(`${PREFIX}/empty.html`); + }); + + test('should report downloads with acceptDownloads: true', async ({ browser }) => { + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + }); + + test('should report downloads for download attribute', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(download.suggestedFilename).toBe('foo.zip'); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + }); + + test('should report non-navigation downloads', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(download.suggestedFilename).toBe('file.txt'); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + }); + + test(`should report download path within page.on('download', …) handler for Files`, async ({ browser }) => { + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + }); + + test(`should report download path within page.on('download', …) handler for Blobs`, async ({ browser }) => { + await browser.goto('/download-blob.html'); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + }); + + test('should report alt-click downloads', async ({ browser }) => { + test.skip(browserName === 'firefox', 'Firefox does not download on alt-click.'); + await browser.goto('/empty.html'); + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap({ modifiers: ['Alt'] })); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + }); + + test('should report new window downloads', async ({ browser }) => { + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + }); + + test('should download large binary.zip', async ({ browser }) => { + const fileContent = Buffer.alloc(1 << 20); + for (let i = 0; i < fileContent.length; i++) fileContent[i] = Math.imul(i + 1, 2654435761) >>> 24; + await browser.goto('/empty.html'); + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + const downloaded = fs.readFileSync(download.absolutePath); + expect(downloaded.byteLength).toBe(fileContent.byteLength); + expect(downloaded.equals(fileContent)).toBe(true); + }); + + test('should report downloads with interception', async ({ browser }) => { + await browser.route(/.*/, (route) => route.continue()); + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + }); + + test('should emit download event from nested iframes', async ({ browser }) => { + const third = content(` download`); + const second = content(``); + await browser.goto(content(``)); + const download = await browser.waitForDownload(() => browser.frameLocator('iframe').frameLocator('iframe').locator('a').tap()); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + }); +}); + +test.describe('download', { requires: ['browser'] }, () => { + test('should be able to download a PDF file', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(content('download')); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + assertDownloadToPDF(download, 'assets/empty.pdf'); + }); + + test('should be able to download a inline PDF file via response interception', async ({ browser }) => { + e2eGap('`route.fulfill` bodies are strings, so binary bytes do not survive the round trip'); + await browser.goto('/empty.html'); + await browser.route('**/empty.pdf', async (route) => { + const response = await route.fetch(); + await route.fulfill({ + status: response.status, + headers: { ...response.headers, 'Content-Disposition': 'attachment' }, + body: await response.text(), + }); + }); + await browser.goto(content('open')); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + assertDownloadToPDF(download, 'assets/empty.pdf'); + }); + + test('should be able to download a inline PDF file via navigation', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(content('open')); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + assertDownloadToPDF(download, 'assets/empty.pdf'); + }); + + test('should download even if there is no "attachment" value', async ({ browser }) => { + await browser.goto(content(`download`)); + await browser.waitForDownload(() => browser.locator('a').tap()); + }); + + test('should convert navigation to a resource with unsupported mime type into download', async ({ browser }) => { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await browser.goto('/empty.html'); + await browser.waitForDownload(async () => { + await browser.goto(respond({ 'content-type': 'application/octet-stream' })).catch(() => undefined); + }); + }); + + test('should download links with data url', async ({ browser }) => { + await browser.goto(content('Download!')); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(download.suggestedFilename).toBe('SomeFile.txt'); + }); + + test('should download successfully when routing', async ({ browser }) => { + await browser.route('**/*', (route) => route.continue()); + await browser.goto('/empty.html'); + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(download.suggestedFilename).toBe('foo.zip'); + }); +}); diff --git a/packages/web/tests/parity/tests/elementhandle-scroll-into-view.e2e.ts b/packages/web/tests/parity/tests/elementhandle-scroll-into-view.e2e.ts new file mode 100644 index 0000000000..7faac83f78 --- /dev/null +++ b/packages/web/tests/parity/tests/elementhandle-scroll-into-view.e2e.ts @@ -0,0 +1,107 @@ +/** + * Adapted from microsoft/playwright tests/page/elementhandle-scroll-into-view.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: an element handle's + * `scrollIntoViewIfNeeded` is a locator `scrollIntoView`, its own `evaluate` + * a page `evaluate` on the same element. + * + * Not ported: + * - should throw for detached element: a handle to a removed element; a locator re-resolves. + */ + +import { test } from '@e2e-dev/web'; +import type { Browser } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +/** + * Starts scrolling the page's one `div` into view, checks it is still + * waiting a second later, runs `after` on the div in the page, and checks the + * scroll then finishes: Playwright's `testWaiting`. + */ +async function testWaiting(browser: Browser, after: string): Promise { + let done = false; + const promise = browser.locator('div').scrollIntoView().then(() => (done = true)); + await new Promise((resolve) => setTimeout(resolve, 1000)); + expect(done).toBe(false); + await browser.evaluate(`() => { const div = document.querySelector('div'); (${after})(div); }`); + await promise; + expect(done).toBe(true); +} + +test.describe('elementhandle scroll into view', { requires: ['browser'] }, () => { + test('should work @smoke', async ({ browser }) => { + await browser.goto('/offscreenbuttons.html'); + const overflow = '(id) => document.getElementById(id).getBoundingClientRect().right - window.innerWidth'; + for (let i = 0; i < 11; ++i) { + const before = await browser.evaluate(overflow, `btn${i}`); + expect(before).toBe(10 * i); + await browser.locator(`#btn${i}`).scrollIntoView(); + const after = await browser.evaluate(overflow, `btn${i}`); + expect(after <= 0).toBe(true); + await browser.evaluate('() => window.scrollTo(0, 0)'); + } + }); + + test('should wait for display:none to become visible', async ({ browser }) => { + await browser.goto(content('
Hello
')); + await testWaiting(browser, "div => div.style.display = 'block'"); + }); + + test('should scroll display:contents into view', async ({ browser }) => { + await browser.goto(content(` + +
+
+
+
Hello
+
+
+
+ `)); + await browser.locator('#target').scrollIntoView(); + const scrollTop = await browser.evaluate("() => document.querySelector('#container').scrollTop"); + expect(Math.abs(scrollTop - 350)).toBeLessThan(1); + }); + + test('should work for visibility:hidden element', async ({ browser }) => { + await browser.goto(content('
Hello
')); + await browser.locator('div').scrollIntoView(); + }); + + test('should work for zero-sized element', async ({ browser }) => { + await browser.goto(content('
Hello
')); + await browser.locator('div').scrollIntoView(); + }); + + test('should wait for nested display:none to become visible', async ({ browser }) => { + await browser.goto(content('
Hello
')); + await testWaiting(browser, "div => div.parentElement.style.display = 'block'"); + }); + + test('should wait for element to stop moving', async ({ browser }) => { + await browser.goto(content(` + +
moving
+ `)); + await testWaiting(browser, "div => div.classList.remove('animated')"); + }); + + test('should timeout waiting for visible', async ({ browser }) => { + await browser.goto(content('
Hello
')); + const error = await browser.locator('div').scrollIntoView({ timeout: 3000 }).catch((e: unknown) => e); + expect(error).toEqual(expect.any(Error)); + }); +}); diff --git a/packages/web/tests/parity/tests/frame-goto.e2e.ts b/packages/web/tests/parity/tests/frame-goto.e2e.ts new file mode 100644 index 0000000000..6271d29e53 --- /dev/null +++ b/packages/web/tests/parity/tests/frame-goto.e2e.ts @@ -0,0 +1,26 @@ +/** + * Adapted from microsoft/playwright tests/page/frame-goto.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: the stalled `/frames/script.js` is a route that sends + * the request to a path the server never answers. + */ + +/* + * Not ported: + * - should navigate subframes: frame.goto and Frame objects. + * - should reject when frame detaches: frame.goto and Frame objects. + * - should return matching responses: frame.goto, Frame objects, and per-request server responses. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { PREFIX } from './helpers.ts'; + +test.describe('frame goto', { requires: ['browser'] }, () => { + test('should continue after client redirect', async ({ browser }) => { + await browser.route('**/frames/script.js', (route) => route.continue({ url: `${PREFIX}/never` })); + const url = `${PREFIX}/frames/child-redirect.html`; + const error = await browser.goto(url, { timeout: 5000, waitUntil: 'networkidle' }).catch((caught: unknown) => caught); + expect(String(error)).toContain('timed out in browser.goto'); + }); +}); diff --git a/packages/web/tests/parity/tests/frame-hierarchy.e2e.ts b/packages/web/tests/parity/tests/frame-hierarchy.e2e.ts new file mode 100644 index 0000000000..b12b2424ca --- /dev/null +++ b/packages/web/tests/parity/tests/frame-hierarchy.e2e.ts @@ -0,0 +1,53 @@ +/** + * Adapted from microsoft/playwright tests/page/frame-hierarchy.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: e2e has no Frame objects, so a frame the original + * finds in `page.frames()` is reached through `frameLocator`. + */ + +/* + * Not ported: + * - should send events when frames are manipulated dynamically: frameattached, framenavigated, and framedetached events. + * - should persist mainFrame on cross-process navigation: page.mainFrame(). + * - should not send attach/detach events for main frame: frame events. + * - should detach child frames on navigation: frame events. + * - should support framesets: frame events. + * - should report frame.name(): Frame objects. + * - should report frame.parent(): Frame objects. + * - should report different frame instance when frame re-attaches: Frame objects and the frameattached event. + * - should refuse to display x-frame-options:deny iframe: console events. + * - should return frame.page(): Frame objects. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { PREFIX } from './helpers.ts'; + +test.describe('frame hierarchy', { requires: ['browser'] }, () => { + test('should handle nested frames', async ({ browser }) => { + await browser.goto('/frames/nested-frames.html'); + await expect(browser.frameLocator('[name=aframe]').locator('div')).toHaveText(`Hi, I'm frame`); + await expect(browser.frameLocator('[name="2frames"]').frameLocator('[name=dos]').locator('div')).toHaveText(`Hi, I'm frame`); + await expect(browser.frameLocator('[name="2frames"]').frameLocator('[name=uno]').locator('div')).toHaveText(`Hi, I'm frame`); + await expect(browser.frameLocator('[name="2frames"]').locator('iframe')).toHaveCount(2); + await expect(browser.locator('iframe')).toHaveCount(2); + }); + + test('should send "framenavigated" when navigating on anchor URLs', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto('/empty.html#foo'); + expect(await browser.url()).toBe(`${PREFIX}/empty.html#foo`); + }); + + test('should report frame from-inside shadow DOM', async ({ browser }) => { + await browser.goto('/shadow.html'); + await browser.evaluate(`async (url) => { + const frame = document.createElement('iframe'); + frame.src = url; + document.body.shadowRoot.appendChild(frame); + await new Promise((x) => (frame.onload = x)); + }`, `${PREFIX}/empty.html`); + await expect(browser.locator('iframe')).toHaveCount(1); + await expect(browser.frameLocator('iframe').locator('body')).toHaveCount(1); + }); +}); diff --git a/packages/web/tests/parity/tests/helpers.ts b/packages/web/tests/parity/tests/helpers.ts new file mode 100644 index 0000000000..439151c8ee --- /dev/null +++ b/packages/web/tests/parity/tests/helpers.ts @@ -0,0 +1,27 @@ +/** What the parity tests share: the server's two origins, inline pages, and which browser runs. */ + +import { test } from '@e2e-dev/web'; + +const port = Number(process.env['PARITY_PORT'] ?? 4311); + +/** The app's origin, Playwright's `server.PREFIX`. */ +export const PREFIX = `http://127.0.0.1:${port}`; + +/** Another origin on the same server, Playwright's `server.CROSS_PROCESS_PREFIX`. */ +export const CROSS = `http://localhost:${port}`; + +/** The browser under test. */ +export const browserName = (process.env['BROWSER'] ?? 'chromium') as 'chromium' | 'firefox'; + +/** A path that serves `html` as a page, for Playwright's `page.setContent(html)`. */ +export function content(html: string): string { + return `/content?html=${Buffer.from(html).toString('base64url')}`; +} + +/** + * Skips the running test where e2e itself differs from Playwright, in every + * browser unless `on.browser` narrows it: `reason` names the difference. + */ +export function e2eGap(reason: string, on: { readonly browser?: 'chromium' | 'firefox' } = {}): void { + test.skip(on.browser === undefined || on.browser === browserName, `e2e: ${reason}`); +} diff --git a/packages/web/tests/parity/tests/locator-convenience.e2e.ts b/packages/web/tests/parity/tests/locator-convenience.e2e.ts new file mode 100644 index 0000000000..8f04ec5899 --- /dev/null +++ b/packages/web/tests/parity/tests/locator-convenience.e2e.ts @@ -0,0 +1,107 @@ +/** + * Adapted from microsoft/playwright tests/page/locator-convenience.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: the `page.(selector)` twins of + * each locator read are locator reads, a `:text("...")` selector is + * `getByText`, and an element's own `evaluate` is a page `evaluate`. + * + * Not ported: + * - should have a nice preview: locator string previews and `evaluateHandle`. + * - innerHTML should work: e2e has no innerHTML. + * - innerText should work: e2e has no innerText. + * - innerText should throw: same. + * - innerText should produce log: same. + * - isEditable should work: e2e has no isEditable. + * - allInnerTexts should work: e2e has no allInnerTexts. + * - should return page: e2e locators have no page(). + * - description should return null for locator without description: e2e has no describe(). + * - description should return description for locator with simple description: same. + * - description should return description with special characters: same. + * - description should return description for chained locators: same. + * - description should return description for locator with multiple describe calls: same. + * - toString() returns formatted locator: e2e locators have no Playwright toString(). + * - toString() prefers description: same. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, e2eGap } from './helpers.ts'; + +test.describe('locator convenience', { requires: ['browser'] }, () => { + test('getAttribute should work', async ({ browser }) => { + await browser.goto('/dom.html'); + const locator = browser.locator('#outer'); + expect(await locator.getAttribute('name')).toBe('value'); + expect(await locator.getAttribute('foo')).toBe(null); + }); + + test('inputValue should work', async ({ browser }) => { + e2eGap('`inputValue()` on an element that is no input reads "" instead of throwing'); + await browser.goto('/dom.html'); + + await browser.locator('#select').selectOption({ value: 'foo' }); + expect(await browser.locator('#select').inputValue()).toBe('foo'); + + await browser.locator('#textarea').fill('text value'); + expect(await browser.locator('#textarea').inputValue()).toBe('text value'); + + await browser.locator('#input').fill('input value'); + expect(await browser.locator('#input').inputValue()).toBe('input value'); + + const error = await browser.locator('#inner').inputValue().catch((e: unknown) => e); + expect(error).toEqual(expect.any(Error)); + }); + + test('textContent should work', async ({ browser }) => { + e2eGap('`textContent()` normalizes whitespace, where Playwright keeps the raw text'); + await browser.goto('/dom.html'); + const locator = browser.locator('#inner'); + expect(await locator.textContent()).toBe('Text,\nmore text'); + }); + + test('isEnabled and isDisabled should work', async ({ screen, browser }) => { + await browser.goto(content(` + + +
div
+ `)); + const div = browser.locator('div'); + expect(await div.isEnabled()).toBe(true); + expect(await div.isDisabled()).toBe(false); + const button1 = screen.getByText('button1', { exact: false }); + expect(await button1.isEnabled()).toBe(false); + expect(await button1.isDisabled()).toBe(true); + const button2 = screen.getByText('button2', { exact: false }); + expect(await button2.isEnabled()).toBe(true); + expect(await button2.isDisabled()).toBe(false); + }); + + test('isChecked should work', async ({ browser }) => { + e2eGap('`isChecked()` on an element that is no checkbox reads false instead of throwing'); + await browser.goto(content(`
Not a checkbox
`)); + const element = browser.locator('input'); + expect(await element.isChecked()).toBe(true); + await browser.evaluate("() => { document.querySelector('input').checked = false; }"); + expect(await element.isChecked()).toBe(false); + const error = await browser.locator('div').isChecked().catch((e: unknown) => e); + expect(error).toEqual(expect.any(Error)); + }); + + test('isChecked should work for indeterminate input', async ({ browser }) => { + await browser.goto(content(``)); + await browser.evaluate("() => { document.querySelector('input').indeterminate = true; }"); + + expect(await browser.locator('input').isChecked()).toBe(true); + await expect(browser.locator('input')).toBeChecked(); + + await browser.locator('input').uncheck(); + + expect(await browser.locator('input').isChecked()).toBe(false); + await expect(browser.locator('input')).not.toBeChecked(); + }); + + test('allTextContents should work', async ({ browser }) => { + await browser.goto(content(`
A
B
C
`)); + expect(await browser.locator('div').allTextContents()).toEqual(['A', 'B', 'C']); + }); +}); diff --git a/packages/web/tests/parity/tests/locator-frame.e2e.ts b/packages/web/tests/parity/tests/locator-frame.e2e.ts new file mode 100644 index 0000000000..8ab6dd7b36 --- /dev/null +++ b/packages/web/tests/parity/tests/locator-frame.e2e.ts @@ -0,0 +1,232 @@ +/** + * Adapted from microsoft/playwright tests/page/locator-frame.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: the routed frame pages are pages the server serves (`content()`). + */ + +/* + * Not ported: + * - should wait for frame: asserts Playwright's `locator('body').locator('iframe').contentFrame()` log text; e2e has no locator.frameLocator. + * - should non work for non-frame: asserts Playwright's error text naming the matched `
`; e2e reports its own. + * - locator.frameLocator should work for iframe: e2e has no locator.frameLocator. + * - locator.frameLocator should throw on ambiguity: e2e has no locator.frameLocator. + * - locator.frameLocator should not throw on first/last/nth: e2e frame locators have no first/last/nth. + * - getBy coverage: e2e has no getByAltText or getByTitle; the other queries are kept as `getBy coverage (role, text, test id, label, placeholder)`. + * - should work with COEP/COOP/CORP isolated iframe: needs an https cross origin and page.frames(). + * - locator.contentFrame should work: e2e has no locator.contentFrame. + * - frameLocator.owner should work: e2e has no frameLocator.owner. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, CROSS, e2eGap } from './helpers.ts'; + +const nested = content(''); + +const iframe = content(` + +
+ + +
+ 1 + 2 + + `); + +const routed = content(``); + +/** Waits `ms` milliseconds. */ +function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +test.describe('locator frame', { requires: ['browser'] }, () => { + test('should work for iframe', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').locator('button'); + await button.waitFor(); + expect(await button.textContent()).toBe('Hello iframe'); + await expect(button).toHaveText('Hello iframe'); + await button.tap(); + }); + + test('should work for nested iframe', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').frameLocator('iframe').locator('button'); + await button.waitFor(); + expect(await button.textContent()).toBe('Hello nested iframe'); + await expect(button).toHaveText('Hello nested iframe'); + await button.tap(); + }); + + test('should work for $ and $$', async ({ browser }) => { + await browser.goto(routed); + const locator = browser.frameLocator('iframe').locator('button'); + await expect(locator).toHaveText('Hello iframe'); + const spans = browser.frameLocator('iframe').locator('span'); + await expect(spans).toHaveCount(2); + }); + + test('should wait for frame 2', async ({ browser }) => { + await browser.goto('about:blank'); + const navigated = delay(300).then(() => browser.goto(routed)); + await browser.frameLocator('iframe').locator('button').tap(); + await navigated; + }); + + test('should wait for frame to go', async ({ browser }) => { + await browser.goto(routed); + const removed = delay(300).then(() => browser.evaluate("() => { document.querySelector('iframe').remove(); }")); + await expect(browser.frameLocator('iframe').locator('button')).toBeHidden(); + await removed; + }); + + test('should not wait for frame', async ({ browser }) => { + await browser.goto('/empty.html'); + await expect(browser.frameLocator('iframe').locator('span')).toBeHidden(); + }); + + test('should not wait for frame 2', async ({ browser }) => { + await browser.goto('/empty.html'); + await expect(browser.frameLocator('iframe').locator('span')).not.toBeVisible(); + }); + + test('should not wait for frame 3', async ({ browser }) => { + await browser.goto('/empty.html'); + await expect(browser.frameLocator('iframe').locator('span')).toHaveCount(0); + }); + + test('should click in lazy iframe', async ({ browser }) => { + const lazy = content(''); + await browser.goto('/empty.html'); + const attached = delay(500) + .then(() => browser.evaluate("() => { document.body.appendChild(document.createElement('iframe')); }")) + .then(() => delay(500)) + .then(() => browser.evaluate("(src) => { document.querySelector('iframe').src = src; }", lazy)); + const button = browser.frameLocator('iframe').locator('button'); + const [, text] = await Promise.all([ + button.tap(), + button.textContent(), + expect(button).toHaveText('Hello iframe'), + attached, + ]); + expect(text).toBe('Hello iframe'); + }); + + test('waitFor should survive frame reattach', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').locator('button').filter({ hasText: 'Hello nested iframe' }); + const promise = button.waitFor(); + await browser.evaluate("() => { document.querySelector('iframe').remove(); }"); + await browser.evaluate("(src) => { const iframe = document.createElement('iframe'); iframe.src = src; document.body.appendChild(iframe); }", nested); + await promise; + }); + + test('click should survive frame reattach', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').locator('button').filter({ hasText: 'Hello nested iframe' }); + const promise = button.tap(); + await browser.evaluate("() => { document.querySelector('iframe').remove(); }"); + await browser.evaluate("(src) => { const iframe = document.createElement('iframe'); iframe.src = src; document.body.appendChild(iframe); }", nested); + await promise; + }); + + test('click should survive iframe navigation', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').locator('button').filter({ hasText: 'Hello nested iframe' }); + const promise = button.tap(); + const navigated = browser.evaluate("(src) => { document.querySelector('iframe').src = src; }", nested); + await promise; + await navigated; + }); + + test('getBy coverage (role, text, test id, label, placeholder)', async ({ browser }) => { + await browser.goto(routed); + const button1 = browser.frameLocator('iframe').getByRole('button'); + const button2 = browser.frameLocator('iframe').getByText('Hello', { exact: false }); + const button3 = browser.frameLocator('iframe').getByTestId('buttonId'); + await expect(button1).toHaveText('Hello iframe'); + await expect(button2).toHaveText('Hello iframe'); + await expect(button3).toHaveText('Hello iframe'); + const input1 = browser.frameLocator('iframe').getByLabel('Name'); + await expect(input1).toHaveValue(''); + const input2 = browser.frameLocator('iframe').getByPlaceholder('Placeholder'); + await expect(input2).toHaveValue(''); + }); + + test('wait for hidden should succeed when frame is not in dom', async ({ browser }) => { + await browser.goto('about:blank'); + const button = browser.frameLocator('iframe1').locator('button'); + expect(await button.isHidden()).toBeTruthy(); + await button.waitFor({ state: 'hidden', timeout: 1000 }); + await button.waitFor({ state: 'detached', timeout: 1000 }); + const error = await button.waitFor({ state: 'attached', timeout: 1000 }).catch((caught: unknown) => caught); + expect(error).toBeDefined(); + }); + + test('should treat elements inside hidden iframe as hidden', async ({ browser }) => { + e2eGap('the visibility read does not count an element inside a `visibility: hidden` iframe as hidden'); + await browser.goto(content(` + +
+ + +
+ + `)); + + for (const button of [ + browser.frameLocator('[name=hidden]').locator('button'), + browser.frameLocator('[name=hidden-parent]').locator('button'), + browser.frameLocator('[name=outer]').frameLocator('[name=inner]').locator('button'), + ]) { + await expect(button).toBeAttached(); + expect(await button.isVisible()).toBe(false); + expect(await button.isHidden()).toBe(true); + await expect(button).toBeHidden(); + await expect(button).not.toBeVisible(); + await button.waitFor({ state: 'hidden' }); + } + + const button = browser.frameLocator('[name=visible-override]').locator('button'); + expect(await button.isVisible()).toBe(true); + await expect(button).toBeVisible(); + await button.waitFor({ state: 'visible' }); + }); + + test('should wait for hidden iframe to become visible', async ({ browser }) => { + e2eGap('the visibility read does not count an element inside a `visibility: hidden` iframe as hidden'); + await browser.goto(content(``)); + const button = browser.frameLocator('[name=frame]').locator('button'); + await expect(button).toBeHidden(); + + const error = await button.tap({ timeout: 1000 }).catch((caught: unknown) => caught); + expect(error).toBeDefined(); + expect(await browser.evaluate("() => document.querySelector('iframe').contentWindow.__clicked === true")).toBe(false); + + const clickPromise = button.tap(); + const visiblePromise = expect(button).toBeVisible(); + await browser.evaluate("() => { document.querySelector('iframe').style.visibility = 'visible'; }"); + await Promise.all([clickPromise, visiblePromise]); + expect(await browser.evaluate("() => document.querySelector('iframe').contentWindow.__clicked")).toBe(true); + + await browser.evaluate("() => { document.querySelector('iframe').style.visibility = 'hidden'; }"); + await expect(button).toBeHidden(); + expect(await button.isVisible()).toBe(false); + }); + + test('should treat elements inside hidden cross-origin iframe as hidden', async ({ browser }) => { + e2eGap('the visibility read does not count an element inside a `visibility: hidden` iframe as hidden'); + await browser.goto('/empty.html'); + await browser.goto(content(``)); + const div = browser.frameLocator('iframe').locator('div'); + await expect(div).toHaveText(`Hi, I'm frame`); + expect(await div.isVisible()).toBe(false); + await expect(div).toBeHidden(); + + await browser.evaluate("() => { document.querySelector('iframe').style.visibility = 'visible'; }"); + await expect(div).toBeVisible(); + expect(await div.isVisible()).toBe(true); + }); +}); diff --git a/packages/web/tests/parity/tests/locator-is-visible.e2e.ts b/packages/web/tests/parity/tests/locator-is-visible.e2e.ts new file mode 100644 index 0000000000..f0b490f1d9 --- /dev/null +++ b/packages/web/tests/parity/tests/locator-is-visible.e2e.ts @@ -0,0 +1,137 @@ +/** + * Adapted from microsoft/playwright tests/page/locator-is-visible.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: the `page.isVisible(selector)` twins + * of each locator read are locator reads, `locator(css, { hasText })` a + * locator `filter({ hasText })`. + * + * Not ported: + * - isVisible with invalid selector should throw: Playwright selector engine names. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +test.describe('locator is visible', { requires: ['browser'] }, () => { + test('isVisible and isHidden should work', async ({ browser }) => { + await browser.goto(content(`
Hi
`)); + + const div = browser.locator('div'); + expect(await div.isVisible()).toBe(true); + expect(await div.isHidden()).toBe(false); + + const span = browser.locator('span'); + expect(await span.isVisible()).toBe(false); + expect(await span.isHidden()).toBe(true); + + expect(await browser.locator('no-such-element').isVisible()).toBe(false); + expect(await browser.locator('no-such-element').isHidden()).toBe(true); + }); + + test('isVisible should be true for opacity:0', async ({ browser }) => { + await browser.goto(content(`
Hi
`)); + await expect(browser.locator('div')).toBeVisible(); + }); + + test('isVisible should be true for element outside view', async ({ browser }) => { + await browser.goto(content(`
Hi
`)); + await expect(browser.locator('div')).toBeVisible(); + }); + + test('isVisible and isHidden should work with details', async ({ browser }) => { + await browser.goto(content(`
+ click to open +
    +
  • hidden item 1
  • +
  • hidden item 2
  • +
  • hidden item 3
  • +
`)); + + await expect(browser.locator('ul')).toBeHidden(); + }); + + test('isVisible and isHidden should work with nested details', async ({ screen, browser }) => { + await browser.goto(content(`
+ outer +
+ inner + +
+
`)); + + await expect(browser.locator('summary').filter({ hasText: 'outer' })).toBeVisible(); + await expect(browser.locator('summary').filter({ hasText: 'inner' })).toBeHidden(); + await expect(browser.locator('button')).toBeHidden(); + await expect(screen.getByRole('button')).toHaveCount(0); + }); + + test('isVisible and isHidden should work with unslotted content', async ({ browser }) => { + await browser.goto(content(` +
hidden 1
hidden 2
+
visible
+ + `)); + + await expect(browser.locator('span').filter({ hasText: 'hidden 1' })).toBeHidden(); + await expect(browser.locator('span').filter({ hasText: 'hidden 2' })).toBeHidden(); + await expect(browser.locator('span').filter({ hasText: 'visible' })).toBeVisible(); + }); + + test('isVisible and isHidden should work with list box options', async ({ screen, browser }) => { + await browser.goto(content(` + + + + `)); + + for (const name of ['visible 1', 'visible 2', 'visible 3']) + await expect(screen.getByRole('option', { name })).toBeVisible(); + for (const text of ['hidden 1', 'hidden 2', 'hidden 3']) + await expect(browser.locator('option').filter({ hasText: text })).toBeHidden(); + }); + + test('isVisible inside a button', async ({ browser }) => { + await browser.goto(content(``)); + const span = browser.locator('span'); + expect(await span.isVisible()).toBe(false); + expect(await span.isHidden()).toBe(true); + await expect(span).not.toBeVisible(); + await expect(span).toBeHidden(); + await span.waitFor({ state: 'hidden' }); + await browser.locator('button').waitFor({ state: 'visible' }); + }); + + test('isVisible inside a role=button', async ({ browser }) => { + await browser.goto(content(`
a button
`)); + const span = browser.locator('span'); + expect(await span.isVisible()).toBe(false); + expect(await span.isHidden()).toBe(true); + await expect(span).not.toBeVisible(); + await expect(span).toBeHidden(); + await span.waitFor({ state: 'hidden' }); + await browser.locator('[role=button]').waitFor({ state: 'visible' }); + }); + + test('isVisible during navigation should not throw', async ({ browser }) => { + for (let i = 0; i < 20; i++) { + await browser.goto(content(` + + `)).catch(() => {}); + expect(await browser.locator('div').isVisible()).toBe(false); + } + }); +}); diff --git a/packages/web/tests/parity/tests/locator-list.e2e.ts b/packages/web/tests/parity/tests/locator-list.e2e.ts new file mode 100644 index 0000000000..541e71340b --- /dev/null +++ b/packages/web/tests/parity/tests/locator-list.e2e.ts @@ -0,0 +1,19 @@ +/** + * Adapted from microsoft/playwright tests/page/locator-list.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `div >> p` is the CSS `div p`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +test.describe('locator list', { requires: ['browser'] }, () => { + test('locator.all should work', async ({ browser }) => { + await browser.goto(content(`

A

B

C

`)); + const texts = []; + for (const p of await browser.locator('div p').all()) + texts.push(await p.textContent()); + expect(texts).toEqual(['A', 'B', 'C']); + }); +}); diff --git a/packages/web/tests/parity/tests/locator-misc-2.e2e.ts b/packages/web/tests/parity/tests/locator-misc-2.e2e.ts new file mode 100644 index 0000000000..3b4be91943 --- /dev/null +++ b/packages/web/tests/parity/tests/locator-misc-2.e2e.ts @@ -0,0 +1,135 @@ +/** + * Adapted from microsoft/playwright tests/page/locator-misc-2.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `scrollIntoViewIfNeeded` is + * `scrollIntoView`, an element's own `evaluate` a page `evaluate`. + * + * Not ported: + * - should select textarea: e2e has no selectText. + * - should type: deprecated `locator.type`; its replacement, pressSequentially, is ported. + * - should take screenshot: compares with Playwright's own golden image. + * - should combine visible with other selectors: `>> visible=true` selector chains. + * - should support filter(visible): e2e filter has no visible option. + * - should support visible(): e2e locators have no visible(). + * - Locator.locator() and FrameLocator.locator() should accept locator: e2e locators have no locator(locator). + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, e2eGap } from './helpers.ts'; + +test.describe('locator misc 2', { requires: ['browser'] }, () => { + test('should press @smoke', async ({ browser }) => { + await browser.goto(content(``)); + await browser.locator('input').press('h'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('h'); + }); + + test('should scroll into view', async ({ browser }) => { + await browser.goto('/offscreenbuttons.html'); + const overflow = '(id) => document.getElementById(id).getBoundingClientRect().right - window.innerWidth'; + for (let i = 0; i < 11; ++i) { + const before = await browser.evaluate(overflow, `btn${i}`); + expect(before).toBe(10 * i); + await browser.locator(`#btn${i}`).scrollIntoView(); + const after = await browser.evaluate(overflow, `btn${i}`); + expect(after <= 0).toBe(true); + await browser.evaluate('() => window.scrollTo(0, 0)'); + } + }); + + test('should scroll zero-sized element into view', async ({ browser }) => { + await browser.goto(content(` + +
+

SCROLL DOWN

+
+
+ + `)); + expect(await browser.locator('#lazyload').boundingBox()).toEqual({ x: 0, y: 2020, width: 1280, height: 0 }); + await browser.locator('#lazyload').scrollIntoView(); + await expect(browser.locator('#lazyload')).toHaveText('LAZY LOADED CONTENT'); + expect(await browser.locator('#lazyload').boundingBox()).toEqual({ x: 0, y: 720, width: 1280, height: 20 }); + }); + + test('should pressSequentially', async ({ browser }) => { + await browser.goto(content(``)); + await browser.locator('input').pressSequentially('hello'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('hello'); + }); + + test('should return bounding box', async ({ browser }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid.html'); + const element = browser.locator('.box:nth-of-type(13)'); + const box = await element.boundingBox(); + expect(box).toEqual({ x: 100, y: 50, width: 50, height: 50 }); + }); + + test('should waitFor', async ({ browser }) => { + await browser.goto(content(`
`)); + const locator = browser.locator('span'); + const promise = locator.waitFor(); + await browser.evaluate("() => { document.querySelector('div').innerHTML = 'target'; }"); + await promise; + await expect(locator).toHaveText('target'); + }); + + test('should waitFor hidden', async ({ browser }) => { + await browser.goto(content(`
target
`)); + const locator = browser.locator('span'); + const promise = locator.waitFor({ state: 'hidden' }); + await browser.evaluate("() => { document.querySelector('div').innerHTML = ''; }"); + await promise; + }); + + test('locator.count should work with deleted Map in main world', async ({ browser }) => { + e2eGap('`browser.evaluate` and the in-page readers run in the main world, so a page that deletes `Map` breaks them; Playwright runs its own in a utility world'); + await browser.goto('/empty.html'); + await browser.evaluate('() => { window.Map = 1; }'); + await browser.locator('#searchResultTableDiv .x-grid3-row').count(); + await expect(browser.locator('#searchResultTableDiv .x-grid3-row')).toHaveCount(0); + }); + + test('should fill programmatically enabled textarea', async ({ browser }) => { + await browser.goto(content(` + +
+ +
+ + `)); + await browser.locator('button').click(); + await browser.locator('#text').fill('Hello'); + await expect(browser.locator('#text')).toHaveValue('Hello'); + }); + + test('press should throw on unknown keys', async ({ screen, browser }) => { + await browser.goto(content(``)); + const locator = screen.getByRole('textbox'); + for (const key of ['NotARealKey', 'ё', '😊']) { + const error = await locator.press(key).catch((e: unknown) => e); + expect(error).toEqual(expect.any(Error)); + expect((error as Error).message).toContain(key); + } + }); +}); diff --git a/packages/web/tests/parity/tests/locator-query.e2e.ts b/packages/web/tests/parity/tests/locator-query.e2e.ts new file mode 100644 index 0000000000..504849ed01 --- /dev/null +++ b/packages/web/tests/parity/tests/locator-query.e2e.ts @@ -0,0 +1,186 @@ +/** + * Adapted from microsoft/playwright tests/page/locator-query.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `locator(css, { hasText, has })` is + * a locator `filter`, `div >> p` the CSS `div p`, a nested `.locator(css)` + * the matching semantic query scoped to the outer locator, `toHaveClass` the + * browser matcher, and `evaluate(e => e.outerHTML)` a text read. + * + * Not ported: + * - should throw on capture w/ nth(): Playwright `*css=` capture selector. + * - should throw on due to strictness 2: `locator.evaluate`. + * - should support locator.and: e2e locators have no and(). + * - should support locator.locator with and/or: e2e locators have no locator(locator) or and(). + * - should support locator.within: e2e locators have no within(). + * - should keep the capture when removing a common frame prefix: `*css=` captures and `contentFrame()`. + * - count() should not throw during navigation: custom selector engines. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +const sections = ` +
+

A

+

A

A

+

A

A

A

+
`; + +test.describe('locator query', { requires: ['browser'] }, () => { + test('should respect first() and last() @smoke', async ({ browser }) => { + await browser.goto(content(sections)); + expect(await browser.locator('div p').count()).toBe(6); + expect(await browser.locator('div').first().getByText('A').count()).toBe(1); + expect(await browser.locator('div').last().getByText('A').count()).toBe(3); + }); + + test('should respect nth()', async ({ browser }) => { + await browser.goto(content(sections)); + expect(await browser.locator('div p').nth(0).count()).toBe(1); + expect(await browser.locator('div').nth(1).getByText('A').count()).toBe(2); + expect(await browser.locator('div').nth(2).getByText('A').count()).toBe(3); + }); + + test('should throw on due to strictness', async ({ browser }) => { + await browser.goto(content(`
A
B
`)); + const error = await browser.locator('div').isVisible().catch((e: unknown) => e); + expect(error).toEqual(expect.any(Error)); + }); + + test('should filter by text', async ({ browser }) => { + await browser.goto(content(`
Foobar
Bar
`)); + await expect(browser.locator('div').filter({ hasText: 'Foo' })).toHaveText('Foobar'); + }); + + test('should filter by text 2', async ({ browser }) => { + await browser.goto(content(`
foo hello world bar
`)); + await expect(browser.locator('div').filter({ hasText: 'hello world' })).toHaveText('foo hello world bar'); + }); + + test('should filter by regex', async ({ browser }) => { + await browser.goto(content(`
Foobar
Bar
`)); + await expect(browser.locator('div').filter({ hasText: /Foo.*/ })).toHaveText('Foobar'); + }); + + test('should filter by text with quotes', async ({ browser }) => { + await browser.goto(content(`
Hello "world"
Hello world
`)); + await expect(browser.locator('div').filter({ hasText: 'Hello "world"' })).toHaveText('Hello "world"'); + }); + + test('should filter by regex with quotes', async ({ browser }) => { + await browser.goto(content(`
Hello "world"
Hello world
`)); + await expect(browser.locator('div').filter({ hasText: /Hello "world"/ })).toHaveText('Hello "world"'); + }); + + test('should filter by regex with a single quote', async ({ screen, browser }) => { + await browser.goto(content(``)); + for (const pattern of [/let's/i, /let's/i, /'s/i, /'s/i, /let['abc]s/i, /let's let's/i, /let's let's/i]) { + await expect.soft(browser.locator('button').filter({ hasText: pattern }).getByText('hello')).toHaveText('hello'); + await expect.soft(screen.getByRole('button', { name: pattern }).getByText('hello')).toHaveText('hello'); + } + await expect.soft(browser.locator('button').filter({ hasText: /let\\'s/i })).not.toBeVisible(); + await expect.soft(screen.getByRole('button', { name: /let\\'s/i })).not.toBeVisible(); + + await browser.goto(content(``)); + await expect.soft(browser.locator('button').filter({ hasText: /let's/i })).not.toBeVisible(); + await expect.soft(screen.getByRole('button', { name: /let's/i })).not.toBeVisible(); + for (const pattern of [/let\\'s/i, /let\\'s/i, /let\\'s let\\'s/i, /let\\'s let\\'s/i]) { + await expect.soft(browser.locator('button').filter({ hasText: pattern }).getByText('hello')).toHaveText('hello'); + await expect.soft(screen.getByRole('button', { name: pattern }).getByText('hello')).toHaveText('hello'); + } + + await browser.goto(content(``)); + await expect.soft(browser.locator('button').filter({ hasText: /let's/iu })).toHaveText(`let's hello`); + await expect.soft(screen.getByRole('button', { name: /let's/iu })).toHaveText(`let's hello`); + }); + + test('should filter by regex and regexp flags', async ({ browser }) => { + await browser.goto(content(`
Hello "world"
Hello world
`)); + await expect(browser.locator('div').filter({ hasText: /hElLo "world"/i })).toHaveText('Hello "world"'); + }); + + test('should filter by case-insensitive regex in a child', async ({ browser }) => { + await browser.goto(content(`
Title Text
`)); + await expect(browser.locator('div').filter({ hasText: /^title text$/i })).toHaveText('Title Text'); + }); + + test('should filter by case-insensitive regex in multiple children', async ({ browser }) => { + await browser.goto(content(`
Title

Text

`)); + await expect(browser).toHaveClass(browser.locator('div').filter({ hasText: /^title text$/i }), 'test'); + }); + + test('should filter by regex with special symbols', async ({ browser }) => { + await browser.goto(content(`
First/"and"

Second\\

`)); + await expect(browser).toHaveClass(browser.locator('div').filter({ hasText: /^first\/".*"second\\$/si }), 'test'); + }); + + test('should support has:locator', async ({ screen, browser }) => { + await browser.goto(content(`
hello
world
`)); + await expect(browser.locator('div').filter({ has: screen.getByText('world', { exact: false }) })).toHaveCount(1); + expect(await browser.locator('div').filter({ has: screen.getByText('world', { exact: false }) }).textContent()).toBe('world'); + await expect(browser.locator('div').filter({ has: screen.getByText('hello') })).toHaveCount(1); + expect(await browser.locator('div').filter({ has: screen.getByText('hello') }).textContent()).toBe('hello'); + await expect(browser.locator('div').filter({ has: browser.locator('span') })).toHaveCount(2); + await expect(browser.locator('div').filter({ has: browser.locator('span').filter({ hasText: 'wor' }) })).toHaveCount(1); + expect(await browser.locator('div').filter({ has: browser.locator('span').filter({ hasText: 'wor' }) }).textContent()).toBe('world'); + await expect(browser.locator('div').filter({ has: browser.locator('span'), hasText: 'wor' })).toHaveCount(1); + }); + + test('should support locator.filter', async ({ browser }) => { + await browser.goto(content(`
hello
world
`)); + await expect(browser.locator('div').filter({ hasText: 'hello' })).toHaveCount(1); + await expect(browser.locator('div').filter({ hasText: 'hello' }).filter({ hasText: 'hello' })).toHaveCount(1); + await expect(browser.locator('div').filter({ hasText: 'hello' }).filter({ hasText: 'world' })).toHaveCount(0); + await expect(browser.locator('section').filter({ hasText: 'hello' }).filter({ hasText: 'world' })).toHaveCount(1); + await expect(browser.locator('div').filter({ hasText: 'hello' }).getByText('hello')).toHaveCount(1); + await expect(browser.locator('div').filter({ has: browser.locator('span').filter({ hasText: 'world' }) })).toHaveCount(1); + await expect(browser.locator('div').filter({ has: browser.locator('span') })).toHaveCount(2); + await expect(browser.locator('div').filter({ has: browser.locator('span'), hasText: 'world' })).toHaveCount(1); + await expect(browser.locator('div').filter({ hasNot: browser.locator('span').filter({ hasText: 'world' }) })).toHaveCount(1); + await expect(browser.locator('div').filter({ hasNot: browser.locator('section') })).toHaveCount(2); + await expect(browser.locator('div').filter({ hasNot: browser.locator('span') })).toHaveCount(0); + await expect(browser.locator('div').filter({ hasNotText: 'hello' })).toHaveCount(1); + await expect(browser.locator('div').filter({ hasNotText: 'foo' })).toHaveCount(2); + }); + + test('should support locator.or', async ({ browser }) => { + await browser.goto(content(`
hello
world`)); + await expect(browser.locator('div').or(browser.locator('span'))).toHaveCount(2); + await expect(browser.locator('div').or(browser.locator('span'))).toHaveText(['hello', 'world']); + await expect(browser.locator('span').or(browser.locator('article')).or(browser.locator('div'))).toHaveText(['hello', 'world']); + await expect(browser.locator('article').or(browser.locator('something'))).toHaveCount(0); + await expect(browser.locator('article').or(browser.locator('div'))).toHaveText('hello'); + await expect(browser.locator('article').or(browser.locator('span'))).toHaveText('world'); + await expect(browser.locator('div').or(browser.locator('article'))).toHaveText('hello'); + await expect(browser.locator('span').or(browser.locator('article'))).toHaveText('world'); + }); + + test('should allow some, but not all nested frameLocators', async ({ browser }) => { + await browser.goto(content(`hello`)); + const frame = browser.frameLocator('iframe'); + await expect(frame.locator('span').or(frame.locator('article'))).toHaveText('world'); + await expect(frame.locator('article').or(frame.locator('span'))).toHaveText('world'); + const error = await expect(frame.locator('div').or(browser.frameLocator('#iframe').locator('span'))).toHaveText('world').catch((e: unknown) => e); + expect(error).toEqual(expect.any(Error)); + }); + + test('should enforce same frame for has/leftOf/rightOf/above/below/near', async ({ browser }) => { + await browser.goto('/frames/two-frames.html'); + const child = browser.frameLocator('iframe[name=uno]'); + let error: unknown; + try { + await browser.locator('div').filter({ has: child.locator('span') }).count(); + } catch (e) { + error = e; + } + expect(error).toEqual(expect.any(Error)); + }); + + test('alias methods coverage', async ({ screen, browser }) => { + await browser.goto(content(`
`)); + await expect(browser.locator('button')).toHaveCount(1); + await expect(browser.locator('div').getByRole('button')).toHaveCount(1); + await expect(screen.getByRole('button')).toHaveCount(1); + }); +}); diff --git a/packages/web/tests/parity/tests/page-check.e2e.ts b/packages/web/tests/parity/tests/page-check.e2e.ts new file mode 100644 index 0000000000..9ad9d8abda --- /dev/null +++ b/packages/web/tests/parity/tests/page-check.e2e.ts @@ -0,0 +1,119 @@ +/** + * Adapted from microsoft/playwright tests/page/page-check.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `page.check(selector)` is a locator check. + */ + +/* + * Not ported: + * - should check the label with position: `check` takes no `position`. + * - trial run should not check: no `trial` option. + * - trial run should not uncheck: no `trial` option. + * - should check the box using setChecked: no `setChecked`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, e2eGap } from './helpers.ts'; + +test.describe('page check', { requires: ['browser'] }, () => { + test('should check the box', async ({ browser }) => { + await browser.goto(content("")); + await browser.locator('input').check(); + expect(await browser.evaluate('() => window.checkbox.checked')).toBe(true); + }); + + test('should not check the checked box', async ({ browser }) => { + await browser.goto(content("")); + await browser.locator('input').check(); + expect(await browser.evaluate('() => window.checkbox.checked')).toBe(true); + }); + + test('should uncheck the box', async ({ browser }) => { + await browser.goto(content("")); + await browser.locator('input').uncheck(); + expect(await browser.evaluate('() => window.checkbox.checked')).toBe(false); + }); + + test('should not uncheck the unchecked box', async ({ browser }) => { + await browser.goto(content("")); + await browser.locator('input').uncheck(); + expect(await browser.evaluate('() => window.checkbox.checked')).toBe(false); + }); + + test('should check radio', async ({ browser }) => { + await browser.goto(content(` + one + two + three`)); + await browser.locator('#two').check(); + expect(await browser.evaluate('() => window.two.checked')).toBe(true); + }); + + test('should check radio by aria role', async ({ browser }) => { + await browser.goto(content(` + `)); + await browser.locator('div').check(); + expect(await browser.evaluate("() => window.checkbox.getAttribute('aria-checked')")).toBe('true'); + }); + + test('should uncheck radio by aria role', async ({ browser }) => { + e2eGap('`uncheck` refuses any radio, a `role=radio` one included, where Playwright clicks it'); + await browser.goto(content(` + `)); + await browser.locator('div').uncheck(); + expect(await browser.evaluate("() => window.checkbox.getAttribute('aria-checked')")).toBe('false'); + }); + + test('should check the box by aria role', async ({ browser }) => { + for (const role of ['checkbox', 'menuitemcheckbox', 'option', 'radio', 'switch', 'menuitemradio', 'treeitem']) { + await browser.goto(content(`
CHECKBOX
+ `)); + await browser.locator('div').check(); + expect(await browser.evaluate("() => window.checkbox.getAttribute('aria-checked')")).toBe('true'); + } + }); + + test('should uncheck the box by aria role', async ({ browser }) => { + e2eGap('`uncheck` refuses any radio, a `role=menuitemradio` one included, where Playwright clicks it'); + for (const role of ['checkbox', 'menuitemcheckbox', 'option', 'radio', 'switch', 'menuitemradio', 'treeitem']) { + await browser.goto(content(`
CHECKBOX
+ `)); + await browser.locator('div').uncheck(); + expect(await browser.evaluate("() => window.checkbox.getAttribute('aria-checked')")).toBe('false'); + } + }); + + test('should throw when not a checkbox', async ({ browser }) => { + await browser.goto(content('
Check me
')); + const error = await browser.locator('div').check().catch((caught: Error) => caught); + expect((error as Error).message).toContain('Not a checkbox or radio button'); + }); + + test('should throw when not a checkbox 2', async ({ browser }) => { + await browser.goto(content('
Check me
')); + const error = await browser.locator('div').check().catch((caught: Error) => caught); + expect((error as Error).message).toContain('Not a checkbox or radio button'); + }); + + test('should check the box inside a button', async ({ browser }) => { + await browser.goto(content("
")); + await browser.locator('input').check(); + expect(await browser.evaluate("() => document.querySelector('input').checked")).toBe(true); + expect(await browser.locator('input').isChecked()).toBe(true); + }); + + test('should throw when trying to uncheck radio button', async ({ browser }) => { + await browser.goto(content("")); + const error = await browser.locator('#radio').uncheck().catch((caught: Error) => caught); + expect((error as Error).message).toContain('uncheck cannot clear a radio button'); + }); +}); diff --git a/packages/web/tests/parity/tests/page-click-scroll.e2e.ts b/packages/web/tests/parity/tests/page-click-scroll.e2e.ts new file mode 100644 index 0000000000..affb3b321a --- /dev/null +++ b/packages/web/tests/parity/tests/page-click-scroll.e2e.ts @@ -0,0 +1,116 @@ +/** + * Adapted from microsoft/playwright tests/page/page-click-scroll.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `page.click(selector)` is a locator + * tap, a `text=` selector a substring `getByText`. + * + * Not ported: + * - should not crash when force-clicking hidden input: e2e tap has no force option. + * - should not scroll the page when scroll is "none": e2e tap has no scroll option. + * - should click in-viewport element when scroll is "none": same. + * - should not scroll nested container when scroll is "none": same. + * - should not scroll on hover when scroll is "none": same, and a `>>` chain. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { browserName, content, CROSS, e2eGap } from './helpers.ts'; + +test.describe('page click scroll', { requires: ['browser'] }, () => { + test('should not hit scroll bar', async ({ screen, browser }) => { + await browser.goto(content(` + +
+ + + + + + + +
+ `)); + await screen.getByText('Story', { exact: false }).tap({ timeout: 2000 }); + }); + + test('should scroll into view display:contents', async ({ screen, browser }) => { + await browser.goto(content(` +
filler
+
+ Example text, and button here: + +
+ `)); + await screen.getByText('click me', { exact: false }).tap({ timeout: 5000 }); + expect(await browser.evaluate('window._clicked')).toBe(true); + }); + + test('should scroll into view display:contents with a child', async ({ screen, browser }) => { + await browser.goto(content(` +
filler
+ Example text, and button here: + + `)); + await screen.getByText('click me', { exact: false }).tap({ timeout: 5000 }); + expect(await browser.evaluate('window._clicked')).toBe(true); + }); + + test('should scroll into view display:contents with position', async ({ screen, browser }) => { + e2eGap('a tap at a position needs a box, which a `display: contents` element has none of on Firefox', { browser: 'firefox' }); + test.skip(browserName === 'chromium', 'Playwright fixme: DOM.getBoxModel does not work for display:contents'); + await browser.goto(content(` +
filler
+
+ Example text, and button here: + +
+ `)); + await screen.getByText('click me', { exact: false }).tap({ position: { x: 5, y: 5 }, timeout: 5000 }); + expect(await browser.evaluate('window._clicked')).toBe(true); + }); + + test('should scroll into view span element', async ({ browser }) => { + await browser.goto(content(` +
+ foo + `)); + await browser.locator('#small').scrollIntoView(); + expect(await browser.evaluate('() => window.scrollY')).toBeGreaterThan(9000); + }); + + test('should scroll into view element in iframe', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(content(` +
+ + `)); + await browser.frameLocator('iframe').getByRole('button').tap({ timeout: 5000 }); + }); + + test('should scroll instantly on retry when scroll-behavior is smooth', async ({ browser }) => { + await browser.goto(content(` + + +
+ +
+ + `)); + await browser.locator('button').tap(); + expect(await browser.evaluate('window.clicked')).toBe(true); + const scrolls = await browser.evaluate("() => window['scrolls']"); + expect(scrolls.length).toBeLessThanOrEqual(2); + }); +}); diff --git a/packages/web/tests/parity/tests/page-click.e2e.ts b/packages/web/tests/parity/tests/page-click.e2e.ts new file mode 100644 index 0000000000..4ce1f0bbcb --- /dev/null +++ b/packages/web/tests/parity/tests/page-click.e2e.ts @@ -0,0 +1,559 @@ +/** + * Adapted from microsoft/playwright tests/page/page-click.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `page.click(selector)` is a locator tap. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, CROSS } from './helpers.ts'; + +/** Two animation frames and a task, Playwright's `rafraf`, so a pending tap has had its chance. */ +const giveItAChanceToClick = '() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(resolve, 0))))'; + +test.describe('page click', { requires: ['browser'] }, () => { + test('should click the button', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.locator('button').tap(); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should click svg', async ({ browser }) => { + await browser.goto(content(` + + + + `)); + await browser.locator('circle').tap(); + expect(await browser.evaluate('__CLICKED')).toBe(42); + }); + + test('should click the button if window.Node is removed', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate('() => { delete window.Node; }'); + await browser.locator('button').tap(); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should click on a span with an inline element inside', async ({ browser }) => { + await browser.goto(content(` + + + `)); + await browser.locator('span').tap(); + expect(await browser.evaluate('CLICKED')).toBe(42); + }); + + for (const [name, style] of [ + ['aligned', ''], + ['half-aligned', 'margin-left: 20.5px; margin-top: 11.5px;'], + ['unaligned v1', 'margin-left: 20.23px; margin-top: 11.65px;'], + ['unaligned v2', 'margin-left: 20.68px; margin-top: 11.13px;'], + ['unaligned v3', 'margin-left: 20.68px; margin-top: 11.52px;'], + ['unaligned v4', 'margin-left: 20.15px; margin-top: 11.24px;'], + ] as const) { + test(`should click the ${name} 1x1 div`, async ({ browser }) => { + await browser.goto(content(`
`)); + await browser.locator('div').tap(); + expect(await browser.evaluate('window.__clicked')).toBe(true); + }); + } + + test('should click the button after navigation', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.locator('button').tap(); + await browser.goto('/input/button.html'); + await browser.locator('button').tap(); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should click the button after a cross origin navigation', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.locator('button').tap(); + await browser.goto(`${CROSS}/input/button.html`); + await browser.locator('button').tap(); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should click when one of inline box children is outside of viewport', async ({ browser }) => { + await browser.goto(content(` + + woofdoggo + `)); + await browser.locator('span').tap(); + expect(await browser.evaluate('CLICKED')).toBe(42); + }); + + test('should click offscreen buttons', async ({ browser }) => { + await browser.goto('/offscreenbuttons.html'); + await browser.evaluate('() => { window.messages = []; console.log = (text) => window.messages.push(text); }'); + for (let index = 0; index < 11; ++index) { + await browser.evaluate('() => window.scrollTo(0, 0)'); + await browser.locator(`#btn${index}`).tap(); + } + expect(await browser.evaluate('messages')).toEqual(Array.from({ length: 11 }, (_, index) => `button #${index} clicked`)); + }); + + test('should waitFor display:none to be gone', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate("() => { document.querySelector('button').style.display = 'none'; }"); + let done = false; + const clicked = browser.locator('button').tap({ timeout: 10_000 }).then(() => (done = true)); + await browser.evaluate(giveItAChanceToClick); + expect(await browser.evaluate('result')).toBe('Was not clicked'); + expect(done).toBe(false); + await browser.evaluate("() => { document.querySelector('button').style.display = 'block'; }"); + await clicked; + expect(done).toBe(true); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should waitFor visibility:hidden to be gone', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate("() => { document.querySelector('button').style.visibility = 'hidden'; }"); + let done = false; + const clicked = browser.locator('button').tap({ timeout: 10_000 }).then(() => (done = true)); + await browser.evaluate(giveItAChanceToClick); + expect(await browser.evaluate('result')).toBe('Was not clicked'); + expect(done).toBe(false); + await browser.evaluate("() => { document.querySelector('button').style.visibility = 'visible'; }"); + await clicked; + expect(done).toBe(true); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should waitFor visible when parent is hidden', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate("() => { document.querySelector('button').parentElement.style.display = 'none'; }"); + let done = false; + const clicked = browser.locator('button').tap({ timeout: 10_000 }).then(() => (done = true)); + await browser.evaluate(giveItAChanceToClick); + expect(done).toBe(false); + await browser.evaluate("() => { document.querySelector('button').parentElement.style.display = 'block'; }"); + await clicked; + expect(done).toBe(true); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should click wrapped links', async ({ browser }) => { + await browser.goto('/wrappedlink.html'); + await browser.locator('a').tap(); + expect(await browser.evaluate('__clicked')).toBe(true); + }); + + test('should click on checkbox input and toggle', async ({ browser }) => { + await browser.goto('/input/checkbox.html'); + expect(await browser.evaluate('() => window.result.check')).toBe(null); + await browser.locator('input#agree').tap(); + expect(await browser.evaluate('() => window.result.check')).toBe(true); + expect(await browser.evaluate('() => window.result.events')).toEqual(['mouseover', 'mouseenter', 'mousemove', 'mousedown', 'mouseup', 'click', 'input', 'change']); + await browser.locator('input#agree').tap(); + expect(await browser.evaluate('() => window.result.check')).toBe(false); + }); + + test('should click on checkbox label and toggle', async ({ browser }) => { + await browser.goto('/input/checkbox.html'); + expect(await browser.evaluate('() => window.result.check')).toBe(null); + await browser.locator('label[for="agree"]').tap(); + expect(await browser.evaluate('() => window.result.check')).toBe(true); + expect(await browser.evaluate('() => window.result.events')).toEqual(['click', 'input', 'change']); + await browser.locator('label[for="agree"]').tap(); + expect(await browser.evaluate('() => window.result.check')).toBe(false); + }); + + test('should scroll and click the button', async ({ browser }) => { + await browser.goto('/input/scrollable.html'); + await browser.locator('#button-5').tap(); + expect(await browser.evaluate("() => document.querySelector('#button-5').textContent")).toBe('clicked'); + await browser.locator('#button-80').tap(); + expect(await browser.evaluate("() => document.querySelector('#button-80').textContent")).toBe('clicked'); + }); + + test('should scroll and click the button with smooth scroll behavior', async ({ browser }) => { + await browser.goto('/input/scrollable.html'); + await browser.evaluate("() => { const style = document.createElement('style'); style.textContent = 'html { scroll-behavior: smooth; }'; document.head.append(style); }"); + for (let index = 0; index < 5; index++) { + await browser.locator('#button-80').tap(); + expect(await browser.evaluate("() => document.querySelector('#button-80').textContent")).toBe('clicked'); + await browser.locator('#button-20').tap(); + expect(await browser.evaluate("() => document.querySelector('#button-20').textContent")).toBe('clicked'); + } + }); + + test('should double click the button', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate("() => { window.double = false; document.querySelector('button').addEventListener('dblclick', () => { window.double = true; }); }"); + await browser.locator('button').doubleTap(); + expect(await browser.evaluate('double')).toBe(true); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should click a partially obscured button', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate("() => { const button = document.querySelector('button'); button.textContent = 'Some really long text that will go offscreen'; button.style.position = 'absolute'; button.style.left = '368px'; }"); + await browser.locator('button').tap(); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should click a rotated button', async ({ browser }) => { + await browser.goto('/input/rotatedButton.html'); + await browser.locator('button').tap(); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should fire contextmenu event on right click', async ({ browser }) => { + await browser.goto('/input/scrollable.html'); + await browser.locator('#button-8').secondaryTap(); + expect(await browser.evaluate("() => document.querySelector('#button-8').textContent")).toBe('context menu'); + }); + + test('should click links which cause navigation', async ({ browser }) => { + await browser.goto(content('empty.html')); + await browser.locator('a').tap(); + await browser.waitForURL('/empty.html'); + }); + + test('should click the button inside an iframe', async ({ browser }) => { + await browser.goto(content('
spacer
')); + const frame = browser.frameLocator('iframe'); + await frame.locator('button').tap(); + expect(await browser.evaluate("() => document.querySelector('iframe').contentWindow.result")).toBe('Clicked'); + }); + + test('should click the button behind sticky header', async ({ browser }) => { + await browser.setViewport({ width: 500, height: 240 }); + await browser.goto(content(` + +
+
    +
  1. hi1
  2. hi2
  3. hi3
  4. hi4
  5. hi5
  6. hi6
  7. hi7
  8. hi8
  9. +
  10. hi9
  11. +
  12. hi10
  13. hi11
  14. hi12
  15. hi13
  16. hi14
  17. +
+ `)); + await browser.evaluate("() => document.querySelector('#li14').scrollIntoView()"); + await browser.locator('#target').tap(); + expect(await browser.evaluate('() => window.__clicked')).toBe(true); + }); + + test('should click the button behind position:absolute header', async ({ browser }) => { + await browser.setViewport({ width: 500, height: 240 }); + await browser.goto(content(` + +
    +
  1. hi1
  2. hi2
  3. hi3
  4. hi4
  5. hi5
  6. hi6
  7. hi7
  8. hi8
  9. +
  10. hi9
  11. +
  12. hi10
  13. hi11
  14. hi12
  15. hi13
  16. hi14
  17. +
+
Overlay
+ `)); + await browser.evaluate("() => { const target = document.querySelector('#target'); document.querySelector('ol').scrollTo({ top: target.offsetTop, behavior: 'instant' }); }"); + await browser.locator('#target').tap(); + expect(await browser.evaluate('() => window.__clicked')).toBe(true); + }); + + test('should wait for stable position', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate(`() => { + const button = document.querySelector('button'); + button.style.transition = 'margin 500ms linear 0s'; + button.style.marginLeft = '200px'; + button.style.borderWidth = '0'; + button.style.width = '200px'; + button.style.height = '20px'; + button.style.display = 'block'; + document.body.style.margin = '0'; + }`); + await browser.evaluate(giveItAChanceToClick); + await browser.locator('button').tap(); + expect(await browser.evaluate('result')).toBe('Clicked'); + expect(await browser.evaluate('pageX')).toBe(300); + expect(await browser.evaluate('pageY')).toBe(10); + }); + + test('should wait for becoming hit target', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate(`() => { + const button = document.querySelector('button'); + button.style.borderWidth = '0'; + button.style.width = '200px'; + button.style.height = '20px'; + document.body.style.margin = '0'; + document.body.style.position = 'relative'; + const flyOver = document.createElement('div'); + flyOver.className = 'flyover'; + flyOver.style.position = 'absolute'; + flyOver.style.width = '400px'; + flyOver.style.height = '20px'; + flyOver.style.left = '-200px'; + flyOver.style.top = '0'; + flyOver.style.background = 'red'; + document.body.appendChild(flyOver); + }`); + let clicked = false; + const tap = browser.locator('button').tap({ timeout: 10_000 }).then(() => (clicked = true)); + expect(clicked).toBe(false); + await browser.evaluate("() => { document.querySelector('.flyover').style.left = '0'; }"); + await browser.evaluate(giveItAChanceToClick); + expect(clicked).toBe(false); + await browser.evaluate("() => { document.querySelector('.flyover').style.left = '200px'; }"); + await tap; + expect(clicked).toBe(true); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + for (const [name, html, enable] of [ + ['button', '', "document.querySelector('button').removeAttribute('disabled')"], + ['input', '', "document.querySelector('input').removeAttribute('disabled')"], + ] as const) { + test(`should wait for ${name} to be enabled`, async ({ browser, screen }) => { + await browser.goto(content(html)); + let done = false; + const tap = (name === 'button' ? screen.getByText('Click target') : browser.locator(name)).tap({ timeout: 10_000 }).then(() => (done = true)); + await browser.evaluate(giveItAChanceToClick); + expect(await browser.evaluate('() => window.__CLICKED')).toBeUndefined(); + expect(done).toBe(false); + await browser.evaluate(`() => { ${enable}; }`); + await tap; + expect(await browser.evaluate('__CLICKED')).toBe(true); + }); + } + + test('should wait for select to be enabled', async ({ browser }) => { + await browser.goto(content(` + + + `)); + let done = false; + const tap = browser.locator('select').tap({ timeout: 10_000 }).then(() => (done = true)); + await browser.evaluate(giveItAChanceToClick); + expect(await browser.evaluate('() => window.__CLICKED')).toBeUndefined(); + expect(done).toBe(false); + await browser.evaluate("() => { document.querySelector('select').removeAttribute('disabled'); }"); + await tap; + expect(await browser.evaluate('__CLICKED')).toBe(true); + }); + + test('should click disabled div', async ({ browser, screen }) => { + await browser.goto(content('
Click target
')); + await screen.getByText('Click target').tap(); + expect(await browser.evaluate('__CLICKED')).toBe(true); + }); + + test('should wait for BUTTON to be clickable when it has pointer-events:none', async ({ browser, screen }) => { + await browser.goto(content('')); + let done = false; + const tap = screen.getByText('Click target').tap({ timeout: 10_000 }).then(() => (done = true)); + await browser.evaluate(giveItAChanceToClick); + expect(await browser.evaluate('() => window.__CLICKED')).toBeUndefined(); + expect(done).toBe(false); + await browser.evaluate("() => { document.querySelector('button').style.removeProperty('pointer-events'); }"); + await tap; + expect(await browser.evaluate('__CLICKED')).toBe(true); + }); + + test('should update modifiers correctly', async ({ browser }) => { + await browser.goto('/input/button.html'); + const button = browser.locator('button'); + await button.tap({ modifiers: ['Shift'] }); + expect(await browser.evaluate('shiftKey')).toBe(true); + await button.tap(); + expect(await browser.evaluate('shiftKey')).toBe(false); + await browser.keyboard.down('Shift'); + await button.tap(); + expect(await browser.evaluate('shiftKey')).toBe(true); + await browser.keyboard.up('Shift'); + await button.tap(); + expect(await browser.evaluate('shiftKey')).toBe(false); + }); + + test('should click an offscreen element when scroll-behavior is smooth', async ({ browser }) => { + await browser.goto(content(` +
+ +
+ `)); + await browser.locator('button').tap(); + expect(await browser.evaluate('window.clicked')).toBe(true); + }); + + test('should click the button when window.innerWidth is corrupted', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate("() => { Object.defineProperty(window, 'innerWidth', { value: 0 }); }"); + await browser.locator('button').tap(); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should click zero-sized input by label', async ({ browser, screen }) => { + await browser.goto(content(` + + `)); + await screen.getByText('Click me').tap(); + expect(await browser.evaluate('window.__clicked')).toBe(true); + }); + + test('should climb dom for inner label with pointer-events:none', async ({ browser, screen }) => { + await browser.goto(content('')); + await screen.getByText('Click target').tap(); + expect(await browser.evaluate('__CLICKED')).toBe(true); + }); + + test('should climb up to [role=button]', async ({ browser, screen }) => { + await browser.goto(content('
Click target
')); + await screen.getByText('Click target').tap(); + expect(await browser.evaluate('__CLICKED')).toBe(true); + }); + + test('should climb up to a anchor', async ({ browser }) => { + await browser.goto(content('
Inner
')); + await browser.locator('#inner').tap(); + expect(await browser.evaluate('__CLICKED')).toBe(true); + }); + + test('should climb up to a [role=link]', async ({ browser }) => { + await browser.goto(content('
Inner
')); + await browser.locator('#inner').tap(); + expect(await browser.evaluate('__CLICKED')).toBe(true); + }); + + test('should click in an iframe with border', async ({ browser }) => { + await browser.goto(content(` + + + `)); + await browser.frameLocator('iframe').locator('div').tap(); + expect(await browser.evaluate('window._clicked')).toBe(true); + }); + + test('should click in a transformed iframe', async ({ browser }) => { + await browser.goto(content(` + + + `)); + await browser.frameLocator('iframe').locator('div').tap(); + expect(await browser.evaluate('window._clicked')).toBe(true); + }); + + test('should click in a nested transformed iframe', async ({ browser }) => { + await browser.goto(content(` + + + `)); + await browser.frameLocator('iframe').frameLocator('iframe').locator('div').tap(); + expect(await browser.evaluate('window._clicked')).toBe(true); + }); + + test('should click if opened select covers the button', async ({ browser }) => { + await browser.goto(content(` +
+ +
+
+ `)); + await browser.locator('select').tap(); + await browser.locator('button').tap(); + expect(await browser.evaluate('window.__CLICKED')).toBe(42); + }); + + test('should fire contextmenu event on right click in correct order', async ({ browser, screen }) => { + await browser.goto(content('')); + await browser.evaluate("() => { window.entries = []; const log = (event) => window.entries.push(event.type); for (const type of ['mousedown', 'mouseup', 'contextmenu']) document.addEventListener(type, log); }"); + await screen.getByRole('button', 'Click me').secondaryTap(); + await expect.poll(() => browser.evaluate('entries')).toEqual(['mousedown', 'contextmenu', 'mouseup']); + }); + + test('should click after a right click', async ({ browser, screen }) => { + await browser.goto(content(` + + + `)); + await screen.getByRole('button').secondaryTap(); + await screen.getByRole('button').tap(); + await expect(screen.getByRole('button')).toHaveText('Clicked!'); + }); + + test('should click into shadow root with slotted div', async ({ browser, screen }) => { + await browser.goto(content(` + + +
Foo
+
+ `)); + await screen.getByRole('button', 'Foo').tap(); + expect(await browser.evaluate('window.__clicked')).toBe(true); + }); + + test('should click shadow root button', async ({ browser }) => { + await browser.goto(content(` + + +
Foo
+
+ `)); + await browser.locator('my-button').tap(); + expect(await browser.evaluate('window.__clicked')).toBe(true); + }); +}); diff --git a/packages/web/tests/parity/tests/page-dialog.e2e.ts b/packages/web/tests/parity/tests/page-dialog.e2e.ts new file mode 100644 index 0000000000..7aea075f26 --- /dev/null +++ b/packages/web/tests/parity/tests/page-dialog.e2e.ts @@ -0,0 +1,124 @@ +/** + * Adapted from microsoft/playwright tests/page/page-dialog.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `page.on('dialog')` is `browser.onDialog`. A dialog no + * handler answers is dismissed as in Playwright, and e2e also fails the next step for it. + */ + +/* + * Not ported: + * - should fire dialogclosed when dialog is accepted: the dialogclosed event. + * - should fire dialogclosed when dialog is dismissed: the dialogclosed event. + * - should fire dialogclosed for auto-dismissed dialogs: the dialogclosed event. + * - should be able to close context with open alert: e2e answers every dialog, so none stays open. + * The `defaultValue()` assertions of the kept tests are dropped: e2e dialogs have no default value. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +/** What `act` threw, or undefined when it did not throw. */ +async function failure(act: () => unknown): Promise { + try { + await act(); + return undefined; + } catch (error) { + return error; + } +} + +test.describe('page dialog', { requires: ['browser'] }, () => { + test('should fire', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.onDialog(async (dialog) => { + expect(dialog.type).toBe('alert'); + expect(dialog.message).toBe('yo'); + await dialog.accept(); + }); + await browser.evaluate("() => alert('yo')"); + }); + + test('should allow accepting prompts', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.onDialog(async (dialog) => { + expect(dialog.type).toBe('prompt'); + expect(dialog.message).toBe('question?'); + await dialog.accept('answer!'); + }); + const result = await browser.evaluate("() => prompt('question?', 'yes.')"); + expect(result).toBe('answer!'); + }); + + test('should dismiss the prompt', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.onDialog((dialog) => dialog.dismiss()); + const result = await browser.evaluate("() => prompt('question?')"); + expect(result).toBe(null); + }); + + test('should accept the confirm prompt', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.onDialog(async (dialog) => { + await dialog.accept(); + }); + const result = await browser.evaluate("() => confirm('boolean?')"); + expect(result).toBe(true); + }); + + test('should dismiss the confirm prompt', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.onDialog(async (dialog) => { + await dialog.dismiss(); + }); + const result = await browser.evaluate("() => confirm('boolean?')"); + expect(result).toBe(false); + }); + + test('should handle multiple alerts', async ({ browser }) => { + await browser.onDialog(async (dialog) => { + await dialog.accept().catch(() => {}); + }); + await browser.goto(content(` +

Hello World

+ + `)); + expect(await browser.locator('p').textContent()).toBe('Hello World'); + }); + + test('should handle multiple confirms', async ({ browser }) => { + await browser.onDialog(async (dialog) => { + await dialog.accept().catch(() => {}); + }); + await browser.goto(content(` +

Hello World

+ + `)); + expect(await browser.locator('p').textContent()).toBe('Hello World'); + }); + + test('should auto-dismiss the prompt without listeners', async ({ browser }) => { + await browser.goto('/empty.html'); + const result = await browser.evaluate("() => prompt('question?')"); + expect(result).toBe(null); + expect(String(await failure(() => browser.title()))).toContain('unhandled prompt dialog: question?'); + }); + + test('should auto-dismiss the alert without listeners', async ({ browser }) => { + await browser.goto(content(`
Click me
`)); + const error = await failure(async () => { + await browser.locator('div').tap(); + await browser.title(); + }); + expect(String(error)).toContain('unhandled alert dialog: 123'); + expect(await browser.evaluate('window._clicked')).toBe(true); + }); +}); diff --git a/packages/web/tests/parity/tests/page-filechooser.e2e.ts b/packages/web/tests/parity/tests/page-filechooser.e2e.ts new file mode 100644 index 0000000000..50e9a5756d --- /dev/null +++ b/packages/web/tests/parity/tests/page-filechooser.e2e.ts @@ -0,0 +1,128 @@ +/** + * Adapted from microsoft/playwright tests/page/page-filechooser.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: a file chooser is answered by `setInputFiles` on the control whose + * click opens it, so the page's own `click()` on the input is a button that does it. + */ + +/* + * Not ported: + * - should emit event once: needs `page.once('filechooser')`. + * - should emit event via prepend: needs `page.prependListener('filechooser')`. + * - should emit event for iframe: needs `filechooser` events. + * - should emit event on/off: needs `page.on('filechooser')` and `page.off`. + * - should emit event addListener/removeListener: needs `page.addListener('filechooser')`. + * - should work when file input is attached to DOM: needs `page.waitForEvent('filechooser')`. + * - should not throw when filechooser belongs to iframe: needs `filechooser` events and `frame.setContent`. + * - should not throw when frame is detached immediately: needs `page.on('filechooser')` and `frame.setContent`. + * - should respect timeout: needs `page.waitForEvent('filechooser')`. + * - should respect default timeout when there is no custom timeout: needs `page.setDefaultTimeout`. + * - should prioritize exact timeout over default timeout: needs `page.setDefaultTimeout`. + * - should work with no timeout: needs `page.waitForEvent('filechooser', { timeout: 0 })`. + * - should abort with signal: needs `page.waitForEvent('filechooser', { signal })`. + * - should return the same file chooser when there are many watchdogs simultaneously: needs `FileChooser` objects. + * - should not trim big uploaded files: no file chooser; ported in page-set-input-files.e2e.ts. + * - should work for single file pick: needs `fileChooser.isMultiple()`. + * - should work for "multiple": needs `fileChooser.isMultiple()`. + * - should work for "webkitdirectory": needs `fileChooser.isMultiple()`. + * - should trigger listener added before navigation: needs `page.once('filechooser')`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { content, CROSS, PREFIX, e2eGap } from './helpers.ts'; + +/** A button whose click clicks the page's file input, as `picker.click()` does in Playwright's tests. */ +const PICKER = ""; + +/** Resolves, in the page, with the first picked file's text once the input fires `input`. */ +const readPicked = `() => { + const picker = document.querySelector('input'); + window.picked = new Promise((x) => { picker.oninput = x; }).then(() => { + const reader = new FileReader(); + const promise = new Promise((fulfill) => { reader.onload = fulfill; }); + reader.readAsText(picker.files[0]); + return promise.then(() => reader.result); + }); +}`; + +test.describe('page filechooser', { requires: ['browser'] }, () => { + test('should upload multiple large files', async ({ browser }) => { + const filesCount = 10; + await browser.goto('/input/fileupload-multi.html'); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'e2e-parity-chooser-')); + const uploadFile = path.join(dir, '50MB_1.zip'); + const str = 'A'.repeat(1024); + const stream = fs.createWriteStream(uploadFile); + for (let i = 0; i < 49 * 1024; i++) { + await new Promise((fulfill, reject) => stream.write(str, (error) => (error ? reject(error) : fulfill()))); + } + await new Promise((fulfill) => stream.end(fulfill)); + const uploadFiles = [uploadFile]; + for (let i = 2; i <= filesCount; i++) { + const dstFile = path.join(dir, `50MB_${i}.zip`); + fs.copyFileSync(uploadFile, dstFile); + uploadFiles.push(dstFile); + } + await browser.evaluate("() => { const button = document.createElement('button'); button.textContent = 'pick'; button.type = 'button'; button.onclick = () => document.querySelector('input[type=\"file\"]').click(); document.body.append(button); }"); + await browser.locator('button').setInputFiles(uploadFiles); + const filesLen = await browser.evaluate('document.getElementsByTagName("input")[0].files.length'); + expect(filesLen).toEqual(filesCount); + fs.rmSync(dir, { recursive: true }); + }); + + test('should work when file input is not attached to DOM', async ({ browser }) => { + await browser.goto(content(``)); + await browser.locator('button').setInputFiles('assets/file-to-upload.txt'); + expect(await browser.evaluate('() => window.picked')).toBe('contents of the file'); + }); + + test('should accept single file', async ({ browser }) => { + await browser.goto(content("")); + await browser.locator('button').setInputFiles('assets/file-to-upload.txt'); + expect(await browser.evaluate("() => document.querySelector('input').files.length")).toBe(1); + expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('file-to-upload.txt'); + }); + + test('should be able to read selected file', async ({ browser }) => { + await browser.goto(content(PICKER)); + await browser.evaluate(readPicked); + await browser.locator('button').setInputFiles('assets/file-to-upload.txt'); + expect(await browser.evaluate('() => window.picked')).toBe('contents of the file'); + }); + + test('should be able to reset selected files with empty file list', async ({ browser }) => { + e2eGap('`setInputFiles([])` is refused; there is no way to clear a file input'); + await browser.goto(content(PICKER)); + const watchLength = "() => { const picker = document.querySelector('input'); window.picked = new Promise((x) => { picker.oninput = x; }).then(() => picker.files.length); }"; + await browser.evaluate(watchLength); + await browser.locator('button').setInputFiles('assets/file-to-upload.txt'); + expect(await browser.evaluate('() => window.picked')).toBe(1); + await browser.evaluate(watchLength); + await browser.locator('button').setInputFiles([]); + expect(await browser.evaluate('() => window.picked')).toBe(0); + }); + + test('should emit event after navigation', async ({ browser }) => { + await browser.goto(`${PREFIX}/empty.html`); + await browser.goto(content(PICKER)); + await browser.locator('button').setInputFiles('assets/file-to-upload.txt'); + expect(await browser.evaluate("() => document.querySelector('input').files.length")).toBe(1); + await browser.goto(`${CROSS}/empty.html`); + await browser.goto(`${CROSS}${content(PICKER)}`); + await browser.locator('button').setInputFiles('assets/file-to-upload.txt'); + expect(await browser.evaluate("() => document.querySelector('input').files.length")).toBe(1); + }); +}); diff --git a/packages/web/tests/parity/tests/page-fill.e2e.ts b/packages/web/tests/parity/tests/page-fill.e2e.ts new file mode 100644 index 0000000000..ec69088df9 --- /dev/null +++ b/packages/web/tests/parity/tests/page-fill.e2e.ts @@ -0,0 +1,375 @@ +/** + * Adapted from microsoft/playwright tests/page/page-fill.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `page.fill(selector, value)` is a locator fill. + */ + +/* + * Not ported: + * - should throw if passed a non-string value: asserts Playwright's protocol validator message for a number; `fill` is typed to strings. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { browserName, content } from './helpers.ts'; + +/** Five pairs of animation frames, Playwright's `rafraf(page, 5)`, so a pending fill has had its chance. */ +const giveItAChanceToFill = '() => new Promise((resolve) => { let frames = 0; const step = () => (++frames === 10 ? setTimeout(resolve, 0) : requestAnimationFrame(step)); requestAnimationFrame(step); })'; + +test.describe('page fill', { requires: ['browser'] }, () => { + test('should fill textarea', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('textarea').fill('some value'); + expect(await browser.evaluate('result')).toBe('some value'); + }); + + test('should fill input', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('input').fill('some value'); + expect(await browser.evaluate('result')).toBe('some value'); + }); + + test('should throw on unsupported inputs', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + for (const type of ['button', 'checkbox', 'file', 'image', 'radio', 'reset', 'submit']) { + await browser.evaluate("(type) => document.querySelector('input').setAttribute('type', type)", type); + const error = await browser.locator('input').fill('').catch((caught: Error) => caught); + expect((error as Error).message).toContain(`Input of type "${type}" cannot be filled`); + } + }); + + test('should fill different input types', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + for (const type of ['password', 'search', 'tel', 'text', 'url', 'invalid-type']) { + await browser.evaluate("(type) => document.querySelector('input').setAttribute('type', type)", type); + await browser.locator('input').fill('text ' + type); + expect(await browser.evaluate('result')).toBe('text ' + type); + } + }); + + test('should fill range input', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').fill('42'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('42'); + }); + + test('should throw on incorrect range value', async ({ browser }) => { + await browser.goto(content('')); + const error1 = await browser.locator('input').fill('foo').catch((caught: Error) => caught); + expect((error1 as Error).message).toContain('Malformed value'); + const error2 = await browser.locator('input').fill('200').catch((caught: Error) => caught); + expect((error2 as Error).message).toContain('Malformed value'); + const error3 = await browser.locator('input').fill('15.43').catch((caught: Error) => caught); + expect((error3 as Error).message).toContain('Malformed value'); + }); + + test('should fill color input', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').fill('#aaaaaa'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('#aaaaaa'); + }); + + test('should fill color input case insensitive', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').fill('#AbCd00'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('#abcd00'); + }); + + test('should throw on incorrect color value', async ({ browser }) => { + await browser.goto(content('')); + const error1 = await browser.locator('input').fill('badvalue').catch((caught: Error) => caught); + expect((error1 as Error).message).toContain('Malformed value'); + }); + + test('should fill date input after clicking', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').tap(); + await browser.locator('input').fill('2020-03-02'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('2020-03-02'); + }); + + for (const [type, value] of Object.entries({ + 'color': '#aaaaaa', + 'date': '2020-03-02', + 'time': '13:15', + 'datetime-local': '2020-03-02T13:15:30', + 'month': '2020-03', + 'range': '42', + 'week': '2020-W50', + })) { + test(`input event.composed should be true and cross shadow dom boundary - ${type}`, async ({ browser }) => { + test.skip(browserName !== 'chromium' && ['month', 'week'].includes(type), 'Some browser/platforms do not implement certain input types'); + await browser.goto('/empty.html'); + await browser.goto(content(``)); + await browser.evaluate(`() => { + window.firedBodyEvents = []; + for (const event of ['input', 'change']) + document.body.addEventListener(event, (e) => window.firedBodyEvents.push(e.type + ':' + e.composed), false); + }`); + await browser.evaluate(`() => { + window.firedEvents = []; + const input = document.querySelector('div').shadowRoot.querySelector('input'); + for (const event of ['input', 'change']) + input.addEventListener(event, (e) => window.firedEvents.push(e.type + ':' + e.composed), false); + }`); + await browser.locator('input').fill(value); + expect(await browser.evaluate('firedEvents')).toEqual(['input:true', 'change:false']); + expect(await browser.evaluate('firedBodyEvents')).toEqual(['input:true']); + }); + } + + test('should throw on incorrect date', async ({ browser }) => { + await browser.goto(content('')); + const error = await browser.locator('input').fill('2020-13-05').catch((caught: Error) => caught); + expect((error as Error).message).toContain('Malformed value'); + }); + + test('should fill time input', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').fill('13:15'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('13:15'); + }); + + test('should fill month input', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').fill('2020-07'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('2020-07'); + }); + + test('should throw on incorrect month', async ({ browser }) => { + test.skip(browserName !== 'chromium', 'Only Chromium supports month inputs'); + await browser.goto(content('')); + const error = await browser.locator('input').fill('2020-13').catch((caught: Error) => caught); + expect((error as Error).message).toContain('Malformed value'); + }); + + test('should fill week input', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').fill('2020-W50'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('2020-W50'); + }); + + test('should throw on incorrect week', async ({ browser }) => { + test.skip(browserName !== 'chromium', 'Only Chromium supports week inputs'); + await browser.goto(content('')); + const error = await browser.locator('input').fill('2020-123').catch((caught: Error) => caught); + expect((error as Error).message).toContain('Malformed value'); + }); + + test('should throw on incorrect time', async ({ browser }) => { + await browser.goto(content('')); + const error = await browser.locator('input').fill('25:05').catch((caught: Error) => caught); + expect((error as Error).message).toContain('Malformed value'); + }); + + test('should fill datetime-local input', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').fill('2020-03-02T05:15'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('2020-03-02T05:15'); + }); + + test('should throw on incorrect datetime-local', async ({ browser }) => { + test.skip(browserName !== 'chromium', 'Only Chromium supports datetime-local inputs'); + await browser.goto(content('')); + const error = await browser.locator('input').fill('abc').catch((caught: Error) => caught); + expect((error as Error).message).toContain('Malformed value'); + }); + + test('should fill contenteditable', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('div[contenteditable]').fill('some value'); + expect(await browser.evaluate("() => document.querySelector('div[contenteditable]').textContent")).toBe('some value'); + }); + + test('should fill contenteditable with new lines', async ({ browser }) => { + test.skip(browserName === 'firefox', 'Firefox does not handle new lines in contenteditable'); + await browser.goto('/empty.html'); + await browser.goto(content('
')); + await browser.locator('div[contenteditable]').fill('John\nDoe'); + expect(await browser.evaluate("() => document.querySelector('div[contenteditable]').innerText")).toBe('John\nDoe'); + }); + + test('should not double-fill in contenteditable with beforeinput handler in Firefox', async ({ browser }) => { + test.skip(browserName === 'firefox', 'https://github.com/microsoft/playwright/issues/36715'); + await browser.goto(content(` +
+ + `)); + const locator = browser.locator('#editor'); + const testValue = 'Playwright'; + await locator.fill(testValue); + await expect(locator).toHaveText(testValue); + }); + + test('should fill elements with existing value and selection', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + + await browser.evaluate("() => { document.querySelector('input').value = 'value one'; }"); + await browser.locator('input').fill('another value'); + expect(await browser.evaluate('result')).toBe('another value'); + + await browser.evaluate("() => { const input = document.querySelector('input'); input.selectionStart = 1; input.selectionEnd = 2; }"); + await browser.locator('input').fill('maybe this one'); + expect(await browser.evaluate('result')).toBe('maybe this one'); + + await browser.evaluate(`() => { + const div = document.querySelector('div[contenteditable]'); + div.innerHTML = 'some text some more text and even more text'; + const range = document.createRange(); + range.selectNodeContents(div.querySelector('span')); + const selection = window.getSelection(); + selection.removeAllRanges(); + selection.addRange(range); + }`); + await browser.locator('div[contenteditable]').fill('replace with this'); + expect(await browser.evaluate("() => document.querySelector('div[contenteditable]').textContent")).toBe('replace with this'); + }); + + test('should throw nice error without injected script stack when element is not an ', async ({ browser }) => { + await browser.goto(content('')); + const error = await browser.locator('select').fill('').catch((caught: Error) => caught); + expect((error as Error).message).toContain('Element is not an ,
')); + for (const locator of [browser.locator('input'), browser.locator('textarea'), browser.locator('div')]) { + await locator.focus(); + await browser.keyboard.press('Alt+KeyA'); + await browser.keyboard.press('Alt+Digit1'); + await browser.keyboard.press('Alt+Shift+KeyA'); + await browser.keyboard.down('Alt'); + await browser.keyboard.press('b'); + await browser.keyboard.up('Alt'); + await locator.press('c'); + } + await expect(browser.locator('input')).toHaveValue('c'); + await expect(browser.locator('textarea')).toHaveValue('c'); + await expect(browser.locator('div')).toHaveText('c'); + }); + + test('should emit keydown, keypress, textInput and input when typing a character', async ({ browser }) => { + await browser.goto(content('')); + await browser.evaluate(`() => { + window.events = []; + for (const type of ['keydown', 'keypress', 'textInput', 'input', 'keyup']) + document.querySelector('input').addEventListener(type, () => window.events.push(type)); + }`); + await browser.locator('input').focus(); + await browser.keyboard.press('f'); + expect(await browser.evaluate('events')).toEqual(['keydown', 'keypress', 'textInput', 'input', 'keyup']); + }); + + test('should dispatch key events in separate tasks', async ({ browser }) => { + test.skip(browserName === 'firefox', 'Firefox/Juggler dispatches keydown and keypress in the same task'); + await browser.goto(content('')); + await browser.evaluate(`() => { + window.log = []; + const input = document.querySelector('input'); + for (const type of ['keydown', 'keypress']) + input.addEventListener(type, () => { window.log.push(type); queueMicrotask(() => window.log.push('microtask-' + type)); }); + input.focus(); + }`); + await browser.keyboard.press('a'); + expect(await browser.evaluate('log')).toEqual(['keydown', 'microtask-keydown', 'keypress', 'microtask-keypress']); + }); + + test('should report shiftKey', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + const keyboard = browser.keyboard; + const codeForKey = { 'Shift': 16, 'Alt': 18, 'Control': 17 }; + for (const modifierKey in codeForKey) { + await keyboard.down(modifierKey); + expect(await browser.evaluate('getResult()')).toBe('Keydown: ' + modifierKey + ' ' + modifierKey + 'Left LEFT [' + modifierKey + ']'); + await keyboard.down('!'); + if (modifierKey === 'Shift') expect(await browser.evaluate('getResult()')).toBe('Keydown: ! Digit1 STANDARD [' + modifierKey + ']\nKeypress: ! Digit1 STANDARD 33 [' + modifierKey + ']'); + else expect(await browser.evaluate('getResult()')).toBe('Keydown: ! Digit1 STANDARD [' + modifierKey + ']'); + + await keyboard.up('!'); + expect(await browser.evaluate('getResult()')).toBe('Keyup: ! Digit1 STANDARD [' + modifierKey + ']'); + await keyboard.up(modifierKey); + expect(await browser.evaluate('getResult()')).toBe('Keyup: ' + modifierKey + ' ' + modifierKey + 'Left LEFT []'); + } + }); + + test('should report multiple modifiers', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + const keyboard = browser.keyboard; + await keyboard.down('Control'); + expect(await browser.evaluate('getResult()')).toBe('Keydown: Control ControlLeft LEFT [Control]'); + await keyboard.down('Alt'); + expect(await browser.evaluate('getResult()')).toBe('Keydown: Alt AltLeft LEFT [Alt Control]'); + await keyboard.down(';'); + expect(await browser.evaluate('getResult()')).toBe('Keydown: ; Semicolon STANDARD [Alt Control]'); + await keyboard.up(';'); + expect(await browser.evaluate('getResult()')).toBe('Keyup: ; Semicolon STANDARD [Alt Control]'); + await keyboard.up('Control'); + expect(await browser.evaluate('getResult()')).toBe('Keyup: Control ControlLeft LEFT [Alt]'); + await keyboard.up('Alt'); + expect(await browser.evaluate('getResult()')).toBe('Keyup: Alt AltLeft LEFT []'); + }); + + test('should send proper codes while typing', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + await browser.keyboard.type('!'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: ! Digit1 STANDARD []', + 'Keypress: ! Digit1 STANDARD 33 []', + 'Keyup: ! Digit1 STANDARD []'].join('\n')); + await browser.keyboard.type('^'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: ^ Digit6 STANDARD []', + 'Keypress: ^ Digit6 STANDARD 94 []', + 'Keyup: ^ Digit6 STANDARD []'].join('\n')); + }); + + test('should send proper codes while typing with shift', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + const keyboard = browser.keyboard; + await keyboard.down('Shift'); + await browser.keyboard.type('~'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: Shift ShiftLeft LEFT [Shift]', + 'Keydown: ~ Backquote STANDARD [Shift]', + 'Keypress: ~ Backquote STANDARD 126 [Shift]', + 'Keyup: ~ Backquote STANDARD [Shift]'].join('\n')); + await keyboard.up('Shift'); + }); + + test('should not type canceled events', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('textarea').focus(); + await browser.evaluate(`() => { + window.addEventListener('keydown', (event) => { + event.stopPropagation(); + event.stopImmediatePropagation(); + if (event.key === 'l') + event.preventDefault(); + if (event.key === 'o') + event.preventDefault(); + }, false); + }`); + await browser.keyboard.type('Hello World!'); + expect(await browser.evaluate("() => document.querySelector('textarea').value")).toBe('He Wrd!'); + }); + + test('should press plus', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + await browser.keyboard.press('+'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: + Equal STANDARD []', + 'Keypress: + Equal STANDARD 43 []', + 'Keyup: + Equal STANDARD []'].join('\n')); + }); + + test('should press shift plus', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + await browser.keyboard.press('Shift++'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: Shift ShiftLeft LEFT [Shift]', + 'Keydown: + Equal STANDARD [Shift]', + 'Keypress: + Equal STANDARD 43 [Shift]', + 'Keyup: + Equal STANDARD [Shift]', + 'Keyup: Shift ShiftLeft LEFT []'].join('\n')); + }); + + test('should support plus-separated modifiers', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + await browser.keyboard.press('Shift+~'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: Shift ShiftLeft LEFT [Shift]', + 'Keydown: ~ Backquote STANDARD [Shift]', + 'Keypress: ~ Backquote STANDARD 126 [Shift]', + 'Keyup: ~ Backquote STANDARD [Shift]', + 'Keyup: Shift ShiftLeft LEFT []'].join('\n')); + }); + + test('should support multiple plus-separated modifiers', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + await browser.keyboard.press('Control+Shift+~'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: Control ControlLeft LEFT [Control]', + 'Keydown: Shift ShiftLeft LEFT [Control Shift]', + 'Keydown: ~ Backquote STANDARD [Control Shift]', + 'Keyup: ~ Backquote STANDARD [Control Shift]', + 'Keyup: Shift ShiftLeft LEFT [Control]', + 'Keyup: Control ControlLeft LEFT []'].join('\n')); + }); + + test('should shift raw codes', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + await browser.keyboard.press('Shift+Digit3'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: Shift ShiftLeft LEFT [Shift]', + 'Keydown: # Digit3 STANDARD [Shift]', + 'Keypress: # Digit3 STANDARD 35 [Shift]', + 'Keyup: # Digit3 STANDARD [Shift]', + 'Keyup: Shift ShiftLeft LEFT []'].join('\n')); + }); + + test('should specify repeat property', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('textarea').focus(); + await browser.evaluate(captureLastKeydown); + await browser.keyboard.down('a'); + expect(await browser.evaluate('lastEvent.repeat')).toBe(false); + await browser.keyboard.press('a'); + expect(await browser.evaluate('lastEvent.repeat')).toBe(true); + + await browser.keyboard.down('b'); + expect(await browser.evaluate('lastEvent.repeat')).toBe(false); + await browser.keyboard.down('b'); + expect(await browser.evaluate('lastEvent.repeat')).toBe(true); + + await browser.keyboard.up('a'); + await browser.keyboard.down('a'); + expect(await browser.evaluate('lastEvent.repeat')).toBe(false); + }); + + test('should type all kinds of characters', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('textarea').focus(); + const text = 'This text goes onto two lines.\nThis character is 嗨.'; + await browser.keyboard.type(text); + expect(await browser.evaluate("() => document.querySelector('textarea').value")).toBe(text); + }); + + test('should specify location', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.evaluate(captureLastKeydown); + const textarea = browser.locator('textarea'); + + await textarea.focus(); + await browser.keyboard.press('Digit5'); + expect.soft(await browser.evaluate('lastEvent.location')).toBe(0); + expect.soft(await browser.evaluate('lastEvent.key')).toBe('5'); + expect.soft(await browser.evaluate('lastEvent.code')).toBe('Digit5'); + + await textarea.focus(); + await browser.keyboard.press('ControlLeft'); + expect.soft(await browser.evaluate('lastEvent.location')).toBe(1); + expect.soft(await browser.evaluate('lastEvent.key')).toBe('Control'); + expect.soft(await browser.evaluate('lastEvent.code')).toBe('ControlLeft'); + + await textarea.focus(); + await browser.keyboard.press('ControlRight'); + expect.soft(await browser.evaluate('lastEvent.location')).toBe(2); + expect.soft(await browser.evaluate('lastEvent.key')).toBe('Control'); + expect.soft(await browser.evaluate('lastEvent.code')).toBe('ControlRight'); + + await textarea.focus(); + await browser.keyboard.press('NumpadSubtract'); + expect.soft(await browser.evaluate('lastEvent.location')).toBe(3); + expect.soft(await browser.evaluate('lastEvent.key')).toBe('-'); + expect.soft(await browser.evaluate('lastEvent.code')).toBe('NumpadSubtract'); + }); + + test('should specify numpad location on keyup', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + await browser.keyboard.press('NumpadSubtract'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: - NumpadSubtract NUMPAD []', + 'Keypress: - NumpadSubtract NUMPAD 45 []', + 'Keyup: - NumpadSubtract NUMPAD []'].join('\n')); + }); + + test('should press NumpadDecimal as Delete', async ({ browser }) => { + await browser.goto(content('')); + await browser.evaluate(captureLastKeydown); + const textarea = browser.locator('textarea'); + + await textarea.focus(); + await browser.keyboard.press('NumpadDecimal'); + expect(await browser.evaluate('lastEvent.key')).toBe('Delete'); + expect(await browser.evaluate('lastEvent.code')).toBe('NumpadDecimal'); + expect(await browser.evaluate('lastEvent.location')).toBe(3); + await expect(textarea).toHaveValue(''); + }); + + test('should type numpad digits with Shift', async ({ browser }) => { + await browser.goto(content('')); + const textarea = browser.locator('textarea'); + await textarea.focus(); + await browser.keyboard.press('Shift+Numpad1'); + await browser.keyboard.press('Shift+NumpadDecimal'); + await browser.keyboard.press('Shift+Numpad9'); + await expect(textarea).toHaveValue('1.9'); + }); + + test('should press Enter', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('textarea').focus(); + await browser.evaluate(captureLastKeydown); + for (const [key, expectedKey, expectedCode] of [ + ['Enter', 'Enter', 'Enter'], + ['NumpadEnter', 'Enter', 'NumpadEnter'], + ['\n', 'Enter', 'Enter'], + ['\r', 'Enter', 'Enter'], + ] as const) { + await browser.keyboard.press(key); + expect(await browser.evaluate('lastEvent.key')).toBe(expectedKey); + expect(await browser.evaluate('lastEvent.code')).toBe(expectedCode); + expect(await browser.evaluate("() => document.querySelector('textarea').value")).toBe('\n'); + await browser.evaluate("() => { document.querySelector('textarea').value = ''; }"); + } + }); + + test('should press audio and media control keys', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').focus(); + await browser.evaluate(captureLastKeydown); + const mediaKeys = [ + { key: 'AudioVolumeMute', code: browserName === 'firefox' ? 'VolumeMute' : 'AudioVolumeMute' }, + { key: 'AudioVolumeDown', code: browserName === 'firefox' ? 'VolumeDown' : 'AudioVolumeDown' }, + { key: 'AudioVolumeUp', code: browserName === 'firefox' ? 'VolumeUp' : 'AudioVolumeUp' }, + { key: 'MediaTrackNext', code: 'MediaTrackNext' }, + { key: 'MediaTrackPrevious', code: 'MediaTrackPrevious' }, + { key: 'MediaPlayPause', code: 'MediaPlayPause' }, + ]; + for (const mediaKey of mediaKeys) { + await browser.keyboard.press(mediaKey.key); + expect.soft(await browser.evaluate('lastEvent.key')).toBe(mediaKey.key); + expect.soft(await browser.evaluate('lastEvent.code')).toBe(mediaKey.code); + expect.soft(await browser.evaluate('lastEvent.location')).toBe(0); + } + }); + + test('should throw on unknown keys', async ({ browser }) => { + await browser.goto('/empty.html'); + let error = await browser.keyboard.press('NotARealKey').catch((caught: Error) => caught); + expect((error as Error).message).toContain('Unknown key: "NotARealKey"'); + + error = await browser.keyboard.press('ё').catch((caught: Error) => caught); + expect(error && (error as Error).message).toContain('Unknown key: "ё"'); + + error = await browser.keyboard.press('😊').catch((caught: Error) => caught); + expect(error && (error as Error).message).toContain('Unknown key: "😊"'); + }); + + test('should type emoji', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('textarea').pressSequentially('👹 Tokyo street Japan 🇯🇵'); + expect(await browser.evaluate("() => document.querySelector('textarea').value")).toBe('👹 Tokyo street Japan 🇯🇵'); + }); + + test('should type emoji into an iframe', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.evaluate(`() => new Promise((resolve) => { + const frame = document.createElement('iframe'); + frame.id = 'emoji-test'; + frame.src = '/input/textarea.html'; + frame.onload = resolve; + document.body.appendChild(frame); + })`); + await browser.frameLocator('#emoji-test').locator('textarea').pressSequentially('👹 Tokyo street Japan 🇯🇵'); + expect(await browser.evaluate("() => document.querySelector('#emoji-test').contentDocument.querySelector('textarea').value")).toBe('👹 Tokyo street Japan 🇯🇵'); + }); + + test('should handle selectAll', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('textarea').pressSequentially('some text'); + await browser.keyboard.down('ControlOrMeta'); + await browser.keyboard.press('a'); + await browser.keyboard.up('ControlOrMeta'); + await browser.keyboard.press('Backspace'); + expect(await browser.evaluate("() => document.querySelector('textarea').value")).toBe(''); + }); + + test('pressing Meta should not result in any text insertion on any platform', async ({ browser }) => { + await browser.goto(content('')); + const input = browser.locator('input'); + await expect(input).toHaveValue('hello world'); + await input.focus(); + await browser.keyboard.press('Meta'); + await expect(input).toHaveValue('hello world'); + }); + + test('should be able to prevent selectAll', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('textarea').pressSequentially('some text'); + await browser.evaluate(`() => { + document.querySelector('textarea').addEventListener('keydown', (event) => { + if (event.key === 'a' && (event.metaKey || event.ctrlKey)) + event.preventDefault(); + }, false); + }`); + await browser.keyboard.down('ControlOrMeta'); + await browser.keyboard.press('a'); + await browser.keyboard.up('ControlOrMeta'); + await browser.keyboard.press('Backspace'); + expect(await browser.evaluate("() => document.querySelector('textarea').value")).toBe('some tex'); + }); + + test('should support MacOS shortcuts', async ({ browser }) => { + test.skip(!isMac); + test.skip(browserName === 'firefox', 'https://github.com/microsoft/playwright/issues/5721'); + await browser.goto('/input/textarea.html'); + await browser.locator('textarea').pressSequentially('some text'); + await browser.keyboard.press('Shift+Control+Alt+KeyB'); + await browser.keyboard.press('Backspace'); + expect(await browser.evaluate("() => document.querySelector('textarea').value")).toBe('some '); + }); + + test('should press the meta key', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.evaluate(captureLastKeydown); + await browser.keyboard.press('Meta'); + const { key, code, metaKey } = await browser.evaluate<{ key: string; code: string; metaKey: boolean }>('lastEvent'); + expect(key).toBe('Meta'); + expect(code).toBe('MetaLeft'); + expect(metaKey).toBe(true); + }); + + test('should work with keyboard events with empty.html', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.evaluate(captureLastKeydown); + await browser.keyboard.press('a'); + expect(await browser.evaluate('lastEvent.key')).toBe('a'); + }); + + test('should work after a cross origin navigation', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(`${CROSS}/empty.html`); + await browser.evaluate(captureLastKeydown); + await browser.keyboard.press('a'); + expect(await browser.evaluate('lastEvent.key')).toBe('a'); + }); + + test('should scroll with PageDown', async ({ browser }) => { + await browser.goto('/input/scrollable.html'); + await browser.locator('body').tap(); + await browser.keyboard.press('PageDown'); + await expect.poll(() => browser.evaluate('scrollY > 0')).toBe(true); + }); + + test('should move around the selection in a contenteditable', async ({ browser }) => { + await browser.goto(content('
')); + await browser.locator('div').focus(); + const modifier = isMac ? 'Alt' : 'Control'; + await browser.keyboard.type('Hello World'); + await browser.keyboard.down(modifier); + await browser.keyboard.down('Shift'); + await browser.keyboard.press('ArrowLeft'); + await browser.keyboard.up('Shift'); + await browser.keyboard.up(modifier); + expect(await browser.evaluate('() => window.getSelection().toString()')).toBe('World'); + }); + + test('should move to the start of the document', async ({ browser }) => { + test.skip(!isMac); + await browser.goto(content('
')); + await browser.locator('div').focus(); + await browser.keyboard.type('1\n2\n3\n'); + await browser.keyboard.press('Shift+Meta+ArrowUp'); + expect(await browser.evaluate('() => window.getSelection().toString()')).toBe('1\n2\n3\n'); + }); + + test('should dispatch a click event on a button when Space gets pressed', async ({ browser }) => { + await browser.goto(content('')); + await browser.evaluate("() => { window.actual = { clicked: false }; document.querySelector('button').addEventListener('click', () => (window.actual.clicked = true)); }"); + await browser.locator('button').focus(); + await browser.keyboard.press('Space'); + expect(await browser.evaluate('actual.clicked')).toBe(true); + }); + + test('should dispatch a click event on a button when Enter gets pressed', async ({ browser }) => { + await browser.goto(content('')); + await browser.evaluate("() => { window.actual = { clicked: false }; document.querySelector('button').addEventListener('click', () => (window.actual.clicked = true)); }"); + await browser.locator('button').focus(); + await browser.keyboard.press('Enter'); + expect(await browser.evaluate('actual.clicked')).toBe(true); + }); + + test('should support simple copy-pasting', async ({ browser }) => { + await browser.goto(content('
123
')); + await browser.locator('div').focus(); + await browser.keyboard.press('ControlOrMeta+KeyA'); + await browser.keyboard.press('ControlOrMeta+KeyC'); + await browser.keyboard.press('ControlOrMeta+KeyV'); + await browser.keyboard.press('ControlOrMeta+KeyV'); + expect(await browser.evaluate("() => document.querySelector('div').textContent")).toBe('123123'); + }); + + test('should support simple cut-pasting', async ({ browser }) => { + await browser.goto(content('
123
')); + await browser.locator('div').focus(); + await browser.keyboard.press('ControlOrMeta+KeyA'); + await browser.keyboard.press('ControlOrMeta+KeyX'); + await browser.keyboard.press('ControlOrMeta+KeyV'); + await browser.keyboard.press('ControlOrMeta+KeyV'); + expect(await browser.evaluate("() => document.querySelector('div').textContent")).toBe('123123'); + }); + + test('should support undo-redo', async ({ browser }) => { + await browser.goto(content('
')); + const div = browser.locator('div'); + await expect(div).toHaveText(''); + await div.pressSequentially('123'); + await expect(div).toHaveText('123'); + await browser.keyboard.press('ControlOrMeta+KeyZ'); + await expect(div).toHaveText(''); + await browser.keyboard.press('Shift+ControlOrMeta+KeyZ'); + await expect(div).toHaveText('123'); + }); + + test('should type repeatedly in contenteditable in shadow dom', async ({ browser }) => { + await browser.goto(content(` + + + + + + + `)); + + const editor = browser.locator('shadow-element > .editor').first(); + await editor.pressSequentially('This is the first box.'); + + const sectionEditor = browser.locator('section .editor'); + await sectionEditor.pressSequentially('This is the second box.'); + + expect(await editor.textContent()).toBe('This is the first box.'); + expect(await sectionEditor.textContent()).toBe('This is the second box.'); + }); + + test('should type repeatedly in contenteditable in shadow dom with nested elements', async ({ browser }) => { + await browser.goto(content(` + + + + + + + `)); + + const editor = browser.locator('shadow-element > .editor').first(); + await editor.pressSequentially('This is the first box: '); + + const sectionEditor = browser.locator('section .editor'); + await sectionEditor.pressSequentially('This is the second box: '); + + expect(await editor.textContent()).toBe('This is the first box: hello'); + expect(await sectionEditor.textContent()).toBe('This is the second box: world'); + }); + + test('should type repeatedly in input in shadow dom', async ({ browser }) => { + await browser.goto(content(` + + + + + + + `)); + + const editor = browser.locator('shadow-element > .editor').first(); + await editor.pressSequentially('This is the first box.'); + + const sectionEditor = browser.locator('section .editor'); + await sectionEditor.pressSequentially('This is the second box.'); + + expect(await editor.inputValue()).toBe('This is the first box.'); + expect(await sectionEditor.inputValue()).toBe('This is the second box.'); + }); + + test('type to non-focusable element should maintain old focus', async ({ browser }) => { + await browser.goto(content(` +
focusable div
+
non-editable, non-focusable
+ `)); + + await browser.locator('#focusable').focus(); + expect(await browser.evaluate('() => document.activeElement?.id')).toBe('focusable'); + await browser.locator('#non-focusable-and-non-editable').pressSequentially('foo'); + expect(await browser.evaluate('() => document.activeElement?.id')).toBe('focusable'); + }); + + test('should have correct Keydown/Keyup order when pressing Escape key', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + await browser.keyboard.press('Escape'); + expect(await browser.evaluate('getResult()')).toBe(` +Keydown: Escape Escape STANDARD [] +Keyup: Escape Escape STANDARD [] +`.trim()); + }); + + test('should close dialog on Escape key press in contenteditable', async ({ browser }) => { + await browser.goto(content(` + +
Edit Me
+
+ `)); + const widget = browser.locator('dialog [contenteditable]'); + await browser.evaluate("() => document.querySelector('dialog').showModal()"); + await expect.poll(() => browser.evaluate("() => document.querySelector('dialog').open")).toBe(true); + await expect(widget).toBeVisible(); + + await widget.press('Escape'); + await expect.poll(() => browser.evaluate("() => document.querySelector('dialog').open")).toBe(false); + await expect(widget).not.toBeVisible(); + }); +}); diff --git a/packages/web/tests/parity/tests/page-network-idle.e2e.ts b/packages/web/tests/parity/tests/page-network-idle.e2e.ts new file mode 100644 index 0000000000..ddf2a476cf --- /dev/null +++ b/packages/web/tests/parity/tests/page-network-idle.e2e.ts @@ -0,0 +1,165 @@ +/** + * Adapted from microsoft/playwright tests/page/page-network-idle.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `page.setContent(html, { waitUntil })` is `browser.goto(content(html), { waitUntil })`, + * and a request the server holds is one a route holds. + */ + +/* + * Not ported: + * - should wait for networkidle in waitForNavigation: needs `page.waitForNavigation`. + * - should wait for networkidle when navigating iframe: needs `frame.goto`. + * - should wait for networkidle from the popup: needs `page.waitForEvent('popup')` and `popup.waitForLoadState`. + */ + +import { test, type Browser } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, PREFIX } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +/** A promise with its resolver, for a route handler the test holds open. */ +function deferred(): { promise: Promise; resolve: (value: T) => void } { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +} + +/** + * Playwright's `networkIdleTest`: holds `fetch-request-a.js` and `fetch-request-b.js` + * until the test answers them, and checks `action` settles only 500ms after the last. + */ +async function networkIdleTest(browser: Browser, action: () => Promise): Promise { + const held = (suffix: string) => { + const requested = deferred(); + const answer = deferred(); + return { suffix, requested, answer }; + }; + const a = held('/fetch-request-a.js'); + const b = held('/fetch-request-b.js'); + for (const request of [a, b]) { + await browser.route(`**${request.suffix}`, async (route) => { + request.requested.resolve(); + await request.answer.promise; + await route.fulfill({ status: 404, body: 'File not found' }); + }); + } + + const actionPromise = action(); + let actionFinished = false; + void actionPromise.then(() => (actionFinished = true)); + + await a.requested.promise; + expect(actionFinished).toBe(false); + + await browser.evaluate("() => window['fetchSecond']()"); + a.answer.resolve(); + + await b.requested.promise; + expect(actionFinished).toBe(false); + + let timerTriggered = false; + const timer = setTimeout(() => (timerTriggered = true), 500); + b.answer.resolve(); + + await actionPromise; + clearTimeout(timer); + expect(timerTriggered).toBe(true); +} + +test.describe('page network idle', { requires: ['browser'] }, () => { + test('should navigate to empty page with networkidle', async ({ browser }) => { + const [response] = await Promise.all([ + browser.waitForResponse('**/empty.html'), + browser.goto(EMPTY_PAGE, { waitUntil: 'networkidle' }), + ]); + expect(response.status).toBe(200); + }); + + test('should wait for networkidle to succeed navigation', async ({ browser }) => { + await networkIdleTest(browser, () => browser.goto('/networkidle.html', { waitUntil: 'networkidle' })); + }); + + test('should wait for networkidle to succeed navigation with request from previous navigation', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content("")); + await networkIdleTest(browser, () => browser.goto('/networkidle.html', { waitUntil: 'networkidle' })); + }); + + test('should wait for networkidle in setContent', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await networkIdleTest(browser, () => browser.goto(content(""), { waitUntil: 'networkidle' })); + }); + + test('should wait for networkidle in setContent with request from previous navigation', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content("")); + await networkIdleTest(browser, () => browser.goto(content(""), { waitUntil: 'networkidle' })); + }); + + test('should wait for networkidle in setContent from the child frame', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await networkIdleTest(browser, () => browser.goto(content(""), { waitUntil: 'networkidle' })); + }); + + test('should wait for networkidle from the child frame', async ({ browser }) => { + await networkIdleTest(browser, () => browser.goto('/networkidle-frame.html', { waitUntil: 'networkidle' })); + }); + + test('should wait for networkidle when iframe attaches and detaches', async ({ browser }) => { + let done = false; + const promise = browser.goto(content(` + + + + `), { waitUntil: 'networkidle' }).then(() => (done = true)); + await new Promise((resolve) => setTimeout(resolve, 600)); + expect(done).toBe(false); + await browser.evaluate("() => { document.querySelector('iframe').remove(); }"); + await promise; + expect(done).toBe(true); + }); + + test('should work after repeated navigations in the same page', async ({ browser }) => { + let requestCount = 0; + await browser.route('**/empty.html', (route) => route.fulfill({ + contentType: 'text/html', + body: ` + `, + })); + await browser.route('**/sample', async (route) => { + requestCount++; + await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ content: 'sample' }) }); + }); + await browser.goto(EMPTY_PAGE, { waitUntil: 'networkidle' }); + expect(requestCount).toBe(1); + await browser.goto(EMPTY_PAGE, { waitUntil: 'networkidle' }); + expect(requestCount).toBe(2); + }); + + test('should not wait for an open EventSource connection', async ({ browser }) => { + const page = content(""); + const [response] = await Promise.all([ + browser.waitForResponse('**/content?**'), + browser.goto(page, { waitUntil: 'networkidle' }), + ]); + expect(response.status).toBe(200); + }); + + test('should not wait for an open EventSource connection in setContent', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content(``), { waitUntil: 'networkidle' }); + await browser.evaluate("() => window['__sseOpened'].then(() => null)"); + }); +}); diff --git a/packages/web/tests/parity/tests/page-request-continue.e2e.ts b/packages/web/tests/parity/tests/page-request-continue.e2e.ts new file mode 100644 index 0000000000..6448a17f65 --- /dev/null +++ b/packages/web/tests/parity/tests/page-request-continue.e2e.ts @@ -0,0 +1,429 @@ +/** + * Adapted from microsoft/playwright tests/page/page-request-continue.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: what the server received is what `/cors-echo` answers with. + */ + +/* + * Not ported: + * - should amend binary post data: `route.continue` takes a string `postData`. + * - should work with Cross-Origin-Opener-Policy: needs `page.on('request' | 'response' | 'requestfinished' | 'requestfailed')`. + * - redirected requests should report overridden headers: needs `route.fallback({ headers })` and `response.request()`. + * - postData should return empty string when overriding body with empty string: needs `page.waitForRequest`. + */ + +import { test, type Browser } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { browserName, content, CROSS, PREFIX, e2eGap } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +type Served = { method: string; headers: Record; body: string; url: string }; + +/** A promise with its resolver, for a route handler the test holds open. */ +function deferred(): { promise: Promise; resolve: (value: T) => void } { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +} + +/** The request the server received for the page now open, which `/cors-echo` printed as its text. */ +async function served(browser: Browser): Promise { + return JSON.parse(await browser.evaluate('document.body.textContent')) as Served; +} + +/** The request the server received for a page `fetch` to `url` with `init`, which `/cors-echo` answered with. */ +async function fetched(browser: Browser, url: string, init = '{}'): Promise { + return JSON.parse(await browser.evaluate(`(url) => fetch(url, ${init}).then((response) => response.text())`, url)) as Served; +} + +test.describe('page request continue', { requires: ['browser'] }, () => { + test('should work', async ({ browser }) => { + await browser.route('**/*', (route) => route.continue()); + await browser.goto(EMPTY_PAGE); + }); + + test('should amend HTTP headers', async ({ browser }) => { + await browser.route('**/*', (route) => route.continue({ headers: { ...route.request.headers, FOO: 'bar' } })); + await browser.goto(EMPTY_PAGE); + const request = await fetched(browser, '/cors-echo'); + expect(request.headers['foo']).toBe('bar'); + }); + + test('should not allow to override unsafe HTTP headers', async ({ browser }) => { + await browser.route('**/*', (route) => route.continue({ headers: { ...route.request.headers, host: 'bar', trailer: 'baz' } })); + await browser.goto('/cors-echo'); + const serverRequest = await served(browser); + expect(serverRequest.headers['trailer']).toBe(undefined); + expect(serverRequest.headers['host']).toBe(new URL(EMPTY_PAGE).host); + }); + + test('should delete header with undefined value', async ({ browser }) => { + e2eGap('a header override takes strings only, so `undefined` cannot delete one'); + await browser.goto('/empty.html'); + await browser.route(`${PREFIX}/cors-echo`, (route) => route.continue({ + headers: { ...route.request.headers, foo: undefined } as unknown as Record, + })); + const serverRequest = await fetched(browser, `${PREFIX}/cors-echo`, "{ headers: { foo: 'a', bar: 'b' } }"); + expect(serverRequest.method).toBe('GET'); + expect(serverRequest.headers['foo']).toBeFalsy(); + expect(serverRequest.headers['bar']).toBe('b'); + }); + + test('should amend method', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', (route) => route.continue({ method: 'POST' })); + const request = await fetched(browser, '/cors-echo'); + expect(request.method).toBe('POST'); + }); + + test('should override request url', async ({ browser }) => { + await browser.route('**/foo', (route) => route.continue({ url: `${PREFIX}/global-var.html` })); + const [response] = await Promise.all([browser.waitForResponse(/\/(foo|global-var\.html)$/), browser.goto(`${PREFIX}/foo`)]); + expect(response.url).toBe(`${PREFIX}/global-var.html`); + expect(await browser.evaluate("() => window['globalVar']")).toBe(123); + }); + + test('should not allow changing protocol when overriding url', async ({ browser }) => { + const failed = deferred(); + await browser.route('**/*', async (route) => { + try { + await route.continue({ url: 'file:///tmp/foo' }); + failed.resolve(null); + } catch (caught) { + failed.resolve(caught as Error); + await route.abort(); + } + }); + const navigation = browser.goto(EMPTY_PAGE).catch(() => undefined); + const error = await failed.promise; + expect(error).toBeTruthy(); + expect(error!.message).toMatch(/scheme/); + await navigation; + }); + + test('should not throw if request was cancelled by the page', async ({ browser }) => { + const routed = deferred(); + const release = deferred(); + await browser.route('**/data.json', async (route) => { + routed.resolve(); + await release.promise; + await route.continue(); + }); + await browser.goto(EMPTY_PAGE); + await browser.evaluate(`(url) => { + globalThis.controller = new AbortController(); + globalThis.failure = fetch(url, { signal: globalThis.controller.signal }).then(() => 'loaded', (error) => error.name); + }`, `${PREFIX}/data.json`); + await routed.promise; + expect(await browser.evaluate('() => { globalThis.controller.abort(); return globalThis.failure; }')).toBe('AbortError'); + release.resolve(); + await browser.evaluate('() => new Promise((resolve) => setTimeout(resolve, 100))'); + }); + + test('should override method along with url', async ({ browser }) => { + await browser.route('**/foo', (route) => route.continue({ url: `${PREFIX}/cors-echo`, method: 'POST' })); + await browser.goto(`${PREFIX}/foo`); + expect((await served(browser)).method).toBe('POST'); + }); + + test('should amend method on main request', async ({ browser }) => { + await browser.route('**/*', (route) => route.continue({ method: 'POST' })); + await browser.goto('/cors-echo'); + expect((await served(browser)).method).toBe('POST'); + }); + + test.describe('post data', () => { + test('should amend post data', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', (route) => route.continue({ postData: 'doggo' })); + const serverRequest = await fetched(browser, '/cors-echo', "{ method: 'POST', body: 'birdy' }"); + expect(serverRequest.body).toBe('doggo'); + }); + + test('should compute content-length from post data', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const data = 'a'.repeat(7500); + await browser.route('**/*', (route) => route.continue({ postData: data, headers: { ...route.request.headers, 'content-type': 'application/json' } })); + const serverRequest = await fetched(browser, '/cors-echo', "{ method: 'PATCH', body: 'birdy' }"); + expect(serverRequest.body).toBe(data); + expect(serverRequest.headers['content-length']).toBe(String(data.length)); + expect(serverRequest.headers['content-type']).toBe('application/json'); + }); + + test('should amend method and post data', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', (route) => route.continue({ method: 'POST', postData: 'doggo' })); + const serverRequest = await fetched(browser, '/cors-echo', "{ method: 'GET' }"); + expect(serverRequest.method).toBe('POST'); + expect(serverRequest.body).toBe('doggo'); + }); + + test('should amend utf8 post data', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', (route) => route.continue({ postData: 'пушкин' })); + const serverRequest = await fetched(browser, '/cors-echo', "{ method: 'POST', body: 'birdy' }"); + expect(serverRequest.method).toBe('POST'); + expect(serverRequest.body).toBe('пушкин'); + }); + + test('should amend longer post data', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', (route) => route.continue({ postData: 'doggo-is-longer-than-birdy' })); + const serverRequest = await fetched(browser, '/cors-echo', "{ method: 'POST', body: 'birdy' }"); + expect(serverRequest.method).toBe('POST'); + expect(serverRequest.body).toBe('doggo-is-longer-than-birdy'); + }); + + test('should use content-type from original request', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route(`${PREFIX}/cors-echo`, (route) => route.continue({ postData: '{"b":2}' })); + const request = await fetched(browser, `${PREFIX}/cors-echo`, `{ method: 'POST', body: '{"a":1}', headers: { 'content-type': 'application/json' } }`); + expect(request.headers['content-type']).toBe('application/json'); + expect(request.body).toBe('{"b":2}'); + }); + }); + + test('should not delete the origin header', async ({ browser }) => { + await browser.goto('/empty.html'); + let interceptedOrigin: string | undefined; + await browser.route(`${CROSS}/cors-echo`, async (route) => { + const headers = { ...route.request.headers }; + interceptedOrigin = headers['origin']; + delete headers['origin']; + await route.continue({ headers }); + }); + const serverRequest = await fetched(browser, `${CROSS}/cors-echo`); + expect(serverRequest.method).toBe('GET'); + expect(interceptedOrigin).toEqual(PREFIX); + expect(serverRequest.headers['origin']).toBe(PREFIX); + }); + + test('should continue preload link requests', async ({ browser }) => { + let intercepted = false; + await browser.route('**/one-style.css', async (route) => { + intercepted = true; + await route.continue({ headers: { ...route.request.headers, custom: 'value' } }); + }); + await browser.goto('/preload.html'); + await browser.evaluate('() => new Promise((resolve) => { const check = () => window.preloadedStyles ? resolve(true) : setTimeout(check, 20); check(); })'); + expect(intercepted).toBe(true); + const color = await browser.evaluate('() => window.getComputedStyle(document.body).backgroundColor'); + expect(color).toBe('rgb(255, 192, 203)'); + }); + + test('should respect set-cookie in redirect response', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/bounce?**', (route) => route.continue({ headers: { ...route.request.headers } })); + await browser.goto(`/bounce?cookie=${encodeURIComponent('foo=bar; max-age=36000')}&to=/cors-echo`); + expect((await served(browser)).headers['cookie']).toBe('foo=bar'); + expect(await browser.evaluate('() => document.cookie')).toBe('foo=bar'); + }); + + test('continue should not propagate cookie override to redirects', async ({ browser }) => { + await browser.goto('/set-cookie?cookie=foo=bar;'); + expect(await browser.evaluate('() => document.cookie')).toBe('foo=bar'); + await browser.route('**/redirect?**', (route) => route.continue({ headers: { ...route.request.headers, cookie: 'override' } })); + await browser.goto(`/redirect?to=${encodeURIComponent(`${PREFIX}/cors-echo`)}`); + expect((await served(browser)).headers['cookie']).toBe('foo=bar'); + }); + + test('continue should not override cookie', async ({ browser }) => { + await browser.goto('/set-cookie?cookie=foo=bar;'); + expect(await browser.evaluate('() => document.cookie')).toBe('foo=bar'); + await browser.route('**', (route) => route.continue({ headers: { ...route.request.headers, cookie: 'override', custom: 'value' } })); + await browser.goto('/cors-echo'); + const serverRequest = await served(browser); + expect(serverRequest.headers['cookie']).toBe('foo=bar'); + expect(serverRequest.headers['custom']).toBe('value'); + }); + + test('continue with headers should send fresh cookie from the browser cookie store', async ({ browser }) => { + await browser.goto('/set-cookie?cookie=foo=v1;'); + expect(await browser.evaluate('() => document.cookie')).toBe('foo=v1'); + await browser.route('**/cors-echo', async (route) => { + await browser.setCookies([{ name: 'foo', value: 'v2', url: PREFIX }]); + await route.continue({ headers: route.request.headers }); + }); + await browser.goto('/cors-echo'); + expect((await served(browser)).headers['cookie']).toBe('foo=v2'); + }); + + test('continue with headers should send fresh cookie after a redirect', async ({ browser }) => { + await browser.goto('/set-cookie?cookie=foo=v1;'); + expect(await browser.evaluate('() => document.cookie')).toBe('foo=v1'); + await browser.route('**/bounce?**', (route) => route.continue({ headers: route.request.headers })); + await browser.goto(`/bounce?cookie=${encodeURIComponent('foo=v2;')}&to=${encodeURIComponent(`${PREFIX}/cors-echo`)}`); + expect((await served(browser)).headers['cookie']).toBe('foo=v2'); + }); + + test('redirect after continue should be able to delete cookie', async ({ browser }) => { + await browser.goto('/set-cookie?cookie=foo=bar;'); + expect(await browser.evaluate('() => document.cookie')).toBe('foo=bar'); + await browser.route('**/redirect?**', (route) => route.continue({ headers: { ...route.request.headers } })); + await browser.goto(`/redirect?to=${encodeURIComponent(`/set-cookie?cookie=${encodeURIComponent('foo=bar; expires=Thu, 01 Jan 1970 00:00:00 GMT')}`)}`); + await browser.goto('/cors-echo'); + expect((await served(browser)).headers['cookie']).toBeFalsy(); + }); + + test('continue should propagate headers to redirects', async ({ browser }) => { + await browser.route('**/redirect?**', (route) => route.continue({ headers: { ...route.request.headers, custom: 'value' } })); + await browser.goto('/redirect?to=/cors-echo'); + expect((await served(browser)).headers['custom']).toBe('value'); + }); + + test('continue should drop content-length on redirects', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/redirect?**', (route) => route.continue({ headers: { ...route.request.headers, custom: 'value' } })); + const serverRequest = await fetched(browser, `${PREFIX}/redirect?to=/cors-echo`, "{ method: 'POST', body: 'foo' }"); + expect(serverRequest.method).toBe('GET'); + expect(serverRequest.headers['content-length']).toBeUndefined(); + expect(serverRequest.headers['content-type']).toBeUndefined(); + expect(serverRequest.headers['custom']).toBe('value'); + }); + + test('continue should delete headers on redirects', async ({ browser }) => { + e2eGap('a header override takes strings only, so `undefined` cannot delete one'); + await browser.goto('/empty.html'); + await browser.route('**/redirect?**', (route) => route.continue({ + headers: { ...route.request.headers, foo: undefined } as unknown as Record, + })); + const serverRequest = await fetched(browser, `${PREFIX}/redirect?to=/cors-echo`, "{ headers: { foo: 'a' } }"); + expect(serverRequest.method).toBe('GET'); + expect(serverRequest.headers['foo']).toBeFalsy(); + }); + + test('propagate headers same origin redirect', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.evaluate("() => { document.cookie = 'a=b'; }"); + const serverRequest = await fetched( + browser, + `${PREFIX}/redirect?to=${encodeURIComponent('/cors-echo?preflight')}`, + "{ headers: { authorization: 'credentials', custom: 'foo' }, credentials: 'include' }", + ); + expect(serverRequest.headers['authorization']).toBe('credentials'); + expect(serverRequest.headers['cookie']).toBe('a=b'); + expect(serverRequest.headers['custom']).toBe('foo'); + }); + + test('propagate headers cross origin', async ({ browser }) => { + await browser.goto('/empty.html'); + const serverRequest = await fetched( + browser, + `${CROSS}/cors-echo?preflight`, + "{ headers: { authorization: 'credentials', custom: 'foo' }, credentials: 'include' }", + ); + expect(serverRequest.headers['authorization']).toBe('credentials'); + expect(serverRequest.headers['custom']).toBe('foo'); + }); + + test('propagate headers cross origin redirect', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.evaluate("() => { document.cookie = 'a=b'; }"); + const serverRequest = await fetched( + browser, + `${PREFIX}/bounce?status=301&to=${encodeURIComponent(`${CROSS}/cors-echo?preflight`)}`, + "{ headers: { authorization: 'credentials', custom: 'foo' }, credentials: 'include' }", + ); + expect(serverRequest.headers['authorization']).toBeFalsy(); + expect(serverRequest.headers['cookie']).toBeFalsy(); + expect(serverRequest.headers['custom']).toBe('foo'); + }); + + test('propagate headers cross origin redirect after interception', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.evaluate("() => { document.cookie = 'a=b'; }"); + await browser.route('**/bounce?**', (route) => route.continue({ headers: { ...route.request.headers, authorization: 'credentials', custom: 'foo' } })); + const serverRequest = await fetched( + browser, + `${PREFIX}/bounce?status=301&to=${encodeURIComponent(`${CROSS}/cors-echo?preflight`)}`, + "{ headers: { authorization: 'none' }, credentials: 'include' }", + ); + expect(serverRequest.headers['authorization']).toBe('credentials'); + expect(serverRequest.headers['cookie']).toBeFalsy(); + expect(serverRequest.headers['custom']).toBe('foo'); + }); + + test('continue should pass on 307 cross-origin redirect', async ({ browser }) => { + const final = `${PREFIX}${content('final

ok

')}`; + await browser.goto('/empty.html'); + await browser.goto(content(` +
+ +
`)); + await browser.route('**/*', (route) => route.continue()); + await Promise.all([ + browser.waitForURL(final), + browser.locator('input').tap(), + ]); + await expect(browser.locator('p')).toHaveText('ok'); + }); + + test('should intercept css variable with background url', async ({ browser }) => { + const intercepted = deferred(); + let interceptedRequests = 0; + await browser.route(`${PREFIX}/pptr.png`, async (route) => { + ++interceptedRequests; + intercepted.resolve(); + await route.continue(); + }); + await browser.goto(content(` + +
Yo!
`)); + expect(await browser.locator('div').textContent()).toBe('Yo!'); + await intercepted.promise; + await new Promise((resolve) => setTimeout(resolve, 1000)); + expect(interceptedRequests).toBe(1); + }); + + test('continue should not change multipart/form-data body', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const sendFormData = async (): Promise => { + const [status, body] = await browser.evaluate<[number, string]>(`async () => { + const newFile = new File(['file content'], 'file.txt'); + const formData = new FormData(); + formData.append('file', newFile); + const response = await fetch('/cors-echo', { method: 'POST', credentials: 'include', body: formData }); + return [response.status, (await response.json()).body]; + }`); + expect(status).toBe(200); + return body; + }; + const reqBefore = await sendFormData(); + await browser.route('**/*', (route) => route.continue()); + const reqAfter = await sendFormData(); + const fileContent = [ + 'Content-Disposition: form-data; name="file"; filename="file.txt"', + 'Content-Type: application/octet-stream', + '', + 'file content', + '------'].join('\r\n'); + expect(reqBefore).toContain(fileContent); + expect(reqAfter).toContain(fileContent); + }); + + test('should not forward Host header on cross-origin redirect', async ({ browser }) => { + await browser.route('**/*', async (route) => { + const headers = route.request.headers; + if (browserName === 'firefox') expect(headers).toHaveProperty('host'); + else expect(headers).not.toHaveProperty('host'); + await route.continue({ headers }); + }); + const [response] = await Promise.all([ + browser.waitForResponse('**/cors-echo'), + browser.goto(`${PREFIX}/bounce?to=${encodeURIComponent(`${CROSS}/cors-echo`)}`), + ]); + expect(response.status).toBe(200); + expect((await served(browser)).headers['host']).toBe(new URL(CROSS).host); + }); +}); diff --git a/packages/web/tests/parity/tests/page-request-fallback.e2e.ts b/packages/web/tests/parity/tests/page-request-fallback.e2e.ts new file mode 100644 index 0000000000..a2941bc0c1 --- /dev/null +++ b/packages/web/tests/parity/tests/page-request-fallback.e2e.ts @@ -0,0 +1,93 @@ +/** + * Adapted from microsoft/playwright tests/page/page-request-fallback.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: a navigation's response is the one `browser.waitForResponse` sees. + */ + +/* + * Not ported: + * - should chain once: needs `route(..., { times })`. + * - should amend HTTP headers: needs `route.fallback({ headers })`. + * - should delete header with undefined value: needs `route.fallback({ headers })`. + * - should amend method: needs `route.fallback({ method })` and `page.waitForRequest`. + * - should override request url: needs `route.fallback({ url })`. + * - post data / should amend post data: needs `route.fallback({ postData })`. + * - post data / should amend binary post data: needs `route.fallback({ postData })` and `request.postDataBuffer()`. + * - post data / should amend json post data: needs `route.fallback({ postData })` and `request.postDataJSON()`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { PREFIX } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +test.describe('page request fallback', { requires: ['browser'] }, () => { + test('should work', async ({ browser }) => { + await browser.route('**/*', (route) => route.fallback()); + await browser.goto(EMPTY_PAGE); + }); + + test('should fall back', async ({ browser }) => { + const intercepted: number[] = []; + for (const index of [1, 2, 3]) { + await browser.route('**/empty.html', async (route) => { + intercepted.push(index); + await route.fallback(); + }); + } + await browser.goto(EMPTY_PAGE); + expect(intercepted).toEqual([3, 2, 1]); + }); + + test('should fall back async', async ({ browser }) => { + const intercepted: number[] = []; + for (const index of [1, 2, 3]) { + await browser.route('**/empty.html', async (route) => { + intercepted.push(index); + await new Promise((resolve) => setTimeout(resolve, 100)); + await route.fallback(); + }); + } + await browser.goto(EMPTY_PAGE); + expect(intercepted).toEqual([3, 2, 1]); + }); + + test('should not chain fulfill', async ({ browser }) => { + let failed = false; + await browser.route('**/empty.html', async (route) => { + failed = true; + await route.continue(); + }); + await browser.route('**/empty.html', (route) => route.fulfill({ status: 200, body: 'fulfilled' })); + await browser.route('**/empty.html', (route) => route.fallback()); + const [response] = await Promise.all([browser.waitForResponse('**/empty.html'), browser.goto(EMPTY_PAGE)]); + expect(await response.text()).toEqual('fulfilled'); + expect(failed).toBeFalsy(); + }); + + test('should not chain abort', async ({ browser }) => { + let failed = false; + await browser.route('**/empty.html', async (route) => { + failed = true; + await route.continue(); + }); + await browser.route('**/empty.html', (route) => route.abort()); + await browser.route('**/empty.html', (route) => route.fallback()); + const e = await browser.goto(EMPTY_PAGE).catch((caught: Error) => caught); + expect(e).toBeTruthy(); + expect(failed).toBeFalsy(); + }); + + test('should fall back after exception', async ({ browser }) => { + await browser.route('**/empty.html', (route) => route.continue()); + await browser.route('**/empty.html', async (route) => { + try { + await route.fulfill({ response: {} } as never); + } catch { + await route.fallback(); + } + }); + await browser.goto(EMPTY_PAGE); + }); +}); diff --git a/packages/web/tests/parity/tests/page-request-fulfill.e2e.ts b/packages/web/tests/parity/tests/page-request-fulfill.e2e.ts new file mode 100644 index 0000000000..a32fd1c476 --- /dev/null +++ b/packages/web/tests/parity/tests/page-request-fulfill.e2e.ts @@ -0,0 +1,241 @@ +/** + * Adapted from microsoft/playwright tests/page/page-request-fulfill.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: a navigation's response is the one `browser.waitForResponse` sees. + */ + +/* + * Not ported: + * - should work with buffer as body: `route.fulfill` takes a string body. + * - should allow mocking binary responses: needs a Buffer body and `toMatchSnapshot`. + * - should fulfill with global fetch result: needs `playwright.request` and `fulfill({ response })`. + * - should fulfill with fetch result: needs `page.request` and `fulfill({ response })`. + * - should fulfill with fetch result and overrides: needs `page.request` and `fulfill({ response })`. + * - headerValue should return set-cookie from intercepted response: expected to fail on Chromium, and e2e has no `test.fail`. + * - should fulfill with har response: HAR. + * - should fulfill with gzip and readback: needs a gzip server and `fulfill({ response })`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, CROSS, PREFIX, e2eGap } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +/** A promise with its resolver, for a route handler the test holds open. */ +function deferred(): { promise: Promise; resolve: (value: T) => void } { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +} + +/** Polls the page until `expression` is truthy, Playwright's `page.waitForFunction`. */ +const waitForFunction = (expression: string): string => + `() => new Promise((resolve) => { const check = () => (${expression}) ? resolve(true) : setTimeout(check, 20); check(); })`; + +test.describe('page request fulfill', { requires: ['browser'] }, () => { + test('should work', async ({ browser }) => { + await browser.route('**/*', (route) => route.fulfill({ status: 201, headers: { foo: 'bar' }, contentType: 'text/html', body: 'Yo, page!' })); + const [response] = await Promise.all([browser.waitForResponse('**/empty.html'), browser.goto(EMPTY_PAGE)]); + expect(response.status).toBe(201); + expect(response.headers['foo']).toBe('bar'); + expect(await browser.evaluate('() => document.body.textContent')).toBe('Yo, page!'); + }); + + test('should work with status code 422', async ({ browser }) => { + await browser.route('**/*', (route) => route.fulfill({ status: 422, body: 'Yo, page!' })); + const [response] = await Promise.all([browser.waitForResponse('**/empty.html'), browser.goto(EMPTY_PAGE)]); + expect(response.status).toBe(422); + expect(await browser.evaluate('() => document.body.textContent')).toBe('Yo, page!'); + }); + + test('should fulfill with unuassigned status codes', async ({ browser }) => { + const fulfilled = deferred(); + await browser.route('**/data.json', async (route) => { + fulfilled.resolve(await route.fulfill({ status: 430, body: 'Yo, page!' }).then(() => undefined, (caught: Error) => caught)); + }); + await browser.goto(EMPTY_PAGE); + const response = await browser.evaluate<{ status: number; statusText: string }, string>( + 'async (url) => { const { status, statusText } = await fetch(url); return { status, statusText }; }', + `${PREFIX}/data.json`, + ); + const error = await fulfilled.promise; + expect(error).toBe(undefined); + expect(response.status).toBe(430); + expect(response.statusText).toBe('Unknown'); + }); + + test('should not throw if request was cancelled by the page', async ({ browser }) => { + const routed = deferred(); + const release = deferred(); + await browser.route('**/data.json', async (route) => { + routed.resolve(); + await release.promise; + await route.fulfill({ status: 200 }); + }); + await browser.goto(EMPTY_PAGE); + await browser.evaluate(`(url) => { + globalThis.controller = new AbortController(); + globalThis.failure = fetch(url, { signal: globalThis.controller.signal }).then(() => 'loaded', (error) => error.name); + }`, `${PREFIX}/data.json`); + await routed.promise; + expect(await browser.evaluate('() => { globalThis.controller.abort(); return globalThis.failure; }')).toBe('AbortError'); + release.resolve(); + await browser.evaluate('() => new Promise((resolve) => setTimeout(resolve, 100))'); + }); + + test('should allow mocking svg with charset', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', (route) => route.fulfill({ + contentType: 'image/svg+xml ; charset=utf-8', + body: '', + })); + const size = await browser.evaluate(`(PREFIX) => { + const img = document.createElement('img'); + img.src = PREFIX + '/does-not-exist.svg'; + document.body.appendChild(img); + return new Promise((resolve, reject) => { img.onload = () => resolve([img.naturalWidth, img.naturalHeight]); img.onerror = reject; }); + }`, PREFIX); + expect(size).toEqual([50, 50]); + }); + + test('should work with file path', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', (route) => route.fulfill({ contentType: 'shouldBeIgnored', path: 'assets/pptr.png' })); + const size = await browser.evaluate(`(PREFIX) => { + const img = document.createElement('img'); + img.src = PREFIX + '/does-not-exist.png'; + document.body.appendChild(img); + return new Promise((resolve) => { img.onload = () => resolve([img.naturalWidth, img.naturalHeight]); }); + }`, PREFIX); + expect(size).toEqual([69, 100]); + }); + + test('should stringify intercepted request response headers', async ({ browser }) => { + await browser.route('**/*', (route) => route.fulfill({ status: 200, headers: { foo: 'true' }, body: 'Yo, page!' })); + const [response] = await Promise.all([browser.waitForResponse('**/empty.html'), browser.goto(EMPTY_PAGE)]); + expect(response.status).toBe(200); + expect(response.headers['foo']).toBe('true'); + expect(await browser.evaluate('() => document.body.textContent')).toBe('Yo, page!'); + }); + + test('should not modify the headers sent to the server', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.route(`${PREFIX}/unused`, (route) => route.continue()); + const fetchServed = 'async (url) => { const data = await fetch(url); return data.text(); }'; + const served = await browser.evaluate(fetchServed, `${CROSS}/cors-echo`); + const before = JSON.parse(served) as { method: string; headers: Record }; + expect(before.method).toBe('GET'); + + await browser.route(`${CROSS}/cors-echo`, (route) => route.continue({ headers: { ...route.request.headers } })); + const servedAfterRoute = await browser.evaluate(fetchServed, `${CROSS}/cors-echo`); + const after = JSON.parse(servedAfterRoute) as { method: string; headers: Record }; + expect(after.method).toBe('GET'); + expect(after.headers).toEqual(before.headers); + }); + + test('should include the origin header', async ({ browser }) => { + await browser.goto('/empty.html'); + let origin: string | undefined; + await browser.route(`${CROSS}/something`, async (route) => { + origin = route.request.headers['origin']; + await route.fulfill({ headers: { 'Access-Control-Allow-Origin': '*' }, contentType: 'text/plain', body: 'done' }); + }); + const text = await browser.evaluate('async (url) => { const data = await fetch(url); return data.text(); }', `${CROSS}/something`); + expect(text).toBe('done'); + expect(origin).toEqual(PREFIX); + }); + + test('should fetch original request and fulfill', async ({ browser }) => { + await browser.route('**/*', async (route) => { + const response = await route.fetch(); + await route.fulfill({ status: response.status, headers: { ...response.headers }, body: await response.text() }); + }); + const [response] = await Promise.all([browser.waitForResponse('**/title.html'), browser.goto('/title.html')]); + expect(response.status).toBe(200); + expect(await browser.title()).toEqual('Woof-Woof'); + }); + + test('should fulfill with multiple set-cookie', async ({ browser }) => { + e2eGap('a header value cannot hold a newline, so a fulfilled response sets one cookie'); + const cookies = ['a=b', 'c=d']; + await browser.route('**/multiple-set-cookie.html', (route) => route.fulfill({ + status: 200, + headers: { 'X-Header-1': 'v1', 'Set-Cookie': cookies.join('\n'), 'X-Header-2': 'v2' }, + body: '', + })); + const [response] = await Promise.all([ + browser.waitForResponse('**/multiple-set-cookie.html'), + browser.goto('/multiple-set-cookie.html'), + ]); + const cookie = await browser.evaluate('() => document.cookie'); + expect(cookie.split(';').map((s) => s.trim()).toSorted()).toEqual(cookies); + expect(response.headers['x-header-1']).toBe('v1'); + expect(response.headers['x-header-2']).toBe('v2'); + }); + + test('should fulfill with fetch response that has multiple set-cookie', async ({ browser }) => { + e2eGap('a header value cannot hold a newline, so a fulfilled response sets one cookie'); + await browser.route('**/respond?*', async (route) => { + const response = await route.fetch(); + await route.fulfill({ status: response.status, headers: { ...response.headers }, body: await response.text() }); + }); + const headers = JSON.stringify({ 'set-cookie': ['a=b', 'c=d'], 'content-type': 'text/html' }); + await browser.goto(`/respond?headers=${encodeURIComponent(headers)}`); + const cookie = await browser.evaluate('() => document.cookie'); + expect(cookie.split(';').map((s) => s.trim()).toSorted()).toEqual(['a=b', 'c=d']); + }); + + test('should fulfill preload link requests', async ({ browser }) => { + let intercepted = false; + await browser.route('**/one-style.css', async (route) => { + intercepted = true; + await route.fulfill({ + status: 200, + headers: { 'content-type': 'text/css; charset=utf-8', 'cache-control': 'no-cache, no-store', custom: 'value' }, + body: 'body { background-color: green; }', + }); + }); + const [response] = await Promise.all([browser.waitForResponse('**/one-style.css'), browser.goto('/preload.html')]); + expect(response.headers['custom']).toBe('value'); + await browser.evaluate(waitForFunction('window.preloadedStyles')); + expect(intercepted).toBe(true); + const color = await browser.evaluate('() => window.getComputedStyle(document.body).backgroundColor'); + expect(color).toBe('rgb(0, 128, 0)'); + }); + + test('should fulfill json', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/data.json', (route) => route.fulfill({ status: 201, headers: { foo: 'bar' }, json: { bar: 'baz' } })); + const [response, body] = await Promise.all([ + browser.waitForResponse('**/*'), + browser.evaluate("() => fetch('./data.json').then((r) => r.text())"), + ]); + expect(response.status).toBe(201); + expect(response.headers['content-type']).toBe('application/json'); + expect(body).toBe(JSON.stringify({ bar: 'baz' })); + }); + + test('should not go to the network for fulfilled requests body', async ({ browser }) => { + const key = `fulfilled-${Date.now()}-${Math.random()}`; + await browser.route(`**/count?key=${key}`, (route) => route.fulfill({ status: 404, contentType: 'text/plain', body: 'Not Found! (mocked)' })); + const [response] = await Promise.all([ + browser.waitForResponse(`**/count?key=${key}`), + browser.goto(content(`
hello, world!
`)), + ]); + expect(await response.text()).toBe('Not Found! (mocked)'); + await browser.unrouteAll(); + const serverHits = await browser.evaluate("(key) => fetch('/count?key=' + key).then((r) => r.text())", key); + expect(serverHits).toBe('11'); + }); + + test('should return body for fulfilled responses', async ({ browser }) => { + for (const status of [100, 200, 404, 500]) { + const bodyOverride = `Custom body ${status}`; + await browser.route('**/one-style.css', (route) => route.fulfill({ status, contentType: 'text/plain', body: bodyOverride })); + const [response] = await Promise.all([browser.waitForResponse('**/one-style.css'), browser.goto('/one-style.html')]); + expect(await response.text()).toBe(bodyOverride); + await browser.unrouteAll(); + } + }); +}); diff --git a/packages/web/tests/parity/tests/page-route.e2e.ts b/packages/web/tests/parity/tests/page-route.e2e.ts new file mode 100644 index 0000000000..f9997f2736 --- /dev/null +++ b/packages/web/tests/parity/tests/page-route.e2e.ts @@ -0,0 +1,655 @@ +/** + * Adapted from microsoft/playwright tests/page/page-route.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: a navigation's response is the one `browser.waitForResponse` sees. + */ + +/* + * Not ported: + * - should show custom HTTP headers: needs `page.setExtraHTTPHeaders`. + * - should work with custom referer headers: needs `page.setExtraHTTPHeaders`. + * - should send referer: needs `page.setExtraHTTPHeaders`. + * - should be abortable with custom error codes: needs `route.abort(errorCode)` and `requestfailed`. + * - should chain fallback w/ dynamic URL: needs `route.fallback({ url })`. + * - should not fulfill with redirect status: WebKit only. + * - should support the times parameter with route matching: needs `route(..., { times })`. + * - should work if handler with times parameter was removed from another handler: needs `route(..., { times })`. + * - should support async handler w/ times: needs `route(..., { times })`. + * - route abort with times: 1 should not affect second sequential fetch: needs `route(..., { times })` and `route.abort(errorCode)`. + * - should contain sec-fetch headers in route: needs `request.allHeaders()`, and fails on Chromium by design. + * - should contain raw response header: needs `request.response()`. + * - should contain raw response header after fulfill: needs `request.response()`. + * - should be able to intercept every navigation to a page controlled by service worker: service workers. + * - should respect URLPattern ignoreCase: `route` takes a glob or RegExp, not a URLPattern. + */ + +import { test, type WebRoute } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { browserName, content, CROSS, PREFIX, e2eGap } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +/** A promise with its resolver, for a route handler the test holds open. */ +function deferred(): { promise: Promise; resolve: (value: T) => void } { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +} + +test.describe('page route', { requires: ['browser'] }, () => { + test('should intercept @smoke', async ({ browser }) => { + let intercepted = false; + await browser.route('**/empty.html', async (route) => { + expect(route.request.url).toContain('empty.html'); + expect(route.request.headers['user-agent']).toBeTruthy(); + expect(route.request.method).toBe('GET'); + expect(route.request.postData).toBe(undefined); + await route.continue(); + intercepted = true; + }); + const [response] = await Promise.all([browser.waitForResponse('**/empty.html'), browser.goto(EMPTY_PAGE)]); + expect(response.status).toBe(200); + expect(intercepted).toBe(true); + }); + + test('should unroute', async ({ browser }) => { + let intercepted: number[] = []; + await browser.route('**/*', async (route) => { + intercepted.push(1); + await route.fallback(); + }); + await browser.route('**/empty.html', async (route) => { + intercepted.push(2); + await route.fallback(); + }); + await browser.route('**/empty.html', async (route) => { + intercepted.push(3); + await route.fallback(); + }); + await browser.route(/empty.html/, async (route) => { + intercepted.push(4); + await route.fallback(); + }); + await browser.goto(EMPTY_PAGE); + expect(intercepted).toEqual([4, 3, 2, 1]); + + intercepted = []; + await browser.unroute(/empty.html/); + await browser.goto(EMPTY_PAGE); + expect(intercepted).toEqual([3, 2, 1]); + + intercepted = []; + await browser.unroute('**/empty.html'); + await browser.goto(EMPTY_PAGE); + expect(intercepted).toEqual([1]); + }); + + test('should not support ? in glob pattern', async ({ browser }) => { + e2eGap('`?` in a route glob matches one character, where Playwright reads it literally'); + await browser.route(/\/index/, async (route) => { + const { pathname, search } = new URL(route.request.url); + const body = { '/index': 'index-no-hello', '/index123hello': 'index123hello', '/index1hello': 'index1hello' }[pathname] ?? `${pathname.slice(1)}${search}`; + await route.fulfill({ body, contentType: 'text/html' }); + }); + await browser.route('**/index?hello', (route) => route.fulfill({ body: 'intercepted any character' })); + await browser.route('**/index\\?hello', (route) => route.fulfill({ body: 'intercepted question mark' })); + + await browser.goto(`${PREFIX}/index?hello`); + expect(await browser.evaluate('document.documentElement.outerHTML')).toContain('intercepted question mark'); + + await browser.goto(`${PREFIX}/index`); + expect(await browser.evaluate('document.documentElement.outerHTML')).toContain('index-no-hello'); + + await browser.goto(`${PREFIX}/index1hello`); + expect(await browser.evaluate('document.documentElement.outerHTML')).toContain('index1hello'); + + await browser.goto(`${PREFIX}/index123hello`); + expect(await browser.evaluate('document.documentElement.outerHTML')).toContain('index123hello'); + }); + + test('should work when POST is redirected with 302', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', (route) => route.continue()); + await browser.goto(content(` +
+ +
+ `)); + await Promise.all([ + browser.evaluate("() => { document.querySelector('form').submit(); }"), + browser.waitForURL('/empty.html'), + ]); + }); + + test('should work when header manipulation headers with redirect', async ({ browser }) => { + await browser.route('**/*', (route) => route.continue({ headers: { ...route.request.headers, foo: 'bar' } })); + await browser.goto('/redirect?to=/empty.html'); + }); + + test('should be able to remove headers', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', async (route) => { + const headers = { ...route.request.headers }; + delete headers['foo']; + await route.continue({ headers }); + }); + const served = await browser.evaluate<{ headers: Record }, string>( + "(url) => fetch(url, { headers: { foo: 'bar' } }).then((response) => response.json())", + `${PREFIX}/cors-echo`, + ); + expect(served.headers['foo']).toBe(undefined); + }); + + test('should contain referer header', async ({ browser }) => { + const requests: WebRoute['request'][] = []; + await browser.route('**/*', async (route) => { + requests.push(route.request); + await route.continue(); + }); + await browser.goto('/one-style.html'); + expect(requests[1]!.url).toContain('/one-style.css'); + expect(requests[1]!.headers['referer']).toContain('/one-style.html'); + }); + + test('should properly return navigation response when URL has cookies', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.setCookies([{ url: EMPTY_PAGE, name: 'foo', value: 'bar' }]); + await browser.route('**/*', (route) => route.continue()); + const [response] = await Promise.all([browser.waitForResponse('**/empty.html'), browser.reload()]); + expect(response.status).toBe(200); + }); + + test('should not override cookie header', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.evaluate("() => { document.cookie = 'original=value'; }"); + let cookieValueInRoute: string | undefined; + await browser.route('**', async (route) => { + const headers = { ...route.request.headers }; + cookieValueInRoute = headers['cookie']; + headers['cookie'] = 'overridden=value'; + await route.continue({ headers }); + }); + await browser.goto('/cors-echo'); + const served = JSON.parse(await browser.evaluate('document.body.textContent')) as { headers: Record }; + expect(cookieValueInRoute).toBe('original=value'); + expect(served.headers['cookie']).toBe('original=value'); + }); + + test('should work with redirect inside sync XHR', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + let continued = false; + await browser.route('**/*', async (route) => { + await route.continue(); + continued = true; + }); + const status = await browser.evaluate(`() => { + const request = new XMLHttpRequest(); + request.open('GET', '/redirect?to=/pptr.png', false); + request.send(null); + return request.status; + }`); + expect(status).toBe(200); + expect(continued).toBe(true); + }); + + test('should pause intercepted XHR until continue', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const routed = deferred(); + const release = deferred(); + await browser.route('**/global-var.html', async (route) => { + routed.resolve(); + await release.promise; + await route.continue(); + }); + let xhrFinished = false; + const statusPromise = browser.evaluate(`() => { + const request = new XMLHttpRequest(); + request.open('GET', '/global-var.html', false); + request.send(null); + return request.status; + }`).then((status) => { + xhrFinished = true; + return status; + }); + await routed.promise; + await new Promise((resolve) => setTimeout(resolve, 500)); + expect(xhrFinished).toBe(false); + release.resolve(); + expect(await statusPromise).toBe(200); + }); + + test('should pause intercepted fetch request until continue', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const routed = deferred(); + const release = deferred(); + await browser.route('**/global-var.html', async (route) => { + routed.resolve(); + await release.promise; + await route.continue(); + }); + let fetchFinished = false; + const statusPromise = browser.evaluate("async () => (await fetch('/global-var.html')).status").then((status) => { + fetchFinished = true; + return status; + }); + await routed.promise; + await new Promise((resolve) => setTimeout(resolve, 500)); + expect(fetchFinished).toBe(false); + release.resolve(); + expect(await statusPromise).toBe(200); + }); + + test('should be abortable', async ({ browser }) => { + await browser.route(/\.css$/, (route) => route.abort()); + const [response] = await Promise.all([browser.waitForResponse('**/one-style.html'), browser.goto('/one-style.html')]); + expect(response.status).toBe(200); + expect(await browser.evaluate('getComputedStyle(document.body).backgroundColor')).not.toBe('rgb(255, 192, 203)'); + }); + + test('should not throw if request was cancelled by the page', async ({ browser }) => { + const routed = deferred(); + const release = deferred(); + await browser.route('**/data.json', async (route) => { + routed.resolve(); + await release.promise; + await route.abort(); + }); + await browser.goto(EMPTY_PAGE); + await browser.evaluate(`(url) => { + globalThis.controller = new AbortController(); + globalThis.failure = fetch(url, { signal: globalThis.controller.signal }).then(() => 'loaded', (error) => error.name); + }`, `${PREFIX}/data.json`); + await routed.promise; + expect(await browser.evaluate('() => { globalThis.controller.abort(); return globalThis.failure; }')).toBe('AbortError'); + release.resolve(); + await browser.evaluate('() => new Promise((resolve) => setTimeout(resolve, 100))'); + }); + + test('should fail navigation when aborting main resource', async ({ browser }) => { + await browser.route('**/*', (route) => route.abort()); + const error = await browser.goto(EMPTY_PAGE).catch((caught: Error) => caught); + expect(error).toBeTruthy(); + if (browserName === 'firefox') expect((error as Error).message).toContain('NS_ERROR_FAILURE'); + else expect((error as Error).message).toContain('net::ERR_FAILED'); + }); + + test('should not work with redirects', async ({ browser }) => { + const intercepted: WebRoute['request'][] = []; + await browser.route('**/*', async (route) => { + await route.continue(); + intercepted.push(route.request); + }); + const chain = ['/non-existing-page.html', '/non-existing-page-2.html', '/non-existing-page-3.html', '/non-existing-page-4.html']; + const start = chain.reduceRight((to, from) => `/redirect?from=${from}&to=${encodeURIComponent(to)}`, '/empty.html'); + const [response] = await Promise.all([browser.waitForResponse('**/empty.html'), browser.goto(start)]); + expect(response.status).toBe(200); + expect(response.url).toContain('empty.html'); + + expect(intercepted.length).toBe(1); + expect(intercepted[0]!.url).toContain('/non-existing-page.html'); + }); + + test('should work with redirects for subresources', async ({ browser }) => { + const intercepted: WebRoute['request'][] = []; + await browser.route('**/*', async (route) => { + await route.continue(); + intercepted.push(route.request); + }); + const chain = ['/one-style.css', '/two-style.css', '/three-style.css']; + const stylesheet = chain.reduceRight((to, from) => `/redirect?from=${from}&to=${encodeURIComponent(to)}`, '/one-style.css'); + const page = content(`
hello, world!
`); + const [response] = await Promise.all([browser.waitForResponse('**/content?**'), browser.goto(page)]); + expect(response.status).toBe(200); + expect(response.url).toContain('/content?'); + + expect(intercepted.length).toBe(2); + expect(intercepted[0]!.url).toContain('/content?'); + expect(intercepted[1]!.url).toContain('/one-style.css'); + }); + + test('should work with equal requests', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const key = `equal-${Date.now()}-${Math.random()}`; + let spinner = false; + await browser.route('**/*', async (route) => { + await (spinner ? route.abort() : route.continue()); + spinner = !spinner; + }); + const results = []; + for (let i = 0; i < 3; i++) { + results.push(await browser.evaluate("(key) => fetch('/count?key=' + key).then((response) => response.text()).catch(() => 'FAILED')", key)); + } + expect(results).toEqual(['11', 'FAILED', '22']); + }); + + test('should navigate to dataURL and not fire dataURL requests', async ({ browser }) => { + e2eGap('`goto` refuses `data:` URLs (POLICY_DENIED)'); + const requests: WebRoute['request'][] = []; + await browser.route('**/*', async (route) => { + requests.push(route.request); + await route.continue(); + }); + await browser.goto('data:text/html,
yo
'); + expect(requests.length).toBe(0); + }); + + test('should be able to fetch dataURL and not fire dataURL requests', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const requests: WebRoute['request'][] = []; + await browser.route('**/*', async (route) => { + requests.push(route.request); + await route.continue(); + }); + const text = await browser.evaluate('(url) => fetch(url).then((response) => response.text())', 'data:text/html,
yo
'); + expect(text).toBe('
yo
'); + expect(requests.length).toBe(0); + }); + + test('should navigate to URL with hash and and fire requests without hash', async ({ browser }) => { + const requests: WebRoute['request'][] = []; + await browser.route('**/*', async (route) => { + requests.push(route.request); + await route.continue(); + }); + const [response] = await Promise.all([browser.waitForResponse('**/empty.html'), browser.goto(`${EMPTY_PAGE}#hash`)]); + expect(response.status).toBe(200); + expect(response.url).toBe(EMPTY_PAGE); + expect(requests.length).toBe(1); + expect(requests[0]!.url).toBe(EMPTY_PAGE); + }); + + test('should work with encoded server', async ({ browser }) => { + await browser.route('**/*', (route) => route.continue()); + const [response] = await Promise.all([browser.waitForResponse(/nonexisting/), browser.goto(`${PREFIX}/some nonexisting page`)]); + expect(response.status).toBe(404); + }); + + test('should work with badly encoded server', async ({ browser }) => { + await browser.route('**/*', (route) => route.continue()); + const [response] = await Promise.all([browser.waitForResponse(/rnd=/), browser.goto(`${PREFIX}/status?rnd=%911`)]); + expect(response.status).toBe(200); + }); + + test('should work with encoded server - 2', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const requests: WebRoute['request'][] = []; + await browser.route('**/*', async (route) => { + await route.continue(); + if (!route.request.url.includes('/content?')) requests.push(route.request); + }); + const [response] = await Promise.all([ + browser.waitForResponse(/\/fonts\?/), + browser.goto(content(``)), + ]); + expect(requests.length).toBe(1); + expect(response.status).toBe(404); + }); + + test('should not throw "Invalid Interception Id" if the request was cancelled', async ({ browser }) => { + await browser.goto(content('')); + const routed = deferred(); + const release = deferred(); + await browser.route('**/*', async (route) => { + routed.resolve(); + await release.promise; + await route.continue(); + }); + await browser.evaluate("(url) => { document.querySelector('iframe').src = url; }", EMPTY_PAGE); + await routed.promise; + await browser.evaluate("() => document.querySelector('iframe').remove()"); + release.resolve(); + await browser.evaluate('() => new Promise((resolve) => setTimeout(resolve, 100))'); + }); + + test('should intercept main resource during cross-process navigation', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + let intercepted = false; + await browser.route(`${CROSS}/empty.html`, async (route) => { + intercepted = true; + await route.continue(); + }); + const [response] = await Promise.all([browser.waitForResponse(`${CROSS}/empty.html`), browser.goto(`${CROSS}/empty.html`)]); + expect(response.status).toBe(200); + expect(intercepted).toBe(true); + }); + + test('should fulfill with redirect status', async ({ browser }) => { + await browser.goto('/title.html'); + await browser.route('**/*', async (route) => { + if (route.request.url !== `${PREFIX}/redirect_this`) return route.continue(); + await route.fulfill({ status: 301, headers: { location: '/status?body=foo' } }); + }); + const text = await browser.evaluate('async (url) => (await fetch(url)).text()', `${PREFIX}/redirect_this`); + expect(text).toBe('foo'); + }); + + test('should support cors with GET', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/cars*', async (route) => { + const headers = { 'access-control-allow-origin': route.request.url.endsWith('allow') ? '*' : 'none' }; + await route.fulfill({ contentType: 'application/json', headers, status: 200, body: JSON.stringify(['electric', 'gas']) }); + }); + const resp = await browser.evaluate("async () => (await fetch('https://example.com/cars?allow', { mode: 'cors' })).json()"); + expect(resp).toEqual(['electric', 'gas']); + const error = await browser.evaluate("async () => (await fetch('https://example.com/cars?reject', { mode: 'cors' })).json()").catch((caught: Error) => caught); + if (browserName === 'chromium') expect((error as Error).message).toContain('Failed'); + if (browserName === 'firefox') expect((error as Error).message).toContain('NetworkError'); + }); + + test('should add Access-Control-Allow-Origin by default when fulfill', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/cars', (route) => route.fulfill({ contentType: 'application/json', status: 200, body: JSON.stringify(['electric', 'gas']) })); + const [result, response] = await Promise.all([ + browser.evaluate(`async () => { + const response = await fetch('https://example.com/cars', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + mode: 'cors', + body: JSON.stringify({ number: 1 }), + }); + return response.json(); + }`), + browser.waitForResponse('https://example.com/cars'), + ]); + expect(result).toEqual(['electric', 'gas']); + expect(response.headers['access-control-allow-origin']).toBe(PREFIX); + }); + + test('should allow null origin for about:blank', async ({ browser }) => { + e2eGap('there is no page before the first `goto`, so no `about:blank` origin to fetch from'); + await browser.route('**/something', (route) => route.fulfill({ contentType: 'text/plain', status: 200, body: 'done' })); + const [response, text] = await Promise.all([ + browser.waitForResponse(`${CROSS}/something`), + browser.evaluate(`async (url) => { + const data = await fetch(url, { method: 'GET', headers: { 'X-PINGOTHER': 'pingpong' } }); + return data.text(); + }`, `${CROSS}/something`), + ]); + expect(text).toBe('done'); + expect(response.headers['access-control-allow-origin']).toBe('null'); + }); + + test('should respect cors overrides', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/something', (route) => route.fulfill({ + contentType: 'text/plain', + status: 200, + headers: { 'Access-Control-Allow-Origin': 'http://non-existent' }, + body: 'done', + })); + const error = await browser.evaluate(`async (url) => { + const data = await fetch(url, { method: 'GET', headers: { 'X-PINGOTHER': 'pingpong' } }); + return data.text(); + }`, `${CROSS}/something`).catch((caught: Error) => caught); + if (browserName === 'chromium') expect((error as Error).message).toContain('Failed to fetch'); + else expect((error as Error).message).toContain('NetworkError when attempting to fetch resource.'); + }); + + test('should not auto-intercept non-preflight OPTIONS without network interception', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const key = `options-${Date.now()}-${Math.random()}`; + const [text1, text2] = await browser.evaluate(`async (url) => { + const response1 = await fetch(url, { method: 'OPTIONS' }); + const text1 = await response1.text(); + const response2 = await fetch(url, { method: 'GET' }); + const text2 = await response2.text(); + return [text1, text2]; + }`, `${CROSS}/options?key=${key}`); + expect(text1).toBe('Hello'); + expect(text2).toBe('World'); + expect(await browser.evaluate('(key) => fetch(`/options-log?key=${key}`).then((response) => response.json())', key)).toEqual(['OPTIONS:/options', 'OPTIONS:/options', 'GET:/options']); + }); + + test('should not auto-intercept non-preflight OPTIONS with network interception', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const key = `options-${Date.now()}-${Math.random()}`; + await browser.route('**/options?*', (route) => route.continue()); + const [text1, text2] = await browser.evaluate(`async (url) => { + const response1 = await fetch(url, { method: 'OPTIONS' }); + const text1 = await response1.text(); + const response2 = await fetch(url, { method: 'GET' }); + const text2 = await response2.text(); + return [text1, text2]; + }`, `${CROSS}/options?key=${key}`); + expect(text1).toBe('Hello'); + expect(text2).toBe('World'); + const requests = await browser.evaluate('(key) => fetch(`/options-log?key=${key}`).then((response) => response.json())', key); + if (browserName === 'chromium') expect(requests).toEqual(['OPTIONS:/options', 'GET:/options']); + else expect(requests).toEqual(['OPTIONS:/options', 'OPTIONS:/options', 'GET:/options']); + }); + + test('should support cors with POST', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/cars', (route) => route.fulfill({ + contentType: 'application/json', + headers: { 'Access-Control-Allow-Origin': '*' }, + status: 200, + body: JSON.stringify(['electric', 'gas']), + })); + const resp = await browser.evaluate(`async () => { + const response = await fetch('https://example.com/cars', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + mode: 'cors', + body: JSON.stringify({ number: 1 }), + }); + return response.json(); + }`); + expect(resp).toEqual(['electric', 'gas']); + }); + + test('should support cors with credentials', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/cars', (route) => route.fulfill({ + contentType: 'application/json', + headers: { 'Access-Control-Allow-Origin': PREFIX, 'Access-Control-Allow-Credentials': 'true' }, + status: 200, + body: JSON.stringify(['electric', 'gas']), + })); + const resp = await browser.evaluate(`async () => { + const response = await fetch('https://example.com/cars', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + mode: 'cors', + body: JSON.stringify({ number: 1 }), + credentials: 'include', + }); + return response.json(); + }`); + expect(resp).toEqual(['electric', 'gas']); + }); + + test('should not abort preflighted cross-origin redirect when a route is registered', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/never-matches', (route) => route.continue()); + const result = await browser.evaluate(`async (url) => { + const response = await fetch(url, { credentials: 'include', headers: { 'X-App-Version': '1.2.3' } }); + const served = await response.json(); + return response.status + ' ' + served.method + ' ' + served.headers['x-app-version']; + }`, `${CROSS}/bounce?to=${encodeURIComponent(`${PREFIX}/cors-echo?preflight`)}`); + expect(result).toBe('200 GET 1.2.3'); + }); + + test('should reject cors with disallowed credentials', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/cars', (route) => route.fulfill({ + contentType: 'application/json', + headers: { 'Access-Control-Allow-Origin': PREFIX }, + status: 200, + body: JSON.stringify(['electric', 'gas']), + })); + const error = await browser.evaluate(`async () => { + const response = await fetch('https://example.com/cars', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + mode: 'cors', + body: JSON.stringify({ number: 1 }), + credentials: 'include', + }); + return response.json(); + }`).then(() => undefined, (caught: Error) => caught); + expect(error).toBeTruthy(); + }); + + test('should support cors for different methods', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/cars', (route) => route.fulfill({ + contentType: 'application/json', + headers: { 'Access-Control-Allow-Origin': '*' }, + status: 200, + body: JSON.stringify([route.request.method, 'electric', 'gas']), + })); + const post = await browser.evaluate(`async () => { + const response = await fetch('https://example.com/cars', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + mode: 'cors', + body: JSON.stringify({ number: 1 }), + }); + return response.json(); + }`); + expect(post).toEqual(['POST', 'electric', 'gas']); + const remove = await browser.evaluate(`async () => { + const response = await fetch('https://example.com/cars', { method: 'DELETE', headers: {}, mode: 'cors', body: '' }); + return response.json(); + }`); + expect(remove).toEqual(['DELETE', 'electric', 'gas']); + }); + + test('should contain raw request header', async ({ browser }) => { + let headers: Readonly> | undefined; + await browser.route('**/*', async (route) => { + headers = route.request.headers; + await route.continue(); + }); + await browser.goto('/empty.html'); + expect(headers?.['accept']).toBeTruthy(); + }); + + for (const method of ['fulfill', 'continue', 'fallback', 'abort'] as const) { + test(`route.${method} should throw if called twice`, async ({ browser }) => { + const handled = deferred(); + await browser.route('**/*', async (route) => { + const decide = (): Promise => (method === 'fulfill' ? route.fulfill({}) : route[method]()); + await decide(); + handled.resolve(await decide().then(() => new Error('decided twice'), (caught: Error) => caught)); + }); + const navigation = browser.goto('/empty.html').catch(() => undefined); + const e = await handled.promise; + expect(e.message).toContain('called twice'); + await navigation; + }); + } + + test('should intercept when postData is more than 1MB', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const intercepted = deferred(); + const POST_BODY = '0'.repeat(2 * 1024 * 1024); + await browser.route('**/404.html', async (route) => { + await route.abort(); + intercepted.resolve(route.request.postData); + }); + await browser.evaluate("(body) => fetch('/404.html', { method: 'POST', body }).then(() => null, () => null)", POST_BODY); + expect(await intercepted.promise).toBe(POST_BODY); + }); +}); diff --git a/packages/web/tests/parity/tests/page-screenshot.e2e.ts b/packages/web/tests/parity/tests/page-screenshot.e2e.ts new file mode 100644 index 0000000000..489b462b33 --- /dev/null +++ b/packages/web/tests/parity/tests/page-screenshot.e2e.ts @@ -0,0 +1,454 @@ +/** + * Adapted from microsoft/playwright tests/page/page-screenshot.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `page.screenshot()` is `app.screenshot()`, read back with + * pngjs, and a `mask` is the `toHaveScreenshot` option, compared against the same viewport with + * boxes of the mask color painted over the masked elements. Playwright's golden images belong to + * its own renderer setup, so a golden comparison becomes a check of the pixels it shows. + */ + +/* + * Not ported: + * - should capture blinking caret if explicitly asked for: e2e has no `caret` option; its screenshots always hide the caret. + * - should clip rect: e2e has no `clip` option. + * - should clip rect with fullPage: e2e has no `clip` or `fullPage` option. + * - should clip elements to the viewport: e2e has no `clip` option. + * - should throw on clip outside the viewport: e2e has no `clip` option. + * - should throw on a negative clip size: e2e has no `clip` option. + * - should run in parallel: e2e has no `clip` option. + * - should take fullPage screenshots: e2e has no `fullPage` option. + * - should take fullPage screenshots and mask elements outside of it: e2e has no `fullPage` option. + * - should restore viewport after fullPage screenshot: e2e has no `fullPage` option. + * - should allow transparency: e2e has no `omitBackground` option. + * - should render white background on jpeg file: e2e screenshots are PNG only. + * - should produce a valid webp screenshot: e2e screenshots are PNG only. + * - path option should detect webp: e2e has no `path` or `type` option. + * - quality option should work for webp: e2e has no `quality` option. + * - webp screenshots should be lossless by default: e2e screenshots are PNG only. + * - should allow transparency with webp: e2e has no `omitBackground` option. + * - quality option should throw for webp when out of range: e2e has no `quality` option. + * - should work with odd clip size on Retina displays: e2e has no `clip` option or device scale factor. + * - should work for webgl: golden only, and headless WebGL renders differently per GPU backend. + * - path option should work: e2e has no `path` option. + * - path option should create subdirectories: e2e has no `path` option. + * - path option should detect jpeg: e2e has no `path` option. + * - path option should throw for unsupported mime type: e2e has no `path` option. + * - quality option should throw for png: e2e has no `quality` option. + * - zero quality option should throw for png: e2e has no `quality` option. + * - quality option should work for jpeg: e2e has no `quality` option. + * - should prefer type over extension: e2e has no `path` or `type` option. + * - should take fullPage screenshots during navigation: e2e has no `fullPage` option. + * - mask option should work with elementhandle: element handles. + * - mask option should hide elements based on attr: e2e has no `style` option. + * - mask option should remove elements based on attr: e2e has no `style` option. + * - page screenshot animations (all 15 tests): e2e has no `animations` option. + * - should throw if screenshot size is too large: e2e has no `fullPage` option. + * - page screenshot should capture css transform: golden only, of a 3D transform with no stable pixel to check. + * The `fullPage` option of should work while navigating and should work with Array deleted is dropped: they take the viewport. + */ + +import { copyFileSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; +import path from 'node:path'; +import { test, type Browser } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { PNG } from 'pngjs'; +import { content, CROSS, PREFIX, e2eGap } from './helpers.ts'; + +/** The part of the `app` fixture these tests use. */ +interface App { + screenshot(label?: string): Promise; +} + +const stored = new Set(); + +/** One element a mask covers: a selector and its match index, inside the iframe `frame` matches when set. */ +interface MaskTarget { + readonly frame?: string; + readonly selector: string; + readonly index: number; +} + +/** The PNG at `file`, decoded. */ +function readPng(file: string): PNG { + return PNG.sync.read(readFileSync(file)); +} + +/** The red, green, and blue of the pixel at (`x`, `y`). */ +function rgb(png: PNG, x: number, y: number): [number, number, number] { + const offset = (y * png.width + x) * 4; + return [png.data[offset]!, png.data[offset + 1]!, png.data[offset + 2]!]; +} + +/** Whether two colors are the same within `slack` per channel. */ +function near(actual: readonly number[], expected: readonly number[], slack = 3): boolean { + return actual.every((value, index) => Math.abs(value - expected[index]!) <= slack); +} + +/** The pixels of `box` cut out of `png`, rounded out to whole pixels. */ +function crop(png: PNG, box: { x: number; y: number; width: number; height: number }): Buffer { + const left = Math.floor(box.x); + const top = Math.floor(box.y); + const right = Math.ceil(box.x + box.width); + const bottom = Math.ceil(box.y + box.height); + const rows: Buffer[] = []; + for (let y = top; y < bottom; y++) rows.push(png.data.subarray((y * png.width + left) * 4, (y * png.width + right) * 4)); + return Buffer.concat(rows); +} + +/** Where `toHaveScreenshot(name)` in this file reads its stored screenshot. */ +function storedPath(name: string): string { + return path.join(import.meta.dirname, 'page-screenshot.e2e.ts-snapshots', `${name}-web-${process.platform}.png`); +} + +/** + * Paints a `color` box over each of `targets`, as a `mask` would cover it, keeps the viewport as + * the stored screenshot `name`, then takes the boxes away. + */ +async function storeMaskedReference(browser: Browser, app: App, name: string, targets: readonly MaskTarget[], color = '#ff00ff'): Promise { + await browser.evaluate(`({ targets, color }) => { + for (const { frame, selector, index } of targets) { + const host = frame === undefined ? undefined : document.querySelector(frame); + const origin = host === undefined ? { left: 0, top: 0 } : host.getBoundingClientRect(); + const offset = host === undefined ? { left: 0, top: 0 } : { left: host.clientLeft, top: host.clientTop }; + const element = (host === undefined ? document : host.contentDocument).querySelectorAll(selector)[index]; + const rect = element.getBoundingClientRect(); + const box = document.createElement('div'); + box.setAttribute('data-parity-mask', ''); + box.style.cssText = 'position: fixed; z-index: 2147483647; pointer-events: none; margin: 0; border: 0; padding: 0;'; + box.style.left = (origin.left + offset.left + rect.left) + 'px'; + box.style.top = (origin.top + offset.top + rect.top) + 'px'; + box.style.width = rect.width + 'px'; + box.style.height = rect.height + 'px'; + box.style.background = color; + document.documentElement.appendChild(box); + } + }`, { targets: targets.map((target) => ({ ...target })), color }); + await storeReference(app, name); + await browser.evaluate("() => { for (const box of document.querySelectorAll('[data-parity-mask]')) box.remove(); }"); +} + +/** Keeps the viewport, as `app.screenshot` takes it, as the stored screenshot `name` until the test ends. */ +async function storeReference(app: App, name: string): Promise { + mkdirSync(path.dirname(storedPath(name)), { recursive: true }); + stored.add(name); + copyFileSync(await app.screenshot(name), storedPath(name)); +} + +/** Appends an iframe with `id` loading `url`, Playwright's `attachFrame`, once it has loaded. */ +async function attachFrame(browser: Browser, id: string, url: string): Promise { + await browser.evaluate(`async ({ id, url }) => { + const frame = document.createElement('iframe'); + frame.src = url; + frame.id = id; + document.body.appendChild(frame); + await new Promise((x) => (frame.onload = x)); + }`, { id, url }); +} + +/** Adds a ` +
+ `)); + const div = browser.locator('div'); + await div.pressSequentially('foo bar'); + const box = (await div.boundingBox())!; + const screenshot = crop(readPng(await app.screenshot()), box); + for (let i = 0; i < 10; ++i) { + await new Promise((x) => setTimeout(x, 150)); + const newScreenshot = crop(readPng(await app.screenshot()), box); + expect(newScreenshot.equals(screenshot)).toBe(true); + } + }); + + test('should capture blinking caret in shadow dom', async ({ app, browser }) => { + await browser.goto('/empty.html'); + await browser.evaluate(`() => { + class CustomElementContainer extends HTMLElement { + #shadowRoot; + constructor() { + super(); + this.#shadowRoot = this.attachShadow({ mode: 'open' }); + this.#shadowRoot.innerHTML = ''; + } + } + class CustomElementInputWrapper extends HTMLElement { + #shadowRoot; + constructor() { + super(); + this.#shadowRoot = this.attachShadow({ mode: 'open' }); + this.#shadowRoot.innerHTML = ''; + } + } + customElements.define('custom-element-input-wrapper', CustomElementInputWrapper); + customElements.define('custom-element-container', CustomElementContainer); + + const container = document.createElement('custom-element-container'); + document.body.appendChild(container); + }`); + + const input = browser.locator('input'); + await input.focus(); + + const box = (await input.boundingBox())!; + const screenshot = crop(readPng(await app.screenshot()), box); + let hasDifferentScreenshots = false; + for (let i = 0; !hasDifferentScreenshots && i < 10; ++i) { + await new Promise((x) => setTimeout(x, 150)); + const newScreenshot = crop(readPng(await app.screenshot()), box); + hasDifferentScreenshots = !newScreenshot.equals(screenshot); + } + expect(hasDifferentScreenshots).toBe(false); + }); + + test('should work for canvas', async ({ app, browser }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/screenshots/canvas.html'); + const screenshot = readPng(await app.screenshot()); + expect(rgb(screenshot, 8 + 30, 8 + 30)).toEqual([0, 0, 0]); + expect(rgb(screenshot, 8 + 120, 8 + 120)).toEqual([0, 0, 0]); + expect(rgb(screenshot, 8 + 60, 8 + 60)).toEqual([255, 255, 255]); + expect(rgb(screenshot, 8 + 75, 8 + 75)).toEqual([255, 255, 255]); + expect(rgb(screenshot, 8 + 140, 8 + 140)).toEqual([255, 255, 255]); + }); + + test('should capture canvas changes', async ({ app, browser }) => { + await browser.goto(content('')); + await browser.evaluate(`() => { + const canvas = document.querySelector('canvas'); + canvas.width = 600; + canvas.height = 600; + }`); + + /** Draws the horizontal line of `step`, 100 pixels below the one before. */ + async function addLine(step: number): Promise { + await browser.evaluate(`(n) => { + const canvas = document.querySelector('canvas'); + const ctx = canvas.getContext('2d'); + ctx.lineWidth = 1; + ctx.beginPath(); + ctx.moveTo(0, n * 100); + ctx.lineTo(300, n * 100); + ctx.stroke(); + }`, step); + } + + /** Whether the line of `step` shows in `screenshot`: the canvas sits at the body margin, 8 pixels in. */ + function hasLine(screenshot: PNG, step: number): boolean { + const y = 8 + step * 100; + return [y - 1, y].some((row) => row >= 8 && rgb(screenshot, 8 + 150, row)[0] < 200); + } + + for (let i = 0; i < 3; i++) { + await addLine(i); + await new Promise((f) => setTimeout(f, 100)); + const screenshot = readPng(await app.screenshot()); + for (let step = 0; step < 3; step++) expect(hasLine(screenshot, step)).toBe(step <= i); + } + }); + + test('should work for translateZ', async ({ app, browser }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/screenshots/translateZ.html'); + const screenshot = readPng(await app.screenshot()); + expect(rgb(screenshot, 120, 120)).toEqual([255, 0, 0]); + expect(rgb(screenshot, 175, 175)).toEqual([0, 128, 0]); + expect(rgb(screenshot, 230, 230)).toEqual([0, 128, 0]); + expect(rgb(screenshot, 300, 300)).toEqual([255, 255, 255]); + }); + + test('should work while navigating', async ({ app, browser }) => { + e2eGap('a screenshot taken while the page navigates fails as stale instead of capturing whichever document shows'); + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/redirectloop1.html'); + for (let i = 0; i < 10; i++) { + const screenshot = readPng(await app.screenshot()); + expect([screenshot.width, screenshot.height]).toEqual([500, 500]); + } + }); + + test('should work with iframe in shadow', async ({ app, browser }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid-iframe-in-shadow.html'); + await expect(browser.frameLocator('iframe').locator('div').first()).toBeVisible(); + const screenshot = readPng(await app.screenshot()); + expect(near(rgb(screenshot, 3, 3), [255, 204, 204])).toBe(true); + expect(rgb(screenshot, 400, 400)).toEqual([255, 255, 255]); + }); + + test('should not issue resize event', async ({ app, browser }) => { + await browser.goto('/grid.html'); + await browser.evaluate("() => { window.__resized = false; window.addEventListener('resize', () => { window.__resized = true; }); }"); + await app.screenshot(); + expect(await browser.evaluate('window.__resized')).toBe(false); + }); + + test('should work with Array deleted', async ({ app, browser }) => { + e2eGap('the evaluate wrapper needs the page\'s `Array`'); + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid.html'); + await browser.evaluate('() => { delete window.Array; }'); + const screenshot = readPng(await app.screenshot()); + expect([screenshot.width, screenshot.height]).toEqual([500, 500]); + expect(near(rgb(screenshot, 3, 3), [255, 204, 204])).toBe(true); + }); + + test.describe('mask option', () => { + test('should work', async ({ app, browser, screen }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid.html'); + await storeMaskedReference(browser, app, 'mask-should-work', [{ selector: 'div', index: 5 }]); + await expect(screen).toHaveScreenshot('mask-should-work', { + mask: [browser.locator('div').nth(5)], + }); + }); + + test('should work with locator', async ({ app, browser }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid.html'); + await storeMaskedReference(browser, app, 'mask-should-work-with-locator', [{ selector: 'div', index: 5 }]); + const bodyLocator = browser.locator('body'); + await expect(bodyLocator).toHaveScreenshot('mask-should-work-with-locator', { + mask: [browser.locator('div').nth(5)], + }); + }); + + test('should mask multiple elements', async ({ app, browser, screen }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid.html'); + await storeMaskedReference(browser, app, 'should-mask-multiple-elements', [{ selector: 'div', index: 5 }, { selector: 'div', index: 12 }]); + await expect(screen).toHaveScreenshot('should-mask-multiple-elements', { + mask: [ + browser.locator('div').nth(5), + browser.locator('div').nth(12), + ], + }); + }); + + test('should mask inside iframe', async ({ app, browser, screen }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid.html'); + await attachFrame(browser, 'frame1', `${PREFIX}/grid.html`); + await addStyleTag(browser, 'iframe { border: none; }'); + await storeMaskedReference(browser, app, 'should-mask-inside-iframe', [{ selector: 'div', index: 5 }, { frame: '#frame1', selector: 'div', index: 12 }]); + await expect(screen).toHaveScreenshot('should-mask-inside-iframe', { + mask: [ + browser.locator('div').nth(5), + browser.frameLocator('#frame1').locator('div').nth(12), + ], + }); + }); + + test('should mask in parallel', async ({ app, browser, screen }) => { + e2eGap('two screenshot steps at once are refused'); + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/empty.html'); + await attachFrame(browser, 'frame1', `${PREFIX}/grid.html`); + await attachFrame(browser, 'frame2', `${PREFIX}/grid.html`); + await addStyleTag(browser, 'iframe { border: none; }'); + await storeMaskedReference(browser, app, 'should-mask-in-parallel-1', [{ frame: '#frame1', selector: 'div', index: 1 }]); + await storeMaskedReference(browser, app, 'should-mask-in-parallel-2', [{ frame: '#frame2', selector: 'div', index: 3 }]); + await Promise.all([ + expect(screen).toHaveScreenshot('should-mask-in-parallel-1', { + mask: [browser.frameLocator('#frame1').locator('div').nth(1)], + }), + expect(screen).toHaveScreenshot('should-mask-in-parallel-2', { + mask: [browser.frameLocator('#frame2').locator('div').nth(3)], + }), + ]); + }); + + test('should remove mask after screenshot', async ({ app, browser, screen }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid.html'); + const screenshot1 = readFileSync(await app.screenshot()); + await storeMaskedReference(browser, app, 'should-remove-mask-after-screenshot', [{ selector: 'div', index: 1 }]); + await expect(screen).toHaveScreenshot('should-remove-mask-after-screenshot', { + mask: [browser.locator('div').nth(1)], + }); + const screenshot2 = readFileSync(await app.screenshot()); + expect(screenshot1.equals(screenshot2)).toBe(true); + }); + + test('should work when subframe has stalled navigation', async ({ app, browser, screen }) => { + e2eGap('no screenshot comes back while a subframe navigation stalls', { browser: 'chromium' }); + let routed!: () => void; + const routeReady = new Promise((f) => (routed = f)); + let release!: () => void; + const released = new Promise((f) => (release = f)); + await browser.route('**/subframe.html', async (route) => { + routed(); + await released; + await route.fulfill({ body: '' }); + }); + + await browser.goto(content('')); + await storeReference(app, 'mask-stalled-subframe'); + await browser.goto(content(``), { waitUntil: 'domcontentloaded' }); + await routeReady; + + await expect(screen).toHaveScreenshot('mask-stalled-subframe', { mask: [browser.locator('non-existent')] }); + release(); + await expect(browser.frameLocator('iframe').locator('body')).toBeAttached(); + }); + + test('should work when subframe used document.open after a weird url', async ({ app, browser, screen }) => { + await browser.goto('/empty.html'); + await browser.evaluate(`() => { + const iframe = document.createElement('iframe'); + iframe.src = 'javascript:hi'; + document.body.appendChild(iframe); + iframe.contentDocument.open(); + iframe.contentDocument.write('Hello'); + iframe.contentDocument.close(); + }`); + await storeReference(app, 'mask-document-open'); + await expect(screen).toHaveScreenshot('mask-document-open', { mask: [browser.locator('non-existent')] }); + }); + + test('should work when mask color is not pink #F0F', async ({ app, browser, screen }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid.html'); + await storeMaskedReference(browser, app, 'mask-color-should-work', [{ selector: 'div', index: 5 }], '#00ff00'); + await expect(screen).toHaveScreenshot('mask-color-should-work', { + mask: [browser.locator('div').nth(5)], + maskColor: '#00FF00', + }); + }); + }); +}); + +test('should capture css box-shadow', { requires: ['browser'] }, async ({ app, browser }) => { + await browser.goto(content(`
`)); + const screenshot = readPng(await app.screenshot()); + expect(rgb(screenshot, 30, 30)).toEqual([255, 255, 255]); + expect(rgb(screenshot, 62, 40)[0]).toBe(255); + expect(rgb(screenshot, 62, 40)[1]).toBeLessThan(200); + expect(rgb(screenshot, 100, 100)).toEqual([255, 255, 255]); +}); diff --git a/packages/web/tests/parity/tests/page-select-option.e2e.ts b/packages/web/tests/parity/tests/page-select-option.e2e.ts new file mode 100644 index 0000000000..e25198ef54 --- /dev/null +++ b/packages/web/tests/parity/tests/page-select-option.e2e.ts @@ -0,0 +1,284 @@ +/** + * Adapted from microsoft/playwright tests/page/page-select-option.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `page.selectOption(selector, value)` is a locator selectOption. + */ + +/* + * Not ported: + * - should select single option by handle: no element handles. + * - should select single option by multiple attributes: `selectOption` takes one of label, value, or index. + * - should not select single option when some attributes do not match: `selectOption` takes one of label, value, or index. + * - should select only first option: `selectOption` takes one option, no arrays. + * - should select multiple options: `selectOption` takes one option, no arrays. + * - should select multiple options with attributes: `selectOption` takes one option, no arrays. + * - should return [] on no matched values: `selectOption` returns nothing and takes no arrays. + * - should return an array of matched values: `selectOption` returns nothing and takes no arrays. + * - should return an array of one element when multiple is not set: `selectOption` returns nothing and takes no arrays. + * - should return [] on no values: `selectOption` returns nothing and takes no arrays. + * - should not allow null items: no arrays or null. + * - should unselect with null: no arrays or null. + * - should deselect all options when passed no values for a multiple select: no arrays. + * - should deselect all options when passed no values for a select without multiple: no arrays. + * - should throw if passed wrong types: asserts Playwright's protocol validator messages; the option is typed. + * - should wait for multiple options to be present: `selectOption` takes one option, no arrays. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, e2eGap } from './helpers.ts'; + +/** Five pairs of animation frames, Playwright's `rafraf(page, 5)`, so a pending select has had its chance. */ +const giveItAChanceToResolve = '() => new Promise((resolve) => { let frames = 0; const step = () => (++frames === 10 ? setTimeout(resolve, 0) : requestAnimationFrame(step)); requestAnimationFrame(step); })'; + +/** Appends a `scarlet` option to the page's select. */ +const addScarlet = "() => { const option = document.createElement('option'); option.value = 'scarlet'; option.textContent = 'Scarlet'; document.querySelector('select').appendChild(option); }"; + +test.describe('page select option', { requires: ['browser'] }, () => { + test('should select single option', async ({ browser }) => { + e2eGap('a bare string selects by label only, where Playwright matches the value or the label'); + await browser.goto('/input/select.html'); + await browser.locator('select').selectOption('blue'); + expect(await browser.evaluate('() => window.result.onInput')).toEqual(['blue']); + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['blue']); + }); + + test('should select single option by value', async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.locator('select').selectOption({ value: 'blue' }); + expect(await browser.evaluate('() => window.result.onInput')).toEqual(['blue']); + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['blue']); + }); + + test('should fall back to selecting by label', async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.locator('select').selectOption('Blue'); + expect(await browser.evaluate('() => window.result.onInput')).toEqual(['blue']); + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['blue']); + }); + + test('should select single option by label', async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.locator('select').selectOption({ label: 'Indigo' }); + expect(await browser.evaluate('() => window.result.onInput')).toEqual(['indigo']); + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['indigo']); + }); + + test('should select single option by label with html whitespace', async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.locator('select').selectOption({ label: 'HTML' }); + expect(await browser.evaluate('() => window.result.onInput')).toEqual(['html']); + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['html']); + }); + + test('should select single option by index', async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.locator('select').selectOption({ index: 2 }); + expect(await browser.evaluate('() => window.result.onInput')).toEqual(['brown']); + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['brown']); + }); + + test('should not throw when select causes navigation', async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.evaluate("() => document.querySelector('select').addEventListener('input', () => window.location.href = '/empty.html')"); + await Promise.all([ + browser.locator('select').selectOption({ value: 'blue' }), + browser.waitForURL(/empty\.html/), + ]); + expect(await browser.url()).toContain('empty.html'); + }); + + test('should respect event bubbling', async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.locator('select').selectOption({ value: 'blue' }); + expect(await browser.evaluate('() => window.result.onBubblingInput')).toEqual(['blue']); + expect(await browser.evaluate('() => window.result.onBubblingChange')).toEqual(['blue']); + }); + + test('should throw when element is not a element'); + }); + + test('should work when re-defining top-level Event class', async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.evaluate('() => { window.Event = null; }'); + await browser.locator('select').selectOption({ value: 'blue' }); + expect(await browser.evaluate('() => window.result.onInput')).toEqual(['blue']); + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['blue']); + }); + + test('should wait for option to be present', async ({ browser }) => { + await browser.goto('/input/select.html'); + const selectPromise = browser.locator('select').selectOption({ value: 'scarlet' }, { timeout: 10_000 }); + let didSelect = false; + void selectPromise.then(() => (didSelect = true)); + await browser.evaluate(giveItAChanceToResolve); + expect(didSelect).toBe(false); + await browser.evaluate(addScarlet); + await selectPromise; + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['scarlet']); + }); + + test('should wait for option index to be present', async ({ browser }) => { + await browser.goto('/input/select.html'); + const len = await browser.evaluate("() => document.querySelector('select').options.length"); + const selectPromise = browser.locator('select').selectOption({ index: len }, { timeout: 10_000 }); + let didSelect = false; + void selectPromise.then(() => (didSelect = true)); + await browser.evaluate(giveItAChanceToResolve); + expect(didSelect).toBe(false); + await browser.evaluate(addScarlet); + await selectPromise; + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['scarlet']); + }); + + test('input event.composed should be true and cross shadow dom boundary', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(content(``)); + await browser.evaluate(`() => { + window.firedBodyEvents = []; + for (const event of ['input', 'change']) + document.body.addEventListener(event, (e) => window.firedBodyEvents.push(e.type + ':' + e.composed), false); + }`); + await browser.evaluate(`() => { + window.firedEvents = []; + const select = document.querySelector('div').shadowRoot.querySelector('select'); + for (const event of ['input', 'change']) + select.addEventListener(event, (e) => window.firedEvents.push(e.type + ':' + e.composed), false); + }`); + await browser.locator('select').selectOption({ value: 'blue' }); + expect(await browser.evaluate('firedEvents')).toEqual(['input:true', 'change:false']); + expect(await browser.evaluate('firedBodyEvents')).toEqual(['input:true']); + }); + + test('should wait for select to be enabled', async ({ browser }) => { + await browser.goto(content(` + + + + `)); + const selectPromise = browser.locator('select').selectOption('two'); + await new Promise((resolve) => setTimeout(resolve, 1000)); + await browser.evaluate('() => window.hydrate()'); + await selectPromise; + expect(await browser.evaluate('result')).toEqual('two'); + await expect(browser.locator('select')).toHaveValue('two'); + }); + + test('should wait for option to be enabled', async ({ browser }) => { + await browser.goto(content(` + + + + `)); + const error = await browser.locator('select').selectOption('two', { timeout: 1000 }).catch((caught: Error) => caught); + expect((error as Error).message).toContain('option being selected is not enabled'); + + const selectPromise = browser.locator('select').selectOption('two'); + await new Promise((resolve) => setTimeout(resolve, 1000)); + await browser.evaluate('() => window.hydrate()'); + await selectPromise; + expect(await browser.evaluate('result')).toEqual('two'); + await expect(browser.locator('select')).toHaveValue('two'); + }); + + test('should wait for optgroup to be enabled', async ({ browser }) => { + await browser.goto(content(` + + + + `)); + const error = await browser.locator('select').selectOption('two', { timeout: 1000 }).catch((caught: Error) => caught); + expect((error as Error).message).toContain('option being selected is not enabled'); + + const selectPromise = browser.locator('select').selectOption('two'); + await new Promise((resolve) => setTimeout(resolve, 1000)); + await browser.evaluate('() => window.hydrate()'); + await selectPromise; + expect(await browser.evaluate('result')).toEqual('two'); + await expect(browser.locator('select')).toHaveValue('two'); + }); + + test('should wait for select to be swapped', async ({ browser }) => { + await browser.goto(content(` + + + + `)); + const selectPromise = browser.locator('select').selectOption('two'); + await new Promise((resolve) => setTimeout(resolve, 1000)); + await browser.evaluate('() => window.hydrate()'); + await selectPromise; + await expect(browser.locator('select')).toHaveValue('two'); + expect(await browser.evaluate('result')).toEqual('two'); + }); +}); diff --git a/packages/web/tests/parity/tests/page-set-input-files.e2e.ts b/packages/web/tests/parity/tests/page-set-input-files.e2e.ts new file mode 100644 index 0000000000..5cdabed0fc --- /dev/null +++ b/packages/web/tests/parity/tests/page-set-input-files.e2e.ts @@ -0,0 +1,279 @@ +/** + * Adapted from microsoft/playwright tests/page/page-set-input-files.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `setInputFiles` is the locator's, its paths resolve from the project + * root, and what the server received is what `/upload` answers with. + */ + +/* + * Not ported: + * - should set from memory: `setInputFiles` takes file paths, not `{ name, mimeType, buffer }` payloads. + * - input event.composed should be true and cross shadow dom boundary: sets a `{ name, mimeType, buffer }` payload, whose events Playwright dispatches itself. + */ + +import { test, type Browser } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { content, PREFIX } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +type UploadedFile = { name: string; filename?: string; mimetype?: string; size: number; base64?: string }; + +/** Reads the first file of the input `selector` matches as text, in the page. */ +const readFirstFile = (selector: string): string => `() => { + const reader = new FileReader(); + const promise = new Promise((fulfill) => { reader.onload = fulfill; }); + reader.readAsText(document.querySelector(${JSON.stringify(selector)}).files[0]); + return promise.then(() => reader.result); +}`; + +/** A fresh directory for files a test writes. */ +function outputDir(): string { + return fs.mkdtempSync(path.join(os.tmpdir(), 'e2e-parity-upload-')); +} + +/** Writes a 200MB file of `A`s, Playwright's large upload. */ +async function writeLargeFile(file: string): Promise { + const str = 'A'.repeat(4 * 1024); + const stream = fs.createWriteStream(file); + for (let i = 0; i < 50 * 1024; i++) { + await new Promise((fulfill, reject) => stream.write(str, (error) => (error ? reject(error) : fulfill()))); + } + await new Promise((fulfill) => stream.end(fulfill)); +} + +/** The files the server parsed from the form the page posted to `/upload`. */ +async function uploaded(browser: Browser): Promise { + return JSON.parse(await browser.evaluate('document.body.textContent')) as UploadedFile[]; +} + +/** Records the input and change events the input `selector` matches dispatches, into `window.events`. */ +const recordEvents = (selector: string): string => `() => { + window.events = []; + const e = document.querySelector(${JSON.stringify(selector)}); + e.addEventListener('input', () => window.events.push('input')); + e.addEventListener('change', () => window.events.push('change')); +}`; + +test.describe('page set input files', { requires: ['browser'] }, () => { + test('should upload the file', async ({ browser }) => { + await browser.goto('/input/fileupload.html'); + await browser.locator('input[type=file]').setInputFiles('assets/file-to-upload.txt'); + expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('file-to-upload.txt'); + expect(await browser.evaluate(readFirstFile('input'))).toBe('contents of the file'); + }); + + test('should upload a folder', async ({ browser }) => { + await browser.goto('/input/folderupload.html'); + const dir = path.join(outputDir(), 'file-upload-test'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'file1.txt'), 'file1 content'); + fs.writeFileSync(path.join(dir, 'file2'), 'file2 content'); + fs.mkdirSync(path.join(dir, 'sub-dir')); + fs.writeFileSync(path.join(dir, 'sub-dir', 'really.txt'), 'sub-dir file content'); + await browser.locator('input[type=file]').setInputFiles(dir); + const webkitRelativePaths = await browser.evaluate("() => [...document.querySelector('input').files].map((f) => f.webkitRelativePath)"); + expect(new Set(webkitRelativePaths)).toEqual(new Set([ + 'file-upload-test/sub-dir/really.txt', + 'file-upload-test/file1.txt', + 'file-upload-test/file2', + ])); + for (let i = 0; i < webkitRelativePaths.length; i++) { + const fileContent = await browser.evaluate(`(i) => { + const reader = new FileReader(); + const promise = new Promise((fulfill) => { reader.onload = fulfill; }); + reader.readAsText(document.querySelector('input').files[i]); + return promise.then(() => reader.result); + }`, i); + expect(fileContent).toEqual(fs.readFileSync(path.join(dir, '..', webkitRelativePaths[i]!)).toString()); + } + }); + + test('should upload a folder and throw for multiple directories', async ({ browser }) => { + await browser.goto('/input/folderupload.html'); + const dir = path.join(outputDir(), 'file-upload-test'); + fs.mkdirSync(path.join(dir, 'folder1'), { recursive: true }); + fs.writeFileSync(path.join(dir, 'folder1', 'file1.txt'), 'file1 content'); + fs.mkdirSync(path.join(dir, 'folder2'), { recursive: true }); + fs.writeFileSync(path.join(dir, 'folder2', 'file2.txt'), 'file2 content'); + const error = await browser.locator('input[type=file]').setInputFiles([path.join(dir, 'folder1'), path.join(dir, 'folder2')]).catch((caught: Error) => caught); + expect((error as Error).message).toContain('Multiple directories are not supported'); + }); + + test('should throw if a directory and files are passed', async ({ browser }) => { + await browser.goto('/input/folderupload.html'); + const dir = path.join(outputDir(), 'file-upload-test'); + fs.mkdirSync(path.join(dir, 'folder1'), { recursive: true }); + fs.writeFileSync(path.join(dir, 'folder1', 'file1.txt'), 'file1 content'); + const error = await browser.locator('input[type=file]').setInputFiles([path.join(dir, 'folder1'), path.join(dir, 'folder1', 'file1.txt')]).catch((caught: Error) => caught); + expect((error as Error).message).toContain('File paths must be all files or a single directory'); + }); + + test('should throw when uploading a folder in a normal file upload input', async ({ browser }) => { + await browser.goto('/input/fileupload.html'); + const dir = path.join(outputDir(), 'file-upload-test'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'file1.txt'), 'file1 content'); + const error = await browser.locator('input[type=file]').setInputFiles(dir).catch((caught: Error) => caught); + expect((error as Error).message).toContain('File input does not support directories, pass individual files instead'); + }); + + test('should throw when uploading a file in a directory upload input', async ({ browser }) => { + await browser.goto('/input/folderupload.html'); + const error = await browser.locator('input[type=file]').setInputFiles('assets/file to upload.txt').catch((caught: Error) => caught); + expect((error as Error).message).toContain('[webkitdirectory] input requires passing a path to a directory'); + }); + + test('should upload a file after popup', async ({ browser }) => { + await browser.goto('/input/fileupload.html'); + await browser.evaluate("() => { window['__popup'] = window.open('about:blank'); }"); + await browser.evaluate("() => { window['__popup'].close(); }"); + await browser.locator('input[type=file]').setInputFiles('assets/file-to-upload.txt'); + expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('file-to-upload.txt'); + }); + + test('should upload large file', async ({ browser }) => { + await browser.goto('/input/fileupload.html'); + const uploadFile = path.join(outputDir(), '200MB.zip'); + await writeLargeFile(uploadFile); + await browser.evaluate(recordEvents('input[type="file"]')); + await browser.locator('input[type="file"]').setInputFiles(uploadFile); + expect(await browser.evaluate("() => document.querySelector('input[type=\"file\"]').files[0].name")).toBe('200MB.zip'); + expect(await browser.evaluate('() => window.events')).toEqual(['input', 'change']); + await Promise.all([ + browser.waitForURL('/upload'), + browser.locator('input[type=submit]').tap(), + ]); + const [file1] = await uploaded(browser); + expect(file1!.filename).toBe('200MB.zip'); + expect(file1!.size).toBe(200 * 1024 * 1024); + fs.unlinkSync(uploadFile); + }); + + test('should throw an error if the file does not exist', async ({ browser }) => { + await browser.goto('/input/fileupload.html'); + const error = await browser.locator('input[type=file]').setInputFiles('i actually do not exist.txt').catch((caught: Error) => caught); + expect((error as Error).message).toContain('ENOENT: no such file or directory'); + expect((error as Error).message).toContain('i actually do not exist.txt'); + }); + + test('should upload large file with relative path', async ({ browser }) => { + await browser.goto('/input/fileupload.html'); + const uploadFile = path.join(outputDir(), '200MB.zip'); + await writeLargeFile(uploadFile); + await browser.evaluate(recordEvents('input[type="file"]')); + const relativeUploadPath = path.relative(process.cwd(), uploadFile); + expect(path.isAbsolute(relativeUploadPath)).toBeFalsy(); + await browser.locator('input[type="file"]').setInputFiles(relativeUploadPath); + expect(await browser.evaluate("() => document.querySelector('input[type=\"file\"]').files[0].name")).toBe('200MB.zip'); + expect(await browser.evaluate('() => window.events')).toEqual(['input', 'change']); + await Promise.all([ + browser.waitForURL('/upload'), + browser.locator('input[type=submit]').tap(), + ]); + const [file1] = await uploaded(browser); + expect(file1!.filename).toBe('200MB.zip'); + expect(file1!.size).toBe(200 * 1024 * 1024); + fs.unlinkSync(uploadFile); + }); + + test('should upload the file with spaces in name', async ({ browser }) => { + await browser.goto('/input/fileupload.html'); + await browser.locator('input[type=file]').setInputFiles('assets/file to upload.txt'); + expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('file to upload.txt'); + expect(await browser.evaluate(readFirstFile('input'))).toBe('contents of the file'); + }); + + test('should work @smoke', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input[type=file]').setInputFiles('assets/file-to-upload.txt'); + expect(await browser.evaluate("() => document.querySelector('input').files.length")).toBe(1); + expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('file-to-upload.txt'); + }); + + test('should work with CSP', async ({ browser }) => { + await browser.goto(`/respond?headers=${encodeURIComponent(JSON.stringify({ 'content-type': 'text/html', 'content-security-policy': 'default-src "none"' }))}&body=${encodeURIComponent('')}`); + await browser.locator('input[type=file]').setInputFiles('assets/file-to-upload.txt'); + expect(await browser.evaluate("() => document.querySelector('input').files.length")).toBe(1); + expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('file-to-upload.txt'); + }); + + test('should detect mime type', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content(` +
+ + + +
`)); + await browser.locator('input[name=file1]').setInputFiles('assets/file-to-upload.txt'); + await browser.locator('input[name=file2]').setInputFiles('assets/pptr.png'); + await Promise.all([ + browser.waitForURL('/upload'), + browser.locator('input[type=submit]').tap(), + ]); + const [file1, file2] = await uploaded(browser); + expect(file1!.filename).toBe('file-to-upload.txt'); + expect(file1!.mimetype).toBe('text/plain'); + expect(Buffer.from(file1!.base64!, 'base64').toString()).toBe(fs.readFileSync('assets/file-to-upload.txt').toString()); + expect(file2!.filename).toBe('pptr.png'); + expect(file2!.mimetype).toBe('image/png'); + expect(Buffer.from(file2!.base64!, 'base64').toString()).toBe(fs.readFileSync('assets/pptr.png').toString()); + }); + + test('should not trim big uploaded files', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const DATA_SIZE = Math.pow(2, 20); + const files = await browser.evaluate(`async (size) => { + const body = new FormData(); + body.set('file', new Blob([new Uint8Array(size)])); + return (await fetch('/upload', { method: 'POST', body })).json(); + }`, DATA_SIZE); + expect(files[0]!.size).toBe(DATA_SIZE); + }); + + test('should emit input and change events', async ({ browser }) => { + await browser.goto(content(` + + `)); + await browser.locator('input[type=file]').setInputFiles('assets/file-to-upload.txt'); + const events = await browser.evaluate<{ type: string }[]>('() => window.events'); + expect(events.length).toBe(2); + expect(events[0]!.type).toBe('input'); + expect(events[1]!.type).toBe('change'); + }); + + test('input should trigger events when files changed second time', async ({ browser }) => { + await browser.goto(content('')); + await browser.evaluate(recordEvents('input')); + + await browser.locator('input[type=file]').setInputFiles('assets/file-to-upload.txt'); + expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('file-to-upload.txt'); + expect(await browser.evaluate('() => window.events')).toEqual(['input', 'change']); + + await browser.evaluate('() => { window.events.length = 0; }'); + + await browser.locator('input[type=file]').setInputFiles('assets/pptr.png'); + expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('pptr.png'); + expect(await browser.evaluate('() => window.events')).toEqual(['input', 'change']); + }); + + test('should preserve lastModified timestamp', async ({ browser }) => { + await browser.goto(content('')); + const files = ['file-to-upload.txt', 'file-to-upload-2.txt']; + await browser.locator('input[type=file]').setInputFiles(files.map((f) => `assets/${f}`)); + expect(await browser.evaluate("() => [...document.querySelector('input').files].map((f) => f.name)")).toEqual(files); + const timestamps = await browser.evaluate("() => [...document.querySelector('input').files].map((f) => f.lastModified)"); + const expectedTimestamps = files.map((file) => Math.round(fs.statSync(`assets/${file}`).mtimeMs)); + for (let i = 0; i < timestamps.length; i++) { + expect(Math.abs(timestamps[i]! - expectedTimestamps[i]!)).toBeLessThanOrEqual(1000); + } + }); +}); diff --git a/packages/web/tests/parity/tests/page-wait-for-navigation.e2e.ts b/packages/web/tests/parity/tests/page-wait-for-navigation.e2e.ts new file mode 100644 index 0000000000..81aa19eb6e --- /dev/null +++ b/packages/web/tests/parity/tests/page-wait-for-navigation.e2e.ts @@ -0,0 +1,168 @@ +/** + * Adapted from microsoft/playwright tests/page/page-wait-for-navigation.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `page.waitForNavigation()` is `browser.waitForURL` with the URL the + * navigation lands on, and a `url` matcher is a RegExp. + */ + +/* + * Not ported: + * - should work with both domcontentloaded and load: needs `waitForNavigation({ waitUntil })`. + * - should work with commit: needs `waitForNavigation({ waitUntil: 'commit' })`. + * - should work with clicking on links which do not commit navigation: needs an HTTPS server with a bad certificate. + * - should work when subframe issues window.stop(): needs `frameattached` and `framenavigated` events. + * - should work on frame: needs `frame.waitForNavigation`. + * - should fail when frame detaches: needs `frame.waitForNavigation`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, CROSS, PREFIX } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +test.describe('page wait for navigation', { requires: ['browser'] }, () => { + test('should work', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await Promise.all([ + browser.waitForURL('/grid.html'), + browser.evaluate('(url) => { window.location.href = url; }', `${PREFIX}/grid.html`), + ]); + expect(await browser.url()).toContain('grid.html'); + }); + + test('should respect timeout', async ({ browser }) => { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await browser.goto('/one-style.html'); + const promise = browser.waitForURL('/frame.html', { timeout: 5000 }); + await browser.goto(EMPTY_PAGE); + const error = await promise.catch((caught: Error) => caught); + expect((error as Error).message).toContain('/frame.html'); + expect((error as Error).message).toContain(EMPTY_PAGE); + }); + + test('should work with clicking on anchor links', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const page = content("foobar"); + await browser.goto(page); + await Promise.all([ + browser.waitForURL(`${page}#foobar`), + browser.locator('a').tap(), + ]); + expect(await browser.url()).toBe(`${PREFIX}${page}#foobar`); + }); + + test('should work with history.pushState()', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content(` + SPA + + `)); + await Promise.all([ + browser.waitForURL('/wow.html'), + browser.locator('a').tap(), + ]); + expect(await browser.url()).toBe(`${PREFIX}/wow.html`); + }); + + test('should work with history.replaceState()', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content(` + SPA + + `)); + await Promise.all([ + browser.waitForURL('/replaced.html'), + browser.locator('a').tap(), + ]); + expect(await browser.url()).toBe(`${PREFIX}/replaced.html`); + }); + + test('should work with DOM history.back()/history.forward()', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content(` + back + forward + + `)); + expect(await browser.url()).toBe(`${PREFIX}/second.html`); + await Promise.all([ + browser.waitForURL('/first.html'), + browser.locator('a#back').tap(), + ]); + expect(await browser.url()).toBe(`${PREFIX}/first.html`); + await Promise.all([ + browser.waitForURL('/second.html'), + browser.locator('a#forward').tap(), + ]); + expect(await browser.url()).toBe(`${PREFIX}/second.html`); + }); + + test('should work with url match', async ({ browser }) => { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await browser.goto(content('

blank

')); + let response1 = false; + const response1Promise = browser.waitForURL(/one-style\.html/).then(() => (response1 = true)); + let response2 = false; + const response2Promise = browser.waitForURL(/\/frame.html/).then(() => (response2 = true)); + let response3 = false; + const response3Promise = browser.waitForURL(/[?&]foo=bar/).then(() => (response3 = true)); + expect(response1).toBe(false); + expect(response2).toBe(false); + expect(response3).toBe(false); + await browser.goto(EMPTY_PAGE); + expect(response1).toBe(false); + expect(response2).toBe(false); + expect(response3).toBe(false); + await browser.goto('/frame.html'); + expect(response1).toBe(false); + await response2Promise; + expect(response2).toBe(true); + expect(response3).toBe(false); + await browser.goto('/one-style.html'); + await response1Promise; + expect(response1).toBe(true); + expect(response2).toBe(true); + expect(response3).toBe(false); + await browser.goto('/frame.html?foo=bar'); + await response3Promise; + expect(response1).toBe(true); + expect(response2).toBe(true); + expect(response3).toBe(true); + await browser.goto('/empty.html'); + }); + + test('should work with url match for same document navigations', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + let resolved = false; + const waitPromise = browser.waitForURL(/third\.html/).then(() => (resolved = true)); + expect(resolved).toBe(false); + await browser.evaluate("() => { history.pushState({}, '', '/first.html'); }"); + expect(resolved).toBe(false); + await browser.evaluate("() => { history.pushState({}, '', '/second.html'); }"); + expect(resolved).toBe(false); + await browser.evaluate("() => { history.pushState({}, '', '/third.html'); }"); + await waitPromise; + expect(resolved).toBe(true); + }); + + test('should work for cross-process navigations', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const url = `${CROSS}/empty.html`; + const waitPromise = browser.waitForURL(url); + const gotoPromise = browser.goto(url, { waitUntil: 'domcontentloaded' }); + await waitPromise; + expect(await browser.url()).toBe(url); + expect(await browser.evaluate('document.location.href')).toBe(url); + await gotoPromise; + }); +}); diff --git a/packages/web/tests/parity/tests/page-wait-for-response.e2e.ts b/packages/web/tests/parity/tests/page-wait-for-response.e2e.ts new file mode 100644 index 0000000000..3f1a7498a0 --- /dev/null +++ b/packages/web/tests/parity/tests/page-wait-for-response.e2e.ts @@ -0,0 +1,57 @@ +/** + * Adapted from microsoft/playwright tests/page/page-wait-for-response.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `browser.waitForResponse` takes a URL pattern. + */ + +/* + * Not ported: + * - should respect timeout: needs `page.waitForEvent('response')`. + * - should respect default timeout: needs `page.setDefaultTimeout` and a predicate. + * - should work with predicate: needs `page.waitForEvent('response', predicate)`. + * - should work with async predicate: needs response predicates. + * - sync predicate should be only called once: needs response predicates. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { PREFIX, e2eGap } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +test.describe('page wait for response', { requires: ['browser'] }, () => { + test('should work', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const [response] = await Promise.all([ + browser.waitForResponse(`${PREFIX}/digits/2.png`), + browser.evaluate(`() => { + void fetch('/digits/1.png'); + void fetch('/digits/2.png'); + void fetch('/digits/3.png'); + }`), + ]); + expect(response.url).toBe(`${PREFIX}/digits/2.png`); + }); + + test('should log the url', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const error1 = await browser.waitForResponse('foo.css', { timeout: 1000 }).catch((caught: Error) => caught); + expect((error1 as Error).message).toContain('"foo.css"'); + const error2 = await browser.waitForResponse(/foo.css/i, { timeout: 1000 }).catch((caught: Error) => caught); + expect((error2 as Error).message).toContain('/foo.css/i'); + }); + + test('should work with no timeout', async ({ browser }) => { + e2eGap('a timeout must be positive; there is no `timeout: 0` for no timeout'); + await browser.goto(EMPTY_PAGE); + const [response] = await Promise.all([ + browser.waitForResponse(`${PREFIX}/digits/2.png`, { timeout: 0 }), + browser.evaluate(`() => setTimeout(() => { + void fetch('/digits/1.png'); + void fetch('/digits/2.png'); + void fetch('/digits/3.png'); + }, 50) && null`), + ]); + expect(response.url).toBe(`${PREFIX}/digits/2.png`); + }); +}); diff --git a/packages/web/tests/parity/tests/page-wait-for-url.e2e.ts b/packages/web/tests/parity/tests/page-wait-for-url.e2e.ts new file mode 100644 index 0000000000..6290b71e7b --- /dev/null +++ b/packages/web/tests/parity/tests/page-wait-for-url.e2e.ts @@ -0,0 +1,106 @@ +/** + * Adapted from microsoft/playwright tests/page/page-wait-for-url.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `waitForURL` takes a URL or a RegExp, so a glob is the URL it names. + */ + +/* + * Not ported: + * - should work with both domcontentloaded and load: needs `waitForURL({ waitUntil })`. + * - should work with commit: needs `waitForURL({ waitUntil })`. + * - should work with commit and about:blank: needs `waitForURL({ waitUntil })`. + * - should work on frame: needs `frame.waitForURL`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, PREFIX } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +test.describe('page wait for url', { requires: ['browser'] }, () => { + test('should work', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.evaluate('(url) => { window.location.href = url; }', `${PREFIX}/grid.html`); + await browser.waitForURL('/grid.html'); + }); + + test('should respect timeout', async ({ browser }) => { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await browser.goto(EMPTY_PAGE); + const promise = browser.waitForURL('/frame.html', { timeout: 2500 }).catch((caught: Error) => caught); + await browser.goto(EMPTY_PAGE); + const error = await promise; + expect((error as Error).message).toContain('frame.html'); + }); + + test('should work with clicking on anchor links', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content("foobar")); + await browser.locator('a').tap(); + await browser.waitForURL(/#foobar$/); + }); + + test('should work with history.pushState()', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content(` + SPA + + `)); + await browser.locator('a').tap(); + await browser.waitForURL('/wow.html'); + expect(await browser.url()).toBe(`${PREFIX}/wow.html`); + }); + + test('should work with history.replaceState()', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content(` + SPA + + `)); + await browser.locator('a').tap(); + await browser.waitForURL('/replaced.html'); + expect(await browser.url()).toBe(`${PREFIX}/replaced.html`); + }); + + test('should work with DOM history.back()/history.forward()', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content(` + back + forward + + `)); + expect(await browser.url()).toBe(`${PREFIX}/second.html`); + + await browser.locator('a#back').tap(); + await browser.waitForURL('/first.html'); + expect(await browser.url()).toBe(`${PREFIX}/first.html`); + + await browser.locator('a#forward').tap(); + await browser.waitForURL('/second.html'); + expect(await browser.url()).toBe(`${PREFIX}/second.html`); + }); + + test('should work with url match for same document navigations', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + let resolved = false; + const waitPromise = browser.waitForURL(/third\.html/).then(() => (resolved = true)); + expect(resolved).toBe(false); + await browser.evaluate("() => { history.pushState({}, '', '/first.html'); }"); + expect(resolved).toBe(false); + await browser.evaluate("() => { history.pushState({}, '', '/second.html'); }"); + expect(resolved).toBe(false); + await browser.evaluate("() => { history.pushState({}, '', '/third.html'); }"); + await waitPromise; + expect(resolved).toBe(true); + }); +}); diff --git a/packages/web/tests/parity/tests/selectors-frame.e2e.ts b/packages/web/tests/parity/tests/selectors-frame.e2e.ts new file mode 100644 index 0000000000..9370b66998 --- /dev/null +++ b/packages/web/tests/parity/tests/selectors-frame.e2e.ts @@ -0,0 +1,164 @@ +/** + * Adapted from microsoft/playwright tests/page/selectors-frame.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `iframe >> internal:control=enter-frame >> x` is + * `frameLocator('iframe').locator(x)`, `:has-text()` a `hasText` filter, and the routed frame + * pages are pages the server serves (`content()`). + */ + +/* + * Not ported: + * - should work for iframe (handle): element handles. + * - should work for nested iframe (handle): element handles. + * - should work for $ and $$ (handle): element handles. + * - should work for $eval (handle): element handles. + * - should work for $$eval (handle): element handles. + * - waitForSelector should survive frame reattach (handle): element handles. + * - waitForSelector should survive iframe navigation (handle): element handles. + * - $eval should throw for missing frame: asserts Playwright's `$eval` error text; e2e has no `$eval`. + * - should not allow dangling enter-frame: Playwright selector syntax, which e2e locators do not take. + * - should not allow leading enter-frame: Playwright selector syntax. + * - should not allow capturing before enter-frame: Playwright selector syntax. + * - should capture after the enter-frame: Playwright selector syntax (`*css=`) and innerHTML. + * - should non work for non-frame: asserts Playwright's error text naming the matched `
`. + * - should match in a descendant frame: `internal:control=any-frame` has no e2e counterpart. + * - should match in a deeply nested frame: `internal:control=any-frame`. + * - should not match a chain across frames: `internal:control=any-frame`. + * - should match multiple elements: `internal:control=any-frame`. + * - should throw when matching elements in multiple frames: `internal:control=any-frame` and page.frames(). + * - should not allow any-frame in the middle of a selector: `internal:control=any-frame`. + * - should allow entering frames from any frame: `internal:control=any-frame`. + * - should not allow any-frame after entering a frame: `internal:control=any-frame`. + * - should not allow dangling enter-frame after any-frame: `internal:control=any-frame`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +const iframe2 = content(''); + +const iframe = content(` + +
+ + +
+ 1 + 2 + `); + +const routed = content(``); + +/** Waits `ms` milliseconds. */ +function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +test.describe('selectors frame', { requires: ['browser'] }, () => { + test('should work for iframe', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').locator('button'); + await button.waitFor(); + expect(await button.textContent()).toBe('Hello iframe'); + await expect(button).toHaveText('Hello iframe'); + await button.tap(); + }); + + test('should work for nested iframe', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').frameLocator('iframe').locator('button'); + await button.waitFor(); + expect(await button.textContent()).toBe('Hello nested iframe'); + await expect(button).toHaveText('Hello nested iframe'); + await button.tap(); + }); + + test('should work for $ and $$', async ({ browser }) => { + await browser.goto(routed); + const element = browser.frameLocator('iframe').locator('button'); + await element.waitFor({ state: 'attached' }); + expect(await element.textContent()).toBe('Hello iframe'); + await browser.frameLocator('iframe').locator('span').nth(1).waitFor({ state: 'attached' }); + expect(await browser.frameLocator('iframe').locator('span').count()).toBe(2); + }); + + test('$ should not wait for frame', async ({ browser }) => { + await browser.goto('/empty.html'); + expect(await browser.frameLocator('iframe').locator('canvas').count()).toBe(0); + }); + + test('$$ should not wait for frame', async ({ browser }) => { + await browser.goto('/empty.html'); + expect(await browser.frameLocator('iframe').locator('canvas').all()).toHaveLength(0); + }); + + test('$$eval should not throw for missing frame', async ({ browser }) => { + await browser.goto('/empty.html'); + expect(await browser.frameLocator('iframe').locator('canvas').allTextContents()).toHaveLength(0); + }); + + test('should work for $eval', async ({ browser }) => { + await browser.goto(routed); + await expect(browser.frameLocator('iframe').getByRole('button')).toHaveCount(1); + await expect(browser.frameLocator('iframe').locator('button')).toHaveCount(1); + }); + + test('should work for $$eval', async ({ browser }) => { + await browser.goto(routed); + await expect(browser.frameLocator('iframe').locator('span')).toHaveCount(2); + expect(await browser.frameLocator('iframe').locator('span').allTextContents()).toEqual(['1', '2']); + }); + + test('should click in lazy iframe', async ({ browser }) => { + const lazy = content(''); + await browser.goto('/empty.html'); + const attached = delay(500) + .then(() => browser.evaluate("() => { document.body.appendChild(document.createElement('iframe')); }")) + .then(() => delay(500)) + .then(() => browser.evaluate("(src) => { document.querySelector('iframe').src = src; }", lazy)); + const button = browser.frameLocator('iframe').locator('button'); + const [, text] = await Promise.all([ + button.tap(), + button.textContent(), + expect(button).toHaveText('Hello iframe'), + attached, + ]); + expect(text).toBe('Hello iframe'); + }); + + test('waitFor should survive frame reattach', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').locator('button').filter({ hasText: 'Hello nested iframe' }); + const promise = button.waitFor(); + await browser.evaluate("() => { document.querySelector('iframe').remove(); }"); + await browser.evaluate("(src) => { const iframe = document.createElement('iframe'); iframe.src = src; document.body.appendChild(iframe); }", iframe2); + await promise; + }); + + test('click should survive frame reattach', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').locator('button').filter({ hasText: 'Hello nested iframe' }); + const promise = button.tap(); + await browser.evaluate("() => { document.querySelector('iframe').remove(); }"); + await browser.evaluate("(src) => { const iframe = document.createElement('iframe'); iframe.src = src; document.body.appendChild(iframe); }", iframe2); + await promise; + }); + + test('click should survive iframe navigation', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').locator('button').filter({ hasText: 'Hello nested iframe' }); + const promise = button.tap(); + const navigated = browser.evaluate("(src) => { document.querySelector('iframe').src = src; }", iframe2); + await promise; + await navigated; + }); + + test('click should survive navigation', async ({ browser }) => { + await browser.goto(iframe); + const promise = browser.locator('button').filter({ hasText: 'Hello nested iframe' }).tap(); + await delay(100); + await browser.goto(iframe2); + await promise; + }); +}); diff --git a/packages/web/tests/parity/tests/selectors-get-by.e2e.ts b/packages/web/tests/parity/tests/selectors-get-by.e2e.ts new file mode 100644 index 0000000000..c848857858 --- /dev/null +++ b/packages/web/tests/parity/tests/selectors-get-by.e2e.ts @@ -0,0 +1,217 @@ +/** + * Adapted from microsoft/playwright tests/page/selectors-get-by.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: a string query is exact by default, + * so Playwright's default substring match is `{ exact: false }` and its + * `{ exact: true }` is the default; `evaluate(e => e.outerHTML)` reads become + * text and attribute reads of the match. + * + * Not ported: + * - getByTestId with custom testId should work: the test id attribute is project config, not per test. + * - getByTestId with comma-separated testIdAttributes should match any: same. + * - getByAltText should work: e2e has no getByAltText. + * - getByTitle should work: e2e has no getByTitle. + * - getByRole with description: e2e getByRole has no description option. + * - getByRole with description via aria-describedby: same. + * - getByRole with description via title fallback: same. + * - getByRole with description whitespace normalization: same. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +test.describe('selectors get by', { requires: ['browser'] }, () => { + test('getByTestId should work', async ({ screen, browser }) => { + await browser.goto(content('
Hello world
')); + await expect(screen.getByTestId('Hello')).toHaveText('Hello world'); + await expect(browser.locator('div').getByTestId('Hello')).toHaveText('Hello world'); + }); + + test('getByTestId should escape id', async ({ screen, browser }) => { + await browser.goto(content(`
Hello world
`)); + await expect(screen.getByTestId('He"llo')).toHaveText('Hello world'); + }); + + test('getByTestId should work for regex', async ({ screen, browser }) => { + await browser.goto(content('
Hello world
')); + await expect(screen.getByTestId(/He[l]*o/)).toHaveText('Hello world'); + await expect(browser.locator('div').getByTestId('Hello')).toHaveText('Hello world'); + }); + + test('getByText should work', async ({ screen, browser }) => { + await browser.goto(content(`
yo
ya
\nye
`)); + expect(await screen.getByText('ye', { exact: false }).textContent()).toBe('ye'); + expect(await screen.getByText(/ye/).textContent()).toBe('ye'); + expect(await screen.getByText(/e/).textContent()).toBe('ye'); + + await browser.goto(content(`
ye
ye
`)); + expect(await screen.getByText('ye').first().boundingBox()).toEqual(await browser.locator('div').first().boundingBox()); + + await browser.goto(content(`
Hello world
Hello
`)); + expect(await screen.getByText('Hello').textContent()).toBe('Hello'); + }); + + test('getByLabel should work', async ({ screen, browser }) => { + await browser.goto(content(`
`)); + expect(await screen.getByText('Name', { exact: false }).getAttribute('for')).toBe('target'); + expect(await screen.getByLabel('Name', { exact: false }).getAttribute('id')).toBe('target'); + expect(await browser.locator('div').getByLabel('Name', { exact: false }).getAttribute('id')).toBe('target'); + }); + + test('getByLabel should work with nested elements', async ({ screen, browser }) => { + await browser.goto(content(``)); + + await expect(screen.getByLabel('last name', { exact: false })).toHaveAttribute('id', 'target'); + await expect(screen.getByLabel('st na', { exact: false })).toHaveAttribute('id', 'target'); + await expect(screen.getByLabel('Name', { exact: false })).toHaveAttribute('id', 'target'); + await expect(screen.getByLabel('Last Name')).toHaveAttribute('id', 'target'); + await expect(screen.getByLabel(/Last\s+name/i)).toHaveAttribute('id', 'target'); + + expect(await screen.getByLabel('Last').count()).toBe(0); + expect(await screen.getByLabel('last name').count()).toBe(0); + expect(await screen.getByLabel('Name').count()).toBe(0); + expect(await screen.getByLabel('what?', { exact: false }).count()).toBe(0); + expect(await screen.getByLabel(/last name/).count()).toBe(0); + }); + + test('getByLabel should work with multiply-labelled input', async ({ screen, browser }) => { + await browser.goto(content(``)); + expect(await screen.getByLabel('Name', { exact: false }).getAttribute('id')).toBe('target'); + expect(await screen.getByLabel('First or Last', { exact: false }).getAttribute('id')).toBe('target'); + }); + + test('getByLabel should work with ancestor label and multiple controls', async ({ screen, browser }) => { + await browser.goto(content(``)); + expect(await screen.getByLabel('Name', { exact: false }).getAttribute('id')).toBe('target'); + }); + + test('getByLabel should work with ancestor label and for', async ({ screen, browser }) => { + await browser.goto(content(` + + + `)); + expect(await screen.getByLabel('Name', { exact: false }).getAttribute('id')).toBe('target'); + }); + + test('getByLabel should work with aria-labelledby', async ({ screen, browser }) => { + await browser.goto(content(``)); + expect(await screen.getByLabel('Name', { exact: false }).textContent()).toBe('Click me'); + }); + + test('getByLabel should prioritize aria-labelledby over native label', async ({ screen, browser }) => { + await browser.goto(content(` + + + `)); + expect(await screen.getByLabel('Name', { exact: false }).textContent()).toBe('Click me'); + }); + + test('getByLabel should work with aria-label', async ({ screen, browser }) => { + await browser.goto(content(``)); + expect(await screen.getByLabel('Name', { exact: false }).getAttribute('id')).toBe('target'); + }); + + test('getByLabel should ignore empty aria-label', async ({ screen, browser }) => { + await browser.goto(content(``)); + expect(await screen.getByLabel('Last Name', { exact: false }).getAttribute('id')).toBe('target'); + }); + + test('getByLabel should prioritize aria-labelledby over aria-label', async ({ screen, browser }) => { + await browser.goto(content(``)); + expect(await screen.getByLabel('Other', { exact: false }).getAttribute('id')).toBe('target'); + }); + + test('getByPlaceholder should work', async ({ screen, browser }) => { + await browser.goto(content(`
+ + +
`)); + await expect(screen.getByPlaceholder('hello', { exact: false })).toHaveCount(2); + await expect(screen.getByPlaceholder('Hello')).toHaveCount(1); + await expect(screen.getByPlaceholder(/wor/i)).toHaveCount(1); + + await expect(browser.locator('div').getByPlaceholder('hello', { exact: false })).toHaveCount(2); + }); + + test('getBy escaping', async ({ screen, browser }) => { + const setAttributes = (value: string) => `() => { const input = document.querySelector('input'); for (const name of ['placeholder', 'title', 'alt']) input.setAttribute(name, ${JSON.stringify(value)}); }`; + + await browser.goto(content(``)); + await browser.evaluate(setAttributes('hello my\nwo"rld')); + await expect.soft(screen.getByText('hello my\nwo"rld', { exact: false })).toHaveAttribute('id', 'label'); + await expect.soft(screen.getByText('hello my wo"rld', { exact: false })).toHaveAttribute('id', 'label'); + await expect.soft(screen.getByLabel('hello my\nwo"rld', { exact: false })).toHaveAttribute('id', 'control'); + await expect.soft(screen.getByPlaceholder('hello my\nwo"rld', { exact: false })).toHaveAttribute('id', 'control'); + + await browser.goto(content(``)); + await browser.evaluate(setAttributes('hello my\nworld')); + await expect.soft(screen.getByText('hello my\nworld', { exact: false })).toHaveAttribute('id', 'label'); + await expect.soft(screen.getByText('hello my world', { exact: false })).toHaveAttribute('id', 'label'); + await expect.soft(screen.getByLabel('hello my\nworld', { exact: false })).toHaveAttribute('id', 'control'); + await expect.soft(screen.getByPlaceholder('hello my\nworld', { exact: false })).toHaveAttribute('id', 'control'); + + await browser.goto(content(``)); + await browser.evaluate(setAttributes('foo >> bar')); + expect.soft(await screen.getByText('foo >> bar', { exact: false }).textContent()).toBe('foo >> bar'); + await expect.soft(browser.locator('label')).toHaveText('foo >> bar'); + await expect.soft(screen.getByText('foo >> bar', { exact: false })).toHaveText('foo >> bar'); + expect.soft(await screen.getByText(/foo >> bar/).textContent()).toBe('foo >> bar'); + await expect.soft(screen.getByLabel('foo >> bar', { exact: false })).toHaveAttribute('id', 'target'); + await expect.soft(screen.getByLabel(/foo >> bar/)).toHaveAttribute('id', 'target'); + await expect.soft(screen.getByPlaceholder('foo >> bar', { exact: false })).toHaveAttribute('id', 'target'); + await expect.soft(screen.getByPlaceholder(/foo >> bar/)).toHaveAttribute('id', 'target'); + }); + + test('getByRole escaping', async ({ screen, browser }) => { + await browser.goto(content(` + issues 123 + he llo 56 + + `)); + expect.soft(await screen.getByRole('button').allTextContents()).toEqual(['Click me']); + expect.soft(await screen.getByRole('link').allTextContents()).toEqual(['issues 123', 'he llo 56']); + + expect.soft(await screen.getByRole('link', { name: 'issues 123', exact: false }).allTextContents()).toEqual(['issues 123']); + expect.soft(await screen.getByRole('link', { name: 'sues', exact: false }).allTextContents()).toEqual(['issues 123']); + expect.soft(await screen.getByRole('link', { name: ' he \n llo ', exact: false }).allTextContents()).toEqual(['he llo 56']); + expect.soft(await screen.getByRole('button', { name: 'issues', exact: false }).allTextContents()).toEqual([]); + + expect.soft(await screen.getByRole('link', { name: 'sues' }).allTextContents()).toEqual([]); + expect.soft(await screen.getByRole('link', { name: ' he \n llo 56 ' }).allTextContents()).toEqual(['he llo 56']); + + expect.soft(await screen.getByRole('button', { name: 'Click me' }).allTextContents()).toEqual(['Click me']); + expect.soft(await screen.getByRole('button', { name: 'Click \\me' }).allTextContents()).toEqual([]); + expect.soft(await screen.getByRole('button', { name: 'Click \\\\me' }).allTextContents()).toEqual([]); + }); + + test('getByRole should accept regexp with v flag', async ({ screen, browser }) => { + await browser.goto(content(``)); + await expect(screen.getByRole('button', { name: new RegExp('Click me', 'v') })).toHaveCount(1); + await expect(screen.getByRole('button', { name: new RegExp('click me', 'iv') })).toHaveCount(1); + await expect(screen.getByRole('button', { name: new RegExp('Missing', 'v') })).toHaveCount(0, { timeout: 1000 }); + }); + + test('locators should not be affected by global and sticky regex flags', async ({ screen, browser }) => { + await browser.goto(content(` +
foo
foo
foo
+ + + + `)); + await expect(screen.getByText(/foo/)).toHaveCount(9); + await expect(screen.getByText(/foo/g)).toHaveCount(9); + await expect(screen.getByText(/foo/y)).toHaveCount(9); + await expect(screen.getByLabel(/foo/)).toHaveCount(3); + await expect(screen.getByLabel(/foo/g)).toHaveCount(3); + await expect(screen.getByLabel(/foo/y)).toHaveCount(3); + await expect(screen.getByRole('button', { name: /foo/ })).toHaveCount(3); + await expect(screen.getByRole('button', { name: /foo/g })).toHaveCount(3); + await expect(screen.getByRole('button', { name: /foo/y })).toHaveCount(3); + await expect(screen.getByPlaceholder(/foo/)).toHaveCount(3); + await expect(screen.getByPlaceholder(/foo/g)).toHaveCount(3); + await expect(screen.getByPlaceholder(/foo/y)).toHaveCount(3); + }); +}); diff --git a/packages/web/tests/parity/tests/selectors-role.e2e.ts b/packages/web/tests/parity/tests/selectors-role.e2e.ts new file mode 100644 index 0000000000..532f7c89f5 --- /dev/null +++ b/packages/web/tests/parity/tests/selectors-role.e2e.ts @@ -0,0 +1,325 @@ +/** + * Adapted from microsoft/playwright tests/page/selectors-role.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: a `role=` selector is `getByRole` + * with the same options, a string name is exact by default so Playwright's + * default substring match is `{ exact: false }`, and an + * `evaluateAll(e => e.outerHTML)` read is the matches' texts or attributes. + * The `include-hidden`, `checked="mixed"`, and `pressed="mixed"` cases are + * left out: e2e getByRole has no includeHidden or mixed state. + * + * Not ported: + * - errors: Playwright `role=` selector parse errors. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import type { Locator } from 'e2e'; +import { content } from './helpers.ts'; + +/** The `aria-label` of every current match, in document order. */ +async function labels(locator: Locator): Promise<(string | null)[]> { + return Promise.all((await locator.all()).map((match) => match.getAttribute('aria-label'))); +} + +test.describe('selectors role', { requires: ['browser'] }, () => { + test('should detect roles', async ({ screen, browser }) => { + await browser.goto(content(` + + + +

Heading

+
Hello
+
I am a dialog
+ `)); + expect(await screen.getByRole('button').allTextContents()).toEqual(['Hello']); + await expect(screen.getByRole('listbox')).toHaveCount(1); + await expect(screen.getByRole('listbox')).toHaveAttribute('multiple', ''); + await expect(screen.getByRole('combobox')).toHaveCount(1); + expect(await screen.getByRole('combobox').getAttribute('multiple')).toBe(null); + expect(await screen.getByRole('heading').allTextContents()).toEqual(['Heading']); + expect(await screen.getByRole('group').allTextContents()).toEqual(['Hello']); + expect(await screen.getByRole('dialog').allTextContents()).toEqual(['I am a dialog']); + expect(await screen.getByRole('menuitem').allTextContents()).toEqual([]); + }); + + test('should support selected', async ({ screen, browser }) => { + await browser.goto(content(` + +
+
Hi
+
Hello
+
+ `)); + expect(await screen.getByRole('option', { selected: true }).allTextContents()).toEqual(['Hello', 'Hi']); + expect(await screen.getByRole('option', { selected: false }).allTextContents()).toEqual(['Hi', 'Hello']); + }); + + test('should support checked', async ({ screen, browser }) => { + await browser.goto(content(` + + + +
Hi
+
Hello
+
Unknown
+ `)); + await browser.evaluate("() => { document.querySelector('[indeterminate]').indeterminate = true; }"); + + const checked = screen.getByRole('checkbox', { checked: true }); + await expect(checked).toHaveCount(2); + await expect(checked.first()).toHaveAttribute('checked', ''); + await expect(checked.nth(1)).toHaveText('Hi'); + + const unchecked = screen.getByRole('checkbox', { checked: false }); + await expect(unchecked).toHaveCount(3); + expect(await unchecked.first().getAttribute('checked')).toBe(null); + expect(await unchecked.first().getAttribute('indeterminate')).toBe(null); + expect(await unchecked.allTextContents()).toEqual(['', 'Hello', 'Unknown']); + + await expect(screen.getByRole('checkbox')).toHaveCount(6); + }); + + test('should support pressed', async ({ screen, browser }) => { + await browser.goto(content(` + + + + + `)); + expect(await screen.getByRole('button', { pressed: true }).allTextContents()).toEqual(['Hello']); + expect(await screen.getByRole('button', { pressed: false }).allTextContents()).toEqual(['Hi', 'Bye']); + expect(await screen.getByRole('button').allTextContents()).toEqual(['Hi', 'Hello', 'Bye', 'Mixed']); + }); + + test('should support expanded', async ({ screen, browser }) => { + await browser.goto(content(` +
Hi
+
Hello
+ + `)); + + expect(await screen.getByRole('treeitem').allTextContents()).toEqual(['Hi', 'Hello', 'Bye']); + expect(await screen.getByRole('treeitem', { expanded: true }).allTextContents()).toEqual(['Hello']); + expect(await screen.getByRole('treeitem', { expanded: false }).allTextContents()).toEqual(['Bye']); + expect(await browser.locator('[role=treeitem]:not([aria-expanded])').allTextContents()).toEqual(['Hi']); + }); + + test('should support disabled', async ({ screen, browser }) => { + await browser.goto(content(` + + + + +
+ +
+ + `)); + expect(await screen.getByRole('button', { disabled: true }).allTextContents()).toEqual(['Bye', 'Hello', 'Yay']); + expect(await screen.getByRole('button', { disabled: false }).allTextContents()).toEqual(['Hi', 'Oh']); + expect(await screen.getByRole('option', { disabled: true }).allTextContents()).toEqual(['one', 'three']); + expect(await screen.getByRole('option', { disabled: false }).allTextContents()).toEqual(['two']); + expect(await screen.getByRole('option').allTextContents()).toEqual(['one', 'two', 'three']); + }); + + test('should inherit disabled from the ancestor', async ({ browser }) => { + await browser.goto(content(` + + + + `)); + await expect(browser.locator('button')).toBeDisabled(); + + await browser.goto(content(` + +

Heading

+
+ `)); + await expect(browser.locator('h1')).not.toBeDisabled(); + }); + + test('should support disabled fieldset', async ({ screen, browser }) => { + await browser.goto(content(` +
+ + + + + +
+ +
+ +
+ +
+
+
+ +
+
+ + + + + + +
+ +
+
+ +
+
+ `)); + + await expect.soft(screen.getByTestId('inside-legend-element')).toBeEnabled(); + await expect.soft(screen.getByTestId('nested-inside-legend-element')).toBeEnabled(); + await expect.soft(screen.getByTestId('first-legend-element')).toBeEnabled(); + await expect.soft(screen.getByTestId('second-legend-element')).toBeDisabled(); + await expect.soft(screen.getByTestId('deep-button')).toBeDisabled(); + }); + + test('should support level', async ({ screen, browser }) => { + await browser.goto(content(` +

Hello

+

Hi

+
Bye
+ `)); + expect(await screen.getByRole('heading', { level: 1 }).allTextContents()).toEqual(['Hello']); + expect(await screen.getByRole('heading', { level: 3 }).allTextContents()).toEqual(['Hi']); + expect(await screen.getByRole('heading', { level: 5 }).allTextContents()).toEqual(['Bye']); + }); + + test('should filter hidden, unless explicitly asked for', async ({ screen, browser }) => { + await browser.goto(content(` + + + + + +
+ +
+
+ +
+ +
+ + + +
+ Open form + +
+ + + + + `)); + expect(await screen.getByRole('button').allTextContents()).toEqual(['Hi', 'Nay', 'Still here', 'Shadow1']); + await expect(screen.getByRole('textbox')).toHaveCount(1); + await expect(screen.getByRole('textbox')).toHaveAttribute('name', 'one'); + expect(await screen.getByRole('option').allTextContents()).toEqual(['One', 'Three']); + }); + + test('should support name', async ({ screen, browser }) => { + await browser.goto(content(` +
+
+ + + + `)); + expect(await labels(screen.getByRole('button', { name: 'Hello' }))).toEqual([' Hello ']); + expect(await labels(screen.getByRole('button', { name: ' \n Hello ' }))).toEqual([' Hello ']); + expect(await labels(screen.getByRole('button', { name: 'Hello', exact: false }))).toEqual([' Hello ']); + expect(await labels(screen.getByRole('button', { name: 'all', exact: false }))).toEqual(['Hallo']); + expect(await labels(screen.getByRole('button', { name: /^H[ae]llo$/ }))).toEqual([' Hello ', 'Hallo']); + expect(await labels(screen.getByRole('button', { name: /h.*o/i }))).toEqual([' Hello ', 'Hallo']); + }); + + test('should support option name with html whitespace', async ({ screen, browser }) => { + await browser.goto(content(` + + `)); + await expect(screen.getByRole('option', { name: 'HTML', exact: false })).toHaveCount(1); + }); + + test('hidden with shadow dom slots', async ({ screen, browser }) => { + await browser.goto(content(` +
+ +
+
+ +
+
+ +
+
+ +
+ + `)); + expect(await screen.getByRole('button').allTextContents()).toEqual(['visible1', 'visible2']); + }); + + test('should support output accessible name', async ({ screen, browser }) => { + await browser.goto(content(``)); + await expect(screen.getByRole('status', { name: 'Output1', exact: false })).toBeVisible(); + }); + + test('should not match scope by default', async ({ screen, browser }) => { + await browser.goto(content(` +
    +
  • + Parent list +
      +
    • child 1
    • +
    • child 2
    • +
    +
  • +
+ `)); + const children = screen.getByRole('listitem', { name: 'Parent list', exact: false }).getByRole('listitem'); + await expect(children).toHaveCount(2); + await expect(children).toHaveText(['child 1', 'child 2']); + }); +}); diff --git a/packages/web/tests/parity/tests/selectors-text.e2e.ts b/packages/web/tests/parity/tests/selectors-text.e2e.ts new file mode 100644 index 0000000000..24964e29bd --- /dev/null +++ b/packages/web/tests/parity/tests/selectors-text.e2e.ts @@ -0,0 +1,64 @@ +/** + * Adapted from microsoft/playwright tests/page/selectors-text.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Rewritten against the e2e public API: `locator(css, { hasText })` is a + * locator `filter({ hasText })`, `toHaveId(id)` an `id` attribute match. + * + * Not ported: + * - should work @smoke: Playwright `text=` and quoted selector strings, `page.$eval`. + * - should work with :text: Playwright `:text`, `:text-is`, `:text-matches` pseudo-classes. + * - should support empty string: same, plus `>>` chains. + * - should work across nodes: same, plus `text=`. + * - should work with text nodes in quoted mode: `text=` selectors. + * - should clear caches: element handles and `text=` selectors. + * - should work with :has-text: Playwright `:has-text` pseudo-class. + * - should work with large DOM: a timing run of Playwright selector engines. + * - should be case sensitive if quotes are specified: `text=` selectors. + * - should search for a substring without quotes: `text=` selectors. + * - should skip head, script and style: element handles and `text=` selectors. + * - should match input[type=button|submit|reset]: `text=` selectors. + * - should work for open shadow roots: `text=`, `text:light=` and `>>` selectors. + * - should prioritize light dom over shadow dom in the same parent: `>>` chain. + * - should waitForSelector with distributed elements: `page.waitForSelector` with a `>>` chain. + * - should match root after >>: `>>` chains. + * - should match root after >> with *: `>>` chain with a capture. + * - should work with leading and trailing spaces: `text=` selectors. + * - should work with unpaired quotes when not at the start: `text=` and `>>` selectors. + * - should work with paired quotes in the middle of selector: `>>` chains. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +test.describe('selectors text', { requires: ['browser'] }, () => { + test('text-is() should ignore comments', async ({ screen, browser }) => { + await browser.goto(content(`
hello + + world
`)); + expect(await browser.locator('div').filter({ hasText: 'hello world' }).getAttribute('id')).toBe('me'); + expect(await screen.getByText('hello world').getAttribute('id')).toBe('me'); + }); + + test('hasText and internal:text should match full node text in strict mode', async ({ screen, browser }) => { + await browser.goto(content(` +
helloworld
+
hello
+ `)); + await expect(screen.getByText('helloworld')).toHaveAttribute('id', 'div1'); + await expect(screen.getByText('hello')).toHaveAttribute('id', 'div2'); + await expect(browser.locator('div').filter({ hasText: /^helloworld$/ })).toHaveAttribute('id', 'div1'); + await expect(browser.locator('div').filter({ hasText: /^hello$/ })).toHaveAttribute('id', 'div2'); + + await browser.goto(content(` +
helloworld
+
hello
+ `)); + await expect(screen.getByText('helloworld')).toHaveAttribute('id', 'div1'); + expect(await screen.getByText('hello').nth(0).getAttribute('id')).toBe('span1'); + expect(await screen.getByText('hello').nth(1).getAttribute('id')).toBe('span2'); + await expect(screen.getByText('hello')).toHaveCount(2); + await expect(browser.locator('div').filter({ hasText: /^helloworld$/ })).toHaveAttribute('id', 'div1'); + await expect(browser.locator('div').filter({ hasText: /^hello$/ })).toHaveAttribute('id', 'div2'); + }); +}); From decbe0a9b66a54a5f3ba07226ae3bc2321634a1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oskar=20Kwas=CC=81niewski?= Date: Sun, 1 Nov 2026 17:54:41 +0100 Subject: [PATCH 3/9] ci: parity suite on the Playwright driver, chromium and firefox --- .github/workflows/spec.yml | 45 +++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/.github/workflows/spec.yml b/.github/workflows/spec.yml index e374d7aff3..2e4943c77b 100644 --- a/.github/workflows/spec.yml +++ b/.github/workflows/spec.yml @@ -118,11 +118,54 @@ jobs: - name: Fresh install with pnpm ${{ matrix.pnpm }} run: node scripts/install-smoke.ts ${{ matrix.pnpm }} + # Playwright's own page tests rewritten against the public API + # (packages/web/tests/parity), so web() keeps Playwright's behavior. + parity: + name: parity (${{ matrix.driver }} ${{ matrix.browser }}) + runs-on: blacksmith-4vcpu-ubuntu-2404 + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + include: + - driver: playwright + browser: chromium + - driver: playwright + browser: firefox + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pnpm/action-setup@9fd676a19091d4595eefd76e4bd31c97133911f1 # v4.2.0 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 26 + cache: pnpm + - run: pnpm install --frozen-lockfile + - name: Build + run: pnpm run build + - name: Install browsers + run: node packages/web/dist/bin.js install ${{ matrix.browser }} --with-deps + - name: Parity + working-directory: packages/web/tests/parity + env: + BROWSER: ${{ matrix.browser }} + run: node ../../node_modules/e2e/dist/cli/bin.js run + - name: Upload report + if: ${{ !cancelled() }} + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: parity-${{ matrix.driver }}-${{ matrix.browser }} + path: | + packages/web/tests/parity/.e2e/report.json + packages/web/tests/parity/.e2e/results + if-no-files-found: warn + retention-days: 7 + # The one check the ruleset requires from this workflow. A skipped job # passes (the change cannot reach it); a failed or cancelled one fails it. gate: name: spec gate - needs: [check, test, install] + needs: [check, test, install, parity] if: ${{ always() }} runs-on: blacksmith-4vcpu-ubuntu-2404 timeout-minutes: 5 From 5f6348efe297e8811510215338100884cacf8027 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oskar=20Kwas=CC=81niewski?= Date: Sun, 1 Nov 2026 18:39:18 +0100 Subject: [PATCH 4/9] test(web): parity server on loopback only, bounded delays and sizes, same-server redirects, trusted CORS origins --- packages/web/tests/parity/server.mjs | 48 +++++++++++++++---- .../parity/tests/selectors-get-by.e2e.ts | 8 ++-- 2 files changed, 42 insertions(+), 14 deletions(-) diff --git a/packages/web/tests/parity/server.mjs b/packages/web/tests/parity/server.mjs index 855c15919e..fbea9e20bc 100644 --- a/packages/web/tests/parity/server.mjs +++ b/packages/web/tests/parity/server.mjs @@ -2,8 +2,8 @@ * The parity suite's app: Playwright's test assets (`assets/`, copied from * microsoft/playwright `tests/assets` at v1.64.1, Apache-2.0) plus the few * dynamic routes Playwright's test server sets per test, fixed here as paths. - * Serves every interface, so `127.0.0.1` and `localhost` on one port are two - * origins for the cross-origin cases. + * Listens on loopback only; `127.0.0.1` and `localhost` on one port are the + * two origins of the cross-origin cases, and the only ones it trusts. */ import { createReadStream, existsSync, statSync } from 'node:fs'; @@ -12,8 +12,35 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), 'assets'); +const PORT = Number(process.env.PORT ?? 4311); +const ORIGINS = new Set([`http://127.0.0.1:${PORT}`, `http://localhost:${PORT}`]); +const MAX_DELAY_MS = 30_000; +const MAX_BYTES = 16 << 20; const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.svg': 'image/svg+xml', '.txt': 'text/plain' }; +/** `value` as a number in [0, max], `fallback` when absent. */ +function bounded(value, fallback, max) { + return Math.min(Math.max(Number(value ?? fallback) || 0, 0), max); +} + +/** A redirect target on this server (a path, or either origin), else the empty page. */ +function sameServer(target) { + if (target === null) return '/empty.html'; + if (target.startsWith('/') && !target.startsWith('//')) return target; + const resolved = URL.canParse(target) ? new URL(target) : undefined; + return resolved !== undefined && ORIGINS.has(resolved.origin) ? resolved.href : '/empty.html'; +} + +/** + * The request's origin when it is one of the server's own, the only ones + * granted credentials, or `null`, the origin a cross-origin redirect leaves. + */ +function trustedOrigin(request) { + const { origin } = request.headers; + if (origin === 'null') return 'null'; + return origin !== undefined && ORIGINS.has(origin) ? origin : `http://127.0.0.1:${PORT}`; +} + /** The request body, read whole. */ function body(request) { return new Promise((resolve) => { @@ -48,13 +75,13 @@ const server = createServer(async (request, response) => { setTimeout(() => { response.writeHead(200, { 'content-type': query.get('type') ?? 'text/plain', 'access-control-allow-origin': '*' }); response.end(query.get('body') ?? 'slow'); - }, Number(query.get('ms') ?? 1000)); + }, bounded(query.get('ms'), 1000, MAX_DELAY_MS)); return; case '/never': request.on('close', () => response.destroy()); return; case '/redirect': - response.writeHead(302, { location: query.get('to') ?? '/empty.html' }); + response.writeHead(302, { location: sameServer(query.get('to')) }); response.end(); return; case '/download': @@ -74,7 +101,7 @@ const server = createServer(async (request, response) => { return; case '/cors-echo': { const allow = { - 'access-control-allow-origin': request.headers.origin ?? '*', + 'access-control-allow-origin': trustedOrigin(request), 'access-control-allow-credentials': 'true', 'access-control-allow-methods': 'POST, GET, OPTIONS, DELETE', 'access-control-allow-headers': request.headers['access-control-request-headers'] ?? '*', @@ -91,8 +118,8 @@ const server = createServer(async (request, response) => { } case '/bounce': { const headers = { - location: query.get('to') ?? '/empty.html', - 'access-control-allow-origin': request.headers.origin ?? '*', + location: sameServer(query.get('to')), + 'access-control-allow-origin': trustedOrigin(request), 'access-control-allow-credentials': 'true', 'access-control-allow-headers': request.headers['access-control-request-headers'] ?? '*', ...(query.has('cookie') ? { 'set-cookie': query.get('cookie') } : {}), @@ -124,7 +151,8 @@ const server = createServer(async (request, response) => { return; case '/upload': { const received = await body(request); - const boundary = Buffer.from(`--${/boundary=(.+)$/.exec(request.headers['content-type'] ?? '')?.[1] ?? ''}`); + const type = request.headers['content-type'] ?? ''; + const boundary = Buffer.from(`--${type.includes('boundary=') ? type.slice(type.indexOf('boundary=') + 'boundary='.length) : ''}`); const files = []; for (let start = received.indexOf(boundary); start !== -1;) { const next = received.indexOf(boundary, start + boundary.length); @@ -147,7 +175,7 @@ const server = createServer(async (request, response) => { return; } case '/binary': { - const data = Buffer.alloc(Number(query.get('bytes') ?? 1 << 20)); + const data = Buffer.alloc(bounded(query.get('bytes'), 1 << 20, MAX_BYTES)); for (let i = 0; i < data.length; i++) data[i] = Math.imul(i + 1, 2654435761) >>> 24; response.writeHead(200, { 'content-type': 'application/zip', 'content-length': data.length }); response.end(data); @@ -175,4 +203,4 @@ const server = createServer(async (request, response) => { createReadStream(file).pipe(response); }); -server.listen(Number(process.env.PORT ?? 4311)); +server.listen(PORT, '127.0.0.1'); diff --git a/packages/web/tests/parity/tests/selectors-get-by.e2e.ts b/packages/web/tests/parity/tests/selectors-get-by.e2e.ts index c848857858..cdfa8dd995 100644 --- a/packages/web/tests/parity/tests/selectors-get-by.e2e.ts +++ b/packages/web/tests/parity/tests/selectors-get-by.e2e.ts @@ -135,11 +135,11 @@ test.describe('selectors get by', { requires: ['browser'] }, () => { }); test('getBy escaping', async ({ screen, browser }) => { - const setAttributes = (value: string) => `() => { const input = document.querySelector('input'); for (const name of ['placeholder', 'title', 'alt']) input.setAttribute(name, ${JSON.stringify(value)}); }`; + const setAttributes = "(value) => { const input = document.querySelector('input'); for (const name of ['placeholder', 'title', 'alt']) input.setAttribute(name, value); }"; await browser.goto(content(``)); - await browser.evaluate(setAttributes('hello my\nwo"rld')); + await browser.evaluate(setAttributes, 'hello my\nwo"rld'); await expect.soft(screen.getByText('hello my\nwo"rld', { exact: false })).toHaveAttribute('id', 'label'); await expect.soft(screen.getByText('hello my wo"rld', { exact: false })).toHaveAttribute('id', 'label'); await expect.soft(screen.getByLabel('hello my\nwo"rld', { exact: false })).toHaveAttribute('id', 'control'); @@ -147,14 +147,14 @@ wo"rld`)); await browser.goto(content(``)); - await browser.evaluate(setAttributes('hello my\nworld')); + await browser.evaluate(setAttributes, 'hello my\nworld'); await expect.soft(screen.getByText('hello my\nworld', { exact: false })).toHaveAttribute('id', 'label'); await expect.soft(screen.getByText('hello my world', { exact: false })).toHaveAttribute('id', 'label'); await expect.soft(screen.getByLabel('hello my\nworld', { exact: false })).toHaveAttribute('id', 'control'); await expect.soft(screen.getByPlaceholder('hello my\nworld', { exact: false })).toHaveAttribute('id', 'control'); await browser.goto(content(``)); - await browser.evaluate(setAttributes('foo >> bar')); + await browser.evaluate(setAttributes, 'foo >> bar'); expect.soft(await screen.getByText('foo >> bar', { exact: false }).textContent()).toBe('foo >> bar'); await expect.soft(browser.locator('label')).toHaveText('foo >> bar'); await expect.soft(screen.getByText('foo >> bar', { exact: false })).toHaveText('foo >> bar'); From 10eaaa56606ddd305a8339b64ed0a50b1e8549df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oskar=20Kwas=CC=81niewski?= Date: Sun, 1 Nov 2026 19:50:43 +0100 Subject: [PATCH 5/9] test(web): parity review fixes: skips only past the matching assertions, /ws handshake, pdf type, backslash-safe redirects, cleanup in finally, fixed PARITY_PORT --- packages/web/tests/parity/README.md | 5 ++- packages/web/tests/parity/e2e.config.ts | 1 + packages/web/tests/parity/server.mjs | 22 +++++++++-- .../parity/tests/locator-convenience.e2e.ts | 4 +- .../web/tests/parity/tests/page-check.e2e.ts | 6 ++- .../parity/tests/page-filechooser.e2e.ts | 37 ++++++++++--------- 6 files changed, 48 insertions(+), 27 deletions(-) diff --git a/packages/web/tests/parity/README.md b/packages/web/tests/parity/README.md index 84000287a6..85f204d093 100644 --- a/packages/web/tests/parity/README.md +++ b/packages/web/tests/parity/README.md @@ -25,5 +25,6 @@ BROWSER=chromium node ../../node_modules/e2e/dist/cli/bin.js run BROWSER=firefox node ../../node_modules/e2e/dist/cli/bin.js run ``` -`PARITY_PORT` (default 4311) moves the server; `--output .e2e-` keeps -parallel runs apart. +`PARITY_PORT` (default 4311) moves the server. Parallel runs each need their +own `PARITY_PORT` and `--output .e2e-`, and must not share a browser: +`page-screenshot` writes its goldens into the shared `tests/` snapshot folder. diff --git a/packages/web/tests/parity/e2e.config.ts b/packages/web/tests/parity/e2e.config.ts index 2830b0007c..82f38e3602 100644 --- a/packages/web/tests/parity/e2e.config.ts +++ b/packages/web/tests/parity/e2e.config.ts @@ -7,6 +7,7 @@ import { web } from '@e2e-dev/web'; * Run it on both browsers (`BROWSER=chromium|firefox`); see README.md. */ const port = Number(process.env['PARITY_PORT'] ?? 4311); +if (!Number.isInteger(port) || port <= 0) throw new Error(`PARITY_PORT must be a fixed port, got ${process.env['PARITY_PORT']}`); export default { projectId: 'dev.e2e.web-parity', diff --git a/packages/web/tests/parity/server.mjs b/packages/web/tests/parity/server.mjs index fbea9e20bc..d8035c8045 100644 --- a/packages/web/tests/parity/server.mjs +++ b/packages/web/tests/parity/server.mjs @@ -6,6 +6,7 @@ * two origins of the cross-origin cases, and the only ones it trusts. */ +import { createHash } from 'node:crypto'; import { createReadStream, existsSync, statSync } from 'node:fs'; import { createServer } from 'node:http'; import path from 'node:path'; @@ -16,7 +17,7 @@ const PORT = Number(process.env.PORT ?? 4311); const ORIGINS = new Set([`http://127.0.0.1:${PORT}`, `http://localhost:${PORT}`]); const MAX_DELAY_MS = 30_000; const MAX_BYTES = 16 << 20; -const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.svg': 'image/svg+xml', '.txt': 'text/plain' }; +const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.pdf': 'application/pdf', '.svg': 'image/svg+xml', '.txt': 'text/plain' }; /** `value` as a number in [0, max], `fallback` when absent. */ function bounded(value, fallback, max) { @@ -26,9 +27,9 @@ function bounded(value, fallback, max) { /** A redirect target on this server (a path, or either origin), else the empty page. */ function sameServer(target) { if (target === null) return '/empty.html'; - if (target.startsWith('/') && !target.startsWith('//')) return target; - const resolved = URL.canParse(target) ? new URL(target) : undefined; - return resolved !== undefined && ORIGINS.has(resolved.origin) ? resolved.href : '/empty.html'; + const resolved = URL.canParse(target, `http://127.0.0.1:${PORT}`) ? new URL(target, `http://127.0.0.1:${PORT}`) : undefined; + if (resolved === undefined || !ORIGINS.has(resolved.origin)) return '/empty.html'; + return target.startsWith('/') ? `${resolved.pathname}${resolved.search}${resolved.hash}` : resolved.href; } /** @@ -203,4 +204,17 @@ const server = createServer(async (request, response) => { createReadStream(file).pipe(response); }); +// `/ws` accepts the handshake and holds the socket open, as Playwright's +// server does, so an open WebSocket is in the page during network-idle tests. +server.on('upgrade', (request, socket) => { + const key = request.headers['sec-websocket-key']; + if (new URL(request.url, 'http://localhost').pathname !== '/ws' || typeof key !== 'string') { + socket.destroy(); + return; + } + const accept = createHash('sha1').update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest('base64'); + socket.on('error', () => socket.destroy()); + socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`); +}); + server.listen(PORT, '127.0.0.1'); diff --git a/packages/web/tests/parity/tests/locator-convenience.e2e.ts b/packages/web/tests/parity/tests/locator-convenience.e2e.ts index 8f04ec5899..961ae0c8d3 100644 --- a/packages/web/tests/parity/tests/locator-convenience.e2e.ts +++ b/packages/web/tests/parity/tests/locator-convenience.e2e.ts @@ -36,7 +36,6 @@ test.describe('locator convenience', { requires: ['browser'] }, () => { }); test('inputValue should work', async ({ browser }) => { - e2eGap('`inputValue()` on an element that is no input reads "" instead of throwing'); await browser.goto('/dom.html'); await browser.locator('#select').selectOption({ value: 'foo' }); @@ -48,6 +47,7 @@ test.describe('locator convenience', { requires: ['browser'] }, () => { await browser.locator('#input').fill('input value'); expect(await browser.locator('#input').inputValue()).toBe('input value'); + e2eGap('`inputValue()` on an element that is no input reads "" instead of throwing'); const error = await browser.locator('#inner').inputValue().catch((e: unknown) => e); expect(error).toEqual(expect.any(Error)); }); @@ -77,12 +77,12 @@ test.describe('locator convenience', { requires: ['browser'] }, () => { }); test('isChecked should work', async ({ browser }) => { - e2eGap('`isChecked()` on an element that is no checkbox reads false instead of throwing'); await browser.goto(content(`
Not a checkbox
`)); const element = browser.locator('input'); expect(await element.isChecked()).toBe(true); await browser.evaluate("() => { document.querySelector('input').checked = false; }"); expect(await element.isChecked()).toBe(false); + e2eGap('`isChecked()` on an element that is no checkbox reads false instead of throwing'); const error = await browser.locator('div').isChecked().catch((e: unknown) => e); expect(error).toEqual(expect.any(Error)); }); diff --git a/packages/web/tests/parity/tests/page-check.e2e.ts b/packages/web/tests/parity/tests/page-check.e2e.ts index 9ad9d8abda..56b4aab63f 100644 --- a/packages/web/tests/parity/tests/page-check.e2e.ts +++ b/packages/web/tests/parity/tests/page-check.e2e.ts @@ -81,8 +81,10 @@ test.describe('page check', { requires: ['browser'] }, () => { }); test('should uncheck the box by aria role', async ({ browser }) => { - e2eGap('`uncheck` refuses any radio, a `role=menuitemradio` one included, where Playwright clicks it'); - for (const role of ['checkbox', 'menuitemcheckbox', 'option', 'radio', 'switch', 'menuitemradio', 'treeitem']) { + const radios = ['radio', 'menuitemradio']; + const roles = ['checkbox', 'menuitemcheckbox', 'option', 'radio', 'switch', 'menuitemradio', 'treeitem']; + for (const role of [...roles.filter((name) => !radios.includes(name)), ...radios]) { + if (role === radios[0]) e2eGap('`uncheck` refuses any radio, a `role=radio` or `role=menuitemradio` one included, where Playwright clicks it'); await browser.goto(content(`
CHECKBOX
`)); - await browser.locator('input[type=file]').setInputFiles('assets/file-to-upload.txt'); + await browser.locator('input[type=file]').setInputFiles(asset('file-to-upload.txt')); const events = await browser.evaluate<{ type: string }[]>('() => window.events'); expect(events.length).toBe(2); expect(events[0]!.type).toBe('input'); @@ -254,13 +254,13 @@ test.describe('page set input files', { requires: ['browser'] }, () => { await browser.goto(content('')); await browser.evaluate(recordEvents('input')); - await browser.locator('input[type=file]').setInputFiles('assets/file-to-upload.txt'); + await browser.locator('input[type=file]').setInputFiles(asset('file-to-upload.txt')); expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('file-to-upload.txt'); expect(await browser.evaluate('() => window.events')).toEqual(['input', 'change']); await browser.evaluate('() => { window.events.length = 0; }'); - await browser.locator('input[type=file]').setInputFiles('assets/pptr.png'); + await browser.locator('input[type=file]').setInputFiles(asset('pptr.png')); expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('pptr.png'); expect(await browser.evaluate('() => window.events')).toEqual(['input', 'change']); }); @@ -268,10 +268,10 @@ test.describe('page set input files', { requires: ['browser'] }, () => { test('should preserve lastModified timestamp', async ({ browser }) => { await browser.goto(content('')); const files = ['file-to-upload.txt', 'file-to-upload-2.txt']; - await browser.locator('input[type=file]').setInputFiles(files.map((f) => `assets/${f}`)); + await browser.locator('input[type=file]').setInputFiles(files.map(asset)); expect(await browser.evaluate("() => [...document.querySelector('input').files].map((f) => f.name)")).toEqual(files); const timestamps = await browser.evaluate("() => [...document.querySelector('input').files].map((f) => f.lastModified)"); - const expectedTimestamps = files.map((file) => Math.round(fs.statSync(`assets/${file}`).mtimeMs)); + const expectedTimestamps = files.map((file) => Math.round(fs.statSync(asset(file)).mtimeMs)); for (let i = 0; i < timestamps.length; i++) { expect(Math.abs(timestamps[i]! - expectedTimestamps[i]!)).toBeLessThanOrEqual(1000); } diff --git a/packages/web/tests/parity/tests/page-wait-for-navigation.e2e.ts b/apps/testbed/tests-parity/page-wait-for-navigation.e2e.ts similarity index 98% rename from packages/web/tests/parity/tests/page-wait-for-navigation.e2e.ts rename to apps/testbed/tests-parity/page-wait-for-navigation.e2e.ts index 81aa19eb6e..a3e6979c08 100644 --- a/packages/web/tests/parity/tests/page-wait-for-navigation.e2e.ts +++ b/apps/testbed/tests-parity/page-wait-for-navigation.e2e.ts @@ -1,6 +1,6 @@ /** * Adapted from microsoft/playwright tests/page/page-wait-for-navigation.spec.ts at v1.64.1. - * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../parity/LICENSE). * Rewritten against the e2e public API: `page.waitForNavigation()` is `browser.waitForURL` with the URL the * navigation lands on, and a `url` matcher is a RegExp. */ @@ -15,9 +15,8 @@ * - should fail when frame detaches: needs `frame.waitForNavigation`. */ -import { test } from '@e2e-dev/web'; import { expect } from 'e2e'; -import { content, CROSS, PREFIX } from './helpers.ts'; +import { content, CROSS, PREFIX, test } from './helpers.ts'; const EMPTY_PAGE = `${PREFIX}/empty.html`; diff --git a/packages/web/tests/parity/tests/page-wait-for-response.e2e.ts b/apps/testbed/tests-parity/page-wait-for-response.e2e.ts similarity index 91% rename from packages/web/tests/parity/tests/page-wait-for-response.e2e.ts rename to apps/testbed/tests-parity/page-wait-for-response.e2e.ts index 3f1a7498a0..28a30d6de2 100644 --- a/packages/web/tests/parity/tests/page-wait-for-response.e2e.ts +++ b/apps/testbed/tests-parity/page-wait-for-response.e2e.ts @@ -1,6 +1,6 @@ /** * Adapted from microsoft/playwright tests/page/page-wait-for-response.spec.ts at v1.64.1. - * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../parity/LICENSE). * Rewritten against the e2e public API: `browser.waitForResponse` takes a URL pattern. */ @@ -13,9 +13,8 @@ * - sync predicate should be only called once: needs response predicates. */ -import { test } from '@e2e-dev/web'; import { expect } from 'e2e'; -import { PREFIX, e2eGap } from './helpers.ts'; +import { PREFIX, test } from './helpers.ts'; const EMPTY_PAGE = `${PREFIX}/empty.html`; @@ -42,7 +41,6 @@ test.describe('page wait for response', { requires: ['browser'] }, () => { }); test('should work with no timeout', async ({ browser }) => { - e2eGap('a timeout must be positive; there is no `timeout: 0` for no timeout'); await browser.goto(EMPTY_PAGE); const [response] = await Promise.all([ browser.waitForResponse(`${PREFIX}/digits/2.png`, { timeout: 0 }), diff --git a/packages/web/tests/parity/tests/page-wait-for-url.e2e.ts b/apps/testbed/tests-parity/page-wait-for-url.e2e.ts similarity index 97% rename from packages/web/tests/parity/tests/page-wait-for-url.e2e.ts rename to apps/testbed/tests-parity/page-wait-for-url.e2e.ts index 6290b71e7b..2c6efdec8f 100644 --- a/packages/web/tests/parity/tests/page-wait-for-url.e2e.ts +++ b/apps/testbed/tests-parity/page-wait-for-url.e2e.ts @@ -1,6 +1,6 @@ /** * Adapted from microsoft/playwright tests/page/page-wait-for-url.spec.ts at v1.64.1. - * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../parity/LICENSE). * Rewritten against the e2e public API: `waitForURL` takes a URL or a RegExp, so a glob is the URL it names. */ @@ -12,9 +12,8 @@ * - should work on frame: needs `frame.waitForURL`. */ -import { test } from '@e2e-dev/web'; import { expect } from 'e2e'; -import { content, PREFIX } from './helpers.ts'; +import { content, PREFIX, test } from './helpers.ts'; const EMPTY_PAGE = `${PREFIX}/empty.html`; diff --git a/packages/web/tests/parity/tests/selectors-frame.e2e.ts b/apps/testbed/tests-parity/selectors-frame.e2e.ts similarity index 98% rename from packages/web/tests/parity/tests/selectors-frame.e2e.ts rename to apps/testbed/tests-parity/selectors-frame.e2e.ts index 9370b66998..ef2257333a 100644 --- a/packages/web/tests/parity/tests/selectors-frame.e2e.ts +++ b/apps/testbed/tests-parity/selectors-frame.e2e.ts @@ -1,6 +1,6 @@ /** * Adapted from microsoft/playwright tests/page/selectors-frame.spec.ts at v1.64.1. - * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../parity/LICENSE). * Rewritten against the e2e public API: `iframe >> internal:control=enter-frame >> x` is * `frameLocator('iframe').locator(x)`, `:has-text()` a `hasText` filter, and the routed frame * pages are pages the server serves (`content()`). @@ -32,9 +32,8 @@ * - should not allow dangling enter-frame after any-frame: `internal:control=any-frame`. */ -import { test } from '@e2e-dev/web'; import { expect } from 'e2e'; -import { content } from './helpers.ts'; +import { content, test } from './helpers.ts'; const iframe2 = content(''); diff --git a/packages/web/tests/parity/tests/selectors-get-by.e2e.ts b/apps/testbed/tests-parity/selectors-get-by.e2e.ts similarity index 99% rename from packages/web/tests/parity/tests/selectors-get-by.e2e.ts rename to apps/testbed/tests-parity/selectors-get-by.e2e.ts index cdfa8dd995..be3f4fa821 100644 --- a/packages/web/tests/parity/tests/selectors-get-by.e2e.ts +++ b/apps/testbed/tests-parity/selectors-get-by.e2e.ts @@ -1,6 +1,6 @@ /** * Adapted from microsoft/playwright tests/page/selectors-get-by.spec.ts at v1.64.1. - * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../parity/LICENSE). * Rewritten against the e2e public API: a string query is exact by default, * so Playwright's default substring match is `{ exact: false }` and its * `{ exact: true }` is the default; `evaluate(e => e.outerHTML)` reads become @@ -17,9 +17,8 @@ * - getByRole with description whitespace normalization: same. */ -import { test } from '@e2e-dev/web'; import { expect } from 'e2e'; -import { content } from './helpers.ts'; +import { content, test } from './helpers.ts'; test.describe('selectors get by', { requires: ['browser'] }, () => { test('getByTestId should work', async ({ screen, browser }) => { diff --git a/packages/web/tests/parity/tests/selectors-role.e2e.ts b/apps/testbed/tests-parity/selectors-role.e2e.ts similarity index 99% rename from packages/web/tests/parity/tests/selectors-role.e2e.ts rename to apps/testbed/tests-parity/selectors-role.e2e.ts index 532f7c89f5..59e354488b 100644 --- a/packages/web/tests/parity/tests/selectors-role.e2e.ts +++ b/apps/testbed/tests-parity/selectors-role.e2e.ts @@ -1,6 +1,6 @@ /** * Adapted from microsoft/playwright tests/page/selectors-role.spec.ts at v1.64.1. - * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../parity/LICENSE). * Rewritten against the e2e public API: a `role=` selector is `getByRole` * with the same options, a string name is exact by default so Playwright's * default substring match is `{ exact: false }`, and an @@ -12,10 +12,9 @@ * - errors: Playwright `role=` selector parse errors. */ -import { test } from '@e2e-dev/web'; import { expect } from 'e2e'; import type { Locator } from 'e2e'; -import { content } from './helpers.ts'; +import { content, test } from './helpers.ts'; /** The `aria-label` of every current match, in document order. */ async function labels(locator: Locator): Promise<(string | null)[]> { diff --git a/packages/web/tests/parity/tests/selectors-text.e2e.ts b/apps/testbed/tests-parity/selectors-text.e2e.ts similarity index 97% rename from packages/web/tests/parity/tests/selectors-text.e2e.ts rename to apps/testbed/tests-parity/selectors-text.e2e.ts index 24964e29bd..93f1dbefcf 100644 --- a/packages/web/tests/parity/tests/selectors-text.e2e.ts +++ b/apps/testbed/tests-parity/selectors-text.e2e.ts @@ -1,6 +1,6 @@ /** * Adapted from microsoft/playwright tests/page/selectors-text.spec.ts at v1.64.1. - * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../LICENSE). + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../parity/LICENSE). * Rewritten against the e2e public API: `locator(css, { hasText })` is a * locator `filter({ hasText })`, `toHaveId(id)` an `id` attribute match. * @@ -27,9 +27,8 @@ * - should work with paired quotes in the middle of selector: `>>` chains. */ -import { test } from '@e2e-dev/web'; import { expect } from 'e2e'; -import { content } from './helpers.ts'; +import { content, test } from './helpers.ts'; test.describe('selectors text', { requires: ['browser'] }, () => { test('text-is() should ignore comments', async ({ screen, browser }) => { diff --git a/apps/testbed/tsconfig.json b/apps/testbed/tsconfig.json index 05f7f48dcb..50e6e2bb6d 100644 --- a/apps/testbed/tsconfig.json +++ b/apps/testbed/tsconfig.json @@ -10,7 +10,10 @@ }, "include": [ "e2e.config.ts", + "e2e.parity.config.ts", "fixtures/**/*.ts", - "tests/**/*.ts" + "scripts/parity*.ts", + "tests/**/*.ts", + "tests-parity/**/*.ts" ] } diff --git a/packages/web/tests/parity/.gitignore b/packages/web/tests/parity/.gitignore deleted file mode 100644 index c91580c936..0000000000 --- a/packages/web/tests/parity/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.e2e*/ diff --git a/packages/web/tests/parity/README.md b/packages/web/tests/parity/README.md deleted file mode 100644 index 85f204d093..0000000000 --- a/packages/web/tests/parity/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# Behavior parity - -Playwright's own page tests, rewritten against the e2e public API, so -`web()` is held to Playwright's behavior. Adapted from microsoft/playwright -`tests/page` (and `tests/library/download.spec.ts`) at `v1.64.1`, the version -`playwright-core` is pinned to. Copyright Microsoft Corporation, Apache -License 2.0: see `LICENSE` and `NOTICE`. - -- `tests/*.e2e.ts`: one file per Playwright spec. Each keeps the original - test's title, inputs, and assertions; `page.click(selector)` becomes a - locator tap, `page.setContent(html)` a page the server serves (`content()`). - A test whose API e2e does not expose is left out; the file header lists them. -- `assets/`: Playwright's `tests/assets` files the tests load, unchanged. -- `server.mjs`: serves `assets/`, plus the routes Playwright's test server sets - per test as fixed paths. `127.0.0.1` and `localhost` on its port are the two - origins of the cross-origin cases. - -A test that hits a place where e2e differs from Playwright on purpose or -by a known gap is skipped with `e2eGap(reason)`. - -```sh -pnpm build -cd packages/web/tests/parity -BROWSER=chromium node ../../node_modules/e2e/dist/cli/bin.js run -BROWSER=firefox node ../../node_modules/e2e/dist/cli/bin.js run -``` - -`PARITY_PORT` (default 4311) moves the server. Parallel runs each need their -own `PARITY_PORT` and `--output .e2e-`, and must not share a browser: -`page-screenshot` writes its goldens into the shared `tests/` snapshot folder. diff --git a/packages/web/tests/parity/e2e.config.ts b/packages/web/tests/parity/e2e.config.ts deleted file mode 100644 index 82f38e3602..0000000000 --- a/packages/web/tests/parity/e2e.config.ts +++ /dev/null @@ -1,26 +0,0 @@ -import type { E2EConfig } from 'e2e'; -import { web } from '@e2e-dev/web'; - -/** - * Behavior parity: Playwright's own page tests (microsoft/playwright - * `tests/page` at v1.64.1, Apache-2.0), rewritten against the public API. - * Run it on both browsers (`BROWSER=chromium|firefox`); see README.md. - */ -const port = Number(process.env['PARITY_PORT'] ?? 4311); -if (!Number.isInteger(port) || port <= 0) throw new Error(`PARITY_PORT must be a fixed port, got ${process.env['PARITY_PORT']}`); - -export default { - projectId: 'dev.e2e.web-parity', - tests: 'tests/**/*.e2e.ts', - targets: [ - { - name: 'web', - engine: web({ browser: (process.env['BROWSER'] ?? 'chromium') as 'chromium' | 'firefox' }), - app: { - url: `http://127.0.0.1:${port}`, - command: { executable: 'node', args: ['server.mjs'], env: { PORT: String(port) } }, - }, - }, - ], - reporters: ['list'], -} satisfies E2EConfig; diff --git a/packages/web/tests/parity/tests/helpers.ts b/packages/web/tests/parity/tests/helpers.ts deleted file mode 100644 index 439151c8ee..0000000000 --- a/packages/web/tests/parity/tests/helpers.ts +++ /dev/null @@ -1,27 +0,0 @@ -/** What the parity tests share: the server's two origins, inline pages, and which browser runs. */ - -import { test } from '@e2e-dev/web'; - -const port = Number(process.env['PARITY_PORT'] ?? 4311); - -/** The app's origin, Playwright's `server.PREFIX`. */ -export const PREFIX = `http://127.0.0.1:${port}`; - -/** Another origin on the same server, Playwright's `server.CROSS_PROCESS_PREFIX`. */ -export const CROSS = `http://localhost:${port}`; - -/** The browser under test. */ -export const browserName = (process.env['BROWSER'] ?? 'chromium') as 'chromium' | 'firefox'; - -/** A path that serves `html` as a page, for Playwright's `page.setContent(html)`. */ -export function content(html: string): string { - return `/content?html=${Buffer.from(html).toString('base64url')}`; -} - -/** - * Skips the running test where e2e itself differs from Playwright, in every - * browser unless `on.browser` narrows it: `reason` names the difference. - */ -export function e2eGap(reason: string, on: { readonly browser?: 'chromium' | 'firefox' } = {}): void { - test.skip(on.browser === undefined || on.browser === browserName, `e2e: ${reason}`); -} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 87925fbc64..28fd25ef3a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -257,9 +257,15 @@ importers: '@types/node': specifier: 26.6.6 version: 26.6.6 + '@types/pngjs': + specifier: 6.0.5 + version: 6.0.5 ai: specifier: 7.0.162 version: 7.0.162(zod@4.6.7) + pngjs: + specifier: 7.0.0 + version: 7.0.0 typescript: specifier: 7.0.2 version: 7.0.2 From 713f892bd86826992e62897e2a5b0d1f6b7536aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oskar=20Kwas=CC=81niewski?= Date: Wed, 4 Nov 2026 14:22:43 +0100 Subject: [PATCH 8/9] test(testbed): fold the Playwright tests into the testbed suite Ported specs live in tests/ tagged playwright, served by the playground (app/playwright/), chromium only. Known gaps are test.fail; four that fail as engine failures are skipped. Drops the parity config, gap file, script, and CI step, and 10 testbed tests the ported ones cover. --- .fallowrc.json | 4 +- .github/workflows/spec.yml | 20 +- .oxlintrc.json | 2 +- apps/testbed/.gitignore | 4 +- apps/testbed/README.md | 15 +- .../{parity => app/playwright}/LICENSE | 0 .../testbed/{parity => app/playwright}/NOTICE | 0 .../assets/button-overlay-oopif.html | 0 .../playwright}/assets/chromium-linux.zip | Bin .../playwright}/assets/consolelog.html | 0 .../playwright}/assets/counter.html | 0 .../playwright}/assets/css-transition.html | 0 .../playwright}/assets/digits/0.png | Bin .../playwright}/assets/digits/1.png | Bin .../playwright}/assets/digits/2.png | Bin .../playwright}/assets/digits/3.png | Bin .../playwright}/assets/digits/4.png | Bin .../playwright}/assets/digits/5.png | Bin .../playwright}/assets/digits/6.png | Bin .../playwright}/assets/digits/7.png | Bin .../playwright}/assets/digits/8.png | Bin .../playwright}/assets/digits/9.png | Bin .../playwright}/assets/dom.html | 0 .../playwright}/assets/download-blob.html | 0 .../playwright}/assets/empty.html | 0 .../playwright}/assets/empty.pdf | Bin .../playwright}/assets/file to upload.txt | 0 .../playwright}/assets/file-to-upload-2.txt | 0 .../playwright}/assets/file-to-upload.txt | 0 .../assets/frames/child-redirect.html | 0 .../playwright}/assets/frames/frame.html | 0 .../playwright}/assets/frames/frameset.html | 0 .../playwright}/assets/frames/lazy-frame.html | 0 .../assets/frames/nested-frames.html | 0 .../playwright}/assets/frames/one-frame.html | 0 .../assets/frames/redirect-my-parent.html | 0 .../playwright}/assets/frames/script.js | 0 .../playwright}/assets/frames/style.css | 0 .../playwright}/assets/frames/two-frames.html | 0 .../playwright}/assets/global-var.html | 0 .../assets/grid-iframe-in-shadow.html | 0 .../playwright}/assets/grid.html | 0 .../playwright}/assets/historyapi.html | 0 .../playwright}/assets/injectedstyle.css | 0 .../assets/input/animating-button.html | 0 .../assets/input/background-fixed.html | 0 .../playwright}/assets/input/button.html | 0 .../playwright}/assets/input/checkbox.html | 0 .../assets/input/drag-n-drop-manual.html | 0 .../assets/input/fileupload-multi.html | 0 .../playwright}/assets/input/fileupload.html | 0 .../assets/input/folderupload.html | 0 .../assets/input/handle-locator.html | 0 .../playwright}/assets/input/keyboard.html | 0 .../playwright}/assets/input/mouse-helper.js | 0 .../assets/input/rotatedButton.html | 0 .../playwright}/assets/input/scrollable.html | 0 .../playwright}/assets/input/scrollable2.html | 0 .../playwright}/assets/input/select.html | 0 .../playwright}/assets/input/textarea.html | 0 .../playwright}/assets/input/touches.html | 0 .../playwright}/assets/networkidle-frame.html | 0 .../playwright}/assets/networkidle.html | 0 .../playwright}/assets/networkidle.js | 0 .../playwright}/assets/offscreenbuttons.html | 0 .../playwright}/assets/one-style.css | 0 .../playwright}/assets/one-style.html | 0 .../playwright}/assets/playground.html | 0 .../playwright}/assets/pptr.png | Bin .../playwright}/assets/preload.html | 0 .../playwright}/assets/redirectloop1.html | 0 .../playwright}/assets/redirectloop2.html | 0 .../playwright}/assets/rotate-pseudo.html | 0 .../assets/rotate-z-shadow-dom.html | 0 .../playwright}/assets/rotate-z.html | 0 .../assets/screenshots/canvas.html | 0 .../assets/screenshots/translateZ.html | 0 .../assets/sectionselectorengine.js | 0 .../playwright}/assets/self-request.html | 0 .../playwright}/assets/shadow.html | 0 .../playwright}/assets/simple.json | 0 .../playwright}/assets/title.html | 0 .../playwright}/assets/wrappedlink.html | 0 apps/testbed/app/playwright/routes.mjs | 225 ++++++++++++++++++ apps/testbed/app/server.mjs | 9 +- apps/testbed/e2e.parity.config.ts | 23 -- apps/testbed/package.json | 1 - apps/testbed/parity/README.md | 36 --- apps/testbed/parity/server.mjs | 220 ----------------- apps/testbed/scripts/parity-gaps.test.ts | 77 ------ apps/testbed/scripts/parity-gaps.ts | 113 --------- apps/testbed/scripts/parity.ts | 60 ----- apps/testbed/tests-parity/expected-gaps.txt | 51 ---- apps/testbed/tests-parity/helpers.ts | 34 --- apps/testbed/tests/browser.e2e.ts | 6 - .../page-check.e2e.ts => tests/check.e2e.ts} | 11 +- .../click-scroll.e2e.ts} | 21 +- .../page-click.e2e.ts => tests/click.e2e.ts} | 7 +- apps/testbed/tests/controls.e2e.ts | 11 +- .../dialog.e2e.ts} | 7 +- apps/testbed/tests/dialogs-frames.e2e.ts | 50 ---- .../{tests-parity => tests}/download.e2e.ts | 14 +- .../elementhandle-scroll-into-view.e2e.ts | 8 +- .../filechooser.e2e.ts} | 11 +- .../page-fill.e2e.ts => tests/fill.e2e.ts} | 25 +- apps/testbed/tests/forms.e2e.ts | 7 - .../{tests-parity => tests}/frame-goto.e2e.ts | 7 +- .../frame-hierarchy.e2e.ts | 7 +- apps/testbed/tests/helpers.ts | 17 ++ .../keyboard.e2e.ts} | 21 +- .../locator-convenience.e2e.ts | 13 +- .../locator-frame.e2e.ts | 13 +- .../locator-is-visible.e2e.ts | 7 +- .../locator-list.e2e.ts | 7 +- .../locator-misc-2.e2e.ts | 9 +- .../locator-query.e2e.ts | 7 +- .../network-idle.e2e.ts} | 8 +- apps/testbed/tests/network.e2e.ts | 19 -- .../request-continue.e2e.ts} | 17 +- .../request-fallback.e2e.ts} | 7 +- .../request-fulfill.e2e.ts} | 11 +- .../page-route.e2e.ts => tests/route.e2e.ts} | 55 ++--- .../screenshot.e2e.ts} | 28 +-- .../select-option.e2e.ts} | 9 +- .../selectors-frame.e2e.ts | 7 +- .../selectors-get-by.e2e.ts | 7 +- .../selectors-role.e2e.ts | 7 +- .../selectors-text.e2e.ts | 7 +- .../set-input-files.e2e.ts} | 10 +- .../wait-for-navigation.e2e.ts} | 7 +- .../wait-for-response.e2e.ts} | 9 +- .../wait-for-url.e2e.ts} | 7 +- apps/testbed/tsconfig.json | 5 +- 133 files changed, 450 insertions(+), 950 deletions(-) rename apps/testbed/{parity => app/playwright}/LICENSE (100%) rename apps/testbed/{parity => app/playwright}/NOTICE (100%) rename apps/testbed/{parity => app/playwright}/assets/button-overlay-oopif.html (100%) rename apps/testbed/{parity => app/playwright}/assets/chromium-linux.zip (100%) rename apps/testbed/{parity => app/playwright}/assets/consolelog.html (100%) rename apps/testbed/{parity => app/playwright}/assets/counter.html (100%) rename apps/testbed/{parity => app/playwright}/assets/css-transition.html (100%) rename apps/testbed/{parity => app/playwright}/assets/digits/0.png (100%) rename apps/testbed/{parity => app/playwright}/assets/digits/1.png (100%) rename apps/testbed/{parity => app/playwright}/assets/digits/2.png (100%) rename apps/testbed/{parity => app/playwright}/assets/digits/3.png (100%) rename apps/testbed/{parity => app/playwright}/assets/digits/4.png (100%) rename apps/testbed/{parity => app/playwright}/assets/digits/5.png (100%) rename apps/testbed/{parity => app/playwright}/assets/digits/6.png (100%) rename apps/testbed/{parity => app/playwright}/assets/digits/7.png (100%) rename apps/testbed/{parity => app/playwright}/assets/digits/8.png (100%) rename apps/testbed/{parity => app/playwright}/assets/digits/9.png (100%) rename apps/testbed/{parity => app/playwright}/assets/dom.html (100%) rename apps/testbed/{parity => app/playwright}/assets/download-blob.html (100%) rename apps/testbed/{parity => app/playwright}/assets/empty.html (100%) rename apps/testbed/{parity => app/playwright}/assets/empty.pdf (100%) rename apps/testbed/{parity => app/playwright}/assets/file to upload.txt (100%) rename apps/testbed/{parity => app/playwright}/assets/file-to-upload-2.txt (100%) rename apps/testbed/{parity => app/playwright}/assets/file-to-upload.txt (100%) rename apps/testbed/{parity => app/playwright}/assets/frames/child-redirect.html (100%) rename apps/testbed/{parity => app/playwright}/assets/frames/frame.html (100%) rename apps/testbed/{parity => app/playwright}/assets/frames/frameset.html (100%) rename apps/testbed/{parity => app/playwright}/assets/frames/lazy-frame.html (100%) rename apps/testbed/{parity => app/playwright}/assets/frames/nested-frames.html (100%) rename apps/testbed/{parity => app/playwright}/assets/frames/one-frame.html (100%) rename apps/testbed/{parity => app/playwright}/assets/frames/redirect-my-parent.html (100%) rename apps/testbed/{parity => app/playwright}/assets/frames/script.js (100%) rename apps/testbed/{parity => app/playwright}/assets/frames/style.css (100%) rename apps/testbed/{parity => app/playwright}/assets/frames/two-frames.html (100%) rename apps/testbed/{parity => app/playwright}/assets/global-var.html (100%) rename apps/testbed/{parity => app/playwright}/assets/grid-iframe-in-shadow.html (100%) rename apps/testbed/{parity => app/playwright}/assets/grid.html (100%) rename apps/testbed/{parity => app/playwright}/assets/historyapi.html (100%) rename apps/testbed/{parity => app/playwright}/assets/injectedstyle.css (100%) rename apps/testbed/{parity => app/playwright}/assets/input/animating-button.html (100%) rename apps/testbed/{parity => app/playwright}/assets/input/background-fixed.html (100%) rename apps/testbed/{parity => app/playwright}/assets/input/button.html (100%) rename apps/testbed/{parity => app/playwright}/assets/input/checkbox.html (100%) rename apps/testbed/{parity => app/playwright}/assets/input/drag-n-drop-manual.html (100%) rename apps/testbed/{parity => app/playwright}/assets/input/fileupload-multi.html (100%) rename apps/testbed/{parity => app/playwright}/assets/input/fileupload.html (100%) rename apps/testbed/{parity => app/playwright}/assets/input/folderupload.html (100%) rename apps/testbed/{parity => app/playwright}/assets/input/handle-locator.html (100%) rename apps/testbed/{parity => app/playwright}/assets/input/keyboard.html (100%) rename apps/testbed/{parity => app/playwright}/assets/input/mouse-helper.js (100%) rename apps/testbed/{parity => app/playwright}/assets/input/rotatedButton.html (100%) rename apps/testbed/{parity => app/playwright}/assets/input/scrollable.html (100%) rename apps/testbed/{parity => app/playwright}/assets/input/scrollable2.html (100%) rename apps/testbed/{parity => app/playwright}/assets/input/select.html (100%) rename apps/testbed/{parity => app/playwright}/assets/input/textarea.html (100%) rename apps/testbed/{parity => app/playwright}/assets/input/touches.html (100%) rename apps/testbed/{parity => app/playwright}/assets/networkidle-frame.html (100%) rename apps/testbed/{parity => app/playwright}/assets/networkidle.html (100%) rename apps/testbed/{parity => app/playwright}/assets/networkidle.js (100%) rename apps/testbed/{parity => app/playwright}/assets/offscreenbuttons.html (100%) rename apps/testbed/{parity => app/playwright}/assets/one-style.css (100%) rename apps/testbed/{parity => app/playwright}/assets/one-style.html (100%) rename apps/testbed/{parity => app/playwright}/assets/playground.html (100%) rename apps/testbed/{parity => app/playwright}/assets/pptr.png (100%) rename apps/testbed/{parity => app/playwright}/assets/preload.html (100%) rename apps/testbed/{parity => app/playwright}/assets/redirectloop1.html (100%) rename apps/testbed/{parity => app/playwright}/assets/redirectloop2.html (100%) rename apps/testbed/{parity => app/playwright}/assets/rotate-pseudo.html (100%) rename apps/testbed/{parity => app/playwright}/assets/rotate-z-shadow-dom.html (100%) rename apps/testbed/{parity => app/playwright}/assets/rotate-z.html (100%) rename apps/testbed/{parity => app/playwright}/assets/screenshots/canvas.html (100%) rename apps/testbed/{parity => app/playwright}/assets/screenshots/translateZ.html (100%) rename apps/testbed/{parity => app/playwright}/assets/sectionselectorengine.js (100%) rename apps/testbed/{parity => app/playwright}/assets/self-request.html (100%) rename apps/testbed/{parity => app/playwright}/assets/shadow.html (100%) rename apps/testbed/{parity => app/playwright}/assets/simple.json (100%) rename apps/testbed/{parity => app/playwright}/assets/title.html (100%) rename apps/testbed/{parity => app/playwright}/assets/wrappedlink.html (100%) create mode 100644 apps/testbed/app/playwright/routes.mjs delete mode 100644 apps/testbed/e2e.parity.config.ts delete mode 100644 apps/testbed/parity/README.md delete mode 100644 apps/testbed/parity/server.mjs delete mode 100644 apps/testbed/scripts/parity-gaps.test.ts delete mode 100644 apps/testbed/scripts/parity-gaps.ts delete mode 100644 apps/testbed/scripts/parity.ts delete mode 100644 apps/testbed/tests-parity/expected-gaps.txt delete mode 100644 apps/testbed/tests-parity/helpers.ts rename apps/testbed/{tests-parity/page-check.e2e.ts => tests/check.e2e.ts} (90%) rename apps/testbed/{tests-parity/page-click-scroll.e2e.ts => tests/click-scroll.e2e.ts} (82%) rename apps/testbed/{tests-parity/page-click.e2e.ts => tests/click.e2e.ts} (99%) rename apps/testbed/{tests-parity/page-dialog.e2e.ts => tests/dialog.e2e.ts} (95%) rename apps/testbed/{tests-parity => tests}/download.e2e.ts (95%) rename apps/testbed/{tests-parity => tests}/elementhandle-scroll-into-view.e2e.ts (96%) rename apps/testbed/{tests-parity/page-filechooser.e2e.ts => tests/filechooser.e2e.ts} (94%) rename apps/testbed/{tests-parity/page-fill.e2e.ts => tests/fill.e2e.ts} (94%) rename apps/testbed/{tests-parity => tests}/frame-goto.e2e.ts (83%) rename apps/testbed/{tests-parity => tests}/frame-hierarchy.e2e.ts (92%) rename apps/testbed/{tests-parity/page-keyboard.e2e.ts => tests/keyboard.e2e.ts} (97%) rename apps/testbed/{tests-parity => tests}/locator-convenience.e2e.ts (86%) rename apps/testbed/{tests-parity => tests}/locator-frame.e2e.ts (93%) rename apps/testbed/{tests-parity => tests}/locator-is-visible.e2e.ts (96%) rename apps/testbed/{tests-parity => tests}/locator-list.e2e.ts (73%) rename apps/testbed/{tests-parity => tests}/locator-misc-2.e2e.ts (93%) rename apps/testbed/{tests-parity => tests}/locator-query.e2e.ts (98%) rename apps/testbed/{tests-parity/page-network-idle.e2e.ts => tests/network-idle.e2e.ts} (96%) rename apps/testbed/{tests-parity/page-request-continue.e2e.ts => tests/request-continue.e2e.ts} (96%) rename apps/testbed/{tests-parity/page-request-fallback.e2e.ts => tests/request-fallback.e2e.ts} (94%) rename apps/testbed/{tests-parity/page-request-fulfill.e2e.ts => tests/request-fulfill.e2e.ts} (95%) rename apps/testbed/{tests-parity/page-route.e2e.ts => tests/route.e2e.ts} (92%) rename apps/testbed/{tests-parity/page-screenshot.e2e.ts => tests/screenshot.e2e.ts} (94%) rename apps/testbed/{tests-parity/page-select-option.e2e.ts => tests/select-option.e2e.ts} (97%) rename apps/testbed/{tests-parity => tests}/selectors-frame.e2e.ts (97%) rename apps/testbed/{tests-parity => tests}/selectors-get-by.e2e.ts (98%) rename apps/testbed/{tests-parity => tests}/selectors-role.e2e.ts (98%) rename apps/testbed/{tests-parity => tests}/selectors-text.e2e.ts (94%) rename apps/testbed/{tests-parity/page-set-input-files.e2e.ts => tests/set-input-files.e2e.ts} (97%) rename apps/testbed/{tests-parity/page-wait-for-navigation.e2e.ts => tests/wait-for-navigation.e2e.ts} (97%) rename apps/testbed/{tests-parity/page-wait-for-response.e2e.ts => tests/wait-for-response.e2e.ts} (84%) rename apps/testbed/{tests-parity/page-wait-for-url.e2e.ts => tests/wait-for-url.e2e.ts} (94%) diff --git a/.fallowrc.json b/.fallowrc.json index 25c9107503..541d166fdf 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -14,8 +14,6 @@ "apps/mobile-benchmark/e2e.*.config.ts", "apps/mobile-benchmark/tests*/**/*.ts", "apps/mobile-benchmark/index.ts", - "apps/testbed/parity/server.mjs", - "apps/testbed/scripts/parity.ts", "packages/e2e/tests/types/sdk-types.ts", "packages/web/tests/types/connection.ts", "packages/web/tests/types/init-scripts.ts", @@ -37,7 +35,7 @@ "examples/**", "**/next-env.d.ts", "**/.e2e/**", - "apps/testbed/parity/assets/**", + "apps/testbed/app/playwright/assets/**", "packages/e2e/tests/tmp-projects/**" ], "ignoreDependencies": [ diff --git a/.github/workflows/spec.yml b/.github/workflows/spec.yml index 2b71dbd2ee..e374d7aff3 100644 --- a/.github/workflows/spec.yml +++ b/.github/workflows/spec.yml @@ -22,7 +22,7 @@ concurrency: jobs: check: runs-on: blacksmith-4vcpu-ubuntu-2404 - timeout-minutes: 25 + timeout-minutes: 15 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -72,24 +72,6 @@ jobs: run: pnpm --filter @e2e-dev/testbed test ${{ github.event_name == 'pull_request' && format('--changed-since origin/{0}', github.base_ref) || '' }} env: AI_GATEWAY_API_KEY: ${{ secrets.AI_GATEWAY_API_KEY }} - # Playwright's own page tests on chromium and firefox: a failure not listed - # in apps/testbed/tests-parity/expected-gaps.txt fails, and so does a - # listed gap that passes. - - name: Playwright parity - run: | - node --test apps/testbed/scripts/parity-gaps.test.ts - pnpm --filter @e2e-dev/testbed test:parity - - name: Upload parity report - if: ${{ failure() }} - continue-on-error: true - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: parity-report - path: | - apps/testbed/.e2e-parity/report.json - apps/testbed/.e2e-parity/results - if-no-files-found: warn - retention-days: 7 test: runs-on: blacksmith-4vcpu-ubuntu-2404 diff --git a/.oxlintrc.json b/.oxlintrc.json index 9e7fa82d84..0ece7fe2f6 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -17,7 +17,7 @@ // Vendored conformance data, kept byte for byte. "packages/*/tests/conformance/*/**", // Playwright's test assets, kept byte for byte. - "apps/testbed/parity/assets/**", + "apps/testbed/app/playwright/assets/**", "packages/*/tests/tmp-projects/**", // Standalone user-facing projects with their own installs; nothing here builds them. "examples/**", diff --git a/apps/testbed/.gitignore b/apps/testbed/.gitignore index 338b80a358..d8320ed41d 100644 --- a/apps/testbed/.gitignore +++ b/apps/testbed/.gitignore @@ -14,5 +14,5 @@ # Verification skill scratch: bug-bash charter output and proofs kept past the next run. .e2e/bugbash/ .e2e/proof/ -# Goldens page-screenshot writes while it runs. -tests-parity/*-snapshots/ +# Goldens the Playwright screenshot tests write while they run. +tests/screenshot.e2e.ts-snapshots/ diff --git a/apps/testbed/README.md b/apps/testbed/README.md index cfbfffc24a..e8b6323f8c 100644 --- a/apps/testbed/README.md +++ b/apps/testbed/README.md @@ -17,6 +17,9 @@ here. `controls` (control states, scrolling, the browser fixture's page, the speed counter, about). `app/pages/index.mjs` merges them and `app/layout.mjs` renders the nav from that registry. +- `app/playwright/` — Playwright's test assets (v1.64.1, Apache-2.0, with its + `LICENSE` and `NOTICE`) and the dynamic routes its test server sets, served + by the playground for any path it has no page for. - `app/bug-garden.mjs` — a bookshop with planted defects, for `e2e explore`. - `dogfood/server.mjs` — an expense-claims app with a test API, for the executor dogfoods. @@ -27,7 +30,12 @@ here. states and the failure codes (`controls`), pointer coordinates and path swipes (`pointer`), viewport and node scrolling (`scroll`), the `browser` fixture's own verbs (`browser`), and the per-action speed floor (`speed`). - `tests/helpers.ts` holds the shared `failure`, `boxOf`, and `centerOf`. + The files tagged `playwright` are Playwright's own `tests/page` specs at + v1.64.1, ported to the public API: each header names its source and the + tests left out, and `fail: 'reason'` marks a test e2e fails on purpose or + by a known gap (`--tag playwright` runs only them). + `tests/helpers.ts` holds the shared `failure`, `boxOf`, and `centerOf`, + and the ported tests' `content`, `asset`, `PREFIX`, and `CROSS`. - `e2e.lightpanda.config.ts` and `e2e.lightpanda-agent.config.ts`: the local suite and the agent suite on `@e2e-dev/lightpanda`, which starts [Lightpanda](https://lightpanda.io) from `LIGHTPANDA_PATH` (or `PATH`), @@ -44,10 +52,6 @@ here. `StepExecutor` with its own tools and transport; the engine is never touched. - `e2e.dogfood-edge.config.ts` + `tests-dogfood-edge/` — steps expected to conclude blocked or failed; the report, not the exit code, is the output. -- `e2e.parity.config.ts` + `tests-parity/` + `parity/`: Playwright's own - page tests at v1.64.1, ported to the public API, on chromium and firefox. - `scripts/parity.ts` runs them and fails on any failure - `tests-parity/expected-gaps.txt` does not list; see `parity/README.md`. - `e2e.stress.config.ts` + `tests-stress/` — failures, timeouts, skips, flakes, and hostile titles for the reporters. - `e2e.explore.config.ts` + `scripts/explore-bench.mjs` — `e2e explore` @@ -66,7 +70,6 @@ AI_GATEWAY_API_KEY=... pnpm --filter @e2e-dev/testbed test:agent # real mode AI_GATEWAY_API_KEY=... pnpm --filter @e2e-dev/testbed test:dogfood AI_GATEWAY_API_KEY=... pnpm --filter @e2e-dev/testbed explore:garden pnpm --filter @e2e-dev/testbed test:stress # reporters only -pnpm --filter @e2e-dev/testbed test:parity # Playwright parity, both browsers ``` The local suite runs in CI on every push. Reports land in `.e2e/report.json`; diff --git a/apps/testbed/parity/LICENSE b/apps/testbed/app/playwright/LICENSE similarity index 100% rename from apps/testbed/parity/LICENSE rename to apps/testbed/app/playwright/LICENSE diff --git a/apps/testbed/parity/NOTICE b/apps/testbed/app/playwright/NOTICE similarity index 100% rename from apps/testbed/parity/NOTICE rename to apps/testbed/app/playwright/NOTICE diff --git a/apps/testbed/parity/assets/button-overlay-oopif.html b/apps/testbed/app/playwright/assets/button-overlay-oopif.html similarity index 100% rename from apps/testbed/parity/assets/button-overlay-oopif.html rename to apps/testbed/app/playwright/assets/button-overlay-oopif.html diff --git a/apps/testbed/parity/assets/chromium-linux.zip b/apps/testbed/app/playwright/assets/chromium-linux.zip similarity index 100% rename from apps/testbed/parity/assets/chromium-linux.zip rename to apps/testbed/app/playwright/assets/chromium-linux.zip diff --git a/apps/testbed/parity/assets/consolelog.html b/apps/testbed/app/playwright/assets/consolelog.html similarity index 100% rename from apps/testbed/parity/assets/consolelog.html rename to apps/testbed/app/playwright/assets/consolelog.html diff --git a/apps/testbed/parity/assets/counter.html b/apps/testbed/app/playwright/assets/counter.html similarity index 100% rename from apps/testbed/parity/assets/counter.html rename to apps/testbed/app/playwright/assets/counter.html diff --git a/apps/testbed/parity/assets/css-transition.html b/apps/testbed/app/playwright/assets/css-transition.html similarity index 100% rename from apps/testbed/parity/assets/css-transition.html rename to apps/testbed/app/playwright/assets/css-transition.html diff --git a/apps/testbed/parity/assets/digits/0.png b/apps/testbed/app/playwright/assets/digits/0.png similarity index 100% rename from apps/testbed/parity/assets/digits/0.png rename to apps/testbed/app/playwright/assets/digits/0.png diff --git a/apps/testbed/parity/assets/digits/1.png b/apps/testbed/app/playwright/assets/digits/1.png similarity index 100% rename from apps/testbed/parity/assets/digits/1.png rename to apps/testbed/app/playwright/assets/digits/1.png diff --git a/apps/testbed/parity/assets/digits/2.png b/apps/testbed/app/playwright/assets/digits/2.png similarity index 100% rename from apps/testbed/parity/assets/digits/2.png rename to apps/testbed/app/playwright/assets/digits/2.png diff --git a/apps/testbed/parity/assets/digits/3.png b/apps/testbed/app/playwright/assets/digits/3.png similarity index 100% rename from apps/testbed/parity/assets/digits/3.png rename to apps/testbed/app/playwright/assets/digits/3.png diff --git a/apps/testbed/parity/assets/digits/4.png b/apps/testbed/app/playwright/assets/digits/4.png similarity index 100% rename from apps/testbed/parity/assets/digits/4.png rename to apps/testbed/app/playwright/assets/digits/4.png diff --git a/apps/testbed/parity/assets/digits/5.png b/apps/testbed/app/playwright/assets/digits/5.png similarity index 100% rename from apps/testbed/parity/assets/digits/5.png rename to apps/testbed/app/playwright/assets/digits/5.png diff --git a/apps/testbed/parity/assets/digits/6.png b/apps/testbed/app/playwright/assets/digits/6.png similarity index 100% rename from apps/testbed/parity/assets/digits/6.png rename to apps/testbed/app/playwright/assets/digits/6.png diff --git a/apps/testbed/parity/assets/digits/7.png b/apps/testbed/app/playwright/assets/digits/7.png similarity index 100% rename from apps/testbed/parity/assets/digits/7.png rename to apps/testbed/app/playwright/assets/digits/7.png diff --git a/apps/testbed/parity/assets/digits/8.png b/apps/testbed/app/playwright/assets/digits/8.png similarity index 100% rename from apps/testbed/parity/assets/digits/8.png rename to apps/testbed/app/playwright/assets/digits/8.png diff --git a/apps/testbed/parity/assets/digits/9.png b/apps/testbed/app/playwright/assets/digits/9.png similarity index 100% rename from apps/testbed/parity/assets/digits/9.png rename to apps/testbed/app/playwright/assets/digits/9.png diff --git a/apps/testbed/parity/assets/dom.html b/apps/testbed/app/playwright/assets/dom.html similarity index 100% rename from apps/testbed/parity/assets/dom.html rename to apps/testbed/app/playwright/assets/dom.html diff --git a/apps/testbed/parity/assets/download-blob.html b/apps/testbed/app/playwright/assets/download-blob.html similarity index 100% rename from apps/testbed/parity/assets/download-blob.html rename to apps/testbed/app/playwright/assets/download-blob.html diff --git a/apps/testbed/parity/assets/empty.html b/apps/testbed/app/playwright/assets/empty.html similarity index 100% rename from apps/testbed/parity/assets/empty.html rename to apps/testbed/app/playwright/assets/empty.html diff --git a/apps/testbed/parity/assets/empty.pdf b/apps/testbed/app/playwright/assets/empty.pdf similarity index 100% rename from apps/testbed/parity/assets/empty.pdf rename to apps/testbed/app/playwright/assets/empty.pdf diff --git a/apps/testbed/parity/assets/file to upload.txt b/apps/testbed/app/playwright/assets/file to upload.txt similarity index 100% rename from apps/testbed/parity/assets/file to upload.txt rename to apps/testbed/app/playwright/assets/file to upload.txt diff --git a/apps/testbed/parity/assets/file-to-upload-2.txt b/apps/testbed/app/playwright/assets/file-to-upload-2.txt similarity index 100% rename from apps/testbed/parity/assets/file-to-upload-2.txt rename to apps/testbed/app/playwright/assets/file-to-upload-2.txt diff --git a/apps/testbed/parity/assets/file-to-upload.txt b/apps/testbed/app/playwright/assets/file-to-upload.txt similarity index 100% rename from apps/testbed/parity/assets/file-to-upload.txt rename to apps/testbed/app/playwright/assets/file-to-upload.txt diff --git a/apps/testbed/parity/assets/frames/child-redirect.html b/apps/testbed/app/playwright/assets/frames/child-redirect.html similarity index 100% rename from apps/testbed/parity/assets/frames/child-redirect.html rename to apps/testbed/app/playwright/assets/frames/child-redirect.html diff --git a/apps/testbed/parity/assets/frames/frame.html b/apps/testbed/app/playwright/assets/frames/frame.html similarity index 100% rename from apps/testbed/parity/assets/frames/frame.html rename to apps/testbed/app/playwright/assets/frames/frame.html diff --git a/apps/testbed/parity/assets/frames/frameset.html b/apps/testbed/app/playwright/assets/frames/frameset.html similarity index 100% rename from apps/testbed/parity/assets/frames/frameset.html rename to apps/testbed/app/playwright/assets/frames/frameset.html diff --git a/apps/testbed/parity/assets/frames/lazy-frame.html b/apps/testbed/app/playwright/assets/frames/lazy-frame.html similarity index 100% rename from apps/testbed/parity/assets/frames/lazy-frame.html rename to apps/testbed/app/playwright/assets/frames/lazy-frame.html diff --git a/apps/testbed/parity/assets/frames/nested-frames.html b/apps/testbed/app/playwright/assets/frames/nested-frames.html similarity index 100% rename from apps/testbed/parity/assets/frames/nested-frames.html rename to apps/testbed/app/playwright/assets/frames/nested-frames.html diff --git a/apps/testbed/parity/assets/frames/one-frame.html b/apps/testbed/app/playwright/assets/frames/one-frame.html similarity index 100% rename from apps/testbed/parity/assets/frames/one-frame.html rename to apps/testbed/app/playwright/assets/frames/one-frame.html diff --git a/apps/testbed/parity/assets/frames/redirect-my-parent.html b/apps/testbed/app/playwright/assets/frames/redirect-my-parent.html similarity index 100% rename from apps/testbed/parity/assets/frames/redirect-my-parent.html rename to apps/testbed/app/playwright/assets/frames/redirect-my-parent.html diff --git a/apps/testbed/parity/assets/frames/script.js b/apps/testbed/app/playwright/assets/frames/script.js similarity index 100% rename from apps/testbed/parity/assets/frames/script.js rename to apps/testbed/app/playwright/assets/frames/script.js diff --git a/apps/testbed/parity/assets/frames/style.css b/apps/testbed/app/playwright/assets/frames/style.css similarity index 100% rename from apps/testbed/parity/assets/frames/style.css rename to apps/testbed/app/playwright/assets/frames/style.css diff --git a/apps/testbed/parity/assets/frames/two-frames.html b/apps/testbed/app/playwright/assets/frames/two-frames.html similarity index 100% rename from apps/testbed/parity/assets/frames/two-frames.html rename to apps/testbed/app/playwright/assets/frames/two-frames.html diff --git a/apps/testbed/parity/assets/global-var.html b/apps/testbed/app/playwright/assets/global-var.html similarity index 100% rename from apps/testbed/parity/assets/global-var.html rename to apps/testbed/app/playwright/assets/global-var.html diff --git a/apps/testbed/parity/assets/grid-iframe-in-shadow.html b/apps/testbed/app/playwright/assets/grid-iframe-in-shadow.html similarity index 100% rename from apps/testbed/parity/assets/grid-iframe-in-shadow.html rename to apps/testbed/app/playwright/assets/grid-iframe-in-shadow.html diff --git a/apps/testbed/parity/assets/grid.html b/apps/testbed/app/playwright/assets/grid.html similarity index 100% rename from apps/testbed/parity/assets/grid.html rename to apps/testbed/app/playwright/assets/grid.html diff --git a/apps/testbed/parity/assets/historyapi.html b/apps/testbed/app/playwright/assets/historyapi.html similarity index 100% rename from apps/testbed/parity/assets/historyapi.html rename to apps/testbed/app/playwright/assets/historyapi.html diff --git a/apps/testbed/parity/assets/injectedstyle.css b/apps/testbed/app/playwright/assets/injectedstyle.css similarity index 100% rename from apps/testbed/parity/assets/injectedstyle.css rename to apps/testbed/app/playwright/assets/injectedstyle.css diff --git a/apps/testbed/parity/assets/input/animating-button.html b/apps/testbed/app/playwright/assets/input/animating-button.html similarity index 100% rename from apps/testbed/parity/assets/input/animating-button.html rename to apps/testbed/app/playwright/assets/input/animating-button.html diff --git a/apps/testbed/parity/assets/input/background-fixed.html b/apps/testbed/app/playwright/assets/input/background-fixed.html similarity index 100% rename from apps/testbed/parity/assets/input/background-fixed.html rename to apps/testbed/app/playwright/assets/input/background-fixed.html diff --git a/apps/testbed/parity/assets/input/button.html b/apps/testbed/app/playwright/assets/input/button.html similarity index 100% rename from apps/testbed/parity/assets/input/button.html rename to apps/testbed/app/playwright/assets/input/button.html diff --git a/apps/testbed/parity/assets/input/checkbox.html b/apps/testbed/app/playwright/assets/input/checkbox.html similarity index 100% rename from apps/testbed/parity/assets/input/checkbox.html rename to apps/testbed/app/playwright/assets/input/checkbox.html diff --git a/apps/testbed/parity/assets/input/drag-n-drop-manual.html b/apps/testbed/app/playwright/assets/input/drag-n-drop-manual.html similarity index 100% rename from apps/testbed/parity/assets/input/drag-n-drop-manual.html rename to apps/testbed/app/playwright/assets/input/drag-n-drop-manual.html diff --git a/apps/testbed/parity/assets/input/fileupload-multi.html b/apps/testbed/app/playwright/assets/input/fileupload-multi.html similarity index 100% rename from apps/testbed/parity/assets/input/fileupload-multi.html rename to apps/testbed/app/playwright/assets/input/fileupload-multi.html diff --git a/apps/testbed/parity/assets/input/fileupload.html b/apps/testbed/app/playwright/assets/input/fileupload.html similarity index 100% rename from apps/testbed/parity/assets/input/fileupload.html rename to apps/testbed/app/playwright/assets/input/fileupload.html diff --git a/apps/testbed/parity/assets/input/folderupload.html b/apps/testbed/app/playwright/assets/input/folderupload.html similarity index 100% rename from apps/testbed/parity/assets/input/folderupload.html rename to apps/testbed/app/playwright/assets/input/folderupload.html diff --git a/apps/testbed/parity/assets/input/handle-locator.html b/apps/testbed/app/playwright/assets/input/handle-locator.html similarity index 100% rename from apps/testbed/parity/assets/input/handle-locator.html rename to apps/testbed/app/playwright/assets/input/handle-locator.html diff --git a/apps/testbed/parity/assets/input/keyboard.html b/apps/testbed/app/playwright/assets/input/keyboard.html similarity index 100% rename from apps/testbed/parity/assets/input/keyboard.html rename to apps/testbed/app/playwright/assets/input/keyboard.html diff --git a/apps/testbed/parity/assets/input/mouse-helper.js b/apps/testbed/app/playwright/assets/input/mouse-helper.js similarity index 100% rename from apps/testbed/parity/assets/input/mouse-helper.js rename to apps/testbed/app/playwright/assets/input/mouse-helper.js diff --git a/apps/testbed/parity/assets/input/rotatedButton.html b/apps/testbed/app/playwright/assets/input/rotatedButton.html similarity index 100% rename from apps/testbed/parity/assets/input/rotatedButton.html rename to apps/testbed/app/playwright/assets/input/rotatedButton.html diff --git a/apps/testbed/parity/assets/input/scrollable.html b/apps/testbed/app/playwright/assets/input/scrollable.html similarity index 100% rename from apps/testbed/parity/assets/input/scrollable.html rename to apps/testbed/app/playwright/assets/input/scrollable.html diff --git a/apps/testbed/parity/assets/input/scrollable2.html b/apps/testbed/app/playwright/assets/input/scrollable2.html similarity index 100% rename from apps/testbed/parity/assets/input/scrollable2.html rename to apps/testbed/app/playwright/assets/input/scrollable2.html diff --git a/apps/testbed/parity/assets/input/select.html b/apps/testbed/app/playwright/assets/input/select.html similarity index 100% rename from apps/testbed/parity/assets/input/select.html rename to apps/testbed/app/playwright/assets/input/select.html diff --git a/apps/testbed/parity/assets/input/textarea.html b/apps/testbed/app/playwright/assets/input/textarea.html similarity index 100% rename from apps/testbed/parity/assets/input/textarea.html rename to apps/testbed/app/playwright/assets/input/textarea.html diff --git a/apps/testbed/parity/assets/input/touches.html b/apps/testbed/app/playwright/assets/input/touches.html similarity index 100% rename from apps/testbed/parity/assets/input/touches.html rename to apps/testbed/app/playwright/assets/input/touches.html diff --git a/apps/testbed/parity/assets/networkidle-frame.html b/apps/testbed/app/playwright/assets/networkidle-frame.html similarity index 100% rename from apps/testbed/parity/assets/networkidle-frame.html rename to apps/testbed/app/playwright/assets/networkidle-frame.html diff --git a/apps/testbed/parity/assets/networkidle.html b/apps/testbed/app/playwright/assets/networkidle.html similarity index 100% rename from apps/testbed/parity/assets/networkidle.html rename to apps/testbed/app/playwright/assets/networkidle.html diff --git a/apps/testbed/parity/assets/networkidle.js b/apps/testbed/app/playwright/assets/networkidle.js similarity index 100% rename from apps/testbed/parity/assets/networkidle.js rename to apps/testbed/app/playwright/assets/networkidle.js diff --git a/apps/testbed/parity/assets/offscreenbuttons.html b/apps/testbed/app/playwright/assets/offscreenbuttons.html similarity index 100% rename from apps/testbed/parity/assets/offscreenbuttons.html rename to apps/testbed/app/playwright/assets/offscreenbuttons.html diff --git a/apps/testbed/parity/assets/one-style.css b/apps/testbed/app/playwright/assets/one-style.css similarity index 100% rename from apps/testbed/parity/assets/one-style.css rename to apps/testbed/app/playwright/assets/one-style.css diff --git a/apps/testbed/parity/assets/one-style.html b/apps/testbed/app/playwright/assets/one-style.html similarity index 100% rename from apps/testbed/parity/assets/one-style.html rename to apps/testbed/app/playwright/assets/one-style.html diff --git a/apps/testbed/parity/assets/playground.html b/apps/testbed/app/playwright/assets/playground.html similarity index 100% rename from apps/testbed/parity/assets/playground.html rename to apps/testbed/app/playwright/assets/playground.html diff --git a/apps/testbed/parity/assets/pptr.png b/apps/testbed/app/playwright/assets/pptr.png similarity index 100% rename from apps/testbed/parity/assets/pptr.png rename to apps/testbed/app/playwright/assets/pptr.png diff --git a/apps/testbed/parity/assets/preload.html b/apps/testbed/app/playwright/assets/preload.html similarity index 100% rename from apps/testbed/parity/assets/preload.html rename to apps/testbed/app/playwright/assets/preload.html diff --git a/apps/testbed/parity/assets/redirectloop1.html b/apps/testbed/app/playwright/assets/redirectloop1.html similarity index 100% rename from apps/testbed/parity/assets/redirectloop1.html rename to apps/testbed/app/playwright/assets/redirectloop1.html diff --git a/apps/testbed/parity/assets/redirectloop2.html b/apps/testbed/app/playwright/assets/redirectloop2.html similarity index 100% rename from apps/testbed/parity/assets/redirectloop2.html rename to apps/testbed/app/playwright/assets/redirectloop2.html diff --git a/apps/testbed/parity/assets/rotate-pseudo.html b/apps/testbed/app/playwright/assets/rotate-pseudo.html similarity index 100% rename from apps/testbed/parity/assets/rotate-pseudo.html rename to apps/testbed/app/playwright/assets/rotate-pseudo.html diff --git a/apps/testbed/parity/assets/rotate-z-shadow-dom.html b/apps/testbed/app/playwright/assets/rotate-z-shadow-dom.html similarity index 100% rename from apps/testbed/parity/assets/rotate-z-shadow-dom.html rename to apps/testbed/app/playwright/assets/rotate-z-shadow-dom.html diff --git a/apps/testbed/parity/assets/rotate-z.html b/apps/testbed/app/playwright/assets/rotate-z.html similarity index 100% rename from apps/testbed/parity/assets/rotate-z.html rename to apps/testbed/app/playwright/assets/rotate-z.html diff --git a/apps/testbed/parity/assets/screenshots/canvas.html b/apps/testbed/app/playwright/assets/screenshots/canvas.html similarity index 100% rename from apps/testbed/parity/assets/screenshots/canvas.html rename to apps/testbed/app/playwright/assets/screenshots/canvas.html diff --git a/apps/testbed/parity/assets/screenshots/translateZ.html b/apps/testbed/app/playwright/assets/screenshots/translateZ.html similarity index 100% rename from apps/testbed/parity/assets/screenshots/translateZ.html rename to apps/testbed/app/playwright/assets/screenshots/translateZ.html diff --git a/apps/testbed/parity/assets/sectionselectorengine.js b/apps/testbed/app/playwright/assets/sectionselectorengine.js similarity index 100% rename from apps/testbed/parity/assets/sectionselectorengine.js rename to apps/testbed/app/playwright/assets/sectionselectorengine.js diff --git a/apps/testbed/parity/assets/self-request.html b/apps/testbed/app/playwright/assets/self-request.html similarity index 100% rename from apps/testbed/parity/assets/self-request.html rename to apps/testbed/app/playwright/assets/self-request.html diff --git a/apps/testbed/parity/assets/shadow.html b/apps/testbed/app/playwright/assets/shadow.html similarity index 100% rename from apps/testbed/parity/assets/shadow.html rename to apps/testbed/app/playwright/assets/shadow.html diff --git a/apps/testbed/parity/assets/simple.json b/apps/testbed/app/playwright/assets/simple.json similarity index 100% rename from apps/testbed/parity/assets/simple.json rename to apps/testbed/app/playwright/assets/simple.json diff --git a/apps/testbed/parity/assets/title.html b/apps/testbed/app/playwright/assets/title.html similarity index 100% rename from apps/testbed/parity/assets/title.html rename to apps/testbed/app/playwright/assets/title.html diff --git a/apps/testbed/parity/assets/wrappedlink.html b/apps/testbed/app/playwright/assets/wrappedlink.html similarity index 100% rename from apps/testbed/parity/assets/wrappedlink.html rename to apps/testbed/app/playwright/assets/wrappedlink.html diff --git a/apps/testbed/app/playwright/routes.mjs b/apps/testbed/app/playwright/routes.mjs new file mode 100644 index 0000000000..e0506ca3d3 --- /dev/null +++ b/apps/testbed/app/playwright/routes.mjs @@ -0,0 +1,225 @@ +/** + * The routes of the tests ported from Playwright: its test assets (`assets/`, + * copied from microsoft/playwright `tests/assets` at v1.64.1, Apache-2.0) plus + * the few dynamic routes Playwright's test server sets per test, fixed here as + * paths. `127.0.0.1` and `localhost` on the app's port are the two origins of + * the cross-origin cases, and the only ones trusted. + */ + +import { createHash } from 'node:crypto'; +import { createReadStream, existsSync, statSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), 'assets'); +const MAX_DELAY_MS = 30_000; +const MAX_BYTES = 16 << 20; +const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.pdf': 'application/pdf', '.svg': 'image/svg+xml', '.txt': 'text/plain' }; + +/** The Playwright routes of the app on `port`: a request handler and a WebSocket upgrade handler. */ +export function playwrightRoutes(port) { + const ORIGINS = new Set([`http://127.0.0.1:${port}`, `http://localhost:${port}`]); + + /** `value` as a number in [0, max], `fallback` when absent. */ + function bounded(value, fallback, max) { + return Math.min(Math.max(Number(value ?? fallback) || 0, 0), max); + } + + /** A redirect target on this server (a path, or either origin), else the empty page. */ + function sameServer(target) { + if (target === null) return '/empty.html'; + const resolved = URL.canParse(target, `http://127.0.0.1:${port}`) ? new URL(target, `http://127.0.0.1:${port}`) : undefined; + if (resolved === undefined || !ORIGINS.has(resolved.origin)) return '/empty.html'; + return target.startsWith('/') ? `${resolved.pathname}${resolved.search}${resolved.hash}` : resolved.href; + } + + /** + * The request's origin when it is one of the server's own, the only ones + * granted credentials, or `null`, the origin a cross-origin redirect leaves. + */ + function trustedOrigin(request) { + const { origin } = request.headers; + if (origin === 'null') return 'null'; + return origin !== undefined && ORIGINS.has(origin) ? origin : `http://127.0.0.1:${port}`; + } + + /** The request body, read whole. */ + function body(request) { + return new Promise((resolve) => { + const chunks = []; + request.on('data', (chunk) => chunks.push(chunk)); + request.on('end', () => resolve(Buffer.concat(chunks))); + }); + } + + const counts = new Map(); + const logs = new Map(); + + /** Serves one request: a dynamic route, else an asset, else a 404. */ + async function handle(request, response) { + const url = new URL(request.url, 'http://localhost'); + const query = url.searchParams; + switch (url.pathname) { + case '/content': + response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); + response.end(Buffer.from(query.get('html') ?? '', 'base64url')); + return; + case '/echo': { + const received = await body(request); + response.writeHead(200, { 'content-type': 'application/json', 'access-control-allow-origin': '*' }); + response.end(JSON.stringify({ method: request.method, headers: request.headers, body: received.toString(), url: request.url })); + return; + } + case '/status': + response.writeHead(Number(query.get('code') ?? 200), { 'content-type': 'text/plain' }); + response.end(query.get('body') ?? ''); + return; + case '/slow': + setTimeout(() => { + response.writeHead(200, { 'content-type': query.get('type') ?? 'text/plain', 'access-control-allow-origin': '*' }); + response.end(query.get('body') ?? 'slow'); + }, bounded(query.get('ms'), 1000, MAX_DELAY_MS)); + return; + case '/never': + request.on('close', () => response.destroy()); + return; + case '/redirect': + response.writeHead(302, { location: sameServer(query.get('to')) }); + response.end(); + return; + case '/download': + response.writeHead(200, { + 'content-type': 'application/octet-stream', + 'content-disposition': `attachment${query.has('name') ? `; filename=${query.get('name')}` : ''}`, + }); + response.end(query.get('body') ?? 'Hello world'); + return; + case '/set-cookie': + response.writeHead(200, { 'set-cookie': query.get('cookie') ?? 'name=value', 'content-type': 'text/html' }); + response.end('cookie'); + return; + case '/respond': + response.writeHead(Number(query.get('status') ?? 200), JSON.parse(query.get('headers') ?? '{}')); + response.end(query.get('body') ?? ''); + return; + case '/cors-echo': { + const allow = { + 'access-control-allow-origin': trustedOrigin(request), + 'access-control-allow-credentials': 'true', + 'access-control-allow-methods': 'POST, GET, OPTIONS, DELETE', + 'access-control-allow-headers': request.headers['access-control-request-headers'] ?? '*', + }; + if (request.method === 'OPTIONS' && query.has('preflight')) { + response.writeHead(204, allow); + response.end(); + return; + } + const received = await body(request); + response.writeHead(200, { 'content-type': 'text/plain', ...allow }); + response.end(JSON.stringify({ method: request.method, headers: request.headers, body: received.toString(), url: request.url })); + return; + } + case '/bounce': { + const headers = { + location: sameServer(query.get('to')), + 'access-control-allow-origin': trustedOrigin(request), + 'access-control-allow-credentials': 'true', + 'access-control-allow-headers': request.headers['access-control-request-headers'] ?? '*', + ...(query.has('cookie') ? { 'set-cookie': query.get('cookie') } : {}), + }; + if (request.method === 'OPTIONS') delete headers.location; + response.writeHead(request.method === 'OPTIONS' ? 204 : Number(query.get('status') ?? 302), headers); + response.end(); + return; + } + case '/count': { + const key = query.get('key') ?? ''; + counts.set(key, (counts.get(key) ?? 0) + 1); + response.writeHead(200, { 'content-type': 'text/plain' }); + response.end(String(counts.get(key) * 11)); + return; + } + case '/options': { + const key = query.get('key') ?? ''; + logs.set(key, [...(logs.get(key) ?? []), `${request.method}:${url.pathname}`]); + response.writeHead(200, request.method === 'OPTIONS' + ? { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'POST, GET, OPTIONS, DELETE', 'access-control-allow-headers': '*', 'cache-control': 'no-cache' } + : { 'access-control-allow-origin': '*' }); + response.end(request.method === 'OPTIONS' ? 'Hello' : 'World'); + return; + } + case '/options-log': + response.writeHead(200, { 'content-type': 'application/json' }); + response.end(JSON.stringify(logs.get(query.get('key') ?? '') ?? [])); + return; + case '/upload': { + const received = await body(request); + const type = request.headers['content-type'] ?? ''; + const boundary = Buffer.from(`--${type.includes('boundary=') ? type.slice(type.indexOf('boundary=') + 'boundary='.length) : ''}`); + const files = []; + for (let start = received.indexOf(boundary); start !== -1;) { + const next = received.indexOf(boundary, start + boundary.length); + if (next === -1) break; + const part = received.subarray(start + boundary.length + 2, next - 2); + const split = part.indexOf('\r\n\r\n'); + const head = part.subarray(0, split).toString(); + const data = part.subarray(split + 4); + files.push({ + name: /name="([^"]*)"/.exec(head)?.[1], + filename: /filename="([^"]*)"/.exec(head)?.[1], + mimetype: /content-type: (.+)/i.exec(head)?.[1], + size: data.length, + base64: data.length <= 65536 ? data.toString('base64') : undefined, + }); + start = next; + } + response.writeHead(200, { 'content-type': 'text/plain', 'access-control-allow-origin': '*' }); + response.end(JSON.stringify(files)); + return; + } + case '/binary': { + const data = Buffer.alloc(bounded(query.get('bytes'), 1 << 20, MAX_BYTES)); + for (let i = 0; i < data.length; i++) data[i] = Math.imul(i + 1, 2654435761) >>> 24; + response.writeHead(200, { 'content-type': 'application/zip', 'content-length': data.length }); + response.end(data); + return; + } + case '/download-stall': + response.writeHead(200, { 'content-type': 'application/octet-stream', 'content-disposition': 'attachment; filename=file.txt' }); + response.write('a'.repeat(4096)); + response.write('foo'); + request.on('close', () => response.destroy()); + return; + case '/sse': + response.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive', 'cache-control': 'no-cache' }); + response.write('data: hello\n\n'); + request.on('close', () => response.destroy()); + return; + } + const file = path.join(ROOT, path.normalize(decodeURIComponent(url.pathname)).replace(/^(\.\.[/\\])+/, '')); + if (!file.startsWith(ROOT) || !existsSync(file) || statSync(file).isDirectory()) { + response.writeHead(404, { 'content-type': 'text/plain' }); + response.end('Not found'); + return; + } + response.writeHead(200, { 'content-type': TYPES[path.extname(file)] ?? 'application/octet-stream', 'cache-control': 'no-store' }); + createReadStream(file).pipe(response); + } + + /** + * `/ws` accepts the handshake and holds the socket open, as Playwright's + * server does, so an open WebSocket is in the page during network-idle tests. + */ + function upgrade(request, socket) { + const key = request.headers['sec-websocket-key']; + if (new URL(request.url, 'http://localhost').pathname !== '/ws' || typeof key !== 'string') { + socket.destroy(); + return; + } + const accept = createHash('sha1').update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest('base64'); + socket.on('error', () => socket.destroy()); + socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`); + } + + return { handle, upgrade }; +} diff --git a/apps/testbed/app/server.mjs b/apps/testbed/app/server.mjs index ef34d5c70d..6edc97cad1 100644 --- a/apps/testbed/app/server.mjs +++ b/apps/testbed/app/server.mjs @@ -1,14 +1,17 @@ /** * Playground app for dogfooding the e2e runner. No dependencies. The pages * live under `pages/` by group; this file serves them, the API, and the - * cookie session. + * cookie session. Any other path goes to the routes of the tests ported from + * Playwright (`playwright/`). */ import { createServer } from 'node:http'; import { layout } from './layout.mjs'; import { pages } from './pages/index.mjs'; +import { playwrightRoutes } from './playwright/routes.mjs'; const PORT = Number(process.env.PORT ?? 4271); +const playwright = playwrightRoutes(PORT); function parseCookies(request) { const header = request.headers.cookie ?? ''; @@ -76,12 +79,14 @@ const server = createServer(async (request, response) => { } if (!(url.pathname in pages)) { - send(404, { 'content-type': 'text/plain' }, 'not found'); + await playwright.handle(request, response); return; } html(render(url.pathname)); }); +server.on('upgrade', playwright.upgrade); + server.listen(PORT, '127.0.0.1', () => { console.log(`playground listening on http://127.0.0.1:${PORT}`); }); diff --git a/apps/testbed/e2e.parity.config.ts b/apps/testbed/e2e.parity.config.ts deleted file mode 100644 index 76e68b6487..0000000000 --- a/apps/testbed/e2e.parity.config.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { E2EConfig } from 'e2e'; -import { web } from '@e2e-dev/web'; - -/** - * Playwright's own page tests at v1.64.1 (Apache-2.0, see parity/LICENSE), - * rewritten against the public API, on chromium and firefox. Both targets - * share one server; the path in each app URL names the browser to the tests - * (tests-parity/helpers.ts). Run through `scripts/parity.ts`, which holds the - * result to tests-parity/expected-gaps.txt. - */ -const command = { executable: 'node', args: ['parity/server.mjs'], env: { PORT: '4311' } }; - -export default { - projectId: 'dev.e2e.testbed-parity', - tests: 'tests-parity/**/*.e2e.ts', - retries: 0, - targets: (['chromium', 'firefox'] as const).map((browser) => ({ - name: browser, - engine: web({ browser }), - app: { url: `http://127.0.0.1:4311/${browser}/`, command }, - })), - reporters: ['list'], -} satisfies E2EConfig; diff --git a/apps/testbed/package.json b/apps/testbed/package.json index 6bcadfd1d1..88d8d13fc4 100644 --- a/apps/testbed/package.json +++ b/apps/testbed/package.json @@ -14,7 +14,6 @@ "test:agent": "node node_modules/e2e/dist/cli/bin.js run --config e2e.agent.config.ts", "test:dogfood": "node node_modules/e2e/dist/cli/bin.js run --config e2e.dogfood.config.ts", "test:stress": "node node_modules/e2e/dist/cli/bin.js run --config e2e.stress.config.ts", - "test:parity": "node scripts/parity.ts", "explore": "node node_modules/e2e/dist/cli/bin.js explore --config e2e.agent.config.ts", "explore:garden": "node node_modules/e2e/dist/cli/bin.js explore --config e2e.explore.config.ts", "explore:bench": "node scripts/explore-bench.mjs" diff --git a/apps/testbed/parity/README.md b/apps/testbed/parity/README.md deleted file mode 100644 index 2eec5f4770..0000000000 --- a/apps/testbed/parity/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# Playwright parity - -Playwright's own page tests, rewritten against the e2e public API, so -`web()` is held to Playwright's behavior. Adapted from microsoft/playwright -`tests/page` (and `tests/library/download.spec.ts`) at `v1.64.1`, the version -`playwright-core` is pinned to. Copyright Microsoft Corporation, Apache -License 2.0: see `LICENSE` and `NOTICE`. - -- `../tests-parity/*.e2e.ts`: one file per Playwright spec. Each keeps the - original test's title, inputs, and assertions; `page.click(selector)` becomes - a locator tap, `page.setContent(html)` a page the server serves - (`content()`). A test whose API e2e does not expose is left out; the file - header lists them. -- `../tests-parity/expected-gaps.txt`: the tests e2e fails on purpose or by a - known gap, per browser, each with its reason. -- `assets/`: Playwright's `tests/assets` files the tests load, unchanged. -- `server.mjs`: serves `assets/`, plus the routes Playwright's test server sets - per test as fixed paths. `127.0.0.1` and `localhost` on port 4311 are the - two origins of the cross-origin cases. - -`../e2e.parity.config.ts` runs every file on a `chromium` and a `firefox` -target against one server. The path of each target's app URL names the -browser, which the tests read as the `browserName` fixture. - -```sh -pnpm build -pnpm --filter @e2e-dev/testbed test:parity -pnpm --filter @e2e-dev/testbed test:parity tests-parity/page-route.e2e.ts -``` - -`test:parity` fails on a failure `expected-gaps.txt` does not list, on a -listed test that passes (the gap closed: delete its line), and on a listed -test that skipped or is gone. After a fix or a new port, -`E2E_PARITY_UPDATE=1 pnpm --filter @e2e-dev/testbed test:parity` rewrites the -list from the run, keeping existing reasons and marking new lines `TODO`, -which fails until the reason is written. diff --git a/apps/testbed/parity/server.mjs b/apps/testbed/parity/server.mjs deleted file mode 100644 index d8035c8045..0000000000 --- a/apps/testbed/parity/server.mjs +++ /dev/null @@ -1,220 +0,0 @@ -/** - * The parity suite's app: Playwright's test assets (`assets/`, copied from - * microsoft/playwright `tests/assets` at v1.64.1, Apache-2.0) plus the few - * dynamic routes Playwright's test server sets per test, fixed here as paths. - * Listens on loopback only; `127.0.0.1` and `localhost` on one port are the - * two origins of the cross-origin cases, and the only ones it trusts. - */ - -import { createHash } from 'node:crypto'; -import { createReadStream, existsSync, statSync } from 'node:fs'; -import { createServer } from 'node:http'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), 'assets'); -const PORT = Number(process.env.PORT ?? 4311); -const ORIGINS = new Set([`http://127.0.0.1:${PORT}`, `http://localhost:${PORT}`]); -const MAX_DELAY_MS = 30_000; -const MAX_BYTES = 16 << 20; -const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.pdf': 'application/pdf', '.svg': 'image/svg+xml', '.txt': 'text/plain' }; - -/** `value` as a number in [0, max], `fallback` when absent. */ -function bounded(value, fallback, max) { - return Math.min(Math.max(Number(value ?? fallback) || 0, 0), max); -} - -/** A redirect target on this server (a path, or either origin), else the empty page. */ -function sameServer(target) { - if (target === null) return '/empty.html'; - const resolved = URL.canParse(target, `http://127.0.0.1:${PORT}`) ? new URL(target, `http://127.0.0.1:${PORT}`) : undefined; - if (resolved === undefined || !ORIGINS.has(resolved.origin)) return '/empty.html'; - return target.startsWith('/') ? `${resolved.pathname}${resolved.search}${resolved.hash}` : resolved.href; -} - -/** - * The request's origin when it is one of the server's own, the only ones - * granted credentials, or `null`, the origin a cross-origin redirect leaves. - */ -function trustedOrigin(request) { - const { origin } = request.headers; - if (origin === 'null') return 'null'; - return origin !== undefined && ORIGINS.has(origin) ? origin : `http://127.0.0.1:${PORT}`; -} - -/** The request body, read whole. */ -function body(request) { - return new Promise((resolve) => { - const chunks = []; - request.on('data', (chunk) => chunks.push(chunk)); - request.on('end', () => resolve(Buffer.concat(chunks))); - }); -} - -const counts = new Map(); -const logs = new Map(); - -const server = createServer(async (request, response) => { - const url = new URL(request.url, 'http://localhost'); - const query = url.searchParams; - switch (url.pathname) { - case '/content': - response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); - response.end(Buffer.from(query.get('html') ?? '', 'base64url')); - return; - case '/echo': { - const received = await body(request); - response.writeHead(200, { 'content-type': 'application/json', 'access-control-allow-origin': '*' }); - response.end(JSON.stringify({ method: request.method, headers: request.headers, body: received.toString(), url: request.url })); - return; - } - case '/status': - response.writeHead(Number(query.get('code') ?? 200), { 'content-type': 'text/plain' }); - response.end(query.get('body') ?? ''); - return; - case '/slow': - setTimeout(() => { - response.writeHead(200, { 'content-type': query.get('type') ?? 'text/plain', 'access-control-allow-origin': '*' }); - response.end(query.get('body') ?? 'slow'); - }, bounded(query.get('ms'), 1000, MAX_DELAY_MS)); - return; - case '/never': - request.on('close', () => response.destroy()); - return; - case '/redirect': - response.writeHead(302, { location: sameServer(query.get('to')) }); - response.end(); - return; - case '/download': - response.writeHead(200, { - 'content-type': 'application/octet-stream', - 'content-disposition': `attachment${query.has('name') ? `; filename=${query.get('name')}` : ''}`, - }); - response.end(query.get('body') ?? 'Hello world'); - return; - case '/set-cookie': - response.writeHead(200, { 'set-cookie': query.get('cookie') ?? 'name=value', 'content-type': 'text/html' }); - response.end('cookie'); - return; - case '/respond': - response.writeHead(Number(query.get('status') ?? 200), JSON.parse(query.get('headers') ?? '{}')); - response.end(query.get('body') ?? ''); - return; - case '/cors-echo': { - const allow = { - 'access-control-allow-origin': trustedOrigin(request), - 'access-control-allow-credentials': 'true', - 'access-control-allow-methods': 'POST, GET, OPTIONS, DELETE', - 'access-control-allow-headers': request.headers['access-control-request-headers'] ?? '*', - }; - if (request.method === 'OPTIONS' && query.has('preflight')) { - response.writeHead(204, allow); - response.end(); - return; - } - const received = await body(request); - response.writeHead(200, { 'content-type': 'text/plain', ...allow }); - response.end(JSON.stringify({ method: request.method, headers: request.headers, body: received.toString(), url: request.url })); - return; - } - case '/bounce': { - const headers = { - location: sameServer(query.get('to')), - 'access-control-allow-origin': trustedOrigin(request), - 'access-control-allow-credentials': 'true', - 'access-control-allow-headers': request.headers['access-control-request-headers'] ?? '*', - ...(query.has('cookie') ? { 'set-cookie': query.get('cookie') } : {}), - }; - if (request.method === 'OPTIONS') delete headers.location; - response.writeHead(request.method === 'OPTIONS' ? 204 : Number(query.get('status') ?? 302), headers); - response.end(); - return; - } - case '/count': { - const key = query.get('key') ?? ''; - counts.set(key, (counts.get(key) ?? 0) + 1); - response.writeHead(200, { 'content-type': 'text/plain' }); - response.end(String(counts.get(key) * 11)); - return; - } - case '/options': { - const key = query.get('key') ?? ''; - logs.set(key, [...(logs.get(key) ?? []), `${request.method}:${url.pathname}`]); - response.writeHead(200, request.method === 'OPTIONS' - ? { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'POST, GET, OPTIONS, DELETE', 'access-control-allow-headers': '*', 'cache-control': 'no-cache' } - : { 'access-control-allow-origin': '*' }); - response.end(request.method === 'OPTIONS' ? 'Hello' : 'World'); - return; - } - case '/options-log': - response.writeHead(200, { 'content-type': 'application/json' }); - response.end(JSON.stringify(logs.get(query.get('key') ?? '') ?? [])); - return; - case '/upload': { - const received = await body(request); - const type = request.headers['content-type'] ?? ''; - const boundary = Buffer.from(`--${type.includes('boundary=') ? type.slice(type.indexOf('boundary=') + 'boundary='.length) : ''}`); - const files = []; - for (let start = received.indexOf(boundary); start !== -1;) { - const next = received.indexOf(boundary, start + boundary.length); - if (next === -1) break; - const part = received.subarray(start + boundary.length + 2, next - 2); - const split = part.indexOf('\r\n\r\n'); - const head = part.subarray(0, split).toString(); - const data = part.subarray(split + 4); - files.push({ - name: /name="([^"]*)"/.exec(head)?.[1], - filename: /filename="([^"]*)"/.exec(head)?.[1], - mimetype: /content-type: (.+)/i.exec(head)?.[1], - size: data.length, - base64: data.length <= 65536 ? data.toString('base64') : undefined, - }); - start = next; - } - response.writeHead(200, { 'content-type': 'text/plain', 'access-control-allow-origin': '*' }); - response.end(JSON.stringify(files)); - return; - } - case '/binary': { - const data = Buffer.alloc(bounded(query.get('bytes'), 1 << 20, MAX_BYTES)); - for (let i = 0; i < data.length; i++) data[i] = Math.imul(i + 1, 2654435761) >>> 24; - response.writeHead(200, { 'content-type': 'application/zip', 'content-length': data.length }); - response.end(data); - return; - } - case '/download-stall': - response.writeHead(200, { 'content-type': 'application/octet-stream', 'content-disposition': 'attachment; filename=file.txt' }); - response.write('a'.repeat(4096)); - response.write('foo'); - request.on('close', () => response.destroy()); - return; - case '/sse': - response.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive', 'cache-control': 'no-cache' }); - response.write('data: hello\n\n'); - request.on('close', () => response.destroy()); - return; - } - const file = path.join(ROOT, path.normalize(decodeURIComponent(url.pathname)).replace(/^(\.\.[/\\])+/, '')); - if (!file.startsWith(ROOT) || !existsSync(file) || statSync(file).isDirectory()) { - response.writeHead(404, { 'content-type': 'text/plain' }); - response.end('Not found'); - return; - } - response.writeHead(200, { 'content-type': TYPES[path.extname(file)] ?? 'application/octet-stream', 'cache-control': 'no-store' }); - createReadStream(file).pipe(response); -}); - -// `/ws` accepts the handshake and holds the socket open, as Playwright's -// server does, so an open WebSocket is in the page during network-idle tests. -server.on('upgrade', (request, socket) => { - const key = request.headers['sec-websocket-key']; - if (new URL(request.url, 'http://localhost').pathname !== '/ws' || typeof key !== 'string') { - socket.destroy(); - return; - } - const accept = createHash('sha1').update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest('base64'); - socket.on('error', () => socket.destroy()); - socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`); -}); - -server.listen(PORT, '127.0.0.1'); diff --git a/apps/testbed/scripts/parity-gaps.test.ts b/apps/testbed/scripts/parity-gaps.test.ts deleted file mode 100644 index b4b2216923..0000000000 --- a/apps/testbed/scripts/parity-gaps.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import assert from 'node:assert/strict'; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import path from 'node:path'; -import { test } from 'node:test'; -import { diffGaps, keyOf, readGaps, TODO_REASON, writeGaps, type ParityResult } from './parity-gaps.ts'; - -/** A selected result in tests-parity/a.e2e.ts on chromium, overridable per test. */ -function result(title: string, status: string, overrides: Partial = {}): ParityResult { - return { file: 'tests-parity/a.e2e.ts', titlePath: ['suite', title], targetId: 'chromium', status, selected: true, ...overrides }; -} - -const gap = (title: string, target = 'chromium', file = 'a.e2e.ts') => `${file} > suite > ${title} [${target}]`; - -/** Writes `lines` to a temporary gaps file, hands it to `body`, and removes it. */ -function withGapsFile(lines: readonly string[], body: (file: string) => void): void { - const dir = mkdtempSync(path.join(tmpdir(), 'parity-gaps-')); - try { - const file = path.join(dir, 'expected-gaps.txt'); - writeFileSync(file, `# header\n\n${lines.join('\n')}\n`); - body(file); - } finally { - rmSync(dir, { recursive: true, force: true }); - } -} - -test('keyOf drops the tests folder and names the target', () => { - assert.equal(keyOf(result('works', 'passed')), 'a.e2e.ts > suite > works [chromium]'); -}); - -test('readGaps splits each line at the target, so a reason may hold the separator', () => { - withGapsFile([`${gap('works ? | yes')} | a | b`], (file) => { - assert.deepEqual([...readGaps(file)], [[gap('works ? | yes'), 'a | b']]); - }); -}); - -test('a listed failure is expected; an unlisted one is not', () => { - const diff = diffGaps(new Map([[gap('known'), 'why']]), [result('known', 'failed'), result('new', 'timed-out')]); - assert.deepEqual(diff, { unexpected: [gap('new')], closed: [], stale: [], todo: [] }); -}); - -test('a listed test that passes closes its gap', () => { - assert.deepEqual(diffGaps(new Map([[gap('fixed'), 'why']]), [result('fixed', 'passed')]).closed, [gap('fixed')]); -}); - -test('a listed test that skipped or is gone from a file that ran is stale', () => { - const gaps = new Map([[gap('skipped'), 'why'], [gap('renamed'), 'why']]); - assert.deepEqual(diffGaps(gaps, [result('skipped', 'skipped'), result('other', 'passed')]).stale, [gap('renamed'), gap('skipped')]); -}); - -test('lines of a file, target, or test the run did not select are left alone', () => { - const gaps = new Map([ - [gap('other file', 'chromium', 'b.e2e.ts'), 'why'], - [gap('other target', 'firefox'), 'why'], - [gap('filtered'), 'why'], - ]); - const diff = diffGaps(gaps, [result('ran', 'passed'), result('filtered', 'skipped', { selected: false })]); - assert.deepEqual(diff, { unexpected: [], closed: [], stale: [], todo: [] }); -}); - -test('a TODO reason is reported', () => { - assert.deepEqual(diffGaps(new Map([[gap('known'), TODO_REASON]]), [result('known', 'failed')]).todo, [gap('known')]); -}); - -test('writeGaps keeps reasons and unjudged lines, drops closed ones, and marks new ones TODO', () => { - const lines = [`${gap('known')} | why`, `${gap('fixed')} | old`, `${gap('elsewhere', 'firefox')} | kept`]; - withGapsFile(lines, (file) => { - writeGaps(file, '# header', readGaps(file), [result('known', 'failed'), result('fixed', 'passed'), result('new', 'interrupted')]); - assert.equal(readFileSync(file, 'utf8'), [ - '# header', - `${gap('elsewhere', 'firefox')} | kept`, - `${gap('known')} | why`, - `${gap('new')} | ${TODO_REASON}`, - '', - ].join('\n')); - }); -}); diff --git a/apps/testbed/scripts/parity-gaps.ts b/apps/testbed/scripts/parity-gaps.ts deleted file mode 100644 index 7560a1f72f..0000000000 --- a/apps/testbed/scripts/parity-gaps.ts +++ /dev/null @@ -1,113 +0,0 @@ -/** - * The committed state of the parity suite: one line per Playwright test e2e - * fails on purpose or by a known gap, each with the reason. A run fails on a - * failure the file does not list, on a listed test that passes (the gap - * closed: delete its line), and on a listed test that no longer fails because - * it was skipped, renamed, or removed. `E2E_PARITY_UPDATE=1` rewrites the file - * from the run, keeping every surviving reason and marking new lines `TODO`, - * which fails until someone writes the reason. - * - * Line format: `file > describe > test [target] | reason`. - */ - -import { readFileSync, writeFileSync } from 'node:fs'; - -export const TODO_REASON = 'TODO: say why e2e differs here, or fix it'; - -const SEPARATOR = ' | '; - -/** The fields of one `report.json` result the check reads. */ -export interface ParityResult { - readonly file: string; - readonly titlePath: readonly string[]; - readonly targetId: string; - readonly status: string; - readonly selected: boolean; -} - -/** What a run shows against the file. */ -export interface ParityDiff { - /** Failed, timed out, or interrupted, and not listed. */ - readonly unexpected: string[]; - /** Listed, and passed. */ - readonly closed: string[]; - /** Listed, in a file and target that ran, but skipped or gone. */ - readonly stale: string[]; - /** Listed with the `TODO` reason. */ - readonly todo: string[]; -} - -const FAILING = new Set(['failed', 'timed-out', 'interrupted']); -const PASSING = new Set(['passed', 'flaky']); - -/** The key of one result: its file under the tests folder, title path, and target. */ -export function keyOf(result: Pick): string { - const file = result.file.replace(/^tests-parity\//, ''); - return `${[file, ...result.titlePath].join(' > ')} [${result.targetId}]`.replaceAll('\n', ' '); -} - -/** The file and target a key belongs to, the unit a run either covers or not. */ -function scopeOf(key: string): string { - return `${key.slice(0, key.indexOf(' > '))} ${key.slice(key.lastIndexOf(' ['))}`; -} - -/** Every listed key with its reason; comment and blank lines are skipped. */ -export function readGaps(file: string): Map { - const gaps = new Map(); - for (const line of readFileSync(file, 'utf8').split('\n')) { - if (line.trim() === '' || line.startsWith('#')) continue; - const cut = line.indexOf(`]${SEPARATOR}`) + 1; - if (cut === 0) throw new Error(`expected-gaps line has no "[target] | reason": ${line}`); - gaps.set(line.slice(0, cut), line.slice(cut + SEPARATOR.length)); - } - return gaps; -} - -/** - * Compares the listed gaps with a run. Only selected results count, and a - * listed key is judged only when its file and target ran, so a run narrowed - * by file or `--grep` leaves the other lines alone. - */ -export function diffGaps(gaps: ReadonlyMap, results: readonly ParityResult[]): ParityDiff { - const selected = results.filter((result) => result.selected); - const scopes = new Set(selected.map((result) => scopeOf(keyOf(result)))); - const byKey = new Map(results.map((result) => [keyOf(result), result])); - const unexpected: string[] = []; - const closed: string[] = []; - const stale: string[] = []; - for (const result of selected) { - const key = keyOf(result); - if (FAILING.has(result.status) && !gaps.has(key)) unexpected.push(key); - } - for (const key of gaps.keys()) { - if (!scopes.has(scopeOf(key))) continue; - const result = byKey.get(key); - if (result === undefined) stale.push(key); - else if (!result.selected) continue; - else if (PASSING.has(result.status)) closed.push(key); - else if (!FAILING.has(result.status)) stale.push(key); - } - const todo = [...gaps].filter(([, reason]) => reason === TODO_REASON).map(([key]) => key); - return { unexpected: unexpected.toSorted(), closed: closed.toSorted(), stale: stale.toSorted(), todo: todo.toSorted() }; -} - -/** - * Rewrites the file from a run: lines of files and targets that did not run, - * and of tests the run did not select, stay as they are; the rest become the - * run's failures, keeping known reasons and marking new ones `TODO`. - */ -export function writeGaps(file: string, header: string, gaps: ReadonlyMap, results: readonly ParityResult[]): void { - const selected = results.filter((result) => result.selected); - const scopes = new Set(selected.map((result) => scopeOf(keyOf(result)))); - const byKey = new Map(results.map((result) => [keyOf(result), result])); - const lines = new Map(); - for (const [key, reason] of gaps) { - if (!scopes.has(scopeOf(key)) || byKey.get(key)?.selected === false) lines.set(key, reason); - } - for (const result of selected) { - const key = keyOf(result); - if (FAILING.has(result.status)) lines.set(key, gaps.get(key) ?? TODO_REASON); - } - const body = [...lines].toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([key, reason]) => `${key}${SEPARATOR}${reason}`); - writeFileSync(file, `${header}\n${body.join('\n')}\n`); -} diff --git a/apps/testbed/scripts/parity.ts b/apps/testbed/scripts/parity.ts deleted file mode 100644 index 5b57890c6c..0000000000 --- a/apps/testbed/scripts/parity.ts +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Runs the parity suite (e2e.parity.config.ts) and holds its result to - * tests-parity/expected-gaps.txt: a failure the file does not list, a listed - * gap that passes or no longer runs, and a `TODO` reason all fail. Extra - * arguments go to `e2e run`. `E2E_PARITY_UPDATE=1` rewrites the file instead. - */ - -import { spawnSync } from 'node:child_process'; -import { existsSync, readFileSync } from 'node:fs'; -import path from 'node:path'; -import { diffGaps, readGaps, writeGaps, type ParityResult } from './parity-gaps.ts'; - -const root = path.join(import.meta.dirname, '..'); -const output = path.join(root, '.e2e-parity'); -const gapsFile = path.join(root, 'tests-parity/expected-gaps.txt'); -const HEADER = [ - '# Playwright tests e2e fails on purpose or by a known gap, one per line:', - '# file > describe > test [target] | reason', - '# Generated by E2E_PARITY_UPDATE=1; edit only the reasons. See scripts/parity-gaps.ts.', -].join('\n'); - -const run = spawnSync( - process.execPath, - ['node_modules/e2e/dist/cli/bin.js', 'run', '--config', 'e2e.parity.config.ts', '--output', output, ...process.argv.slice(2)], - { cwd: root, stdio: 'inherit' }, -); -// 1 is a failed test and 3 an infrastructure failure, either of which can be a listed gap. -const reportFile = path.join(output, 'report.json'); -if (![0, 1, 3].includes(run.status ?? -1) || !existsSync(reportFile)) { - console.error(`parity: e2e run exited ${run.status ?? run.signal} without a report to check`); - process.exit(1); -} -const results = (JSON.parse(readFileSync(reportFile, 'utf8')) as { run: { results: ParityResult[] } }).run.results; -const gaps = readGaps(gapsFile); - -if (process.env['E2E_PARITY_UPDATE'] === '1') { - writeGaps(gapsFile, HEADER, gaps, results); - console.log(`parity: rewrote ${path.relative(root, gapsFile)}`); - process.exit(0); -} - -const diff = diffGaps(gaps, results); -const groups = [ - ['failed, and not listed in expected-gaps.txt', diff.unexpected], - ['gap closed: passes now, delete its line', diff.closed], - ['listed, but skipped or gone: delete or rename its line', diff.stale], - ['listed without a reason', diff.todo], -] as const; -let failed = false; -for (const [title, keys] of groups) { - if (keys.length === 0) continue; - failed = true; - console.error(`\nparity: ${title} (${keys.length}):`); - for (const key of keys) console.error(` ${key}`); -} -if (failed) { - console.error('\nparity: E2E_PARITY_UPDATE=1 rewrites the file from this run'); - process.exit(1); -} -console.log(`\nparity: every failure is a listed gap (${gaps.size} listed)`); diff --git a/apps/testbed/tests-parity/expected-gaps.txt b/apps/testbed/tests-parity/expected-gaps.txt deleted file mode 100644 index e439bcb212..0000000000 --- a/apps/testbed/tests-parity/expected-gaps.txt +++ /dev/null @@ -1,51 +0,0 @@ -# Playwright tests e2e fails on purpose or by a known gap, one per line: -# file > describe > test [target] | reason -# Generated by E2E_PARITY_UPDATE=1; edit only the reasons. See scripts/parity-gaps.ts. -download.e2e.ts > download > should be able to download a inline PDF file via response interception [chromium] | `route.fulfill` bodies are strings, so binary bytes do not survive the round trip -download.e2e.ts > download > should be able to download a inline PDF file via response interception [firefox] | `route.fulfill` bodies are strings, so binary bytes do not survive the round trip -locator-convenience.e2e.ts > locator convenience > inputValue should work [chromium] | `inputValue()` on an element that is no input reads "" instead of throwing -locator-convenience.e2e.ts > locator convenience > inputValue should work [firefox] | `inputValue()` on an element that is no input reads "" instead of throwing -locator-convenience.e2e.ts > locator convenience > isChecked should work [chromium] | `isChecked()` on an element that is no checkbox reads false instead of throwing -locator-convenience.e2e.ts > locator convenience > isChecked should work [firefox] | `isChecked()` on an element that is no checkbox reads false instead of throwing -locator-convenience.e2e.ts > locator convenience > textContent should work [chromium] | `textContent()` normalizes whitespace, where Playwright keeps the raw text -locator-convenience.e2e.ts > locator convenience > textContent should work [firefox] | `textContent()` normalizes whitespace, where Playwright keeps the raw text -locator-frame.e2e.ts > locator frame > should treat elements inside hidden cross-origin iframe as hidden [chromium] | the visibility read does not count an element inside a `visibility: hidden` iframe as hidden -locator-frame.e2e.ts > locator frame > should treat elements inside hidden cross-origin iframe as hidden [firefox] | the visibility read does not count an element inside a `visibility: hidden` iframe as hidden -locator-frame.e2e.ts > locator frame > should treat elements inside hidden iframe as hidden [chromium] | the visibility read does not count an element inside a `visibility: hidden` iframe as hidden -locator-frame.e2e.ts > locator frame > should treat elements inside hidden iframe as hidden [firefox] | the visibility read does not count an element inside a `visibility: hidden` iframe as hidden -locator-frame.e2e.ts > locator frame > should wait for hidden iframe to become visible [chromium] | the visibility read does not count an element inside a `visibility: hidden` iframe as hidden -locator-frame.e2e.ts > locator frame > should wait for hidden iframe to become visible [firefox] | the visibility read does not count an element inside a `visibility: hidden` iframe as hidden -locator-misc-2.e2e.ts > locator misc 2 > locator.count should work with deleted Map in main world [chromium] | `browser.evaluate` and the in-page readers run in the main world, so a page that deletes `Map` breaks them; Playwright runs its own in a utility world -locator-misc-2.e2e.ts > locator misc 2 > locator.count should work with deleted Map in main world [firefox] | `browser.evaluate` and the in-page readers run in the main world, so a page that deletes `Map` breaks them; Playwright runs its own in a utility world -page-check.e2e.ts > page check > should uncheck radio by aria role [chromium] | `uncheck` refuses a `role=radio`, where Playwright clicks it and refuses only a native radio -page-check.e2e.ts > page check > should uncheck radio by aria role [firefox] | `uncheck` refuses a `role=radio`, where Playwright clicks it and refuses only a native radio -page-check.e2e.ts > page check > should uncheck the box by aria role [chromium] | `uncheck` refuses a `role=radio`, where Playwright clicks it and refuses only a native radio -page-check.e2e.ts > page check > should uncheck the box by aria role [firefox] | `uncheck` refuses a `role=radio`, where Playwright clicks it and refuses only a native radio -page-click-scroll.e2e.ts > page click scroll > should scroll into view display:contents with position [firefox] | a tap at a position needs a box, which a `display: contents` element has none of on Firefox -page-filechooser.e2e.ts > page filechooser > should be able to reset selected files with empty file list [chromium] | `setInputFiles([])` is refused; there is no way to clear a file input -page-filechooser.e2e.ts > page filechooser > should be able to reset selected files with empty file list [firefox] | `setInputFiles([])` is refused; there is no way to clear a file input -page-request-continue.e2e.ts > page request continue > continue should delete headers on redirects [chromium] | a header override takes strings only, so `undefined` cannot delete one -page-request-continue.e2e.ts > page request continue > continue should delete headers on redirects [firefox] | a header override takes strings only, so `undefined` cannot delete one -page-request-continue.e2e.ts > page request continue > should delete header with undefined value [chromium] | a header override takes strings only, so `undefined` cannot delete one -page-request-continue.e2e.ts > page request continue > should delete header with undefined value [firefox] | a header override takes strings only, so `undefined` cannot delete one -page-request-fulfill.e2e.ts > page request fulfill > should fulfill with fetch response that has multiple set-cookie [chromium] | a header value cannot hold a newline, so a fulfilled response sets one cookie -page-request-fulfill.e2e.ts > page request fulfill > should fulfill with fetch response that has multiple set-cookie [firefox] | a header value cannot hold a newline, so a fulfilled response sets one cookie -page-request-fulfill.e2e.ts > page request fulfill > should fulfill with multiple set-cookie [chromium] | a header value cannot hold a newline, so a fulfilled response sets one cookie -page-request-fulfill.e2e.ts > page request fulfill > should fulfill with multiple set-cookie [firefox] | a header value cannot hold a newline, so a fulfilled response sets one cookie -page-route.e2e.ts > page route > should allow null origin for about:blank [chromium] | there is no page before the first `goto`, so no `about:blank` origin to fetch from -page-route.e2e.ts > page route > should allow null origin for about:blank [firefox] | there is no page before the first `goto`, so no `about:blank` origin to fetch from -page-route.e2e.ts > page route > should navigate to dataURL and not fire dataURL requests [chromium] | `goto` refuses `data:` URLs (POLICY_DENIED) -page-route.e2e.ts > page route > should navigate to dataURL and not fire dataURL requests [firefox] | `goto` refuses `data:` URLs (POLICY_DENIED) -page-route.e2e.ts > page route > should not support ? in glob pattern [chromium] | `?` in a route glob matches one character, where Playwright reads it literally -page-route.e2e.ts > page route > should not support ? in glob pattern [firefox] | `?` in a route glob matches one character, where Playwright reads it literally -page-screenshot.e2e.ts > page screenshot > mask option > should mask in parallel [chromium] | two screenshot steps at once are refused -page-screenshot.e2e.ts > page screenshot > mask option > should mask in parallel [firefox] | two screenshot steps at once are refused -page-screenshot.e2e.ts > page screenshot > mask option > should work when subframe has stalled navigation [chromium] | no screenshot comes back while a subframe navigation stalls -page-screenshot.e2e.ts > page screenshot > should work while navigating [chromium] | a screenshot taken while the page navigates fails as stale instead of capturing whichever document shows -page-screenshot.e2e.ts > page screenshot > should work while navigating [firefox] | a screenshot taken while the page navigates fails as stale instead of capturing whichever document shows -page-screenshot.e2e.ts > page screenshot > should work with Array deleted [chromium] | the evaluate wrapper needs the page's `Array` -page-screenshot.e2e.ts > page screenshot > should work with Array deleted [firefox] | the evaluate wrapper needs the page's `Array` -page-select-option.e2e.ts > page select option > should select single option [chromium] | a bare string selects by label only, where Playwright matches the value or the label -page-select-option.e2e.ts > page select option > should select single option [firefox] | a bare string selects by label only, where Playwright matches the value or the label -page-wait-for-response.e2e.ts > page wait for response > should work with no timeout [chromium] | a timeout must be positive; there is no `timeout: 0` for no timeout -page-wait-for-response.e2e.ts > page wait for response > should work with no timeout [firefox] | a timeout must be positive; there is no `timeout: 0` for no timeout diff --git a/apps/testbed/tests-parity/helpers.ts b/apps/testbed/tests-parity/helpers.ts deleted file mode 100644 index 459a7f462f..0000000000 --- a/apps/testbed/tests-parity/helpers.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** What the parity tests share: the server's two origins, inline pages, assets, and which browser runs. */ - -import path from 'node:path'; -import { test as base, type WebApp } from '@e2e-dev/web'; - -type BrowserName = 'chromium' | 'firefox'; - -/** The app's origin, Playwright's `server.PREFIX`. */ -export const PREFIX = 'http://127.0.0.1:4311'; - -/** Another origin on the same server, Playwright's `server.CROSS_PROCESS_PREFIX`. */ -export const CROSS = 'http://localhost:4311'; - -/** The browser under test: the path its target's app URL ends in (e2e.parity.config.ts). */ -export function browserNameOf(app: WebApp): BrowserName { - const name = new URL(app.baseUrl ?? PREFIX).pathname.replaceAll('/', ''); - if (name !== 'chromium' && name !== 'firefox') throw new Error(`parity app URL names no browser: ${app.baseUrl}`); - return name; -} - -/** The web `test` with `browserName`, Playwright's fixture of the same name. */ -export const test = base.extend<{ browserName: BrowserName }>({ - browserName: async ({ app }, use) => use(browserNameOf(app)), -}); - -/** A path that serves `html` as a page, for Playwright's `page.setContent(html)`. */ -export function content(html: string): string { - return `/content?html=${Buffer.from(html).toString('base64url')}`; -} - -/** The absolute path of one of Playwright's test assets. */ -export function asset(name: string): string { - return path.join(import.meta.dirname, '../parity/assets', name); -} diff --git a/apps/testbed/tests/browser.e2e.ts b/apps/testbed/tests/browser.e2e.ts index 62241a104e..2384655bf4 100644 --- a/apps/testbed/tests/browser.e2e.ts +++ b/apps/testbed/tests/browser.e2e.ts @@ -21,12 +21,6 @@ test.describe('browser fixture', { requires: ['browser'], tags: ['browser'] }, ( await expect(browser).toHaveURL(/about$/); }); - test('waitForURL waits out a delayed navigation', async ({ screen, browser }) => { - await screen.getByRole('button', 'Go to about, soon').tap(); - await browser.waitForURL('/about'); - await expect(screen.getByRole('heading', 'About')).toBeVisible(); - }); - test('reload runs the page again', async ({ screen, browser }) => { await expect(screen.getByLabel('Loads')).toHaveText('loads: 1'); await browser.reload(); diff --git a/apps/testbed/tests-parity/page-check.e2e.ts b/apps/testbed/tests/check.e2e.ts similarity index 90% rename from apps/testbed/tests-parity/page-check.e2e.ts rename to apps/testbed/tests/check.e2e.ts index 4848b4dee6..38dca1edd1 100644 --- a/apps/testbed/tests-parity/page-check.e2e.ts +++ b/apps/testbed/tests/check.e2e.ts @@ -1,6 +1,6 @@ /** * Adapted from microsoft/playwright tests/page/page-check.spec.ts at v1.64.1. - * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../parity/LICENSE). + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). * Rewritten against the e2e public API: `page.check(selector)` is a locator check. */ @@ -12,10 +12,11 @@ * - should check the box using setChecked: no `setChecked`. */ +import { test } from '@e2e-dev/web'; import { expect } from 'e2e'; -import { content, test } from './helpers.ts'; +import { content } from './helpers.ts'; -test.describe('page check', { requires: ['browser'] }, () => { +test.describe('page check', { requires: ['browser'], tags: ['playwright'] }, () => { test('should check the box', async ({ browser }) => { await browser.goto(content("")); await browser.locator('input').check(); @@ -58,7 +59,7 @@ test.describe('page check', { requires: ['browser'] }, () => { expect(await browser.evaluate("() => window.checkbox.getAttribute('aria-checked')")).toBe('true'); }); - test('should uncheck radio by aria role', async ({ browser }) => { + test('should uncheck radio by aria role', { fail: '`uncheck` refuses a `role=radio`, where Playwright clicks it and refuses only a native radio' }, async ({ browser }) => { await browser.goto(content(`