diff --git a/.changeset/electron-window-download-waits.md b/.changeset/electron-window-download-waits.md new file mode 100644 index 0000000000..45cf22d10e --- /dev/null +++ b/.changeset/electron-window-download-waits.md @@ -0,0 +1,5 @@ +--- +'@e2e-dev/electron': patch +--- + +`electron.waitForWindow()` and `electron.waitForDownload()` count their trigger's time in their timeout, as `browser.waitForPopup()` and `browser.waitForDownload()` do: a trigger that hangs fails the wait at its timeout, and a window or download that arrives after it is not taken. A wait whose step is cancelled ends as `CANCELLED` at once, runs no trigger when cancelled before it starts, and shows no window it opened. A download wait also ends in its time while the app's main process is too busy to answer. A download the engine saves is numbered around a file of that name the app wrote in the downloads folder itself, rather than replacing it. diff --git a/apps/electron-testbed/tests/parity.e2e.ts b/apps/electron-testbed/tests/parity.e2e.ts index 2e93a4ccba..f15338d181 100644 --- a/apps/electron-testbed/tests/parity.e2e.ts +++ b/apps/electron-testbed/tests/parity.e2e.ts @@ -49,8 +49,27 @@ test.describe('what an Electron target shares with the web', () => { expect(file.suggestedFilename).toBe('note.txt'); expect(file.path).toMatch(/^downloads\/\d+-note\.txt$/); expect(readFileSync(file.absolutePath, 'utf8')).toBe('downloaded note'); - const none = await electron.waitForDownload(() => Promise.resolve(), { timeout: 500 }).then(() => undefined, (error: unknown) => error); - expect(none).toMatchObject({ code: 'ACTION_FAILED', message: expect.stringMatching(/no download finished/) }); + // A second leaves a loaded machine's main process time to answer the read before the trigger. + const none = await electron.waitForDownload(() => Promise.resolve(), { timeout: 1000 }).then(() => undefined, (error: unknown) => error); + expect(none).toMatchObject({ code: 'ACTION_FAILED', message: expect.stringMatching(/^no download finished within 1000ms; the trigger resolved after \d+ms$/) }); + // The wait includes the trigger's own time: one still running when it is out fails the wait then, not when it returns. + const started = Date.now(); + const slow = await electron.waitForDownload(() => new Promise((resolve) => setTimeout(resolve, 3000)), { timeout: 500 }).then(() => undefined, (error: unknown) => error); + // The read before the trigger shares that half second, so a loaded machine can end the wait there too. + expect(slow).toMatchObject({ code: 'ACTION_FAILED', message: expect.stringMatching(/^(electron\.waitForDownload exceeded its timeout of 500ms while its trigger ran|no download finished within 500ms: the app's main process did not answer)$/) }); + expect(Date.now() - started).toBeLessThan(2500); + }); + + test('says the app did not answer when its main process is too busy to list its downloads', async ({ electron }) => { + // The main process loops for two seconds once this call has returned. + await electron.evaluate(() => { + setTimeout(() => { + const until = Date.now() + 2000; + while (Date.now() < until); + }, 0); + }); + const blocked = await electron.waitForDownload(() => Promise.resolve(), { timeout: 500 }).then(() => undefined, (error: unknown) => error); + expect(blocked).toMatchObject({ code: 'ACTION_FAILED', message: 'no download finished within 500ms: the app\'s main process did not answer' }); }); test('refuses a tap on a link another element covers, though both sit in a checkbox label', async ({ screen }) => { diff --git a/apps/electron-testbed/tests/sign-in.e2e.ts b/apps/electron-testbed/tests/sign-in.e2e.ts index e3f0069957..956b9ecfa0 100644 --- a/apps/electron-testbed/tests/sign-in.e2e.ts +++ b/apps/electron-testbed/tests/sign-in.e2e.ts @@ -386,6 +386,14 @@ test.describe('windows', () => { const none = await electron.waitForWindow(() => Promise.resolve(), { timeout: 500 }).then(() => undefined, (error: unknown) => error); expect(none).toMatchObject({ code: 'ACTION_FAILED', message: expect.stringMatching(/no window opened within 500ms/) }); expect(await electron.evaluate(() => (globalThis as unknown as { testbedState: { settingsOpened: number } }).testbedState.settingsOpened)).toBe(1); + // The wait includes the trigger's own time: a trigger still running when it ran out fails the wait, and the window + // it opened before then is not taken. + const late = await electron.waitForWindow(async () => { + await screen.getByRole('button', 'Open settings').tap(); + await new Promise((resolve) => setTimeout(resolve, 800)); + }, { timeout: 500 }).then(() => undefined, (error: unknown) => error); + expect(late).toMatchObject({ code: 'ACTION_FAILED', message: 'electron.waitForWindow exceeded its timeout of 500ms while its trigger ran' }); + expect(main!.isActive()).toBe(true); }); test('gives a window with no document title the OS window\'s, which is a title it is found by', async ({ app, electron }) => { @@ -409,6 +417,11 @@ test.describe('windows', () => { expect(electron.windows()[0]?.isActive()).toBe(true); await expect(screen.getByTestId('status')).toHaveText('Not signed in'); expect(await settings.activate().then(() => undefined, (error: unknown) => error)).toMatchObject({ code: 'ACTION_FAILED' }); + // A trigger that does not return its promise, as JavaScript allows: the window it opens is still waited for. + const unreturned = await electron.waitForWindow((() => { + void screen.getByRole('button', 'Open settings').tap(); + }) as unknown as () => Promise); + expect(await unreturned.title()).toBe('Settings'); }); test('types into a field inside a closed shadow root', async ({ app, screen, electron }) => { diff --git a/docs/electron.mdx b/docs/electron.mdx index f1e755647b..e67d16e99f 100644 --- a/docs/electron.mdx +++ b/docs/electron.mdx @@ -267,11 +267,10 @@ expect(file.suggestedFilename).toBe('report.csv'); // file.absolutePath is the saved file ``` -Downloads never land in your own Downloads folder: the app saves them inside -the test's user-data directory. A name a file there had at launch, or another -download took, gets a number, as `note (1).txt`; a file the app writes there -itself is not counted. A download that starts before the app's first window -loads goes where the app would save it. +Downloads go inside the test's user-data directory, not your own Downloads +folder, unless the app picks the path itself or the download starts before its +first window loads. A name already taken there gets a number, as +`note (1).txt` ([details](/reference/electron#waitfordownload)). ## Record video @@ -313,8 +312,9 @@ Forge's default) keeps a launcher of the same name beside its `app-` folders. Name the `.exe` inside the version folder. - If the build disables the `EnableNodeCliInspectArguments` fuse, `screen`, - `expect`, and the agent still work, but `electron.evaluate()` fails and - `electron.window({ title })` matches document titles only. On Windows and + `expect`, and the agent still work, but `electron.evaluate()` and + `electron.waitForDownload()` fail and `electron.window({ title })` matches + document titles only. On Windows and Linux, a screenshot of a window the app hid with `hide()` also times out, and a recording of one has no frames. - On macOS, an unsigned build that reads the keychain (`safeStorage`) can diff --git a/docs/reference/electron.mdx b/docs/reference/electron.mdx index 4768325d94..63046409c4 100644 --- a/docs/reference/electron.mdx +++ b/docs/reference/electron.mdx @@ -430,7 +430,7 @@ const settings = await electron.waitForWindow(() => | Throws | When | | --- | --- | | `INVALID_ARGUMENT` | `trigger` is not a function. | -| `ACTION_FAILED` | No window opened in time. The message is `no window opened within ms; the trigger resolved after ms`. | +| `ACTION_FAILED` | No window opened in time. The message is `no window opened within ms; the trigger resolved after ms`, or `electron.waitForWindow exceeded its timeout of ms while its trigger ran`. | #### `window` @@ -470,15 +470,24 @@ expect(file.suggestedFilename).toBe('report.csv'); - It registers the file as a `download` artifact, saved as `downloads/-`, and returns that relative `path`, the `absolutePath` of the saved copy, and `suggestedFilename`. -- Downloads never land in your own Downloads folder: the app saves them in - the `Downloads` folder of the test's [user-data directory](#userdatadir). -- A trigger that throws fails with its own error. +- The engine saves a download in the `Downloads` folder of the test's + [user-data directory](#userdatadir), not your own Downloads folder. A name + already taken there gets a number, as `note (1).txt`: by a file there at + launch, one the app wrote or saved there itself, or another download. An + Electron older than 32 knows only the files there at launch and the + downloads. A path the app sets in its own `will-download` handler stays as + the app set it, with no number. A download that starts before the app's + first window loads goes where the app would save it, and `waitForDownload` + does not see it. +- The wait includes the trigger's own time. A trigger that throws fails with + its own error. | Throws | When | | --- | --- | | `INVALID_ARGUMENT` | `trigger` is not a function. | -| `ACTION_FAILED` | No download finished in time. The message is `no download finished within ms of the trigger`. | +| `ACTION_FAILED` | No download finished in time. The message is `no download finished within ms; the trigger resolved after ms`, `electron.waitForDownload exceeded its timeout of ms while its trigger ran`, or `no download finished within ms: the app's main process did not answer` while it is too busy to. | | `ENGINE_FAILURE` | The download ended without completing, such as one the app cancelled. | +| `UNSUPPORTED_CAPABILITY` | The main process opened no inspector, as a packaged app built with the `EnableNodeCliInspectArguments` fuse off does: the engine reads the app's downloads there. | #### `onDialog` diff --git a/packages/electron/src/app-process.ts b/packages/electron/src/app-process.ts index e0f5d57430..293e27dd68 100644 --- a/packages/electron/src/app-process.ts +++ b/packages/electron/src/app-process.ts @@ -445,7 +445,7 @@ export class AppProcess { } const NO_INSPECTOR = - 'the app\'s main process opened no inspector, so electron.evaluate cannot run in it and windows are known by their document titles only: a packaged app built with the EnableNodeCliInspectArguments fuse off ignores --inspect'; + 'the app\'s main process opened no inspector, so electron.evaluate and electron.waitForDownload cannot run in it and windows are known by their document titles only: a packaged app built with the EnableNodeCliInspectArguments fuse off ignores --inspect'; /** Ends an app: a graceful quit within `graceMs`, then its process tree killed and waited for. */ async function stop(app: RunningApp, graceMs: number): Promise { @@ -573,11 +573,15 @@ async function placeDownloads(main: MainProcess, directory: string, withinMs: nu electronApp.setPath('downloads', downloads); // Compared without case: two names that differ only in case are one file on macOS and Windows. const taken = new Set(earlier.map((name) => name.toLowerCase())); + // A file the app wrote there itself since launch is taken too; an Electron before getBuiltinModule knows only the list. + const files = (process as { getBuiltinModule?: (id: string) => unknown }).getBuiltinModule?.('node:fs') as { existsSync(file: string): boolean } | undefined; + // A file's folder, its separators either way round: an app on Windows may write either. + const folderOf = (file: string): string => file.replace(/[\\/][^\\/]*$/, '').replaceAll('\\', '/').toLowerCase(); const unique = (name: string): string => { const dot = name.lastIndexOf('.'); const [stem, extension] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, '']; let candidate = name; - for (let count = 1; taken.has(candidate.toLowerCase()); count += 1) candidate = `${stem} (${count})${extension}`; + for (let count = 1; taken.has(candidate.toLowerCase()) || files?.existsSync(`${downloads}/${candidate}`) === true; count += 1) candidate = `${stem} (${count})${extension}`; taken.add(candidate.toLowerCase()); return candidate; }; @@ -588,7 +592,10 @@ async function placeDownloads(main: MainProcess, directory: string, withinMs: nu if (placed.has(target)) return; placed.add(target); target.on('will-download', (_event, item) => { - if (item.getSavePath() === '') item.setSavePath(`${downloads}/${unique(item.getFilename())}`); + const chosen = item.getSavePath(); + if (chosen === '') item.setSavePath(`${downloads}/${unique(item.getFilename())}`); + // A path the app chose in the downloads folder is taken, so a later download is not given it. + else if (folderOf(chosen) === folderOf(`${downloads}/-`)) taken.add((chosen.split(/[\\/]/).pop() ?? '').toLowerCase()); // What `electron.waitForDownload` reads: each download the app started, and how it ended. const entry = { filename: item.getFilename(), path: item.getSavePath(), state: 'progressing' }; const log = ((globalThis as { e2eDownloads?: (typeof entry)[] }).e2eDownloads ??= []); diff --git a/packages/electron/src/surface.ts b/packages/electron/src/surface.ts index a4c46454a9..740ee9592c 100644 --- a/packages/electron/src/surface.ts +++ b/packages/electron/src/surface.ts @@ -14,7 +14,7 @@ import { copyFileSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; -import { ConfigurationError, Deadline, EngineError, pollCondition, sleep, TestError, validateComputedStyleProperties } from '@e2e-dev/core/engine'; +import { ConfigurationError, Deadline, EngineError, pollCondition, raceAbort, sleep, TestError, validateComputedStyleProperties, withTimeout } from '@e2e-dev/core/engine'; import type { ComputedStyleProperty, ComputedStyleValues, @@ -455,8 +455,14 @@ export class ElectronSurface { /** `window.activate()`: reads and acts in the window from now on. */ async activateWindow(window: AppWindow, operation: OperationContext): Promise { this.failOnDialog(); - this.windowList.activate(window); - await withBudget(operation, 'activate window', () => window.page.bringToFront().catch(() => undefined)); + await withBudget(operation, 'activate window', async (budget) => { + // A call cancelled meanwhile (a waitForWindow whose trigger outlasted the step) shows no other window, one cancelled + // while the window is raised included: the window `screen` reads changes last. + budget.check(); + await window.page.bringToFront().catch(() => undefined); + budget.check(); + this.windowList.activate(window); + }); } /** `window.close()`: any window, the app's last one too. */ @@ -503,19 +509,21 @@ export class ElectronSurface { this.failOnDialog(); if (!this.app.running) throw this.app.notRunning(); const before = new Set(this.windowList.open()); - const started = Date.now(); - await trigger(); - const triggerMs = Date.now() - started; + const deadline = new Deadline(operation.timeoutMs); + const triggerMs = await runTrigger(trigger, deadline, 'electron.waitForWindow', operation); + const timedOut = (): TestError => new TestError('ACTION_FAILED', `no window opened within ${operation.timeoutMs}ms; the trigger resolved after ${triggerMs}ms`); + // The wait includes the trigger's own time: a window it opened after that ran out is not taken. + if (deadline.expired()) throw timedOut(); let opened: AppWindow | undefined; await pollCondition({ - deadline: new Deadline(Math.max(1, operation.timeoutMs - triggerMs)), + deadline, signal: operation.signal, negated: false, evaluate: () => { opened = this.windowList.open().find((window) => !before.has(window)); return Promise.resolve(opened !== undefined); }, - onTimeout: () => new TestError('ACTION_FAILED', `no window opened within ${operation.timeoutMs}ms; the trigger resolved after ${triggerMs}ms`), + onTimeout: timedOut, }); if (opened === undefined) throw invalidState('the window was lost'); await this.activateWindow(opened, operation); @@ -587,21 +595,39 @@ export class ElectronSurface { const attempt = this.attempt; if (attempt === undefined) throw invalidState('a download is waited for inside a test'); this.failOnDialog(); - const before = (await this.app.downloads()).length; - await trigger(); + const deadline = new Deadline(operation.timeoutMs); + const unanswered = (): TestError => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms: the app's main process did not answer`); + // Read in the main process, which a busy app keeps from answering: each read ends with the wait. Its timeout is an + // operation timeout, which the poll takes for a read the deadline cut off when it started with under a tick left. + const readTimedOut = (): EngineError => new EngineError('OPERATION_TIMEOUT', 'electron.waitForDownload: the app\'s main process did not answer', { retryable: false }); + // A step cancelled while the app was asked ends then, as cancelled. + const downloads = (): Promise => + raceAbort(() => withTimeout(this.app.downloads(), Math.max(1, deadline.remaining()), readTimedOut), operation.signal, 'electron.waitForDownload'); + // Any other read that timed out had time to answer in: the main process did not. + const blocked = (cause: unknown): unknown => (cause instanceof EngineError && cause.code === 'OPERATION_TIMEOUT' ? unanswered() : cause); + const before = (await downloads().catch((cause: unknown) => Promise.reject(blocked(cause)))).length; + // A trigger never runs once the wait is out of time, or its step was cancelled while the app was asked. + // Worded as raceAbort words the same cancel. + if (operation.signal.aborted) throw new EngineError('CANCELLED', 'electron.waitForDownload cancelled', { retryable: false }); + if (deadline.expired()) throw unanswered(); + const triggerMs = await runTrigger(trigger, deadline, 'electron.waitForDownload', operation); + const timedOut = (): TestError => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms; the trigger resolved after ${triggerMs}ms`); + // The wait includes the trigger's own time, as the window wait's does. + if (deadline.expired()) throw timedOut(); let finished: AppDownload | undefined; + // The last read starts at the deadline with almost no time: the poll ends that one with the ordinary timeout. await pollCondition({ - deadline: new Deadline(operation.timeoutMs), + deadline, signal: operation.signal, negated: false, evaluate: async () => { - const next = (await this.app.downloads())[before]; + const next = (await downloads())[before]; if (next === undefined || next.state === 'progressing') return false; finished = next; return true; }, - onTimeout: () => new TestError('ACTION_FAILED', `no download finished within ${operation.timeoutMs}ms of the trigger`), - }); + onTimeout: timedOut, + }).catch((cause: unknown) => Promise.reject(blocked(cause))); if (finished === undefined) throw invalidState('the download was lost'); if (finished.state !== 'completed') throw new EngineError('ENGINE_FAILURE', `the download of ${finished.filename} was ${finished.state}`, { retryable: false }); this.artifactCounter += 1; @@ -646,3 +672,25 @@ export class ElectronSurface { return (await recorder?.stop()) ?? []; } } + +/** + * Runs a wait's trigger, test code, within the wait's deadline, and returns + * how long it took. A trigger still running at the deadline fails the wait + * and is left to finish on its own; its error, before then, is its own. + */ +async function runTrigger(trigger: () => Promise, deadline: Deadline, api: string, operation: OperationContext): Promise { + const started = Date.now(); + // A step cancelled before its trigger runs never runs it; one cancelled while it runs ends then, as cancelled, not at + // its timeout. + await raceAbort( + () => { + // Test code: a trigger written in JavaScript, or one that does not return its promise, returns none. + const running = (async () => await trigger())(); + running.catch(() => undefined); + return withTimeout(running, Math.max(1, deadline.remaining()), () => new TestError('ACTION_FAILED', `${api} exceeded its timeout of ${operation.timeoutMs}ms while its trigger ran`)); + }, + operation.signal, + api, + ); + return Date.now() - started; +} diff --git a/packages/electron/tests/integration/launch.test.ts b/packages/electron/tests/integration/launch.test.ts index 88f397ee2e..c9729a972b 100644 --- a/packages/electron/tests/integration/launch.test.ts +++ b/packages/electron/tests/integration/launch.test.ts @@ -5,7 +5,7 @@ import { execFileSync, spawnSync } from 'node:child_process'; import { Transformer } from '@napi-rs/image'; -import { existsSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; @@ -17,6 +17,7 @@ import { DevTools } from '../../src/devtools.ts'; import { ensureFfmpeg } from '../../src/ffmpeg.ts'; import { readWindow } from '../../src/locate.ts'; import { resolveOptions } from '../../src/options.ts'; +import { ElectronSurface } from '../../src/surface.ts'; import { Recorder } from '../../src/video.ts'; import { DialogRouter } from '../../src/dialogs.ts'; import { Windows, type AppWindow } from '../../src/windows.ts'; @@ -327,6 +328,139 @@ describe('dialogs', () => { }); }); +describe('electron.waitForWindow', () => { + it('shows no window for a wait cancelled while its trigger ran', async () => { + const { app, windows, dialogs, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); + await launch(); + const surface = new ElectronSurface(resolveOptions({})); + Object.assign(surface, { app, windowList: windows, dialogs }); + const first = windows.require(); + const cancel = new AbortController(); + const operation = { signal: cancel.signal, timeoutMs: 5000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext; + const failure = await surface.waitForWindow(async () => { + await app.evaluate(({ BrowserWindow }) => void new BrowserWindow({ show: false }).loadURL('data:text/html,Second'), undefined); + await expect.poll(() => windows.open().length).toBe(2); + cancel.abort(); + }, operation).then(() => undefined, (error: unknown) => error); + expect(failure).toMatchObject({ code: 'CANCELLED' }); + expect(windows.current()).toBe(first); + }); + + it('shows no window for a wait cancelled while the window is brought to the front', async () => { + const { app, windows, dialogs, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); + await launch(); + const surface = new ElectronSurface(resolveOptions({})); + Object.assign(surface, { app, windowList: windows, dialogs }); + const first = windows.require(); + const cancel = new AbortController(); + const operation = { signal: cancel.signal, timeoutMs: 5000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext; + const failure = await surface.waitForWindow(async () => { + await app.evaluate(({ BrowserWindow }) => void new BrowserWindow({ show: false }).loadURL('data:text/html,Second'), undefined); + await expect.poll(() => windows.open().length).toBe(2); + const second = windows.open()[1]!; + // The step is cancelled while the engine raises the new window. + Object.assign(second.page, { + bringToFront: () => { + cancel.abort(); + return Promise.resolve(); + }, + }); + }, operation).then(() => undefined, (error: unknown) => error); + expect(failure).toMatchObject({ code: 'CANCELLED' }); + expect(windows.current()).toBe(first); + }); + + it('ends as cancelled, then, when its step is cancelled while its trigger still runs', async () => { + const { app, windows, dialogs, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); + await launch(); + const surface = new ElectronSurface(resolveOptions({})); + Object.assign(surface, { app, windowList: windows, dialogs }); + const cancel = new AbortController(); + setTimeout(() => cancel.abort(), 50); + const operation = { signal: cancel.signal, timeoutMs: 2000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext; + const started = Date.now(); + const failure = await surface.waitForWindow(() => new Promise(() => undefined), operation).then(() => undefined, (error: unknown) => error); + expect(failure).toMatchObject({ code: 'CANCELLED' }); + expect(Date.now() - started).toBeLessThan(1000); + }); + + it('runs no trigger for a step cancelled before it starts', async () => { + const { app, windows, dialogs, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); + await launch(); + const surface = new ElectronSurface(resolveOptions({})); + Object.assign(surface, { app, windowList: windows, dialogs }); + const cancel = new AbortController(); + cancel.abort(); + const operation = { signal: cancel.signal, timeoutMs: 2000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext; + let triggered = false; + const failure = await surface.waitForWindow(() => { + triggered = true; + return Promise.resolve(); + }, operation).then(() => undefined, (error: unknown) => error); + expect(failure).toMatchObject({ code: 'CANCELLED' }); + expect(triggered).toBe(false); + }); +}); + +describe('electron.waitForDownload', () => { + it('fails in its time, and runs no trigger, while the app\'s main process is too busy to answer', async () => { + const { app, windows, dialogs, directory, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); + await launch(); + const surface = new ElectronSurface(resolveOptions({})); + Object.assign(surface, { app, windowList: windows, dialogs, attempt: { artifactsDir: path.join(directory, 'artifacts') } }); + // The main process loops for four seconds: nothing it is asked is answered until then. + void app.evaluate(() => { + const until = Date.now() + 4000; + while (Date.now() < until); + }, undefined).catch(() => undefined); + let triggered = false; + const operation = { signal: new AbortController().signal, timeoutMs: 1000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext; + const started = Date.now(); + const failure = await surface.waitForDownload(() => { + triggered = true; + return Promise.resolve(); + }, operation).then(() => undefined, (error: unknown) => error); + expect(failure).toMatchObject({ code: 'ACTION_FAILED', message: 'no download finished within 1000ms: the app\'s main process did not answer' }); + expect(Date.now() - started).toBeLessThan(2000); + expect(triggered).toBe(false); + }); + + it('ends as cancelled, at once, when its step is cancelled while the busy main process is asked', async () => { + const { app, windows, dialogs, directory, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); + await launch(); + const surface = new ElectronSurface(resolveOptions({})); + Object.assign(surface, { app, windowList: windows, dialogs, attempt: { artifactsDir: path.join(directory, 'artifacts') } }); + void app.evaluate(() => { + const until = Date.now() + 1500; + while (Date.now() < until); + }, undefined).catch(() => undefined); + const cancel = new AbortController(); + setTimeout(() => cancel.abort(), 50); + const operation = { signal: cancel.signal, timeoutMs: 1000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext; + const started = Date.now(); + const failure = await surface.waitForDownload(() => Promise.resolve(), operation).then(() => undefined, (error: unknown) => error); + expect(failure).toMatchObject({ code: 'CANCELLED', message: 'electron.waitForDownload cancelled' }); + expect(Date.now() - started).toBeLessThan(500); + }); + + it('runs no trigger for a step cancelled while the app was asked for its downloads', async () => { + const { app, windows, dialogs, directory, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); + await launch(); + const surface = new ElectronSurface(resolveOptions({})); + Object.assign(surface, { app, windowList: windows, dialogs, attempt: { artifactsDir: path.join(directory, 'artifacts') } }); + const cancel = new AbortController(); + cancel.abort(); + let triggered = false; + const operation = { signal: cancel.signal, timeoutMs: 5000, runId: 'run', attemptId: 'attempt', origin: 'test' } as OperationContext; + const failure = await surface.waitForDownload(() => { + triggered = true; + return Promise.resolve(); + }, operation).then(() => undefined, (error: unknown) => error); + expect(failure).toMatchObject({ code: 'CANCELLED', message: 'electron.waitForDownload cancelled' }); + expect(triggered).toBe(false); + }); +}); + describe('electron.evaluate', () => { it('returns a number JSON has no word for, and refuses an argument that is not JSON as the test\'s own mistake', async () => { const { app, launch } = appWith(`app.whenReady().then(() => { ${LOADED}; });`); @@ -364,6 +498,100 @@ describe('downloads', () => { await expect.poll(() => (existsSync(downloads) ? readdirSync(downloads) : [])).toContain('later.txt'); expect(existsSync(path.join(launched.directory, 'outside', 'later.txt'))).toBe(false); }); + + it.skipIf(process.platform === 'win32')('numbers a download whose name the app took itself, by a download or a file written after launch', async () => { + const launched = appWith(`let first = true; + app.whenReady().then(() => { + require('electron').session.defaultSession.on('will-download', (_event, item) => { + // The app saves its first download itself, under the name it suggests. + if (first) item.setSavePath(require('node:path').join(app.getPath('downloads'), item.getFilename())); + first = false; + }); + const server = require('node:http').createServer((request, response) => { + if (request.url === '/') return response.end('Loaded'); + response.setHeader('Content-Disposition', 'attachment; filename="' + request.url.slice(1) + '"'); + response.end(request.url); + }); + server.listen(0, '127.0.0.1', () => new BrowserWindow({ show: false }).loadURL('http://127.0.0.1:' + server.address().port + '/')); + });`); + await launched.launch(); + const origin = new URL(launched.windows.require().page.url()).origin; + const downloads = path.join(launched.directory, 'data', 'Downloads'); + const download = async (name: string, expected: string): Promise => { + await launched.app.evaluate(({ BrowserWindow }, url) => BrowserWindow.getAllWindows()[0]?.webContents.downloadURL(url), `${origin}/${name}`); + await expect.poll(() => (existsSync(downloads) ? readdirSync(downloads).toSorted() : [])).toContain(expected); + }; + await download('report.txt', 'report.txt'); + await download('report.txt', 'report (1).txt'); + // A file the app wrote there itself after launch. + writeFileSync(path.join(downloads, 'notes.txt'), 'the app\'s own'); + await download('notes.txt', 'notes (1).txt'); + expect(readFileSync(path.join(downloads, 'report.txt'), 'utf8')).toBe('/report.txt'); + expect(readFileSync(path.join(downloads, 'notes.txt'), 'utf8')).toBe('the app\'s own'); + }); + + it.skipIf(process.platform === 'win32')('numbers a download whose name the app took for one still downloading, with no file of that name on disk', async () => { + const launched = appWith(`let first = true; + app.whenReady().then(() => { + require('electron').session.defaultSession.on('will-download', (_event, item) => { + // The app saves its first download itself, under the name it suggests. + if (first) item.setSavePath(require('node:path').join(app.getPath('downloads'), item.getFilename())); + first = false; + }); + const server = require('node:http').createServer((request, response) => { + if (request.url === '/') return response.end('Loaded'); + response.setHeader('Content-Disposition', 'attachment; filename="report.txt"'); + if (request.url === '/now') return response.end('now'); + // The first download never finishes: Chromium starts a download once it has a kilobyte of the body. + response.write(' '.repeat(2048)); + }); + server.listen(0, '127.0.0.1', () => new BrowserWindow({ show: false }).loadURL('http://127.0.0.1:' + server.address().port + '/')); + });`); + await launched.launch(); + const origin = new URL(launched.windows.require().page.url()).origin; + const downloads = path.join(launched.directory, 'data', 'Downloads'); + const download = (route: string): Promise => launched.app.evaluate(({ BrowserWindow }, url) => BrowserWindow.getAllWindows()[0]?.webContents.downloadURL(url), `${origin}${route}`); + const placed = async (): Promise => (await launched.app.downloads()).map(({ path: saved, state }) => [path.basename(saved), state]); + await download('/held'); + await expect.poll(placed).toEqual([['report.txt', 'progressing']]); + // Chromium writes the file as soon as the app names it, so it is removed: only the name the app took is left to number around. + await expect.poll(() => existsSync(path.join(downloads, 'report.txt'))).toBe(true); + rmSync(path.join(downloads, 'report.txt')); + await download('/now'); + await expect.poll(placed).toEqual([ + ['report.txt', 'progressing'], + ['report (1).txt', 'completed'], + ]); + expect(readFileSync(path.join(downloads, 'report (1).txt'), 'utf8')).toBe('now'); + }); + + it.skipIf(process.platform === 'win32')('gives a download the name of one the app saved in a folder of its own', async () => { + const launched = appWith(`let first = true; + app.whenReady().then(() => { + require('electron').session.defaultSession.on('will-download', (_event, item) => { + // The app saves its first download itself, in a folder outside the downloads folder. + if (first) item.setSavePath(require('node:path').join(__dirname, 'exports', item.getFilename())); + first = false; + }); + const server = require('node:http').createServer((request, response) => { + if (request.url === '/') return response.end('Loaded'); + response.setHeader('Content-Disposition', 'attachment; filename="' + request.url.slice(1) + '"'); + response.end(request.url); + }); + server.listen(0, '127.0.0.1', () => new BrowserWindow({ show: false }).loadURL('http://127.0.0.1:' + server.address().port + '/')); + });`); + await launched.launch(); + const origin = new URL(launched.windows.require().page.url()).origin; + const downloads = path.join(launched.directory, 'data', 'Downloads'); + const exports = path.join(launched.directory, 'exports'); + const download = async (name: string): Promise => { + await launched.app.evaluate(({ BrowserWindow }, url) => BrowserWindow.getAllWindows()[0]?.webContents.downloadURL(url), `${origin}/${name}`); + }; + await download('report.txt'); + await expect.poll(() => (existsSync(exports) ? readdirSync(exports) : [])).toContain('report.txt'); + await download('report.txt'); + await expect.poll(() => (existsSync(downloads) ? readdirSync(downloads) : [])).toEqual(['report.txt']); + }); }); describe('an app with no inspector', () => { diff --git a/packages/electron/tests/unit/download-wait.test.ts b/packages/electron/tests/unit/download-wait.test.ts new file mode 100644 index 0000000000..6791d78280 --- /dev/null +++ b/packages/electron/tests/unit/download-wait.test.ts @@ -0,0 +1,36 @@ +import type { OperationContext } from '@e2e-dev/core/engine'; +import { describe, expect, it } from 'vitest'; +import type { AppDownload } from '../../src/app-process.ts'; +import { resolveOptions } from '../../src/options.ts'; +import { ElectronSurface } from '../../src/surface.ts'; + +/** A surface mid-attempt whose app lists its downloads through `downloads`. */ +function surfaceWith(downloads: () => Promise): ElectronSurface { + const surface = new ElectronSurface(resolveOptions({})); + Object.assign(surface, { attempt: { artifactsDir: '/nonexistent' } }); + Object.assign(Reflect.get(surface, 'app') as object, { downloads }); + return surface; +} + +const operation = (timeoutMs: number): OperationContext => ({ signal: new AbortController().signal, timeoutMs, runId: 'run', attemptId: 'attempt', origin: 'test' }) as OperationContext; + +describe('electron.waitForDownload with no download', () => { + it('times out as no download, not as an app that did not answer, when the app answers each read in a few milliseconds', async () => { + // The last read starts at the deadline, with a millisecond to answer in: fewer than this app takes. + const surface = surfaceWith(() => new Promise((resolve) => setTimeout(() => resolve([]), 5))); + await expect(surface.waitForDownload(() => Promise.resolve(), operation(300))).rejects.toMatchObject({ + code: 'ACTION_FAILED', + message: expect.stringMatching(/^no download finished within 300ms; the trigger resolved after \d+ms$/), + }); + }); + + it('says the app did not answer when a read with time left gets no answer', async () => { + let reads = 0; + // The first read answers; every later one hangs, as a main process stuck in a loop does. + const surface = surfaceWith(() => (reads++ === 0 ? Promise.resolve([]) : new Promise(() => undefined))); + await expect(surface.waitForDownload(() => Promise.resolve(), operation(300))).rejects.toMatchObject({ + code: 'ACTION_FAILED', + message: 'no download finished within 300ms: the app\'s main process did not answer', + }); + }); +});