diff --git a/.changeset/electron-per-test-launch.md b/.changeset/electron-per-test-launch.md new file mode 100644 index 0000000000..e306d68224 --- /dev/null +++ b/.changeset/electron-per-test-launch.md @@ -0,0 +1,16 @@ +--- +'@e2e-dev/electron': patch +--- + +The `electron` fixture covers what a real app's suite needs beside `screen`: + +- `electron.launch({ args, env, cwd })` launches the app with arguments, environment variables, and a working directory of one test (`electron({ cwd })` sets the directory for every test), and `electron.userDataDir` is there before the launch, so a test can put data in it first. [Per-test arguments](https://e2e.com/docs/electron#launch-with-per-test-arguments) +- `electron.keyboard` and `electron.mouse` send input to the active window, wherever its focus is: `await electron.keyboard.press('Escape')`. [Keyboard and mouse](https://e2e.com/docs/electron#keyboard-and-mouse) +- `electron.activeWindow()` returns the window `screen` reads, and a window has `evaluate(fn, arg)`, which runs in its page, and `reload()`. [Run code in a window](https://e2e.com/docs/electron#run-code-in-a-window) + +Fixes: + +- A button drawn as an icon font's glyph and text, such as ``, is named `Scan`, as on the web. The glyph was part of its name, so `getByRole('button', 'Scan')` found nothing. +- `getByText` on text in a container such as a toolbar, inside elements the accessibility tree leaves out, taps the text. It tapped the middle of the container, which could miss the element that handles the click. +- A step that starts while the active window closes, such as a sign-in popup that closes itself, reads the window active after it instead of failing with `APP_NOT_OPEN`. +- `locator.focus()` succeeds when the element hands focus to a part of itself, as a grid row does to its editor. It failed with `ACTION_FAILED`. diff --git a/apps/electron-testbed/app/controls.html b/apps/electron-testbed/app/controls.html index 4bba4f1f1a..5304f07c99 100644 --- a/apps/electron-testbed/app/controls.html +++ b/apps/electron-testbed/app/controls.html @@ -10,6 +10,7 @@ header { position: sticky; top: 0; height: 60px; background: #fff; border-bottom: 1px solid #ccc; z-index: 1; display: flex; align-items: center; padding: 0 24px; } #cover { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.2); } .spacer { height: 900px; } + .glyph::before { content: '\f090'; } @@ -95,6 +96,13 @@

Levels

0
0 + +
Unselect All
+ 0 + +
Open row
+ 0 +

Far below

diff --git a/apps/electron-testbed/app/controls.js b/apps/electron-testbed/app/controls.js index 61f3d49ab6..2ff7d36974 100644 --- a/apps/electron-testbed/app/controls.js +++ b/apps/electron-testbed/app/controls.js @@ -110,3 +110,7 @@ const hostButton = document.createElement('button'); hostButton.textContent = 'Hosted action'; hostButton.addEventListener('click', () => count('host-clicks')); document.querySelector('[data-testid="disabled-host"]').attachShadow({ mode: 'open' }).append(hostButton); +document.querySelector('#unselect').addEventListener('click', () => count('unselect-clicks')); +document.querySelector('#open-row').addEventListener('click', () => count('open-row-clicks')); +const compositeRow = document.querySelector('[data-testid="composite-row"]'); +compositeRow.addEventListener('focus', () => compositeRow.querySelector('input').focus()); diff --git a/apps/electron-testbed/tests/controls.e2e.ts b/apps/electron-testbed/tests/controls.e2e.ts index 0365432e24..ad2a24faeb 100644 --- a/apps/electron-testbed/tests/controls.e2e.ts +++ b/apps/electron-testbed/tests/controls.e2e.ts @@ -199,6 +199,28 @@ test.describe('controls page', () => { await expect(screen.getByTestId('hold-state')).toHaveText('up', { timeout: 100 }); }); + test('names a button by its text, not its icon font\'s glyph, as web() does', async ({ screen }) => { + await expect(screen.getByRole('button', 'Scan')).toBeVisible(); + await expect(screen.getByTestId('glyph-button')).toHaveAccessibleName('Scan'); + }); + + test('taps text where it is, not the middle of the container the tree folds it into', async ({ screen }) => { + await screen.getByText('Unselect All').tap(); + await expect(screen.getByTestId('unselect-clicks')).toHaveText('1'); + await screen.getByText('Open row').tap(); + await expect(screen.getByTestId('open-row-clicks')).toHaveText('1'); + // A control is its text wherever the text is drawn: the query answers with the button, and its state. + await expect(screen.getByText('Wide save')).toBeDisabled(); + await expect(screen.getByText('Wide save')).toHaveRole('button'); + }); + + test('focuses a composite that hands focus to a part of itself, and types there', async ({ screen }) => { + await screen.getByTestId('composite-row').focus(); + await expect(screen.getByTestId('row-name')).toBeFocused(); + await screen.getByTestId('composite-row').pressSequentially('abc'); + await expect(screen.getByTestId('row-name')).toHaveValue('abc'); + }); + test('refuses a secret as electron.evaluate\'s argument', async ({ electron }) => { const refused = await failure(electron.evaluate((_main, arg: unknown) => JSON.stringify(arg), { password: credentials.user('ada').password })); expect(refused).toMatchObject({ code: 'POLICY_DENIED' }); diff --git a/apps/electron-testbed/tests/fixture.e2e.ts b/apps/electron-testbed/tests/fixture.e2e.ts new file mode 100644 index 0000000000..7d9765b7d4 --- /dev/null +++ b/apps/electron-testbed/tests/fixture.e2e.ts @@ -0,0 +1,140 @@ +import { existsSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { test } from '@e2e-dev/electron'; +import { credentials, expect } from 'e2e'; + +/** The page's document, as far as these tests read it: the project compiles without the DOM library. */ +interface PageGlobals { + readonly document: { readonly title: string; querySelector(selector: string): { readonly type: string } | null }; +} + +/** What a rejected step threw, for checking its code. */ +function failure(promise: Promise): Promise { + return promise.then(() => undefined, (error: unknown) => error); +} + +test.describe('electron.launch', () => { + test('gives the test its data directory before the app runs, and launches on what it put there', async ({ electron }) => { + expect(existsSync(electron.userDataDir)).toBe(true); + writeFileSync(path.join(electron.userDataDir, 'seeded'), 'by the test'); + await electron.launch(); + const read = await electron.evaluate(({ app }) => { + const fs = process.getBuiltinModule('node:fs'); + const file = process.getBuiltinModule('node:path').join(app.getPath('userData'), 'seeded'); + return fs.readFileSync(file, 'utf8'); + }); + expect(read).toBe('by the test'); + }); + + test('adds arguments and variables of the test\'s own, and keeps them through a restart', async ({ app, screen, electron }) => { + const launched = (): Promise<{ readonly args: readonly string[]; readonly mode: string | undefined }> => + electron.evaluate(() => ({ args: process.argv.filter((argument) => argument.startsWith('--greeting=') || argument === '--per-test'), mode: process.env['TESTBED_MODE'] })); + await electron.launch({ args: ['--per-test'], env: { TESTBED_MODE: 'per-test' } }); + await expect(screen.getByRole('heading', 'Hello from e2e')).toBeVisible(); + // After the target's own arguments, and over the engine's `env`, which is still there. + expect(await launched()).toEqual({ args: ['--greeting=Hello from e2e', '--per-test'], mode: 'per-test' }); + expect(await electron.evaluate(() => process.env['E2E_ELECTRON_HIDDEN'])).toBeDefined(); + await app.restart(); + expect(await launched()).toEqual({ args: ['--greeting=Hello from e2e', '--per-test'], mode: 'per-test' }); + }); + + test('starts the app\'s process in the directory the test names', async ({ electron }) => { + await electron.launch({ cwd: 'app' }); + expect(await electron.evaluate(() => process.cwd())).toMatch(/electron-testbed[\\/]app$/); + }); + + test('starts the next test without them', async ({ app, screen, electron }) => { + await app.open(); + await expect(screen.getByRole('heading', 'Hello from e2e')).toBeVisible(); + expect(await electron.evaluate(() => process.env['TESTBED_MODE'] ?? null)).toBeNull(); + }); + + test('refuses an argument the engine owns, a variable it never sets, and an option it does not know', async ({ electron }) => { + expect(await failure(electron.launch({ args: ['--user-data-dir=/tmp/elsewhere'] }))).toMatchObject({ code: 'INVALID_ARGUMENT', message: expect.stringContaining('electron.launch({ args })') }); + expect(await failure(electron.launch({ env: { TOKEN: credentials.user('ada').password as never } }))).toMatchObject({ code: 'POLICY_DENIED' }); + expect(await failure(electron.launch({ env: { NODE_OPTIONS: '--inspect' } }))).toMatchObject({ code: 'INVALID_ARGUMENT' }); + expect(await failure(electron.launch({ cwd: 'no-such-directory' }))).toMatchObject({ code: 'INVALID_ARGUMENT', message: expect.stringContaining('not a directory') }); + expect(await failure(electron.launch({ headless: true } as never))).toMatchObject({ code: 'INVALID_ARGUMENT' }); + }); +}); + +test.describe('the app not running', () => { + test('has no active window to hand out', async ({ electron }) => { + let thrown: unknown; + try { + electron.activeWindow(); + } catch (error) { + thrown = error; + } + expect(thrown).toMatchObject({ code: 'INVALID_STATE' }); + }); +}); + +test.describe('electron.keyboard and a window\'s page', () => { + test.beforeEach(async ({ app }) => { + await app.open(); + }); + + test('types and presses into whatever holds focus, with a held modifier', async ({ screen, electron }) => { + const username = screen.getByRole('textbox', 'Username'); + await username.focus(); + await electron.keyboard.type('ada', { delay: 5 }); + await expect(username).toHaveValue('ada'); + await electron.keyboard.down('Shift'); + await electron.keyboard.press('ArrowLeft'); + await electron.keyboard.up('Shift'); + await electron.keyboard.press('Backspace'); + await expect(username).toHaveValue('ad'); + await electron.keyboard.press('ControlOrMeta+A'); + await electron.keyboard.insertText('grace'); + await expect(username).toHaveValue('grace'); + // A chord with a modifier the test holds leaves it held: the next arrow still selects. + await username.fill('ada'); + await electron.keyboard.down('Shift'); + await electron.keyboard.press('Shift+ArrowLeft'); + await electron.keyboard.press('ArrowLeft'); + await electron.keyboard.up('Shift'); + await electron.keyboard.press('Backspace'); + await expect(username).toHaveValue('a'); + expect(await failure(electron.keyboard.down('NoSuchKey'))).toMatchObject({ code: 'UNSUPPORTED_CAPABILITY' }); + expect(await failure(electron.keyboard.type(credentials.user('ada').password as never))).toMatchObject({ code: 'POLICY_DENIED' }); + }); + + test('runs code in the active window\'s page, with its argument and its own error', async ({ electron }) => { + const window = electron.activeWindow(); + expect(window.isActive()).toBe(true); + expect(await window.evaluate(() => (globalThis as unknown as PageGlobals).document.title)).toBe('Sign In'); + expect(await window.evaluate((name: string) => (globalThis as unknown as PageGlobals).document.querySelector(`[name=${name}]`)?.type, 'password')).toBe('password'); + expect(await window.evaluate(async () => await Promise.resolve({ nested: [1, 2] }))).toEqual({ nested: [1, 2] }); + expect(await failure(window.evaluate(() => { throw new Error('from the page'); }))).toMatchObject({ code: 'EVALUATE_FAILED', message: expect.stringContaining('from the page') }); + expect(await failure(window.evaluate((held: unknown) => held, { nested: [credentials.user('ada').password] }))).toMatchObject({ code: 'POLICY_DENIED' }); + // What comes back is plain data, as from the main process: a bigint as its digits, a function left out. + expect(await window.evaluate(() => ({ big: 10n, run: () => 1, kept: 'yes' }))).toEqual({ big: '10', kept: 'yes' }); + // The new document is there when reload() resolves: what the old one held is gone, with no wait. + await window.evaluate(() => { + (globalThis as { marked?: boolean }).marked = true; + }); + await window.reload(); + expect(await window.evaluate(() => (globalThis as { marked?: boolean }).marked ?? null)).toBeNull(); + expect(await window.evaluate(() => (globalThis as unknown as { document: { readyState: string } }).document.readyState)).toBe('complete'); + }); + + test('moves, presses, and scrolls with the mouse where the test points it', async ({ screen, electron }) => { + const box = await screen.getByRole('button', 'Add one').boundingBox(); + if (box === null) throw new Error('the button has no box'); + await electron.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + await electron.mouse.down(); + await electron.mouse.up(); + await expect(screen.getByTestId('count')).toHaveText('1'); + // A right press is no click. + await electron.mouse.down({ button: 'right' }); + await electron.mouse.up({ button: 'right' }); + await expect(screen.getByTestId('count')).toHaveText('1'); + const scrolled = (): Promise => electron.activeWindow().evaluate(() => (globalThis as unknown as { scrollY: number }).scrollY); + const before = await scrolled(); + await electron.mouse.wheel(0, 200); + await expect.poll(scrolled).toBeGreaterThan(before); + expect(await failure(electron.mouse.move(Number.NaN, 0))).toMatchObject({ code: 'INVALID_ARGUMENT' }); + expect(await failure(electron.mouse.down({ button: 'side' as never }))).toMatchObject({ code: 'INVALID_ARGUMENT' }); + }); +}); diff --git a/docs/electron.mdx b/docs/electron.mdx index a65b29fb14..8d124d8286 100644 --- a/docs/electron.mdx +++ b/docs/electron.mdx @@ -89,13 +89,45 @@ test('signs in and opens settings', async ({ app, screen, electron }) => { | Method | What it does | | --- | --- | +| `launch({ args, env, cwd, timeout }?)` | Launches the app with [arguments and variables for this test](#launch-with-per-test-arguments) | +| `userDataDir` | The test's user-data directory, which exists before the app is launched | | `evaluate(fn, arg?)` | Runs `fn` in the main process with the `electron` module and returns its JSON-serializable result | | `windows()` | The open windows, in the order they opened | +| `activeWindow()` | The window `screen` reads | | `waitForWindow(trigger, { timeout }?)` | Runs `trigger`, waits for the window it opens, and makes that window active | | `window({ title, url }, { timeout }?)` | Waits for a window by title or URL and returns it, without making it active | | `waitForDownload(trigger, { timeout }?)` | Runs `trigger` and waits for the [download](#downloads) it starts | | `onDialog(handler)` | Answers the app's [`alert()` and `confirm()` dialogs](#handle-alert-and-confirm-dialogs) | | `locator(selector)` | Queries the current window by CSS selector | +| `keyboard`, `mouse` | [Keyboard and pointer input](#keyboard-and-mouse) for the active window | + +## Launch with per-test arguments + +`electron.launch()` launches the app as `app.open()` does, and adds arguments +and environment variables for this test to the target's. `cwd` sets the +directory the process starts in. `app.open()`, `app.restart()`, and +`app.clearState()` keep them until the test ends. Another `launch()` replaces +them. + +`electron.userDataDir` exists before the app is launched, so a test can put +data in it first: + +```ts +import { writeFileSync } from 'node:fs'; +import path from 'node:path'; + +test('opens on saved settings', async ({ electron, screen }) => { + writeFileSync(path.join(electron.userDataDir, 'settings.json'), '{"theme":"dark"}'); + await electron.launch({ + args: ['--skip-onboarding'], + env: { APP_DATA_PATH: electron.userDataDir }, + }); + await expect(screen.getByRole('heading', 'Projects')).toBeVisible(); +}); +``` + +To launch this way in every test, call `electron.launch()` from a +[fixture](/fixtures). ## Work with several windows @@ -116,8 +148,8 @@ await main.activate(); await settings.close(); ``` -A window has `title()`, `url()`, `isActive()`, `isClosed()`, `activate()`, and -`close()`. For a window the app opens by itself, such as the main window after +A window has `title()`, `url()`, `isActive()`, `isClosed()`, `activate()`, +`close()`, `reload()`, and [`evaluate()`](#run-code-in-a-window). For a window the app opens by itself, such as the main window after a splash screen, find it with `electron.window()`: ```ts @@ -152,6 +184,37 @@ values as `arg` (plain JSON only; secrets are refused) and return plain data. `require` isn't in scope inside `fn`; use the `electron` argument or `process.getBuiltinModule('node:fs')`. +## Run code in a window + +`window.evaluate()` runs a function in the window's page, where the app's own +globals are. It follows the same rules as `electron.evaluate()`: `fn` is sent +as text, and `arg` and the result are plain JSON. + +```ts +const window = electron.activeWindow(); +const theme = await window.evaluate((key) => localStorage.getItem(key), 'theme'); +await window.reload(); +``` + +## Keyboard and mouse + +`electron.keyboard` and `electron.mouse` send input to the active window, +wherever its focus and pointer are. Prefer `locator.press()` and +`locator.fill()` when there is an element to name. + +```ts +await electron.keyboard.press('Escape'); +await electron.keyboard.press('ControlOrMeta+P'); +await electron.keyboard.type('hello', { delay: 20 }); +await electron.mouse.move(0, 0); +``` + +- `keyboard` has `press`, `down`, `up`, `type`, and `insertText`. `mouse` has + `move`, `down`, `up`, and `wheel`. +- A shortcut the page handles works. A menu accelerator doesn't: see + [Limits](#limits). +- `type` never takes a secret. Fill one with `locator.fill()`. + ## Handle alert and confirm dialogs `electron.onDialog()` answers the dialogs the app opens from then on, the @@ -259,6 +322,7 @@ The engine adds `--no-sandbox` on Linux automatically. | Area | On Electron | | --- | --- | +| Finding elements | An element inside an `inert` subtree, such as the page behind a modal, is not in the tree: `getByRole`, `getByText`, and `getByLabel` don't find it, and `electron.locator()` does | | Launch arguments | The engine adds `--inspect=0`, `--remote-debugging-pipe`, `--force-color-profile=srgb`, `--user-data-dir=...`, switches that keep a covered or hidden window drawing, and `--no-sandbox` on Linux. Strict argument parsers must allow them | | Parallel workers | Each test gets its own user-data directory, so tests run in parallel. If your app overrides `app.setPath('userData', ...)`, set `workers: 1` | | Clipboard | The app uses your OS clipboard, so a test's copy overwrites yours. Set `workers: 1` for clipboard tests | @@ -300,7 +364,6 @@ The engine adds `--no-sandbox` on Linux automatically. - Content inside an `iframe` or `webview` (a `webview` guest is listed as a window, so `electron.window()` reaches it) - Routes and cookies (use `session.defaultSession` in `electron.evaluate()` instead) - Session save and restore -- A `keyboard` fixture to hold a key down - Reading the app's console from a test ## Options @@ -308,6 +371,7 @@ The engine adds `--no-sandbox` on Linux automatically. | Option | Type | Default | What it sets | | --- | --- | --- | --- | | `executablePath` | `string` | project's `electron` | Binary to start, such as a [packaged app](#test-a-packaged-app) | +| `cwd` | `string` | project root | Directory the app's process starts in: absolute, or relative to the project root | | `env` | `Record` | `{}` | Extra environment variables for the app (not `ELECTRON_RUN_AS_NODE` or `NODE_OPTIONS`); see [Security](#security) | | `testIdAttribute` | `string` | `'data-testid'` | Attribute `getByTestId` reads | | `settle` | `number \| false` | `100` | Wait time in milliseconds after an agent action before the next read (`false` skips it) | diff --git a/docs/migrate/playwright.mdx b/docs/migrate/playwright.mdx index d5e4341102..ce05887da3 100644 --- a/docs/migrate/playwright.mdx +++ b/docs/migrate/playwright.mdx @@ -421,13 +421,17 @@ config by hand. | Playwright | e2e | | --- | --- | | `_electron.launch({ args })` in a fixture, `electronApp.firstWindow()` | `await app.open()` in `beforeEach`. Arguments the app reads, and Chromium switches, go in the target's `app.launchArguments`, the same for every test | +| `_electron.launch({ args, env })` with values of one test, a data directory filled before the launch | `await electron.launch({ args, env })` and `electron.userDataDir`, see [per-test arguments](/electron#launch-with-per-test-arguments). The app doesn't inherit the runner's environment: name a variable it reads, such as `PLAYWRIGHT_TEST`, in `electron({ env })` | | `electronApp.evaluate(fn, arg)` | `electron.evaluate(fn, arg)` | -| `page.evaluate(fn)` in the renderer | `electron.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].webContents.executeJavaScript('…'))`. Pick the window by title: `getAllWindows()` is not in the order `electron.windows()` lists | +| `page.evaluate(fn, arg)` in the renderer, `page.reload()`, `page.url()` | `electron.activeWindow().evaluate(fn, arg)`, `reload()`, `url()` | +| `page.keyboard`, `page.mouse` | `electron.keyboard`, `electron.mouse` | +| `page.waitForURL(re)`, `page.waitForFunction(fn)` | `await expect.poll(() => window.url()).toMatch(re)`, `await expect.poll(() => window.evaluate(fn)).toBeTruthy()` | | `electronApp.waitForEvent('window')` | `await electron.waitForWindow(() => screen.getByRole('button', 'Open').tap())`, which makes the new window active. For a window the app opens on its own, `await electron.window({ title: 'Settings' })` | | `page.on('dialog')` | `await electron.onDialog('accept')`, `'dismiss'`, or a handler | | `page.waitForEvent('close')` | `await expect.poll(() => window.isClosed()).toBe(true)` | | `expect(page).toHaveTitle(title)` | `await expect.poll(() => window.title()).toBe(title)` | -| `page.getByRole`, `getByLabel`, `getByTestId`, `locator(css)` | `screen.getByRole`, `getByLabel`, `getByTestId`, and `electron.locator(css)`, which takes CSS only | +| `page.getByRole`, `getByLabel`, `getByTestId`, `locator(css)` | `screen.getByRole`, `getByLabel`, `getByTestId`, and `electron.locator(css)`, which takes CSS only: no `text=`, `:has-text()`, `:visible`, or `>>`. Use `.filter({ hasText })` and `.filter({ has })` | +| A query for an element behind an open modal | `electron.locator(css)`: the page behind a modal is `inert`, and `screen` queries leave an inert subtree out | | `page.on('console')`, `electronApp.on('console')` | Recorded in the test's trace under App log, main-process lines prefixed `[main]`. A test cannot read them | | `electronApp.close()` | Nothing: every test ends with the app quit | diff --git a/docs/reference/errors.mdx b/docs/reference/errors.mdx index b4b03202ef..5461f5872b 100644 --- a/docs/reference/errors.mdx +++ b/docs/reference/errors.mdx @@ -186,7 +186,7 @@ These appear in terminal output and in the report as plain string codes. | `WORKER_PROTOCOL` | A worker reported the wrong unit, an attempt overlapped a live attempt, `openHost` tried to acquire an engine instance another host owns, or `host.openSession` tried to reuse a closed host or overlap an opening, live, or closing session. In `@e2e-dev/core`, `launch` on an engine instance another host owns, or `host.newSession` on a closed host or while a session is open | infrastructure | 3 | | `SESSION_KEY_INVALID` | A worker received a session key that is not 32 bytes. Packaging or IPC fault. | infrastructure | 3 | | `REPORT_WRITE_FAILED` | `report.json` or `ai-trace.json` could not be written. Recorded as a run error; the in-memory outcome is still complete. A `junit.xml`, `summary.md`, or `ctrf.json` that could not be written is a line on its reporter's stderr instead | infrastructure | 3 | -| `EVALUATE_FAILED` | `browser.evaluate` threw inside the page, `electron.evaluate` threw in the main process (`@e2e-dev/electron`), a page timer threw while `browser.clock` ran it, or the page deleted or replaced a JavaScript built-in (such as `Map`) that the engine's in-page code needs, which fails later evaluates and locators (`@e2e-dev/web`) | test | 1 | +| `EVALUATE_FAILED` | `browser.evaluate` threw inside the page, `electron.evaluate` threw in the main process or `window.evaluate` in a window's page (`@e2e-dev/electron`), a page timer threw while `browser.clock` ran it, or the page deleted or replaced a JavaScript built-in (such as `Map`) that the engine's in-page code needs, which fails later evaluates and locators (`@e2e-dev/web`) | test | 1 | | `INTERRUPTED` | A user or CI signal aborted the run. A test cut short by `--max-failures` or the time limit also ends with this code, and its message names the limit; that run exits 1, not 130 | interrupted | 130 | #### Test code errors diff --git a/packages/electron/README.md b/packages/electron/README.md index 03b08120c3..8cce1f16f3 100644 --- a/packages/electron/README.md +++ b/packages/electron/README.md @@ -57,8 +57,10 @@ test('signs in', async ({ app, screen }) => { - **Act.** Trusted mouse and keyboard input, once the node is enabled, on screen, and topmost at its point. - **Windows.** The agent sees them as tabs. The `electron` fixture has - `evaluate` (main process), `windows`, `waitForWindow`, `window`, - `waitForDownload`, `onDialog`, and `locator` (CSS). + `launch` (per-test arguments and environment), `userDataDir`, `evaluate` + (main process), `windows`, `activeWindow`, `waitForWindow`, `window`, + `waitForDownload`, `onDialog`, `locator` (CSS), `keyboard`, and `mouse`. A + window has `evaluate` (its page) and `reload`. - **Video.** The shown window's screencast, encoded to one `.webm` by ffmpeg, which the engine downloads on the first recording when the machine has none. - **Secrets.** Password fields report no value, and screenshots paint them diff --git a/packages/electron/src/actions.ts b/packages/electron/src/actions.ts index dfb19e5a3b..4bc16fefb6 100644 --- a/packages/electron/src/actions.ts +++ b/packages/electron/src/actions.ts @@ -146,7 +146,17 @@ export async function typeText(context: ActionContext, window: AppWindow, text: await withModifiers(budget, window, ['ControlOrMeta'], () => keyboard.press('A')); await budget.send(() => keyboard.press('Delete')); } - for (const character of text) await budget.send(() => keyboard.type(character)); + await typeKeys(window, text, 0, budget); +} + +/** Types text into whatever holds focus, key by key, `delayMs` apart: each character's key, or the character inserted when the layout has none. */ +export async function typeKeys(window: AppWindow, text: string, delayMs: number, budget: Budget): Promise { + let first = true; + for (const character of text) { + if (!first && delayMs > 0) await sleep(delayMs, budget.operation.signal); + first = false; + await budget.send(() => window.page.keyboard.type(character)); + } } /** Presses a key in the shown window, wherever focus is. */ @@ -421,6 +431,8 @@ export async function withModifiers(budget: Budget, window: AppWindow, modifiers const held: string[] = []; try { for (const modifier of modifiers) { + // One the test already holds (`electron.keyboard.down('Shift')`) stays the test's to release. + if (keyboard.holds(modifier)) continue; await budget.send(() => { held.push(modifier); return keyboard.down(modifier); diff --git a/packages/electron/src/app-process.ts b/packages/electron/src/app-process.ts index b685733e03..584c59c12e 100644 --- a/packages/electron/src/app-process.ts +++ b/packages/electron/src/app-process.ts @@ -15,7 +15,8 @@ import type { ElectronMainModule } from './fixtures.ts'; import { closedWindow, invalidState, unsupported } from './errors.ts'; import { appDirectory } from './file-bound.ts'; import { ElectronProcess, type ProcessExit } from './launcher.ts'; -import { MainEvaluateError, MainProcess } from './main-process.ts'; +import { EvaluateError } from './evaluate.ts'; +import { MainProcess } from './main-process.ts'; import { REFUSED_ENV, type ResolvedElectronOptions } from './options.ts'; import { PageTarget } from './page.ts'; import type { Windows } from './windows.ts'; @@ -34,6 +35,16 @@ export interface LaunchSetup { readonly env: Readonly>; readonly userDataDir: string; readonly attempt: EngineAttemptContext; + /** What `electron.launch()` added for this attempt, over the target's arguments and the engine's `env`. */ + readonly extra?: LaunchExtra; +} + +/** The arguments and variables one attempt's launches add to the target's own. */ +export interface LaunchExtra { + readonly args: readonly string[]; + readonly env: Readonly>; + /** The directory the process starts in, over the engine's `cwd`. */ + readonly cwd?: string; } /** How long the main process gets to answer a question whose answer is optional. */ @@ -209,8 +220,8 @@ export class AppProcess { /** Starts the binary. Nothing is awaited: a binary that cannot start shows as a process that ended. */ private start(setup: LaunchSetup): RunningApp { const { appPath, launchArguments } = setup.app; - const args = [`--user-data-dir=${setup.userDataDir}`, ...(appPath === undefined ? [] : [path.resolve(setup.projectRoot, appPath)]), ...(launchArguments ?? [])]; - const process = new ElectronProcess({ executable: setup.executable, args, cwd: setup.projectRoot, env: launchEnv(setup.env, this.options.env) }); + const args = [`--user-data-dir=${setup.userDataDir}`, ...(appPath === undefined ? [] : [path.resolve(setup.projectRoot, appPath)]), ...(launchArguments ?? []), ...(setup.extra?.args ?? [])]; + const process = new ElectronProcess({ executable: setup.executable, args, cwd: path.resolve(setup.projectRoot, setup.extra?.cwd ?? this.options.cwd ?? '.'), env: launchEnv(setup.env, [this.options.env, setup.extra?.env ?? {}]) }); let withoutMain: () => void = () => undefined; const none = new Promise((resolve) => { withoutMain = () => resolve(undefined); @@ -328,7 +339,7 @@ export class AppProcess { }); session.on('Page.loadEventFired', () => { this.windows.markLoaded(page); - page.emit('load'); + page.markLoaded(); }); session.on('Page.frameNavigated', ({ frame }) => { if (frame.parentId !== undefined) return; @@ -374,7 +385,7 @@ export class AppProcess { const exiting = this.app === app && (closedWindow(cause) || /Execution context was destroyed/.test(String(cause))); if (exiting) await answerWithin(app.process.exited, ANSWER_MS); if (this.app !== app) throw new EngineError('INVALID_STATE', 'the app quit while electron.evaluate ran', { retryable: false, cause }); - if (!(cause instanceof MainEvaluateError)) throw cause; + if (!(cause instanceof EvaluateError)) throw cause; // Its message is the test's, never read for a pattern. throw new TestError('EVALUATE_FAILED', `electron.evaluate: ${cause.message}`, { cause }); } @@ -572,20 +583,24 @@ async function placeDownloads(main: MainProcess, directory: string, withinMs: nu /** * The app's environment: the few variables of the run's that a process needs - * to start and draw (`INHERITED_ENV`, and the locale's `LC_*`), with the - * engine's `env` option over them. The rest of the run's environment stays + * to start and draw (`INHERITED_ENV`, and the locale's `LC_*`), with each of + * `layers` over them in turn: the engine's `env` option, then a test's own. The rest of the run's environment stays * with the runner: it holds provider keys and tokens, and an app can log or * upload what it is given. Never `ELECTRON_RUN_AS_NODE`, which would start * the binary as plain Node.js, nor `NODE_OPTIONS`. */ -export function launchEnv(runEnv: Readonly>, extra: Readonly>): Record { +export function launchEnv(runEnv: Readonly>, layers: readonly Readonly>[], platform: NodeJS.Platform = process.platform): Record { const env: Record = {}; - // Windows reads a variable's name in any case. + // Windows reads a variable's name in any case: a later layer's `path` replaces an earlier `PATH`, never sits beside it. + const set = (key: string, value: string): void => { + if (platform === 'win32') for (const known of Object.keys(env)) if (known !== key && known.toUpperCase() === key.toUpperCase()) delete env[known]; + env[key] = value; + }; for (const [key, value] of Object.entries(runEnv)) { const name = key.toUpperCase(); - if (value !== undefined && (INHERITED_ENV.has(name) || name.startsWith('LC_'))) env[key] = value; + if (value !== undefined && (INHERITED_ENV.has(name) || name.startsWith('LC_'))) set(key, value); } - for (const [key, value] of Object.entries(extra)) if (!REFUSED_ENV.has(key.toUpperCase())) env[key] = value; + for (const layer of layers) for (const [key, value] of Object.entries(layer)) if (!REFUSED_ENV.has(key.toUpperCase())) set(key, value); return env; } diff --git a/packages/electron/src/cdp/input.ts b/packages/electron/src/cdp/input.ts index 6eacc0a619..2d96cd16f6 100644 --- a/packages/electron/src/cdp/input.ts +++ b/packages/electron/src/cdp/input.ts @@ -54,6 +54,12 @@ export class Keyboard { return this.heldModifiers; } + /** Whether a modifier is held now, by any name it is pressed by (`ControlOrMeta` too). */ + holds(modifier: string): boolean { + const key = platformKey(modifier); + return isModifier(key) && this.heldModifiers.has(key); + } + /** Forgets what is held: the renderer that held it is gone. */ reset(): void { this.heldModifiers.clear(); diff --git a/packages/electron/src/electron.ts b/packages/electron/src/electron.ts index e9dd2d879a..a6afa8c975 100644 --- a/packages/electron/src/electron.ts +++ b/packages/electron/src/electron.ts @@ -4,8 +4,12 @@ * `electron.` step bounded by the action timeout. */ -import { ConfigurationError, isSecret, stepTimeout, type EngineFixtureContext, type FixtureOperation } from '@e2e-dev/core/engine'; +import { ConfigurationError, isSecret, stepTimeout, TestError, type EngineFixtureContext, type FixtureOperation } from '@e2e-dev/core/engine'; import type { Electron, ElectronMainModule, ElectronWindow } from './fixtures.ts'; +import { typeKeys } from './actions.ts'; +import { hasKey, type MouseButton } from './cdp/input.ts'; +import { unsupported } from './errors.ts'; +import { checkLaunchOptions } from './options.ts'; import type { ElectronSurface } from './surface.ts'; import type { AppWindow } from './windows.ts'; @@ -21,13 +25,80 @@ export function createElectronFixture(surface: ElectronSurface, context: EngineF url: () => Promise.resolve(window.page.url()), isActive: () => surface.isActiveWindow(window), isClosed: () => window.page.isClosed(), + async evaluate(fn: (arg: A) => R | Promise, arg?: A): Promise { + if (holdsSecret(arg)) throw new ConfigurationError('POLICY_DENIED', 'window.evaluate cannot take a secret as its argument: fill it into a field with locator.fill'); + return await surface.evaluateInWindow(window, fn, arg as A, context.operation()); + }, + reload: () => surface.reloadWindow(window, context.operation()), activate: () => surface.activateWindow(window, context.operation()), close: () => surface.closeWindow(window, context.operation()), - }, { title: windowAction, url: windowAction, activate: windowAction, close: windowAction }); + }, { title: windowAction, url: windowAction, activate: windowAction, close: windowAction, evaluate: windowAction, reload: windowAction }); handles.set(window, made); return made; }; + const mouseButton = (options: { readonly button?: MouseButton } | undefined): MouseButton => { + const chosen = options?.button ?? 'left'; + if (chosen !== 'left' && chosen !== 'right' && chosen !== 'middle') throw new TestError('INVALID_ARGUMENT', "electron.mouse takes { button: 'left' | 'right' | 'middle' }"); + return chosen; + }; + const numbers = (call: string, ...values: readonly unknown[]): void => { + if (values.some((value) => typeof value !== 'number' || !Number.isFinite(value))) throw new TestError('INVALID_ARGUMENT', `electron.mouse.${call} takes two numbers`); + }; + const plainText = (value: unknown, method: string): string => { + if (isSecret(value)) throw new ConfigurationError('POLICY_DENIED', `electron.keyboard.${method} cannot take a secret: fill it into a field with locator.fill`); + if (typeof value !== 'string') throw new TestError('INVALID_ARGUMENT', `electron.keyboard.${method} takes a string`); + return value; + }; + const holdKey = (direction: 'down' | 'up') => async (key: string): Promise => { + const name = plainText(key, direction); + if (!hasKey(name)) throw unsupported(`the keyboard has no key ${JSON.stringify(name)}: name a key such as "Shift" or "Enter", or a character of a US keyboard`); + await surface.input(`keyboard.${direction}`, (window, budget) => budget.send(() => window.page.keyboard[direction](name)), context.operation()); + }; const electron: Electron = { + get userDataDir() { + return surface.dataDirectory(); + }, + async launch(options) { + // A secret would reach the app's command line or environment, where any process can read it. + if (holdsSecret(options)) throw new ConfigurationError('POLICY_DENIED', 'electron.launch() cannot take a secret in its arguments or variables'); + const extra = checkLaunchOptions(options, surface.root); + await surface.launchWith(extra, context.operation(stepTimeout(options?.timeout, 'electron.launch') ?? context.timeouts.test)); + }, + activeWindow: () => handle(surface.shownWindow()), + keyboard: { + press: async (key) => surface.pressKey(plainText(key, 'press'), context.operation()), + down: holdKey('down'), + up: holdKey('up'), + async type(value, options) { + const delay = options?.delay ?? 0; + if (typeof delay !== 'number' || !Number.isFinite(delay) || delay < 0) throw new TestError('INVALID_ARGUMENT', 'electron.keyboard.type({ delay }) takes a number of milliseconds'); + const typed = plainText(value, 'type'); + // One budget for the whole text: the action timeout, and the time its delays ask on top. + await surface.input('keyboard.type', (window, budget) => typeKeys(window, typed, delay, budget), context.operation(context.timeouts.action + [...typed].length * delay)); + }, + async insertText(value) { + const inserted = plainText(value, 'insertText'); + await surface.input('keyboard.insertText', (window, budget) => budget.send(() => window.page.keyboard.insertText(inserted)), context.operation()); + }, + }, + mouse: { + async move(x, y) { + numbers('move(x, y)', x, y); + await surface.input('mouse.move', (window, budget) => budget.send(() => window.page.mouse.move(x, y)), context.operation()); + }, + async down(options) { + const pressed = mouseButton(options); + await surface.input('mouse.down', (window, budget) => budget.send(() => window.page.mouse.down(pressed)), context.operation()); + }, + async up(options) { + const released = mouseButton(options); + await surface.input('mouse.up', (window, budget) => budget.send(() => window.page.mouse.up(released)), context.operation()); + }, + async wheel(deltaX, deltaY) { + numbers('wheel(deltaX, deltaY)', deltaX, deltaY); + await surface.input('mouse.wheel', (window, budget) => budget.send(() => window.page.mouse.wheel(deltaX, deltaY)), context.operation()); + }, + }, async evaluate(fn: (electron: ElectronMainModule, arg: A) => R | Promise, arg?: A): Promise { // A secret handle would reach the main process as its name and purpose, never its value: refused, as every JSON sink refuses one. if (holdsSecret(arg)) throw new ConfigurationError('POLICY_DENIED', 'electron.evaluate cannot take a secret as its argument: resolve the value in the test and pass a string, or keep it out of the main process'); @@ -66,7 +137,17 @@ export function createElectronFixture(surface: ElectronSurface, context: EngineF return context.locator({ kind: 'selector', selector }); }, }; + const input: FixtureOperation = { kind: 'resource' }; return context.fixture('electron', electron, { + launch: { kind: 'resource', timeout: false }, + keyboard: { + press: { ...input, label: (key) => String(key) }, + down: { ...input, label: (key) => String(key) }, + up: { ...input, label: (key) => String(key) }, + type: { kind: 'resource', timeout: false, label: (value) => `${typeof value === 'string' ? [...value].length : 0} chars` }, + insertText: { ...input, label: (value) => `${typeof value === 'string' ? [...value].length : 0} chars` }, + }, + mouse: { move: input, down: input, up: input, wheel: input }, evaluate: { kind: 'resource' }, waitForWindow: { kind: 'resource', timeout: false }, window: { kind: 'resource', timeout: (_which, options) => options?.timeout, label: (which) => JSON.stringify({ title: which.title?.toString(), url: which.url?.toString() }) }, diff --git a/packages/electron/src/engine-entry.ts b/packages/electron/src/engine-entry.ts index 6447f7cb10..7a6e440ebf 100644 --- a/packages/electron/src/engine-entry.ts +++ b/packages/electron/src/engine-entry.ts @@ -11,4 +11,4 @@ export type { ElectronEngine } from './engine.ts'; export { electron as default } from './engine.ts'; export type { ElectronOptions } from './options.ts'; export type { Dialog, DialogHandler } from './dialogs.ts'; -export type { Electron, ElectronFixtures, ElectronMainModule, ElectronWindow, WindowMatcher } from './fixtures.ts'; +export type { Electron, ElectronFixtures, ElectronKeyboard, ElectronLaunchOptions, ElectronMainModule, ElectronMouse, ElectronWindow, WindowMatcher } from './fixtures.ts'; diff --git a/packages/electron/src/evaluate.ts b/packages/electron/src/evaluate.ts new file mode 100644 index 0000000000..617280cbc1 --- /dev/null +++ b/packages/electron/src/evaluate.ts @@ -0,0 +1,111 @@ +/** + * Test code run inside the app, in its main process or in a window's page: + * the function sent as source text, its argument as a protocol value, and + * what it returns brought back as plain data. + */ + +import type { Protocol } from 'devtools-protocol'; +import { TestError } from '@e2e-dev/core/engine'; +import type { Session } from './cdp/connection.ts'; + +/** What a function run in the app threw: its own failure, not the engine's. */ +export class EvaluateError extends Error {} + +/** Refuses an argument that is not JSON, in the caller's name: it crosses the protocol as a value. */ +export function checkJsonArgument(arg: unknown, caller: string): void { + try { + JSON.stringify(arg); + } catch (cause) { + throw new TestError('INVALID_ARGUMENT', `${caller}: its argument is not JSON (${cause instanceof Error ? (cause.message.split('\n')[0] ?? '') : String(cause)}); pass plain data`, { cause }); + } +} + +/** + * Calls the function `source` on the remote object `objectId` with `leading` + * and then `arg`, awaits it, and returns its result as plain data + * (`plainData`). Rejects with `EvaluateError` when the function throws. + */ +export async function callForPlainData( + session: Session, + call: { readonly objectId: string; readonly source: string; readonly leading?: readonly Protocol.Runtime.CallArgument[]; readonly arg: unknown; readonly userGesture?: boolean }, +): Promise { + const { result, exceptionDetails } = await session.send('Runtime.callFunctionOn', { + objectId: call.objectId, + functionDeclaration: `async function (...args) { return (${plainData.toString()})(await (${call.source})(...args)); }`, + arguments: [...(call.leading ?? []), call.arg === undefined ? {} : { value: call.arg }], + returnByValue: true, + awaitPromise: true, + ...(call.userGesture === true ? { userGesture: true } : {}), + }); + if (exceptionDetails !== undefined) throw new EvaluateError(describeException(exceptionDetails)); + // NaN, an infinity, and -0 have no JSON: the protocol names them instead. + return result.unserializableValue === undefined ? result.value : Number(result.unserializableValue); +} + +/** + * A function's source as an expression. A method written in shorthand + * (`{ run() {} }.run`) prints without the `function` keyword, which is put + * back. The source is only compiled here, never run. + */ +export function functionSource(fn: (...args: never[]) => unknown, caller: string): string { + if (typeof fn !== 'function') throw new TestError('INVALID_ARGUMENT', `${caller} takes a function`); + const source = fn.toString(); + if (compiles(source)) return source; + const method = source.replace(/^(async\s+)?(\*\s*)?/, (_match, async: string | undefined, star: string | undefined) => `${async ?? ''}function ${star ?? ''}`); + if (compiles(method)) return method; + throw new TestError('INVALID_ARGUMENT', `${caller}: its function cannot be sent as source text; pass an arrow function or a function expression`); +} + +function compiles(source: string): boolean { + try { + // oxlint-disable-next-line no-new-func -- compiled to check its syntax, never called + void new Function(`(${source})`); + return true; + } catch { + return false; + } +} + +/** What a thrown value says of itself, on one line. */ +export function describeException(details: Protocol.Runtime.ExceptionDetails): string { + const { exception } = details; + if (exception?.description !== undefined) return exception.description.split('\n')[0] ?? details.text; + return exception?.value === undefined ? details.text : `${details.text} ${String(exception.value)}`; +} + +/** + * A value as the plain data that crosses the protocol: objects and arrays of + * primitives. A function or a symbol is left out, as is a reference back to + * an object that holds it, so a `BrowserWindow` or a timer comes back as the + * plain part of what it is rather than failing the call. Runs in the main + * process, sent as source text: self-contained. + */ +export function plainData(value: unknown): unknown { + const holders = new Set(); + const plain = (item: unknown, depth: number): unknown => { + if (typeof item === 'function' || typeof item === 'symbol') return undefined; + if (typeof item === 'bigint') return item.toString(); + if (typeof item !== 'object' || item === null) return item; + if (item instanceof Date) return item.toJSON(); + if (holders.has(item) || depth > 32) return undefined; + holders.add(item); + try { + if (Array.isArray(item)) return item.map((entry) => plain(entry, depth + 1) ?? null); + const out: Record = {}; + for (const key of Object.keys(item)) { + let entry: unknown; + try { + entry = plain((item as Record)[key], depth + 1); + } catch { + // A getter that throws has no value to send. + } + // Defined, not assigned: a key named __proto__ is data too. + if (entry !== undefined) Object.defineProperty(out, key, { value: entry, enumerable: true, writable: true, configurable: true }); + } + return out; + } finally { + holders.delete(item); + } + }; + return plain(value, 0); +} diff --git a/packages/electron/src/fixtures.ts b/packages/electron/src/fixtures.ts index 23b1a5ad3f..2364b20c70 100644 --- a/packages/electron/src/fixtures.ts +++ b/packages/electron/src/fixtures.ts @@ -23,6 +23,16 @@ export interface ElectronWindow { isClosed(): boolean; /** Makes this the active window. Rejects with `ACTION_FAILED` when it has closed. */ activate(): Promise; + /** + * Runs `fn` in the window's page, with the app's own globals, and returns + * what it returns, which must be JSON. `fn` is sent as source text: it + * cannot close over the test's variables, so pass them as `arg`. + */ + evaluate(fn: () => R | Promise): Promise; + /** Runs `fn` in the window's page with `arg`, which must be JSON. */ + evaluate(fn: (arg: A) => R | Promise, arg: A): Promise; + /** Reloads the window's document and resolves once it has loaded again. */ + reload(): Promise; /** Closes the window, past any `beforeunload` guard. When it was the active window, the window that opened it is active again, else the one active before it. */ close(): Promise; } @@ -40,8 +50,66 @@ export interface WindowMatcher { */ export type ElectronMainModule = typeof import('electron'); +/** What `electron.launch` adds to the target's own launch arguments and the engine's `env`. */ +export interface ElectronLaunchOptions { + /** Arguments after the target's `app.launchArguments`: the app's own switches and Chromium's. */ + readonly args?: readonly string[] | undefined; + /** Variables over the engine's `env`. Never `ELECTRON_RUN_AS_NODE` or `NODE_OPTIONS`. */ + readonly env?: Readonly> | undefined; + /** The directory the app's process starts in, over the engine's `cwd`: absolute, or relative to the project root. */ + readonly cwd?: string | undefined; + /** How long the launch may take, in milliseconds. Default: the test's `timeout`. */ + readonly timeout?: number | undefined; +} + +/** Keyboard input to the active window, for whatever holds focus there. */ +export interface ElectronKeyboard { + /** Presses one key, with its modifiers: `'Escape'`, `'ControlOrMeta+A'`, `'Shift+Tab'`. */ + press(key: string): Promise; + /** Holds one key until `up`; a held modifier applies to the keys and mouse events after it. */ + down(key: string): Promise; + /** Releases a held key. */ + up(key: string): Promise; + /** Types plain text key by key, `delay` milliseconds apart. Never a secret: fill one with `locator.fill`. */ + type(text: string, options?: { readonly delay?: number }): Promise; + /** Inserts text as an input method's commit would: input events and no key events. */ + insertText(text: string): Promise; +} + +/** Pointer input to the active window, in viewport CSS pixels. */ +export interface ElectronMouse { + /** Moves the pointer to a point of the viewport. */ + move(x: number, y: number): Promise; + /** Presses a button where the pointer is; the left one by default. */ + down(options?: { readonly button?: 'left' | 'right' | 'middle' }): Promise; + /** Releases a button where the pointer is; the left one by default. */ + up(options?: { readonly button?: 'left' | 'right' | 'middle' }): Promise; + /** Scrolls by a wheel turn where the pointer is. */ + wheel(deltaX: number, deltaY: number): Promise; +} + /** Deterministic Electron app management exposed to tests as `electron`. */ export interface Electron { + /** + * The directory the app keeps its data in for this test, empty until the + * app writes to it. It exists before the app is launched, so a test can + * put data in it first, or pass it on with `launch({ env })`. + */ + readonly userDataDir: string; + /** + * Launches the app fresh, as `app.open()` does, with arguments and + * variables of this test's own added to the target's. They stay for the + * rest of the test: `app.open()`, `app.restart()`, and `app.clearState()` + * launch with them too. Another `launch()` replaces them; it does not add + * to them. + */ + launch(options?: ElectronLaunchOptions): Promise; + /** The active window, the one `screen`, `expect`, and the agent act on. Throws `INVALID_STATE` when the app has no open window. */ + activeWindow(): ElectronWindow; + /** Keyboard input to the active window. */ + readonly keyboard: ElectronKeyboard; + /** Pointer input to the active window. */ + readonly mouse: ElectronMouse; /** * Runs `fn` in the app's main process and returns what it returns, which * must be serializable. `fn` is sent as source text: it cannot close over diff --git a/packages/electron/src/in-page/node-ops.ts b/packages/electron/src/in-page/node-ops.ts index 2defb3674f..909282785d 100644 --- a/packages/electron/src/in-page/node-ops.ts +++ b/packages/electron/src/in-page/node-ops.ts @@ -194,6 +194,11 @@ export function nodeOp(node: Node, name: K, args: Param if (target instanceof HTMLElement || target instanceof SVGElement) target.focus(); target.removeEventListener('focus', onFocus); if (holdsFocus(target)) return 'held'; + // A composite widget hands focus to a part of itself (a grid row to its editor): the element holds it through + // that part, and what is typed next goes where a person who tabbed here would type. + const root = target.getRootNode(); + const active = root instanceof Document || root instanceof ShadowRoot ? root.activeElement : null; + if (took && active !== null && target.contains(active)) return 'held'; return took ? 'moved' : 'none'; }, blur() { diff --git a/packages/electron/src/main-process.ts b/packages/electron/src/main-process.ts index 3df4540953..2bd6460386 100644 --- a/packages/electron/src/main-process.ts +++ b/packages/electron/src/main-process.ts @@ -4,15 +4,11 @@ * console is read. An app that opens no inspector has none of this. */ -import type { Protocol } from 'devtools-protocol'; -import { TestError } from '@e2e-dev/core/engine'; import { Connection, webSocketTransport } from './cdp/connection.ts'; import { consoleText } from './console-text.ts'; +import { callForPlainData, checkJsonArgument, describeException, functionSource } from './evaluate.ts'; import type { ElectronMainModule } from './fixtures.ts'; -/** What a function run in the main process threw: its own failure, not the engine's. */ -export class MainEvaluateError extends Error {} - /** One line the main process wrote to its console. */ export type MainConsole = (type: string, text: string) => void; @@ -39,7 +35,7 @@ export class MainProcess { const module = (async () => { // `require` is in scope only with the command-line API, since Electron 28. const { result, exceptionDetails } = await this.connection.root.send('Runtime.evaluate', { expression: "require('electron')", includeCommandLineAPI: true }); - if (exceptionDetails !== undefined || result.objectId === undefined) throw new Error(`the main process has no electron module: ${exceptionDetails === undefined ? result.type : describe(exceptionDetails)}`); + if (exceptionDetails !== undefined || result.objectId === undefined) throw new Error(`the main process has no electron module: ${exceptionDetails === undefined ? result.type : describeException(exceptionDetails)}`); return result.objectId; })(); this.module = module; @@ -56,23 +52,10 @@ export class MainProcess { * source text, and `arg` as JSON. */ async evaluate(fn: (electron: ElectronMainModule, arg: A) => R | Promise, arg: A): Promise { - try { - JSON.stringify(arg); - } catch (cause) { - throw new TestError('INVALID_ARGUMENT', `electron.evaluate: its argument is not JSON (${cause instanceof Error ? cause.message.split('\n')[0] : String(cause)}); pass plain data`, { cause }); - } - const source = functionSource(fn); + checkJsonArgument(arg, 'electron.evaluate'); + const source = functionSource(fn, 'electron.evaluate'); const objectId = await this.electronModule(); - const { result, exceptionDetails } = await this.connection.root.send('Runtime.callFunctionOn', { - objectId, - functionDeclaration: `async function (electron, arg) { return (${plainData.toString()})(await (${source})(electron, arg)); }`, - arguments: [{ objectId }, arg === undefined ? {} : { value: arg }], - returnByValue: true, - awaitPromise: true, - }); - if (exceptionDetails !== undefined) throw new MainEvaluateError(describe(exceptionDetails)); - // NaN, an infinity, and -0 have no JSON: the protocol names them instead. - return (result.unserializableValue === undefined ? result.value : Number(result.unserializableValue)) as R; + return (await callForPlainData(this.connection.root, { objectId, source, leading: [{ objectId }], arg })) as R; } /** Disconnects. Node waits for its inspector's clients before it exits, so a quitting app is let go of here. */ @@ -80,69 +63,3 @@ export class MainProcess { this.connection.close(); } } - -/** - * A function's source as an expression. A method written in shorthand - * (`{ run() {} }.run`) prints without the `function` keyword, which is put - * back. The source is only compiled here, never run. - */ -export function functionSource(fn: (...args: never[]) => unknown): string { - const source = fn.toString(); - if (compiles(source)) return source; - const method = source.replace(/^(async\s+)?(\*\s*)?/, (_match, async: string | undefined, star: string | undefined) => `${async ?? ''}function ${star ?? ''}`); - if (compiles(method)) return method; - throw new TestError('INVALID_ARGUMENT', 'electron.evaluate: its function cannot be sent as source text; pass an arrow function or a function expression'); -} - -function compiles(source: string): boolean { - try { - // oxlint-disable-next-line no-new-func -- compiled to check its syntax, never called - void new Function(`(${source})`); - return true; - } catch { - return false; - } -} - -function describe(details: Protocol.Runtime.ExceptionDetails): string { - const { exception } = details; - if (exception?.description !== undefined) return exception.description.split('\n')[0] ?? details.text; - return exception?.value === undefined ? details.text : `${details.text} ${String(exception.value)}`; -} - -/** - * A value as the plain data that crosses the protocol: objects and arrays of - * primitives. A function or a symbol is left out, as is a reference back to - * an object that holds it, so a `BrowserWindow` or a timer comes back as the - * plain part of what it is rather than failing the call. Runs in the main - * process, sent as source text: self-contained. - */ -export function plainData(value: unknown): unknown { - const holders = new Set(); - const plain = (item: unknown, depth: number): unknown => { - if (typeof item === 'function' || typeof item === 'symbol') return undefined; - if (typeof item === 'bigint') return item.toString(); - if (typeof item !== 'object' || item === null) return item; - if (item instanceof Date) return item.toJSON(); - if (holders.has(item) || depth > 32) return undefined; - holders.add(item); - try { - if (Array.isArray(item)) return item.map((entry) => plain(entry, depth + 1) ?? null); - const out: Record = {}; - for (const key of Object.keys(item)) { - let entry: unknown; - try { - entry = plain((item as Record)[key], depth + 1); - } catch { - // A getter that throws has no value to send. - } - // Defined, not assigned: a key named __proto__ is data too. - if (entry !== undefined) Object.defineProperty(out, key, { value: entry, enumerable: true, writable: true, configurable: true }); - } - return out; - } finally { - holders.delete(item); - } - }; - return plain(value, 0); -} diff --git a/packages/electron/src/options.ts b/packages/electron/src/options.ts index 7b19b0b53c..e248579ec1 100644 --- a/packages/electron/src/options.ts +++ b/packages/electron/src/options.ts @@ -4,7 +4,9 @@ * the engine starts Electron and reads its windows. */ -import { ConfigurationError, rejectUnknownKeys } from '@e2e-dev/core/engine'; +import { statSync } from 'node:fs'; +import path from 'node:path'; +import { ConfigurationError, rejectUnknownKeys, TestError } from '@e2e-dev/core/engine'; /** Variables no app is started with, whoever sets them, by their upper-case names. */ export const REFUSED_ENV: ReadonlySet = new Set(['ELECTRON_RUN_AS_NODE', 'NODE_OPTIONS']); @@ -23,6 +25,8 @@ export interface ElectronOptions { readonly executablePath?: string | undefined; /** Variables added to the app's environment, over the run's own. */ readonly env?: Readonly> | undefined; + /** The directory the app's process starts in: absolute, or relative to the project root. Default: the project root. */ + readonly cwd?: string | undefined; /** The attribute `getByTestId` reads. Default `data-testid`. */ readonly testIdAttribute?: string | undefined; /** @@ -36,6 +40,7 @@ export interface ElectronOptions { const OPTION_KEYS = Object.keys({ executablePath: true, env: true, + cwd: true, testIdAttribute: true, settle: true, } satisfies Record); @@ -44,6 +49,7 @@ const OPTION_KEYS = Object.keys({ export interface ResolvedElectronOptions { readonly executablePath?: string; readonly env: Readonly>; + readonly cwd?: string; readonly testIdAttribute: string; readonly settleMs: number; } @@ -82,21 +88,12 @@ export function resolveOptions(options: ElectronOptions | undefined): ResolvedEl const bag: ElectronOptions = options === undefined ? {} : options; if (typeof bag !== 'object' || bag === null || Array.isArray(bag)) throw new ConfigurationError('INVALID_CONFIG', 'electron() options must be an object'); rejectUnknownKeys('electron() options', bag, OPTION_KEYS); - const { executablePath, env, testIdAttribute, settle } = bag; + const { executablePath, env, cwd, testIdAttribute, settle } = bag; if (executablePath !== undefined && (typeof executablePath !== 'string' || executablePath === '')) { throw new ConfigurationError('INVALID_CONFIG', 'electron({ executablePath }) must be a path to an executable'); } - if (env !== undefined && (typeof env !== 'object' || env === null || Array.isArray(env) || Object.values(env).some((value) => typeof value !== 'string'))) { - throw new ConfigurationError('INVALID_CONFIG', 'electron({ env }) must be an object of variable name to string value'); - } - // Windows reads a variable's name in any case. - const refused = env === undefined ? undefined : Object.keys(env).find((name) => REFUSED_ENV.has(name.toUpperCase())); - if (refused !== undefined) { - throw new ConfigurationError( - 'INVALID_CONFIG', - `electron({ env }) must not set ${refused}: ${refused.toUpperCase() === 'NODE_OPTIONS' ? 'the engine starts the app with its own Node.js switches' : 'it starts the binary as plain Node.js, which opens no window'}`, - ); - } + checkEnv('electron({ env })', env, 'INVALID_CONFIG'); + checkCwdShape('electron({ cwd })', cwd, 'INVALID_CONFIG'); if (testIdAttribute !== undefined && (typeof testIdAttribute !== 'string' || !ATTRIBUTE_NAME.test(testIdAttribute))) { throw new ConfigurationError('INVALID_CONFIG', `electron({ testIdAttribute }) must be an attribute name such as "data-testid", got ${JSON.stringify(testIdAttribute)}`); } @@ -106,7 +103,57 @@ export function resolveOptions(options: ElectronOptions | undefined): ResolvedEl return { ...(executablePath === undefined ? {} : { executablePath }), env: env ?? {}, + ...(cwd === undefined ? {} : { cwd }), testIdAttribute: testIdAttribute ?? 'data-testid', settleMs: settle === false ? 0 : (settle ?? DEFAULT_SETTLE_MS), }; } + +type RefusalCode = 'INVALID_CONFIG' | 'INVALID_ARGUMENT'; + +/** A config's mistake is a configuration error; a test's call with the same mistake is the test's. */ +function refusal(code: RefusalCode, message: string): Error { + return code === 'INVALID_CONFIG' ? new ConfigurationError(code, message) : new TestError(code, message); +} + +/** Checks variables for the app's environment: names to strings, none of the ones no app is started with. */ +function checkEnv(label: string, env: unknown, code: RefusalCode): asserts env is Readonly> | undefined { + if (env === undefined) return; + if (typeof env !== 'object' || env === null || Array.isArray(env) || Object.values(env).some((value) => typeof value !== 'string')) { + throw refusal(code, `${label} must be an object of variable name to string value`); + } + // Windows reads a variable's name in any case. + const refused = Object.keys(env).find((name) => REFUSED_ENV.has(name.toUpperCase())); + if (refused !== undefined) { + throw refusal(code, `${label} must not set ${refused}: ${refused.toUpperCase() === 'NODE_OPTIONS' ? 'the engine starts the app with its own Node.js switches' : 'it starts the binary as plain Node.js, which opens no window'}`); + } +} + +function checkCwdShape(label: string, cwd: unknown, code: RefusalCode): asserts cwd is string | undefined { + if (cwd !== undefined && (typeof cwd !== 'string' || cwd === '')) throw refusal(code, `${label} must be a path to a directory`); +} + +/** Checks that `cwd` names a directory a process can start in, from the project root. */ +export function checkCwd(label: string, projectRoot: string, cwd: string | undefined, code: RefusalCode): void { + if (cwd === undefined) return; + const resolved = path.resolve(projectRoot, cwd); + if (statSync(resolved, { throwIfNoEntry: false })?.isDirectory() !== true) throw refusal(code, `${label} names ${resolved}, which is not a directory`); +} + +const LAUNCH_KEYS = ['args', 'env', 'cwd', 'timeout']; + +/** What `electron.launch()` was given, checked: the arguments, variables, and directory one test adds to its launches. */ +export function checkLaunchOptions(options: unknown, projectRoot: string): { readonly args: readonly string[]; readonly env: Readonly>; readonly cwd?: string } { + const label = 'electron.launch()'; + if (options === undefined) return { args: [], env: {} }; + if (typeof options !== 'object' || options === null || Array.isArray(options)) throw refusal('INVALID_ARGUMENT', `${label} takes an object of options`); + rejectUnknownKeys(`${label} options`, options, LAUNCH_KEYS, 'INVALID_ARGUMENT'); + const { args = [], env, cwd } = options as { readonly args?: unknown; readonly env?: unknown; readonly cwd?: unknown }; + if (!Array.isArray(args) || args.some((argument) => typeof argument !== 'string')) throw refusal('INVALID_ARGUMENT', 'electron.launch({ args }) must be a list of strings'); + const owned = (args as string[]).map(ownedArgument).find((reason) => reason !== undefined); + if (owned !== undefined) throw refusal('INVALID_ARGUMENT', `electron.launch({ args }) ${owned}`); + checkEnv('electron.launch({ env })', env, 'INVALID_ARGUMENT'); + checkCwdShape('electron.launch({ cwd })', cwd, 'INVALID_ARGUMENT'); + checkCwd('electron.launch({ cwd })', projectRoot, cwd, 'INVALID_ARGUMENT'); + return { args: [...(args as string[])], env: { ...env }, ...(cwd === undefined ? {} : { cwd }) }; +} diff --git a/packages/electron/src/page.ts b/packages/electron/src/page.ts index 0ce33aea6e..0ed5d26660 100644 --- a/packages/electron/src/page.ts +++ b/packages/electron/src/page.ts @@ -7,6 +7,7 @@ import type { Deadline } from '@e2e-dev/core/engine'; import type { Session } from './cdp/connection.ts'; import { Keyboard, Mouse, type InputTarget } from './cdp/input.ts'; +import { callForPlainData } from './evaluate.ts'; /** How long past its operation's end a gesture may still hold the page's input, to release what it pressed. */ const RELEASE_MS = 1_000; @@ -14,7 +15,7 @@ const RELEASE_MS = 1_000; /** The isolated world the engine's own page-side reads run in, apart from the app's globals. */ export const WORLD_NAME = '__e2e_electron__'; -type PageEvent = 'close' | 'crash' | 'load'; +type PageEvent = 'close' | 'crash' | 'load' | 'document'; /** What a page function threw, as the protocol reports it. */ export function thrown(details: { readonly text: string; readonly exception?: { readonly description?: string } }): string { @@ -28,6 +29,8 @@ export class PageTarget implements InputTarget { private closed = false; private isolated: Promise | undefined; private documents = 0; + /** Whether the current document fired its load event. */ + private loaded = false; private gestures: Promise = Promise.resolve(); private readonly handlers = new Map void>>(); @@ -102,10 +105,18 @@ export class PageTarget implements InputTarget { return this.documents; } + /** The current document fired its load event. */ + markLoaded(): void { + this.loaded = true; + this.emit('load'); + } + /** The page has another document: the isolated world of the last one is dropped, and its nodes are no longer this page's. */ documentChanged(): void { this.isolated = undefined; this.documents += 1; + this.loaded = false; + this.emit('document'); } /** @@ -185,6 +196,45 @@ export class PageTarget implements InputTarget { return this.isolated; } + /** + * Runs test code in the page's own world, where the app's globals are: + * `source` is a function expression called with `arg`. Rejects with + * `EvaluateError` when the code throws. + */ + async evaluateInPage(source: string, arg: unknown): Promise { + const { session } = this; + const { result: scope } = await session.send('Runtime.evaluate', { expression: 'globalThis' }); + if (scope.objectId === undefined) throw new Error('the page has no global object to run code on'); + try { + return await callForPlainData(session, { objectId: scope.objectId, source, arg, userGesture: true }); + } finally { + void session.send('Runtime.releaseObject', { objectId: scope.objectId }).catch(() => undefined); + } + } + + /** + * Reloads the page's document and resolves once the new one has loaded: a + * load the document before it was still finishing does not count. Rejects + * when the window closes or its renderer crashes instead. + */ + async reload(): Promise { + const before = this.documents; + let stop: () => void = () => undefined; + const ended = new Promise((_resolve, reject) => { + const gone = (): void => reject(new Error('the window closed or its renderer crashed while it reloaded (Target closed)')); + const stops = [this.on('close', gone), this.on('crash', gone)]; + stop = () => stops.forEach((off) => off()); + }); + ended.catch(() => undefined); + try { + await this.session.send('Page.reload'); + while (this.documents === before) await Promise.race([this.next('document'), ended]); + if (!this.loaded) await Promise.race([this.next('load'), ended]); + } finally { + stop(); + } + } + /** Calls a self-contained page function in the isolated world with JSON arguments and returns its JSON result. */ async evaluate(fn: (...args: A) => R | Promise, ...args: A): Promise { const session = this.session; diff --git a/packages/electron/src/snapshot.ts b/packages/electron/src/snapshot.ts index 04a55137c5..838fa35472 100644 --- a/packages/electron/src/snapshot.ts +++ b/packages/electron/src/snapshot.ts @@ -142,6 +142,11 @@ export class DomSnapshot { return from >= 0 && to > from && (this.blanks[to - 1] ?? 0) - (this.blanks[from] ?? 0) > 0; } + /** The snapshot index of the node's parent, or -1 for the document. */ + parentOf(index: number): number { + return this.parents[index] ?? -1; + } + /** The node's nearest table cell, from the DOM: Chromium gives a layout table's cells no cell role. */ cellOf(index: number): number { return this.cells[index] ?? -1; diff --git a/packages/electron/src/surface.ts b/packages/electron/src/surface.ts index d25df94ddb..037ba5e199 100644 --- a/packages/electron/src/surface.ts +++ b/packages/electron/src/surface.ts @@ -38,18 +38,19 @@ import type { ViewportPoint, } from '@e2e-dev/core/engine'; import { performAtPoint, performOnNode, pressKey, swipeWindow, typeText, type ActionContext } from './actions.ts'; -import { AppProcess, DISCARD_CLOSE_MS, RESTART_CLOSE_MS, type AppDownload } from './app-process.ts'; +import { AppProcess, DISCARD_CLOSE_MS, RESTART_CLOSE_MS, type AppDownload, type LaunchExtra } from './app-process.ts'; import { answerWithin, withBudget, type Budget } from './budget.ts'; import { screenshotFile, screenshotName, withPixels } from './capture.ts'; import { DevTools } from './devtools.ts'; import { DialogRouter, type DialogHandler } from './dialogs.ts'; import type { ElectronMainModule } from './fixtures.ts'; import { closedWindow, invalidState, notActionable } from './errors.ts'; +import { checkJsonArgument, EvaluateError, functionSource } from './evaluate.ts'; import { ensureFfmpeg } from './ffmpeg.ts'; import { outsideApp } from './file-bound.ts'; import { appPathProblem, describeExecutable, ensureElectronBinary, resolveExecutable } from './executable.ts'; import { locateIn, projectRead, readWindow, type ProjectionContext, type RawRead } from './locate.ts'; -import { checkLaunchArguments, type ResolvedElectronOptions } from './options.ts'; +import { checkCwd, checkLaunchArguments, type ResolvedElectronOptions } from './options.ts'; import type { WindowMatcher } from './fixtures.ts'; import { Recorder } from './video.ts'; import { ROOT_ID, Windows, type AppWindow } from './windows.ts'; @@ -63,6 +64,8 @@ const TRACE_READ_MS = 1_000; /** How long a window gets to say its document's title. */ const TITLE_MS = 1_000; +const NO_EXTRA: LaunchExtra = { args: [], env: {} }; + function crashed(): Error { return invalidState('the window\'s renderer crashed: reload it from the main process with electron.evaluate, or restart the app'); } @@ -74,6 +77,8 @@ export class ElectronSurface { private executable: string | undefined; private attempt: EngineAttemptContext | undefined; private userDataDir: string | undefined; + /** What `electron.launch()` added to this attempt's launches. */ + private launchExtra: LaunchExtra = NO_EXTRA; private uploadsDir: string | undefined; private artifactCounter = 0; private recorder: Recorder | undefined; @@ -112,6 +117,7 @@ export class ElectronSurface { const problem = info.app.appPath === undefined ? undefined : appPathProblem(info.projectRoot, info.app.appPath); if (problem !== undefined) throw new ConfigurationError('INVALID_CONFIG', problem); checkLaunchArguments(info.app.launchArguments); + checkCwd('electron({ cwd })', info.projectRoot, this.options.cwd, 'INVALID_CONFIG'); } startAttempt(context: EngineAttemptContext): Promise { @@ -119,6 +125,7 @@ export class ElectronSurface { this.artifactCounter = 0; this.recordings = 0; this.dialogs.reset(); + this.launchExtra = NO_EXTRA; // The app's data lives here for the whole attempt: `app.restart()` keeps it, `app.clearState()` empties it. this.userDataDir = mkdtempSync(path.join(tmpdir(), 'e2e-electron-')); return Promise.resolve(); @@ -169,11 +176,32 @@ export class ElectronSurface { }); } + /** `electron.userDataDir`: the attempt's own directory, there before the app is launched so a test can put data in it. */ + dataDirectory(): string { + if (this.userDataDir === undefined) throw invalidState('electron.userDataDir is read inside a test: no attempt is running'); + return this.userDataDir; + } + + /** `electron.launch()`: a fresh launch as `app.open()` does, with `extra` added to this and every later launch of the attempt. */ + launchWith(extra: LaunchExtra, operation: OperationContext): Promise { + return this.app.serialized(async () => { + // Set in turn with the launches: one already under way starts with what it was asked for. + this.launchExtra = extra; + await this.app.quit(operation, RESTART_CLOSE_MS); + await this.launch(operation); + }); + } + + /** The project root, which a test's relative paths resolve against. */ + get root(): string { + return this.projectRoot; + } + private async launch(operation: OperationContext): Promise { const { attempt, userDataDir, executable } = this; if (attempt === undefined || userDataDir === undefined) throw invalidState('app.open() runs inside a test: no attempt is running'); if (executable === undefined) throw invalidState('the electron engine was not initialized'); - await this.app.launch({ executable, projectRoot: this.projectRoot, app: this.appInfo, env: this.runEnv, userDataDir, attempt }, operation); + await this.app.launch({ executable, projectRoot: this.projectRoot, app: this.appInfo, env: this.runEnv, userDataDir, attempt, extra: this.launchExtra }, operation); await this.recorder?.snap(); } @@ -216,14 +244,24 @@ export class ElectronSurface { const raw = await Promise.race([readWindow(this.devtools, window), crash]); if (raw !== 'crashed') return raw; } catch (cause) { - if (!window.page.isClosed() && !closedWindow(cause)) throw cause; - this.windowList.discard(window.page); + if (!this.closedUnder(window, cause)) throw cause; } finally { stopWaiting(); } } } + /** + * Whether work on a window failed because the window closed, which can + * happen before its close event arrives. It is forgotten here, so the + * caller goes on with the window shown in its place. + */ + private closedUnder(window: AppWindow, cause: unknown): boolean { + if (!window.page.isClosed() && !closedWindow(cause)) return false; + this.windowList.discard(window.page); + return true; + } + async observe(operation: OperationContext, options?: EngineObserveOptions): Promise { return await withBudget(operation, 'observe', async () => { // An observation (the agent's, failure evidence) never waits on a crashed window. @@ -244,17 +282,25 @@ export class ElectronSurface { return await withBudget(operation, 'locate', async (budget) => { // A crashed window is waited on briefly, for a reload already under way; every read waiting the whole timeout // would make each step of a test whose app crashed take it. - const raw = await this.readShown(new Deadline(Math.min(CRASH_RELOAD_WAIT_MS, budget.waits.remaining()))); - if (raw === undefined) return []; - const sink = this.attempt?.screen; - if (sink !== undefined && this.leftApp(raw.window) === undefined) { + for (;;) { + const raw = await this.readShown(new Deadline(Math.min(CRASH_RELOAD_WAIT_MS, budget.waits.remaining()))); + if (raw === undefined) return []; + const sink = this.attempt?.screen; + if (sink !== undefined && this.leftApp(raw.window) === undefined) { + try { + sink(projectRead(raw, 'tree', this.projection())); + } catch { + // The trace is evidence; a sink that throws never fails the step. + } + } try { - sink(projectRead(raw, 'tree', this.projection())); - } catch { - // The trace is evidence; a sink that throws never fails the step. + return await locateIn(this.devtools, raw, expression, this.projection()); + } catch (cause) { + // The window closed between its read and the query (a popup that closes itself): the window shown in its + // place is the one to find the node in, as a read that met the closed window does. + if (!this.closedUnder(raw.window, cause)) throw cause; } } - return await locateIn(this.devtools, raw, expression, this.projection()); }); } @@ -348,6 +394,18 @@ export class ElectronSurface { await this.act(operation, 'keyboard.press', window, (budget) => pressKey(window, key, budget)); } + // --- the fixture's keyboard and mouse --- + + /** + * `electron.keyboard.*` and `electron.mouse.*`: input to the shown window, + * wherever its focus and pointer are, taking its turn after the gestures + * before it as every action does. + */ + async input(label: string, send: (window: AppWindow, budget: Budget) => Promise, operation: OperationContext): Promise { + const window = this.requireWindow(); + await this.act(operation, label, window, (budget) => send(window, budget)); + } + // --- windows as tabs --- async switchTab(index: number, operation: OperationContext): Promise { @@ -367,6 +425,12 @@ export class ElectronSurface { return this.windowList.open(); } + /** `electron.activeWindow()`: the window `screen` reads. */ + shownWindow(): AppWindow { + if (!this.app.running) throw this.app.notRunning(); + return this.windowList.require(); + } + isActiveWindow(window: AppWindow): boolean { return this.windowList.isShownPage(window.page); } @@ -384,6 +448,28 @@ export class ElectronSurface { await withBudget(operation, 'close window', (budget) => budget.send(() => this.app.closeWindow(window.page))); } + /** `window.evaluate()`: runs test code in the window's page, with the app's own globals. */ + async evaluateInWindow(window: AppWindow, fn: (arg: A) => R | Promise, arg: A, operation: OperationContext): Promise { + this.failOnDialog(); + if (window.page.isClosed()) throw new TestError('ACTION_FAILED', 'window.evaluate: the window has closed'); + checkJsonArgument(arg, 'window.evaluate'); + // Its message is the test's, never read for a pattern. + const run = window.page.evaluateInPage(functionSource(fn, 'window.evaluate'), arg).catch((cause: unknown) => { + throw cause instanceof EvaluateError ? new TestError('EVALUATE_FAILED', `window.evaluate: ${cause.message}`, { cause }) : cause; + }); + // A cancelled step never awaits it. + run.catch(() => undefined); + // Not input: a timeout is the function's, and nothing the engine sent may have committed. + return (await withBudget(operation, 'window.evaluate', () => run)) as R; + } + + /** `window.reload()`: the window's document loaded again. */ + async reloadWindow(window: AppWindow, operation: OperationContext): Promise { + this.failOnDialog(); + if (window.page.isClosed()) throw new TestError('ACTION_FAILED', 'window.reload: the window has closed'); + await withBudget(operation, 'window.reload', (budget) => budget.send(() => window.page.reload())); + } + /** `electron.window()`: the first open window `which` matches, waited for until the operation's deadline. */ async findWindow(which: WindowMatcher, operation: OperationContext): Promise { this.failOnDialog(); diff --git a/packages/electron/src/tree.ts b/packages/electron/src/tree.ts index fc807e7916..9d13259600 100644 --- a/packages/electron/src/tree.ts +++ b/packages/electron/src/tree.ts @@ -15,6 +15,24 @@ import { OBSERVED_NAME_LIMIT, OBSERVED_TEXT_LIMIT, type SemanticNode } from '@e2 import { elementFields, isButtonInput, isCheckable, isFocusable, isHiddenSubtree, isSecure, isTextField, roleOf, stringOf, type AXNode, type FieldContext, type ProjectionPolicy } from './fields.ts'; import { collapse, type DomFacts, type DomSnapshot } from './snapshot.ts'; +/** Controls that are their text wherever it is drawn: a text query answers with the control, and its state. */ +const TEXT_IS_THE_NODE = new Set([ + 'button', 'link', 'heading', 'tab', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'checkbox', 'radio', 'switch', 'treeitem', 'textbox', 'searchbox', 'combobox', +]); + +/** An icon font's glyphs: private-use code points Chromium puts in a name from CSS generated content. */ +const ICON_GLYPHS = /\p{Co}/gu; + +/** + * A name as a person reads it: an icon font's glyph is a picture, not a + * character, so a button drawn as an icon and "Scan" is named "Scan". A name + * of glyphs alone is kept as it is, the only name the node has. + */ +function spokenName(name: string): string { + const spoken = collapse(name.replace(ICON_GLYPHS, ' ')); + return spoken === '' ? collapse(name) : spoken; +} + /** How the window's layout maps the snapshot's device pixels to the viewport's CSS pixels. */ export interface WindowGeometry { /** Device pixels per CSS pixel. */ @@ -226,7 +244,7 @@ class TreeProjector { const unnamed = node.ignored && facts?.bounds !== undefined ? this.snapshot.sourceText(facts.index) : undefined; if (backend !== undefined && unnamed !== undefined) return this.textRun(backend, facts, unnamed); const { role, silent } = roleOf(node, facts, this.policy); - const name = collapse(stringOf(node.name) ?? ''); + const name = spokenName(stringOf(node.name) ?? ''); // A container Chromium leaves out, or one that says nothing, gives its place to its children: unless a test id, // a name, a locator's selector, or taking focus makes it addressable, so an action reaches it rather than the // container its text would fold into. @@ -325,7 +343,22 @@ class TreeProjector { const text = textOf(draft, this.policy.descendantText, this.snapshot); if (text !== '') draft.text = cut(text, this.policy.textLimit); } - if (onlyText && (!this.policy.descendantText || draft.children.length === 1)) draft.children = []; + if (!onlyText) return; + if (!this.policy.descendantText) draft.children = []; + else if (draft.children.length === 1 && !this.runStandsApart(draft, draft.children[0]!)) draft.children = []; + } + + /** + * Whether a node's lone text run stays a node of its own for a locator: + * the run sits inside elements the tree leaves out + * (`
Unselect All
`), so the text has + * a box of its own, which is where a tap on the text belongs and what a + * text query on the web answers with. Decided by the document's structure + * alone, never by where things are drawn. + */ + private runStandsApart(draft: Draft, run: Draft): boolean { + if (draft.role !== undefined && TEXT_IS_THE_NODE.has(draft.role)) return false; + return this.snapshot.parentOf(run.order) !== draft.order; } /** diff --git a/packages/electron/tests/integration/node-ops.test.ts b/packages/electron/tests/integration/node-ops.test.ts index 89cb7352e6..1ae66cf029 100644 --- a/packages/electron/tests/integration/node-ops.test.ts +++ b/packages/electron/tests/integration/node-ops.test.ts @@ -169,6 +169,13 @@ describe('nodeOp', () => { expect(await run(await element('#hands-off'), 'focus')).toBe('moved'); }); + it('counts focus a composite hands to a part of itself as held', async () => { + await window.setContent(`
`); + await window.inPage(() => document.querySelector('#row')!.addEventListener('focus', () => (document.querySelector('#editor') as HTMLInputElement).focus())); + expect(await run(await element('#row'), 'focus')).toBe('held'); + expect(await window.inPage(() => document.activeElement?.id)).toBe('editor'); + }); + it('points at the value an option has when a label names none', async () => { await window.setContent(``); expect(await run(await element('#kind'), 'checkSelect', { label: 'work' })).toEqual({ ok: false, reason: 'no option matches {"label":"work"}; the options are "Work"; an option has the value "work": pass { value: "work" }' }); diff --git a/packages/electron/tests/unit/engine.test.ts b/packages/electron/tests/unit/engine.test.ts index e1576aa164..555b8e55fa 100644 --- a/packages/electron/tests/unit/engine.test.ts +++ b/packages/electron/tests/unit/engine.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import { electron } from '../../src/engine.ts'; -import { checkLaunchArguments, resolveOptions } from '../../src/options.ts'; +import { checkCwd, checkLaunchArguments, checkLaunchOptions, resolveOptions } from '../../src/options.ts'; describe('electron()', () => { it('declares the capabilities of a Chromium window driven over the DevTools protocol', () => { @@ -58,5 +58,38 @@ describe('resolveOptions', () => { expect(() => resolveOptions({ env: { A: 1 } } as never)).toThrow(/string value/); expect(() => resolveOptions({ testIdAttribute: 'data test' })).toThrow(/testIdAttribute/); expect(() => resolveOptions(null as never)).toThrow(/must be an object/); + expect(() => resolveOptions({ cwd: '' })).toThrow(/electron\(\{ cwd \}\) must be a path/); + expect(resolveOptions({ cwd: 'app' }).cwd).toBe('app'); + }); + + it('refuses a cwd that names no directory, from the project root', () => { + const root = import.meta.dirname; + expect(() => checkCwd('electron({ cwd })', root, '.', 'INVALID_CONFIG')).not.toThrow(); + expect(() => checkCwd('electron({ cwd })', root, undefined, 'INVALID_CONFIG')).not.toThrow(); + expect(() => checkCwd('electron({ cwd })', root, 'no-such-directory', 'INVALID_CONFIG')).toThrow(expect.objectContaining({ code: 'INVALID_CONFIG', message: expect.stringMatching(/no-such-directory, which is not a directory/) })); + expect(() => checkCwd('electron({ cwd })', root, 'engine.test.ts', 'INVALID_CONFIG')).toThrow(/not a directory/); + }); +}); + +describe('checkLaunchOptions', () => { + const root = import.meta.dirname; + + it('gives a test\'s launch its arguments, variables, and directory, with nothing by default', () => { + expect(checkLaunchOptions(undefined, root)).toEqual({ args: [], env: {} }); + expect(checkLaunchOptions({ args: ['--flag'], env: { A: '1' }, cwd: '.', timeout: 1000 }, root)).toEqual({ args: ['--flag'], env: { A: '1' }, cwd: '.' }); + }); + + it('refuses what the config refuses, as the test\'s own mistake', () => { + const refused = (options: unknown, message: RegExp): void => + expect(() => checkLaunchOptions(options, root)).toThrow(expect.objectContaining({ code: 'INVALID_ARGUMENT', message: expect.stringMatching(message) })); + refused({ headless: true }, /headless/); + refused({ args: '--flag' }, /args \}\) must be a list of strings/); + refused({ args: ['--user-data-dir=/tmp/x'] }, /electron\.launch\(\{ args \}\) must not set --user-data-dir/); + refused({ args: ['--inspect=9229'] }, /--inspect/); + refused({ env: { A: 1 } }, /string value/); + refused({ env: { node_options: '--inspect' } }, /node_options: the engine starts the app with its own Node\.js switches/); + refused({ cwd: '' }, /cwd \}\) must be a path/); + refused({ cwd: 'no-such-directory' }, /not a directory/); + refused(null, /takes an object/); }); }); diff --git a/packages/electron/tests/unit/main-process.test.ts b/packages/electron/tests/unit/evaluate.test.ts similarity index 85% rename from packages/electron/tests/unit/main-process.test.ts rename to packages/electron/tests/unit/evaluate.test.ts index 44b9a6e4e4..9c30b0399a 100644 --- a/packages/electron/tests/unit/main-process.test.ts +++ b/packages/electron/tests/unit/evaluate.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; import type { Protocol } from 'devtools-protocol'; import { consoleText } from '../../src/console-text.ts'; -import { functionSource, plainData } from '../../src/main-process.ts'; +import { functionSource, plainData } from '../../src/evaluate.ts'; describe('functionSource', () => { it('keeps a function that is an expression, and puts the keyword back on a shorthand method', () => { @@ -14,15 +14,15 @@ describe('functionSource', () => { }, async: (value: number) => value, }; - expect(functionSource(() => 1)).toBe('() => 1'); - expect(functionSource(methods.async)).toBe('(value) => value'); - expect(functionSource(methods.plain)).toMatch(/^function plain\(\)/); - expect(functionSource(methods.later)).toMatch(/^async function later\(\)/); - expect(functionSource(function named() {})).toMatch(/^function named\(\)/); + expect(functionSource(() => 1, 'electron.evaluate')).toBe('() => 1'); + expect(functionSource(methods.async, 'electron.evaluate')).toBe('(value) => value'); + expect(functionSource(methods.plain, 'electron.evaluate')).toMatch(/^function plain\(\)/); + expect(functionSource(methods.later, 'electron.evaluate')).toMatch(/^async function later\(\)/); + expect(functionSource(function named() {}, 'electron.evaluate')).toMatch(/^function named\(\)/); }); it('refuses a function with no source of its own', () => { - expect(() => functionSource(Math.max)).toThrow(/cannot be sent as source text/); + expect(() => functionSource(Math.max, 'electron.evaluate')).toThrow(/cannot be sent as source text/); }); }); diff --git a/packages/electron/tests/unit/launch.test.ts b/packages/electron/tests/unit/launch.test.ts index 7b590ddc9f..428e948632 100644 --- a/packages/electron/tests/unit/launch.test.ts +++ b/packages/electron/tests/unit/launch.test.ts @@ -6,11 +6,20 @@ import { engineArguments } from '../../src/launcher.ts'; describe('launchEnv', () => { it('gives the app what a process needs to start and draw, never the rest of the run\'s environment', () => { const run = { PATH: '/bin', HOME: '/home/ada', DISPLAY: ':99', LC_ALL: 'C', SystemRoot: 'C:\\Windows', OPENAI_API_KEY: 'sk-secret', AI_GATEWAY_API_KEY: 'secret', GITHUB_TOKEN: 'ghs', MODE: 'run', UNSET: undefined }; - expect(launchEnv(run, {})).toEqual({ PATH: '/bin', HOME: '/home/ada', DISPLAY: ':99', LC_ALL: 'C', SystemRoot: 'C:\\Windows' }); + expect(launchEnv(run, [])).toEqual({ PATH: '/bin', HOME: '/home/ada', DISPLAY: ':99', LC_ALL: 'C', SystemRoot: 'C:\\Windows' }); }); it('adds the engine\'s env option over it, and never ELECTRON_RUN_AS_NODE or NODE_OPTIONS in any case', () => { - expect(launchEnv({ PATH: '/bin', ELECTRON_RUN_AS_NODE: '1', NODE_OPTIONS: '--inspect' }, { PATH: '/app/bin', API_URL: 'http://localhost', electron_run_as_node: '1', Node_Options: '--x' })).toEqual({ PATH: '/app/bin', API_URL: 'http://localhost' }); + expect(launchEnv({ PATH: '/bin', ELECTRON_RUN_AS_NODE: '1', NODE_OPTIONS: '--inspect' }, [{ PATH: '/app/bin', API_URL: 'http://localhost', electron_run_as_node: '1', Node_Options: '--x' }])).toEqual({ PATH: '/app/bin', API_URL: 'http://localhost' }); + }); + + it('lays a test\'s variables over the engine\'s, by name in any case on Windows', () => { + const layers = [{ TESTBED_MODE: 'engine', KEPT: '1' }, { testbed_mode: 'test' }]; + expect(launchEnv({ Path: 'C:\\bin' }, layers, 'win32')).toEqual({ Path: 'C:\\bin', KEPT: '1', testbed_mode: 'test' }); + expect(launchEnv({ Path: 'C:\\bin' }, [{ PATH: 'C:\\app' }], 'win32')).toEqual({ PATH: 'C:\\app' }); + // Elsewhere the two names are two variables. + expect(launchEnv({}, layers, 'linux')).toEqual({ TESTBED_MODE: 'engine', KEPT: '1', testbed_mode: 'test' }); + expect(launchEnv({}, [{ MODE: 'engine' }, { MODE: 'test' }], 'linux')).toEqual({ MODE: 'test' }); }); }); diff --git a/packages/electron/tests/unit/modifiers.test.ts b/packages/electron/tests/unit/modifiers.test.ts index fc61dee3a6..04206d523c 100644 --- a/packages/electron/tests/unit/modifiers.test.ts +++ b/packages/electron/tests/unit/modifiers.test.ts @@ -34,6 +34,17 @@ describe('withModifiers', () => { expect(events).toEqual(['rawKeyDown Control', 'rawKeyDown Shift', 'rawKeyDown Enter', 'keyUp Enter', 'keyUp Shift', 'keyUp Control']); }); + it('leaves a modifier the test already holds held, and releases only its own', async () => { + const { window, events, answer } = slowWindow(); + const answering = setInterval(answer, 1); + await window.page.keyboard.down('Shift'); + await withModifiers(new Budget(operation(new AbortController().signal), 'press'), window, ['Shift', 'Control'], () => window.page.keyboard.press('Enter')); + expect(window.page.keyboard.holds('Shift')).toBe(true); + await window.page.keyboard.up('Shift'); + clearInterval(answering); + expect(events).toEqual(['rawKeyDown Shift', 'rawKeyDown Control', 'rawKeyDown Enter', 'keyUp Enter', 'keyUp Control', 'keyUp Shift']); + }); + it('sends no key after a modifier the app took too long to answer, and releases the modifier', async () => { const { window, events, answer } = slowWindow(); const cancel = new AbortController(); diff --git a/packages/electron/tests/unit/tree.test.ts b/packages/electron/tests/unit/tree.test.ts index 6267c9a87a..3bc8f5b00c 100644 --- a/packages/electron/tests/unit/tree.test.ts +++ b/packages/electron/tests/unit/tree.test.ts @@ -17,10 +17,10 @@ const captured = JSON.parse(readFileSync(new URL('../fixtures/sign-in.json', imp metrics: { layoutViewport: { clientWidth: number }; cssLayoutViewport: { clientWidth: number }; cssVisualViewport: { pageX: number; pageY: number; clientWidth: number; clientHeight: number } }; }; -function project(mode: ProjectionMode, extra: { maxNodes?: number; keep?: ReadonlySet } = {}) { +function project(mode: ProjectionMode, extra: { maxNodes?: number; keep?: ReadonlySet } = {}, ax: AXNode[] = captured.ax) { const { metrics } = captured; return projectTree( - captured.ax, + ax, new DomSnapshot(captured.snapshot.documents[0]!, captured.snapshot.strings), { scale: metrics.layoutViewport.clientWidth / metrics.cssLayoutViewport.clientWidth, @@ -311,4 +311,13 @@ describe('unmaskableCount', () => { expect(new DomSnapshot(documentWith({ name: 3, attributes: [4, 5], shadow: 6, rendered: false }), strings).unmaskableCount()).toBe(0); expect(new DomSnapshot(documentWith({ name: 3, attributes: [4, 9], shadow: 6 }), strings).unmaskableCount()).toBe(0); }); + + it('names a control by its text, not its icon font\'s glyph, and keeps a name of glyphs alone', () => { + const renamed = (from: string, to: string): AXNode[] => captured.ax.map((node) => (node.name?.value === from && node.role?.value === 'button' ? { ...node, name: { ...node.name, value: to } } : node)); + for (const mode of ['tree', 'node'] as const) { + expect(all(project(mode, {}, renamed('Sign in', '\uf090 Sign in')).root).filter((node) => node.role === 'button').map((node) => node.name)).toContain('Sign in'); + expect(all(project(mode, {}, renamed('Sign in', 'Save\uf00c all')).root).filter((node) => node.role === 'button').map((node) => node.name)).toContain('Save all'); + expect(all(project(mode, {}, renamed('Sign in', '\uf1f8')).root).filter((node) => node.role === 'button').map((node) => node.name)).toContain('\uf1f8'); + } + }); });