Skip to content

Commit 6fdb1c2

Browse files
fix(web): fail setInputFiles on a missing path as INVALID_ARGUMENT before clicking (#2039)
* fix(web): fail setInputFiles on a missing path as INVALID_ARGUMENT before clicking * fix(web): stat upload paths through a shared helper that survives EACCES * docs(web): say setInputFiles checks reachability, not read permission, and clean up the unit temp dir * fix(web): keep Node's ENOENT text in the setInputFiles path error --------- Co-authored-by: Kunal Roy Choudhury <[email protected]>
1 parent 53f5cf6 commit 6fdb1c2

9 files changed

Lines changed: 92 additions & 23 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@e2e-dev/web": patch
3+
---
4+
5+
`locator.setInputFiles` with a path that does not exist or sits under a directory the runner cannot search now fails as `INVALID_ARGUMENT`, a test error with exit code 1, before the engine clicks anything. Before, Playwright's `ENOENT` came back as infrastructure `ENGINE_FAILURE` with exit code 3, and a button that opens a file chooser was clicked first.

‎docs/reference/screen.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -945,7 +945,7 @@ Web only. An empty array clears the input and fires `input` and `change`. It als
945945

946946
| Throws | When |
947947
| --- | --- |
948-
| `INVALID_ARGUMENT` | A blank path. |
948+
| `INVALID_ARGUMENT` | A blank path, or a path that does not exist or sits under a directory the runner cannot search. |
949949
| `UNSUPPORTED_CAPABILITY` | On a device, which has no file input. |
950950
| `ACTION_FAILED` | A button that opens no file chooser. |
951951

‎packages/web/src/actions.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/** Locator action dispatch for the Playwright engine. */
22

33
import type { ElementHandle, Page } from 'playwright-core';
4-
import { Deadline, EngineError, pollCondition, type KeyModifier, type LocatorAction, type NodeRef, type PointerAction, type ViewportPoint } from '@e2e-dev/core/engine';
4+
import { Deadline, EngineError, pollCondition, TestError, type KeyModifier, type LocatorAction, type NodeRef, type PointerAction, type ViewportPoint } from '@e2e-dev/core/engine';
55
import {
66
asActionable,
77
isClassified,
@@ -14,6 +14,7 @@ import {
1414
performPointerDrag,
1515
performViewportSwipe,
1616
POST_DISPATCH_PATTERN,
17+
statPath,
1718
translatePwError,
1819
targetPage,
1920
type ActionTarget,
@@ -231,9 +232,15 @@ function radioKind(element: ElementHandle<Element>): Promise<'native' | 'aria' |
231232
* Playwright retargets a label to its control. Anything else is clicked
232233
* with the chooser already awaited, and fails if no chooser opens. Every
233234
* step shares the operation's deadline, and a cancelled operation sets no
234-
* files, even when its chooser opens after the cancel.
235+
* files, even when its chooser opens after the cancel. A path that does not
236+
* exist or sits under a directory the runner cannot search fails before
237+
* anything is clicked.
235238
*/
236239
async function uploadFiles(target: ActionTarget, paths: readonly string[], operation: ConnectionBudget): Promise<void> {
240+
for (const file of paths) {
241+
const stats = statPath(file);
242+
if (stats instanceof Error) throw new TestError('INVALID_ARGUMENT', `setInputFiles path does not exist or is under a directory the runner cannot search: ${stats.message}`);
243+
}
237244
const deadline = new Deadline(operation.timeoutMs);
238245
const remaining = (): number => Math.max(1, deadline.remaining());
239246
const element =

‎packages/web/src/route-options.ts‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@
77
* the same `resolveUrl` `goto` uses.
88
*/
99

10-
import { statSync } from 'node:fs';
1110
import { types } from 'node:util';
1211
import { rejectUnknownOptions, TestError, validateJsonValue, type JsonValue } from '@e2e-dev/core/engine';
1312
import { headerProblem } from './protected-app.ts';
13+
import { statPath } from './support.ts';
1414

1515
/** What `route.fulfill` hands Playwright once the response is validated. */
1616
export interface FulfillDecision {
@@ -173,13 +173,8 @@ function requireBody(value: unknown): string | Buffer {
173173

174174
/** Rejects a path that does not name a regular file; synchronous so the check lands before the decision. */
175175
function requireFile(file: string): void {
176-
let isFile = false;
177-
try {
178-
isFile = statSync(file, { throwIfNoEntry: false })?.isFile() === true;
179-
} catch {
180-
// A directory on the path the runner may not search (`EACCES`): not a file the route can serve.
181-
}
182-
if (!isFile) {
176+
const stats = statPath(file);
177+
if (stats instanceof Error || !stats.isFile()) {
183178
throw new TestError('INVALID_ARGUMENT', `route.fulfill path is not a readable file: ${file}`);
184179
}
185180
}

‎packages/web/src/support.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
/** Shared error translation, filename, and swipe helpers for the Playwright engine. */
22

3+
import { statSync, type Stats } from 'node:fs';
34
import { setTimeout } from 'node:timers/promises';
45
import type { ElementHandle, FrameLocator, Locator as PwLocator, Mouse, Page } from 'playwright-core';
56
import { EngineError, withinCleanupBudget, type EngineCleanupContext, type Momentum, type ScrollDirection, type ViewportPoint, type ViewportSize } from '@e2e-dev/core/engine';
@@ -191,6 +192,15 @@ export function message(cause: unknown): string {
191192
return text.replace(ANSI_PATTERN, '');
192193
}
193194

195+
/** Stats a caller-supplied path, or returns Node's error when it is missing or a directory on it may not be searched (`EACCES`). */
196+
export function statPath(file: string): Stats | Error {
197+
try {
198+
return statSync(file);
199+
} catch (cause) {
200+
return cause as Error;
201+
}
202+
}
203+
194204
/** Constrains a caller-supplied artifact label to a safe filename. */
195205
export function sanitizeFilename(name: string): string {
196206
return name.replaceAll(/[^A-Za-z0-9._-]/g, '_').slice(0, 64) || 'artifact';

‎packages/web/tests/integration/upload-actions.test.ts‎

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
* engine acts on: a file input and a label for one take the files without a
44
* click, a button that opens a hidden input's chooser is clicked and the
55
* chooser takes them, an empty list clears either, and a button that opens
6-
* nothing fails.
6+
* nothing or a path that does not exist fails.
77
*/
88

9-
import { mkdtempSync, writeFileSync } from 'node:fs';
9+
import { chmodSync, mkdirSync, mkdtempSync, statSync, writeFileSync } from 'node:fs';
1010
import { tmpdir } from 'node:os';
1111
import path from 'node:path';
1212
import { chromium, type Browser, type Page } from 'playwright-core';
@@ -67,6 +67,16 @@ function state(): Promise<{ files: string; clicks: number }> {
6767

6868
const COUNT_CLICKS = '<script>window.clicks = 0; document.addEventListener("click", () => window.clicks++, true)</script>';
6969

70+
/** Node's own message for a path that cannot be stat'ed, which the engine reports as is. */
71+
function statFailure(target: string): string {
72+
try {
73+
statSync(target);
74+
} catch (cause) {
75+
return (cause as Error).message;
76+
}
77+
throw new Error(`${target} exists`);
78+
}
79+
7080
describe.each(KINDS)('through the %s target', (kind) => {
7181
it('sets a file input directly', async () => {
7282
await page.setContent(`<input id="avatar" type="file">${COUNT_CLICKS}`);
@@ -106,6 +116,39 @@ describe.each(KINDS)('through the %s target', (kind) => {
106116
expect(await page.evaluate(() => (window as unknown as { events: string[] }).events)).toEqual(['input', 'change']);
107117
});
108118

119+
it.each([
120+
['a file input', '<input id="avatar" type="file">', '#avatar'],
121+
['a button over a hidden input', `<button id="pick" type="button" onclick="document.getElementById('avatar').click()">Choose avatar</button><input id="avatar" type="file" hidden>`, '#pick'],
122+
])('fails a path that does not exist as INVALID_ARGUMENT before it touches %s', async (_name, html, selector) => {
123+
await page.setContent(`${html}${COUNT_CLICKS}`);
124+
for (const missing of [path.join(path.dirname(file), 'missing.png'), path.join(file, 'inside-a-file.png')]) {
125+
const error = await upload(await targetOf(kind, selector), [file, missing]);
126+
expect(error).toMatchObject({ code: 'INVALID_ARGUMENT', category: 'test', message: `setInputFiles path does not exist or is under a directory the runner cannot search: ${statFailure(missing)}` });
127+
expect((error as Error).message).toContain(missing);
128+
}
129+
expect(await state()).toEqual({ files: '', clicks: 0 });
130+
});
131+
132+
// Permission bits do not stop a Windows or root process, so only a non-root POSIX runner sees `EACCES`.
133+
it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(
134+
'fails a path under a directory it may not search as INVALID_ARGUMENT',
135+
async () => {
136+
await page.setContent(`<input id="avatar" type="file">${COUNT_CLICKS}`);
137+
const locked = path.join(path.dirname(file), `locked-${kind}`);
138+
mkdirSync(locked);
139+
const hidden = path.join(locked, 'avatar.png');
140+
writeFileSync(hidden, 'png');
141+
chmodSync(locked, 0o000);
142+
try {
143+
const error = await upload(await targetOf(kind, '#avatar'), [hidden]);
144+
expect(error).toMatchObject({ code: 'INVALID_ARGUMENT', category: 'test', message: `setInputFiles path does not exist or is under a directory the runner cannot search: EACCES: permission denied, stat '${hidden}'` });
145+
} finally {
146+
chmodSync(locked, 0o700);
147+
}
148+
expect(await state()).toEqual({ files: '', clicks: 0 });
149+
},
150+
);
151+
109152
it('fails when the button opens no file chooser', async () => {
110153
await page.setContent(`<button id="pick" type="button">Choose avatar</button><input id="avatar" type="file" hidden>${COUNT_CLICKS}`);
111154
const error = await upload(await targetOf(kind, '#pick'));

‎packages/web/tests/unit/actions.test.ts‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,21 @@
55
* support.ts).
66
*/
77

8+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
9+
import { tmpdir } from 'node:os';
10+
import path from 'node:path';
811
import type { Locator as PwLocator, Page } from 'playwright-core';
9-
import { describe, expect, it, vi } from 'vitest';
12+
import { afterAll, describe, expect, it, vi } from 'vitest';
1013
import { EngineError, TestError, type LocatorAction } from '@e2e-dev/core/engine';
1114
import { classifyActionError, dispatchLocatorAction, dispatchPointerAction } from '../../src/actions.ts';
1215
import { dispatchedInput, type ActionTarget } from '../../src/support.ts';
1316

17+
/** A real file: setInputFiles stats every path before it touches the element. */
18+
const UPLOAD_DIR = mkdtempSync(path.join(tmpdir(), 'e2e-actions-'));
19+
const UPLOAD = path.join(UPLOAD_DIR, 'a.txt');
20+
writeFileSync(UPLOAD, 'a');
21+
afterAll(() => rmSync(UPLOAD_DIR, { recursive: true, force: true }));
22+
1423
vi.mock('node:timers/promises', () => ({
1524
setTimeout: (ms: number, value?: unknown, options?: { signal?: AbortSignal }) =>
1625
new Promise((resolve, reject) => {
@@ -235,18 +244,18 @@ describe('dispatchLocatorAction', () => {
235244

236245
it('uploads through a file chooser it awaits before clicking a button', async () => {
237246
const { element, target, page, chooser, calls } = stubUpload(false);
238-
await dispatchLocatorAction(target, { kind: 'setInputFiles', paths: ['/tmp/a.txt'] }, OPERATION, lookup);
247+
await dispatchLocatorAction(target, { kind: 'setInputFiles', paths: [UPLOAD] }, OPERATION, lookup);
239248
expect(calls).toEqual(['waitForEvent', 'click', 'setFiles']);
240249
expect(page.waitForEvent).toHaveBeenCalledWith('filechooser', { timeout: expect.any(Number) });
241-
expect(chooser.setFiles).toHaveBeenCalledWith(['/tmp/a.txt'], { timeout: expect.any(Number) });
250+
expect(chooser.setFiles).toHaveBeenCalledWith([UPLOAD], { timeout: expect.any(Number) });
242251
expect(element.setInputFiles).not.toHaveBeenCalled();
243252
expect(element.dispose).toHaveBeenCalled();
244253
});
245254

246255
it('sets a file input directly', async () => {
247256
const { element, target, page } = stubUpload(true);
248-
await dispatchLocatorAction(target, { kind: 'setInputFiles', paths: ['/tmp/a.txt'] }, OPERATION, lookup);
249-
expect(element.setInputFiles).toHaveBeenCalledWith(['/tmp/a.txt'], { timeout: expect.any(Number) });
257+
await dispatchLocatorAction(target, { kind: 'setInputFiles', paths: [UPLOAD] }, OPERATION, lookup);
258+
expect(element.setInputFiles).toHaveBeenCalledWith([UPLOAD], { timeout: expect.any(Number) });
250259
expect(element.click).not.toHaveBeenCalled();
251260
expect(page.waitForEvent).not.toHaveBeenCalled();
252261
});
@@ -255,7 +264,7 @@ describe('dispatchLocatorAction', () => {
255264
const { target, page } = stubUpload(false);
256265
page.waitForEvent.mockRejectedValue(Object.assign(new Error('Timeout 7ms exceeded'), { name: 'TimeoutError' }));
257266
await expect(
258-
dispatchLocatorAction(target, { kind: 'setInputFiles', paths: ['/tmp/a.txt'] }, OPERATION, lookup),
267+
dispatchLocatorAction(target, { kind: 'setInputFiles', paths: [UPLOAD] }, OPERATION, lookup),
259268
).rejects.toMatchObject({ code: 'NOT_ACTIONABLE', message: expect.stringContaining('opened no file chooser') });
260269
});
261270

@@ -266,7 +275,7 @@ describe('dispatchLocatorAction', () => {
266275
page.waitForEvent.mockReturnValue(new Promise((resolve) => (openChooser = resolve)));
267276
const upload = dispatchLocatorAction(
268277
target,
269-
{ kind: 'setInputFiles', paths: ['/tmp/a.txt'] },
278+
{ kind: 'setInputFiles', paths: [UPLOAD] },
270279
{ timeoutMs: 1000, signal: cancel.signal },
271280
lookup,
272281
);
@@ -285,7 +294,7 @@ describe('dispatchLocatorAction', () => {
285294
Object.assign(page, { waitForEvent: () => pending });
286295
element.click.mockRejectedValue(new Error('element is not enabled'));
287296
await expect(
288-
dispatchLocatorAction(target, { kind: 'setInputFiles', paths: ['/tmp/a.txt'] }, OPERATION, lookup),
297+
dispatchLocatorAction(target, { kind: 'setInputFiles', paths: [UPLOAD] }, OPERATION, lookup),
289298
).rejects.toThrow('element is not enabled');
290299
rejectChooser(Object.assign(new Error('Timeout 7ms exceeded'), { name: 'TimeoutError' }));
291300
await new Promise((resolve) => setTimeout(resolve, 0));

‎plugins/e2e/skills/e2e/references/writing-tests.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ Each action resolves one node, waits up to `config.actionTimeout` (30 s, or
318318
`press(key)`, `check()`, `uncheck()`,
319319
`selectOption(label | { label } | { value } | { index })` (one option; an
320320
array is `INVALID_ARGUMENT`), `focus()`, `blur()`, `hover()`, `setInputFiles(paths)`
321-
(relative to the project root; `[]` clears), `dragTo(locator)`, `scrollIntoView()`,
321+
(relative to the project root; `[]` clears; a missing path, or one under a directory the runner cannot search, is `INVALID_ARGUMENT`), `dragTo(locator)`, `scrollIntoView()`,
322322
`swipe({ direction, momentum? })`. Web only, `UNSUPPORTED_CAPABILITY` on a
323323
device: `blur`, `secondaryTap`, `selectOption`, `setInputFiles`, `scrollIntoView`,
324324
and `modifiers`.

‎skills/e2e/references/writing-tests.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ Each action resolves one node, waits up to `config.actionTimeout` (30 s, or
318318
`press(key)`, `check()`, `uncheck()`,
319319
`selectOption(label | { label } | { value } | { index })` (one option; an
320320
array is `INVALID_ARGUMENT`), `focus()`, `blur()`, `hover()`, `setInputFiles(paths)`
321-
(relative to the project root; `[]` clears), `dragTo(locator)`, `scrollIntoView()`,
321+
(relative to the project root; `[]` clears; a missing path, or one under a directory the runner cannot search, is `INVALID_ARGUMENT`), `dragTo(locator)`, `scrollIntoView()`,
322322
`swipe({ direction, momentum? })`. Web only, `UNSUPPORTED_CAPABILITY` on a
323323
device: `blur`, `secondaryTap`, `selectOption`, `setInputFiles`, `scrollIntoView`,
324324
and `modifiers`.

0 commit comments

Comments
 (0)