From c052627138dd581aea93d74d2896e96077b4f69c Mon Sep 17 00:00:00 2001 From: Max Schmitt Date: Wed, 12 Feb 2025 14:21:57 +0100 Subject: [PATCH 01/13] fix: allow empty userDataDir (#34730) --- packages/playwright-core/src/client/browserType.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/playwright-core/src/client/browserType.ts b/packages/playwright-core/src/client/browserType.ts index 59ce8c56d7..9afdb8dc0a 100644 --- a/packages/playwright-core/src/client/browserType.ts +++ b/packages/playwright-core/src/client/browserType.ts @@ -100,7 +100,7 @@ export class BrowserType extends ChannelOwner imple ignoreAllDefaultArgs: !!options.ignoreDefaultArgs && !Array.isArray(options.ignoreDefaultArgs), env: options.env ? envObjectToArray(options.env) : undefined, channel: options.channel, - userDataDir: path.isAbsolute(userDataDir) ? userDataDir : path.resolve(userDataDir), + userDataDir: (path.isAbsolute(userDataDir) || !userDataDir) ? userDataDir : path.resolve(userDataDir), }; return await this._wrapApiCall(async () => { const result = await this._channel.launchPersistentContext(persistentParams); From 3e976e9f100c74a137817265bf29e1b8727533b4 Mon Sep 17 00:00:00 2001 From: Dmitry Gozman Date: Wed, 12 Feb 2025 13:22:35 +0000 Subject: [PATCH 02/13] chore(chromium): re-enable PlzDedicatedWorker feature (#34400) --- .../playwright-core/src/server/chromium/chromiumSwitches.ts | 3 +-- tests/page/interception.spec.ts | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/playwright-core/src/server/chromium/chromiumSwitches.ts b/packages/playwright-core/src/server/chromium/chromiumSwitches.ts index 9d64d58f1c..0f6415745e 100644 --- a/packages/playwright-core/src/server/chromium/chromiumSwitches.ts +++ b/packages/playwright-core/src/server/chromium/chromiumSwitches.ts @@ -37,11 +37,10 @@ export const chromiumSwitches = [ // PaintHolding - https://github.com/microsoft/playwright/issues/28023 // ThirdPartyStoragePartitioning - https://github.com/microsoft/playwright/issues/32230 // LensOverlay - Hides the Lens feature in the URL address bar. Its not working in unofficial builds. - // PlzDedicatedWorker - https://github.com/microsoft/playwright/issues/31747 // DeferRendererTasksAfterInput - this makes Page.frameScheduledNavigation arrive much later after a click, // making our navigation auto-wait after click not working. Can be removed once we deperecate noWaitAfter. // See https://github.com/microsoft/playwright/pull/34372. - '--disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync,Translate,HttpsUpgrades,PaintHolding,ThirdPartyStoragePartitioning,LensOverlay,PlzDedicatedWorker,DeferRendererTasksAfterInput', + '--disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync,Translate,HttpsUpgrades,PaintHolding,ThirdPartyStoragePartitioning,LensOverlay,DeferRendererTasksAfterInput', '--allow-pre-commit-input', '--disable-hang-monitor', '--disable-ipc-flooding-protection', diff --git a/tests/page/interception.spec.ts b/tests/page/interception.spec.ts index eef67e8b37..9447a80fcd 100644 --- a/tests/page/interception.spec.ts +++ b/tests/page/interception.spec.ts @@ -126,7 +126,6 @@ it('should intercept worker requests when enabled after worker creation', { }, async ({ page, server, isAndroid, browserName, browserMajorVersion }) => { it.skip(isAndroid); it.skip(browserName === 'chromium' && browserMajorVersion < 130, 'fixed in Chromium 130'); - it.fixme(browserName === 'chromium', 'requires PlzDedicatedWorker to be enabled'); await page.goto(server.EMPTY_PAGE); server.setRoute('/data_for_worker', (req, res) => res.end('failed to intercept')); From b7785e1662606ee324a6de39d2044cc49bef9499 Mon Sep 17 00:00:00 2001 From: Simon Knott Date: Wed, 12 Feb 2025 14:51:00 +0100 Subject: [PATCH 03/13] feat(runner): enable gitCommitInfo by default on GH Actions (#34743) --- docs/src/test-api/class-testconfig.md | 2 ++ packages/playwright/src/common/config.ts | 3 ++- packages/playwright/types/test.d.ts | 2 ++ tests/playwright-test/playwright-test-fixtures.ts | 1 + 4 files changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/src/test-api/class-testconfig.md b/docs/src/test-api/class-testconfig.md index 5b89e62b88..5515252b39 100644 --- a/docs/src/test-api/class-testconfig.md +++ b/docs/src/test-api/class-testconfig.md @@ -334,6 +334,8 @@ Whether to populate `'git.commit.info'` field of the [`property: TestConfig.meta This information will appear in the HTML and JSON reports and is available in the Reporter API. +On Github Actions, this feature is enabled by default. + **Usage** ```js title="playwright.config.ts" diff --git a/packages/playwright/src/common/config.ts b/packages/playwright/src/common/config.ts index b0bc394873..59d1973578 100644 --- a/packages/playwright/src/common/config.ts +++ b/packages/playwright/src/common/config.ts @@ -78,7 +78,7 @@ export class FullConfigInternal { const privateConfiguration = (userConfig as any)['@playwright/test']; this.plugins = (privateConfiguration?.plugins || []).map((p: any) => ({ factory: p })); this.singleTSConfigPath = pathResolve(configDir, userConfig.tsconfig); - this.populateGitInfo = takeFirst(userConfig.populateGitInfo, false); + this.populateGitInfo = takeFirst(userConfig.populateGitInfo, defaultPopulateGitInfo); this.globalSetups = (Array.isArray(userConfig.globalSetup) ? userConfig.globalSetup : [userConfig.globalSetup]).map(s => resolveScript(s, configDir)).filter(script => script !== undefined); this.globalTeardowns = (Array.isArray(userConfig.globalTeardown) ? userConfig.globalTeardown : [userConfig.globalTeardown]).map(s => resolveScript(s, configDir)).filter(script => script !== undefined); @@ -301,6 +301,7 @@ function resolveScript(id: string | undefined, rootDir: string): string | undefi export const defaultGrep = /.*/; export const defaultReporter = process.env.CI ? 'dot' : 'list'; +const defaultPopulateGitInfo = process.env.GITHUB_ACTIONS === 'true'; const configInternalSymbol = Symbol('configInternalSymbol'); diff --git a/packages/playwright/types/test.d.ts b/packages/playwright/types/test.d.ts index ab23b480b2..a31bb858d5 100644 --- a/packages/playwright/types/test.d.ts +++ b/packages/playwright/types/test.d.ts @@ -1367,6 +1367,8 @@ interface TestConfig { * * This information will appear in the HTML and JSON reports and is available in the Reporter API. * + * On Github Actions, this feature is enabled by default. + * * **Usage** * * ```js diff --git a/tests/playwright-test/playwright-test-fixtures.ts b/tests/playwright-test/playwright-test-fixtures.ts index 5d6aab5b8e..789ed1feb6 100644 --- a/tests/playwright-test/playwright-test-fixtures.ts +++ b/tests/playwright-test/playwright-test-fixtures.ts @@ -222,6 +222,7 @@ export function cleanEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { CI_COMMIT_SHA: undefined, CI_JOB_URL: undefined, CI_PROJECT_URL: undefined, + GITHUB_ACTIONS: undefined, GITHUB_REPOSITORY: undefined, GITHUB_RUN_ID: undefined, GITHUB_SERVER_URL: undefined, From 0501f8c1325d5cd749ca065f6469fb868a388105 Mon Sep 17 00:00:00 2001 From: Adam Gastineau Date: Wed, 12 Feb 2025 05:55:36 -0800 Subject: [PATCH 04/13] chore(html-report): make scrollbar gutter stable (#34732) --- packages/html-reporter/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/html-reporter/index.html b/packages/html-reporter/index.html index 054507220c..54ab833d2b 100644 --- a/packages/html-reporter/index.html +++ b/packages/html-reporter/index.html @@ -15,7 +15,7 @@ --> - + From 1ad7aad5fb35b399f0fa701f7f0bcf011341bf11 Mon Sep 17 00:00:00 2001 From: Simon Knott Date: Wed, 12 Feb 2025 15:44:45 +0100 Subject: [PATCH 05/13] fix: prompt should mention contents (#34746) --- packages/web/src/components/prompts.ts | 11 ++++++++++- tests/playwright-test/reporter-html.spec.ts | 9 +++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/packages/web/src/components/prompts.ts b/packages/web/src/components/prompts.ts index 8ecc78e9c6..d446dfa17d 100644 --- a/packages/web/src/components/prompts.ts +++ b/packages/web/src/components/prompts.ts @@ -19,9 +19,18 @@ function stripAnsiEscapes(str: string): string { return str.replace(ansiRegex, ''); } +function enumerate(items: string[]) { + if (items.length === 0) + return ''; + if (items.length === 1) + return items[0]; + return items.slice(0, -1).join(', ') + ' and ' + items[items.length - 1]; +} + export function fixTestPrompt(error: string, diff?: string, pageSnapshot?: string) { + const includedData = ['the error', diff && 'a code diff', pageSnapshot && 'a snapshot of the page'].filter((v): v is string => Boolean(v)); const promptParts = [ - `My Playwright test failed. What's going wrong?`, + `My Playwright test failed, what's going wrong? I've included ${enumerate(includedData)} below.`, `Please give me a suggestion how to fix it, and then explain what went wrong. Be very concise and apply Playwright best practices.`, `Don't include many headings in your output. Make sure what you're saying is correct, and take into account whether there might be a bug in the app.`, 'Here is the error:', diff --git a/tests/playwright-test/reporter-html.spec.ts b/tests/playwright-test/reporter-html.spec.ts index acfd4cd187..bf88f52ade 100644 --- a/tests/playwright-test/reporter-html.spec.ts +++ b/tests/playwright-test/reporter-html.spec.ts @@ -2706,7 +2706,10 @@ for (const useIntermediateMergeReport of [true, false] as const) { `, 'example.spec.ts': ` import { test, expect } from '@playwright/test'; - test('sample', async ({}) => { expect(2).toBe(3); }); + test('sample', async ({ page }) => { + await page.setContent(''); + expect(2).toBe(3); + }); `, }; const baseDir = await writeFiles(files); @@ -2744,8 +2747,10 @@ for (const useIntermediateMergeReport of [true, false] as const) { await page.getByRole('link', { name: 'sample' }).click(); await page.getByRole('button', { name: 'Fix with AI' }).click(); const prompt = await page.evaluate(() => navigator.clipboard.readText()); + expect(prompt, 'first line').toContain(`My Playwright test failed, what's going wrong? I've included the error, a code diff and a snapshot of the page below.`); expect(prompt, 'contains error').toContain('expect(received).toBe(expected)'); - expect(prompt, 'contains diff').toContain(`+ test('sample', async ({}) => { expect(2).toBe(3); });`); + expect(prompt, 'contains snapshot').toContain('- button "Click me"'); + expect(prompt, 'contains diff').toContain(`+ expect(2).toBe(3);`); }); }); } From 8eb816b363fac41d1c1b17edc725dd5142ac2877 Mon Sep 17 00:00:00 2001 From: Dmitry Gozman Date: Wed, 12 Feb 2025 15:41:16 +0000 Subject: [PATCH 06/13] fix(trace): do not save trace on failure after success in test+hooks (#34724) --- packages/playwright/src/index.ts | 2 +- packages/playwright/src/worker/testTracing.ts | 30 +++++++-- packages/playwright/src/worker/workerMain.ts | 2 + .../playwright.connect.spec.ts | 63 ++++++++++++++++++- 4 files changed, 89 insertions(+), 8 deletions(-) diff --git a/packages/playwright/src/index.ts b/packages/playwright/src/index.ts index 9b0fb456ab..a8d0cc0387 100644 --- a/packages/playwright/src/index.ts +++ b/packages/playwright/src/index.ts @@ -726,7 +726,7 @@ class ArtifactsRecorder { return; (tracing as any)[this._startedCollectingArtifacts] = true; if (this._testInfo._tracing.traceOptions() && (tracing as any)[kTracingStarted]) - await tracing.stopChunk({ path: this._testInfo._tracing.generateNextTraceRecordingPath() }); + await tracing.stopChunk({ path: this._testInfo._tracing.maybeGenerateNextTraceRecordingPath() }); } } diff --git a/packages/playwright/src/worker/testTracing.ts b/packages/playwright/src/worker/testTracing.ts index a90c006616..ba215c8792 100644 --- a/packages/playwright/src/worker/testTracing.ts +++ b/packages/playwright/src/worker/testTracing.ts @@ -46,6 +46,7 @@ export class TestTracing { private _artifactsDir: string; private _tracesDir: string; private _contextCreatedEvent: trace.ContextCreatedTraceEvent; + private _didFinishTestFunctionAndAfterEachHooks = false; constructor(testInfo: TestInfoImpl, artifactsDir: string) { this._testInfo = testInfo; @@ -113,6 +114,10 @@ export class TestTracing { } } + didFinishTestFunctionAndAfterEachHooks() { + this._didFinishTestFunctionAndAfterEachHooks = true; + } + artifactsDir() { return this._artifactsDir; } @@ -133,7 +138,7 @@ export class TestTracing { return `${this._testInfo.testId}${retrySuffix}${ordinalSuffix}`; } - generateNextTraceRecordingPath() { + private _generateNextTraceRecordingPath() { const file = path.join(this._artifactsDir, createGuid() + '.zip'); this._temporaryTraceFiles.push(file); return file; @@ -143,6 +148,22 @@ export class TestTracing { return this._options; } + maybeGenerateNextTraceRecordingPath() { + // Forget about traces that should be saved on failure, when no failure happened + // during the test and beforeEach/afterEach hooks. + // This avoids downloading traces over the wire when not really needed. + if (this._didFinishTestFunctionAndAfterEachHooks && this._shouldAbandonTrace()) + return; + return this._generateNextTraceRecordingPath(); + } + + private _shouldAbandonTrace() { + if (!this._options) + return true; + const testFailed = this._testInfo.status !== this._testInfo.expectedStatus; + return !testFailed && (this._options.mode === 'retain-on-failure' || this._options.mode === 'retain-on-first-failure'); + } + async stopIfNeeded() { if (!this._options) return; @@ -151,10 +172,7 @@ export class TestTracing { if (error) throw error; - const testFailed = this._testInfo.status !== this._testInfo.expectedStatus; - const shouldAbandonTrace = !testFailed && (this._options.mode === 'retain-on-failure' || this._options.mode === 'retain-on-first-failure'); - - if (shouldAbandonTrace) { + if (this._shouldAbandonTrace()) { for (const file of this._temporaryTraceFiles) await fs.promises.unlink(file).catch(() => {}); return; @@ -213,7 +231,7 @@ export class TestTracing { await new Promise(f => { zipFile.end(undefined, () => { - zipFile.outputStream.pipe(fs.createWriteStream(this.generateNextTraceRecordingPath())).on('close', f); + zipFile.outputStream.pipe(fs.createWriteStream(this._generateNextTraceRecordingPath())).on('close', f); }); }); diff --git a/packages/playwright/src/worker/workerMain.ts b/packages/playwright/src/worker/workerMain.ts index 5188614271..30b59c36e7 100644 --- a/packages/playwright/src/worker/workerMain.ts +++ b/packages/playwright/src/worker/workerMain.ts @@ -399,6 +399,8 @@ export class WorkerMain extends ProcessRunner { firstAfterHooksError = firstAfterHooksError ?? error; } + testInfo._tracing.didFinishTestFunctionAndAfterEachHooks(); + try { // Teardown test-scoped fixtures. Attribute to 'test' so that users understand // they should probably increase the test timeout to fix this issue. diff --git a/tests/playwright-test/playwright.connect.spec.ts b/tests/playwright-test/playwright.connect.spec.ts index 083a01ac5e..e86e7370ca 100644 --- a/tests/playwright-test/playwright.connect.spec.ts +++ b/tests/playwright-test/playwright.connect.spec.ts @@ -14,7 +14,9 @@ * limitations under the License. */ -import { test, expect } from './playwright-test-fixtures'; +import { test, expect, countTimes } from './playwright-test-fixtures'; +import { parseTrace } from '../config/utils'; +import fs from 'fs'; test('should work with connectOptions', async ({ runInlineTest }) => { const result = await runInlineTest({ @@ -167,3 +169,62 @@ test('should print debug log when failed to connect', async ({ runInlineTest }) expect(result.output).toContain('b-debug-log-string'); expect(result.results[0].attachments).toEqual([]); }); + +test('should record trace', async ({ runInlineTest }) => { + const result = await runInlineTest({ + 'playwright.config.js': ` + module.exports = { + globalSetup: './global-setup', + use: { + connectOptions: { + wsEndpoint: process.env.CONNECT_WS_ENDPOINT, + }, + trace: 'retain-on-failure', + }, + }; + `, + 'global-setup.ts': ` + import { chromium } from '@playwright/test'; + module.exports = async () => { + const server = await chromium.launchServer(); + process.env.CONNECT_WS_ENDPOINT = server.wsEndpoint(); + process.env.DEBUG = 'pw:channel'; + return () => server.close(); + }; + `, + 'a.test.ts': ` + import { test, expect } from '@playwright/test'; + test('pass', async ({ page }) => { + expect(1).toBe(1); + }); + test('fail', async ({ page }) => { + expect(1).toBe(2); + }); + `, + }); + expect(result.exitCode).toBe(1); + expect(result.passed).toBe(1); + expect(result.failed).toBe(1); + + // A single tracing artifact should be created. We see it in the logs twice: + // as a regular message and wrapped inside a jsonPipe. + expect(countTimes(result.output, `"type":"Artifact","initializer"`)).toBe(2); + + expect(fs.existsSync(test.info().outputPath('test-results', 'a-pass', 'trace.zip'))).toBe(false); + + const trace = await parseTrace(test.info().outputPath('test-results', 'a-fail', 'trace.zip')); + expect(trace.apiNames).toEqual([ + 'Before Hooks', + 'fixture: context', + 'browser.newContext', + 'fixture: page', + 'browserContext.newPage', + 'expect.toBe', + 'After Hooks', + 'locator.ariaSnapshot', + 'fixture: page', + 'fixture: context', + 'Worker Cleanup', + 'fixture: browser', + ]); +}); From 703ca9f8516f302ab545ab6c8bf32d0b8eba2be1 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Wed, 12 Feb 2025 09:00:01 -0800 Subject: [PATCH 07/13] =?UTF-8?q?Revert=20"chore(bidi):=20use=20fractional?= =?UTF-8?q?=20coordinates=20for=20pointerAction=20(#3=E2=80=A6=20(#34753)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/playwright-core/src/server/bidi/bidiInput.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/playwright-core/src/server/bidi/bidiInput.ts b/packages/playwright-core/src/server/bidi/bidiInput.ts index e460a9f3ef..e40b13bb2e 100644 --- a/packages/playwright-core/src/server/bidi/bidiInput.ts +++ b/packages/playwright-core/src/server/bidi/bidiInput.ts @@ -79,6 +79,9 @@ export class RawMouseImpl implements input.RawMouse { } async move(x: number, y: number, button: types.MouseButton | 'none', buttons: Set, modifiers: Set, forClick: boolean): Promise { + // Bidi throws when x/y are not integers. + x = Math.floor(x); + y = Math.floor(y); await this._performActions([{ type: 'pointerMove', x, y }]); } @@ -91,6 +94,9 @@ export class RawMouseImpl implements input.RawMouse { } async wheel(x: number, y: number, buttons: Set, modifiers: Set, deltaX: number, deltaY: number): Promise { + // Bidi throws when x/y are not integers. + x = Math.floor(x); + y = Math.floor(y); await this._session.send('input.performActions', { context: this._session.sessionId, actions: [ From f54478a23e0daa450fe524905eabc8aabf6efb07 Mon Sep 17 00:00:00 2001 From: Pavel Feldman Date: Wed, 12 Feb 2025 09:34:01 -0800 Subject: [PATCH 08/13] chore: move utils that are user in server to server/utils (3) (#34739) --- packages/playwright-core/src/DEPS.list | 4 +- packages/playwright-core/src/cli/driver.ts | 2 +- .../playwright-core/src/client/android.ts | 6 +- .../src/client/browserContext.ts | 4 +- .../playwright-core/src/client/browserType.ts | 6 +- .../src/client/clientHelper.ts | 2 +- .../src/client/elementHandle.ts | 2 +- packages/playwright-core/src/client/errors.ts | 2 +- packages/playwright-core/src/client/fetch.ts | 4 +- .../playwright-core/src/client/locator.ts | 4 +- .../playwright-core/src/client/network.ts | 8 +- packages/playwright-core/src/client/page.ts | 6 +- packages/playwright-core/src/client/video.ts | 2 +- packages/playwright-core/src/client/worker.ts | 2 +- packages/playwright-core/src/outofprocess.ts | 4 +- packages/playwright-core/src/remote/DEPS.list | 1 + .../src/remote/playwrightServer.ts | 2 +- .../src/server/android/android.ts | 2 +- .../playwright-core/src/server/artifact.ts | 2 +- .../src/server/chromium/chromium.ts | 2 +- packages/playwright-core/src/server/frames.ts | 2 +- .../src/server/har/harRecorder.ts | 2 +- .../src/server/har/harTracer.ts | 2 +- .../playwright-core/src/server/javascript.ts | 2 +- .../playwright-core/src/server/network.ts | 2 +- packages/playwright-core/src/server/page.ts | 2 +- .../playwright-core/src/server/progress.ts | 2 +- .../src/server/recorder/contextRecorder.ts | 2 +- .../src/server/recorder/recorderCollection.ts | 2 +- .../src/server/registry/browserFetcher.ts | 2 +- .../server/registry/oopDownloadBrowserMain.ts | 2 +- .../src/server/screenshotter.ts | 2 +- .../src/server/utils/DEPS.list | 2 +- .../src/server/utils/fileUtils.ts | 2 +- .../src/server/utils/happyEyeballs.ts | 4 +- .../src/server/utils/httpServer.ts | 2 +- packages/playwright-core/src/utils.ts | 25 ++-- packages/playwright-core/src/utils/DEPS.list | 2 + .../playwright-core/src/utils/expectUtils.ts | 2 +- .../src/utils/{ => isomorphic}/headers.ts | 0 .../utils/{ => isomorphic}/manualPromise.ts | 11 +- .../src/utils/{ => isomorphic}/multimap.ts | 0 .../src/utils/{ => isomorphic}/rtti.ts | 2 +- .../src/utils/{ => isomorphic}/semaphore.ts | 0 .../src/utils/{ => isomorphic}/sequence.ts | 0 .../src/utils/isomorphic/time.ts | 19 +++ .../utils/{ => isomorphic}/timeoutRunner.ts | 2 +- .../src/utils/isomorphic/traceUtils.ts | 23 ++- .../playwright-core/src/utils/localUtils.ts | 7 +- .../transport.ts => utils/pipeTransport.ts} | 8 +- .../playwright-core/src/utils/stackTrace.ts | 8 +- .../playwright-core/src/utils/stackUtils.ts | 136 +++++++++--------- packages/playwright-core/src/utils/time.ts | 32 ----- .../playwright-core/src/utils/traceUtils.ts | 39 ----- packages/playwright/src/util.ts | 4 +- .../events/remove-all-listeners-wait.spec.ts | 2 +- tests/library/unit/sequence.spec.ts | 2 +- tests/page/page-leaks.spec.ts | 2 +- tests/page/page-listeners.spec.ts | 2 +- .../ui-mode-test-progress.spec.ts | 2 +- 60 files changed, 204 insertions(+), 227 deletions(-) rename packages/playwright-core/src/utils/{ => isomorphic}/headers.ts (100%) rename packages/playwright-core/src/utils/{ => isomorphic}/manualPromise.ts (92%) rename packages/playwright-core/src/utils/{ => isomorphic}/multimap.ts (100%) rename packages/playwright-core/src/utils/{ => isomorphic}/rtti.ts (95%) rename packages/playwright-core/src/utils/{ => isomorphic}/semaphore.ts (100%) rename packages/playwright-core/src/utils/{ => isomorphic}/sequence.ts (100%) create mode 100644 packages/playwright-core/src/utils/isomorphic/time.ts rename packages/playwright-core/src/utils/{ => isomorphic}/timeoutRunner.ts (98%) rename packages/playwright-core/src/{protocol/transport.ts => utils/pipeTransport.ts} (95%) delete mode 100644 packages/playwright-core/src/utils/time.ts delete mode 100644 packages/playwright-core/src/utils/traceUtils.ts diff --git a/packages/playwright-core/src/DEPS.list b/packages/playwright-core/src/DEPS.list index 026473f98a..ec14e89070 100644 --- a/packages/playwright-core/src/DEPS.list +++ b/packages/playwright-core/src/DEPS.list @@ -14,4 +14,6 @@ utils/ client/ protocol/ utils/ -common/ \ No newline at end of file +utils/isomorphic +server/utils +common/ diff --git a/packages/playwright-core/src/cli/driver.ts b/packages/playwright-core/src/cli/driver.ts index 2b49b65ee7..1e16de00bf 100644 --- a/packages/playwright-core/src/cli/driver.ts +++ b/packages/playwright-core/src/cli/driver.ts @@ -19,7 +19,7 @@ import * as fs from 'fs'; import * as playwright from '../..'; -import { PipeTransport } from '../protocol/transport'; +import { PipeTransport } from '../utils/pipeTransport'; import { PlaywrightServer } from '../remote/playwrightServer'; import { DispatcherConnection, PlaywrightDispatcher, RootDispatcher, createPlaywright } from '../server'; import { gracefullyProcessExitDoNotHang } from '../server/utils/processLauncher'; diff --git a/packages/playwright-core/src/client/android.ts b/packages/playwright-core/src/client/android.ts index 7f062143fc..f6e0419c2c 100644 --- a/packages/playwright-core/src/client/android.ts +++ b/packages/playwright-core/src/client/android.ts @@ -22,9 +22,9 @@ import { TargetClosedError, isTargetClosedError } from './errors'; import { Events } from './events'; import { Waiter } from './waiter'; import { TimeoutSettings } from '../common/timeoutSettings'; -import { isRegExp, isString } from '../utils/rtti'; -import { monotonicTime } from '../utils/time'; -import { raceAgainstDeadline } from '../utils/timeoutRunner'; +import { isRegExp, isString } from '../utils/isomorphic/rtti'; +import { monotonicTime } from '../utils/isomorphic/time'; +import { raceAgainstDeadline } from '../utils/isomorphic/timeoutRunner'; import type { Page } from './page'; import type * as types from './types'; diff --git a/packages/playwright-core/src/client/browserContext.ts b/packages/playwright-core/src/client/browserContext.ts index d625135f73..7c0210ceaf 100644 --- a/packages/playwright-core/src/client/browserContext.ts +++ b/packages/playwright-core/src/client/browserContext.ts @@ -36,9 +36,9 @@ import { WebError } from './webError'; import { Worker } from './worker'; import { TimeoutSettings } from '../common/timeoutSettings'; import { mkdirIfNeeded } from '../utils/fileUtils'; -import { headersObjectToArray } from '../utils/headers'; +import { headersObjectToArray } from '../utils/isomorphic/headers'; import { urlMatchesEqual } from '../utils/isomorphic/urlMatch'; -import { isRegExp, isString } from '../utils/rtti'; +import { isRegExp, isString } from '../utils/isomorphic/rtti'; import { rewriteErrorMessage } from '../utils/stackTrace'; import type { BrowserType } from './browserType'; diff --git a/packages/playwright-core/src/client/browserType.ts b/packages/playwright-core/src/client/browserType.ts index 9afdb8dc0a..79d2fbd521 100644 --- a/packages/playwright-core/src/client/browserType.ts +++ b/packages/playwright-core/src/client/browserType.ts @@ -22,9 +22,9 @@ import { ChannelOwner } from './channelOwner'; import { envObjectToArray } from './clientHelper'; import { Events } from './events'; import { assert } from '../utils/debug'; -import { headersObjectToArray } from '../utils/headers'; -import { monotonicTime } from '../utils/time'; -import { raceAgainstDeadline } from '../utils/timeoutRunner'; +import { headersObjectToArray } from '../utils/isomorphic/headers'; +import { monotonicTime } from '../utils/isomorphic/time'; +import { raceAgainstDeadline } from '../utils/isomorphic/timeoutRunner'; import type { Playwright } from './playwright'; import type { ConnectOptions, LaunchOptions, LaunchPersistentContextOptions, LaunchServerOptions, Logger } from './types'; diff --git a/packages/playwright-core/src/client/clientHelper.ts b/packages/playwright-core/src/client/clientHelper.ts index 4ae343224a..3ffe01034b 100644 --- a/packages/playwright-core/src/client/clientHelper.ts +++ b/packages/playwright-core/src/client/clientHelper.ts @@ -15,7 +15,7 @@ * limitations under the License. */ -import { isString } from '../utils/rtti'; +import { isString } from '../utils/isomorphic/rtti'; import type * as types from './types'; import type { Platform } from '../utils/platform'; diff --git a/packages/playwright-core/src/client/elementHandle.ts b/packages/playwright-core/src/client/elementHandle.ts index e39e4413e7..6bca1c7e82 100644 --- a/packages/playwright-core/src/client/elementHandle.ts +++ b/packages/playwright-core/src/client/elementHandle.ts @@ -21,7 +21,7 @@ import { Frame } from './frame'; import { JSHandle, parseResult, serializeArgument } from './jsHandle'; import { assert } from '../utils/debug'; import { fileUploadSizeLimit, mkdirIfNeeded } from '../utils/fileUtils'; -import { isString } from '../utils/rtti'; +import { isString } from '../utils/isomorphic/rtti'; import { mime } from '../utilsBundle'; import { WritableStream } from './writableStream'; diff --git a/packages/playwright-core/src/client/errors.ts b/packages/playwright-core/src/client/errors.ts index 81f32080b7..5d1465261f 100644 --- a/packages/playwright-core/src/client/errors.ts +++ b/packages/playwright-core/src/client/errors.ts @@ -15,7 +15,7 @@ */ import { parseSerializedValue, serializeValue } from '../protocol/serializers'; -import { isError } from '../utils/rtti'; +import { isError } from '../utils/isomorphic/rtti'; import type { SerializedError } from '@protocol/channels'; diff --git a/packages/playwright-core/src/client/fetch.ts b/packages/playwright-core/src/client/fetch.ts index eba881a5ca..11c28e7c20 100644 --- a/packages/playwright-core/src/client/fetch.ts +++ b/packages/playwright-core/src/client/fetch.ts @@ -21,8 +21,8 @@ import { RawHeaders } from './network'; import { Tracing } from './tracing'; import { assert } from '../utils/debug'; import { mkdirIfNeeded } from '../utils/fileUtils'; -import { headersObjectToArray } from '../utils/headers'; -import { isString } from '../utils/rtti'; +import { headersObjectToArray } from '../utils/isomorphic/headers'; +import { isString } from '../utils/isomorphic/rtti'; import type { Playwright } from './playwright'; import type { ClientCertificate, FilePayload, Headers, SetStorageState, StorageState } from './types'; diff --git a/packages/playwright-core/src/client/locator.ts b/packages/playwright-core/src/client/locator.ts index 04cfa5fadf..5d0f0aa0c3 100644 --- a/packages/playwright-core/src/client/locator.ts +++ b/packages/playwright-core/src/client/locator.ts @@ -19,8 +19,8 @@ import { parseResult, serializeArgument } from './jsHandle'; import { asLocator } from '../utils/isomorphic/locatorGenerators'; import { getByAltTextSelector, getByLabelSelector, getByPlaceholderSelector, getByRoleSelector, getByTestIdSelector, getByTextSelector, getByTitleSelector } from '../utils/isomorphic/locatorUtils'; import { escapeForTextSelector } from '../utils/isomorphic/stringUtils'; -import { isString } from '../utils/rtti'; -import { monotonicTime } from '../utils/time'; +import { isString } from '../utils/isomorphic/rtti'; +import { monotonicTime } from '../utils/isomorphic/time'; import type { Frame } from './frame'; import type { FilePayload, FrameExpectParams, Rect, SelectOption, SelectOptionOptions, TimeoutOptions } from './types'; diff --git a/packages/playwright-core/src/client/network.ts b/packages/playwright-core/src/client/network.ts index ae7c7bb251..20675492eb 100644 --- a/packages/playwright-core/src/client/network.ts +++ b/packages/playwright-core/src/client/network.ts @@ -24,11 +24,11 @@ import { Frame } from './frame'; import { Waiter } from './waiter'; import { Worker } from './worker'; import { assert } from '../utils/debug'; -import { headersObjectToArray } from '../utils/headers'; +import { headersObjectToArray } from '../utils/isomorphic/headers'; import { urlMatches } from '../utils/isomorphic/urlMatch'; -import { LongStandingScope, ManualPromise } from '../utils/manualPromise'; -import { MultiMap } from '../utils/multimap'; -import { isRegExp, isString } from '../utils/rtti'; +import { LongStandingScope, ManualPromise } from '../utils/isomorphic/manualPromise'; +import { MultiMap } from '../utils/isomorphic/multimap'; +import { isRegExp, isString } from '../utils/isomorphic/rtti'; import { rewriteErrorMessage } from '../utils/stackTrace'; import { zones } from '../utils/zones'; import { mime } from '../utilsBundle'; diff --git a/packages/playwright-core/src/client/page.ts b/packages/playwright-core/src/client/page.ts index d4bb32ffbd..d71afce060 100644 --- a/packages/playwright-core/src/client/page.ts +++ b/packages/playwright-core/src/client/page.ts @@ -36,11 +36,11 @@ import { Worker } from './worker'; import { TimeoutSettings } from '../common/timeoutSettings'; import { assert } from '../utils/debug'; import { mkdirIfNeeded } from '../utils/fileUtils'; -import { headersObjectToArray } from '../utils/headers'; +import { headersObjectToArray } from '../utils/isomorphic/headers'; import { trimStringWithEllipsis } from '../utils/isomorphic/stringUtils'; import { urlMatches, urlMatchesEqual } from '../utils/isomorphic/urlMatch'; -import { LongStandingScope } from '../utils/manualPromise'; -import { isObject, isRegExp, isString } from '../utils/rtti'; +import { LongStandingScope } from '../utils/isomorphic/manualPromise'; +import { isObject, isRegExp, isString } from '../utils/isomorphic/rtti'; import type { BrowserContext } from './browserContext'; import type { Clock } from './clock'; diff --git a/packages/playwright-core/src/client/video.ts b/packages/playwright-core/src/client/video.ts index 993647dc72..1ff4065be7 100644 --- a/packages/playwright-core/src/client/video.ts +++ b/packages/playwright-core/src/client/video.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { ManualPromise } from '../utils/manualPromise'; +import { ManualPromise } from '../utils/isomorphic/manualPromise'; import type { Artifact } from './artifact'; import type { Connection } from './connection'; diff --git a/packages/playwright-core/src/client/worker.ts b/packages/playwright-core/src/client/worker.ts index ee9c2dcd6e..5a5a5fe246 100644 --- a/packages/playwright-core/src/client/worker.ts +++ b/packages/playwright-core/src/client/worker.ts @@ -18,7 +18,7 @@ import { ChannelOwner } from './channelOwner'; import { TargetClosedError } from './errors'; import { Events } from './events'; import { JSHandle, assertMaxArguments, parseResult, serializeArgument } from './jsHandle'; -import { LongStandingScope } from '../utils/manualPromise'; +import { LongStandingScope } from '../utils/isomorphic/manualPromise'; import type { BrowserContext } from './browserContext'; import type { Page } from './page'; diff --git a/packages/playwright-core/src/outofprocess.ts b/packages/playwright-core/src/outofprocess.ts index 3af4065e1d..8dcb8fa45a 100644 --- a/packages/playwright-core/src/outofprocess.ts +++ b/packages/playwright-core/src/outofprocess.ts @@ -18,8 +18,8 @@ import * as childProcess from 'child_process'; import * as path from 'path'; import { Connection } from './client/connection'; -import { PipeTransport } from './protocol/transport'; -import { ManualPromise } from './utils/manualPromise'; +import { PipeTransport } from './utils/pipeTransport'; +import { ManualPromise } from './utils/isomorphic/manualPromise'; import { nodePlatform } from './utils/platform'; import type { Playwright } from './client/playwright'; diff --git a/packages/playwright-core/src/remote/DEPS.list b/packages/playwright-core/src/remote/DEPS.list index 62660da37d..bf3843dca0 100644 --- a/packages/playwright-core/src/remote/DEPS.list +++ b/packages/playwright-core/src/remote/DEPS.list @@ -6,4 +6,5 @@ ../server/dispatchers/ ../server/utils/ ../utils/ +../utils/isomorphic ../utilsBundle.ts diff --git a/packages/playwright-core/src/remote/playwrightServer.ts b/packages/playwright-core/src/remote/playwrightServer.ts index 06193a618a..911fa1b97c 100644 --- a/packages/playwright-core/src/remote/playwrightServer.ts +++ b/packages/playwright-core/src/remote/playwrightServer.ts @@ -17,7 +17,7 @@ import { PlaywrightConnection } from './playwrightConnection'; import { createPlaywright } from '../server/playwright'; import { debugLogger } from '../utils/debugLogger'; -import { Semaphore } from '../utils/semaphore'; +import { Semaphore } from '../utils/isomorphic/semaphore'; import { WSServer } from '../server/utils/wsServer'; import { wrapInASCIIBox } from '../server/utils/ascii'; import { getPlaywrightVersion } from '../utils/userAgent'; diff --git a/packages/playwright-core/src/server/android/android.ts b/packages/playwright-core/src/server/android/android.ts index e47e115112..c3e2cbb22c 100644 --- a/packages/playwright-core/src/server/android/android.ts +++ b/packages/playwright-core/src/server/android/android.ts @@ -20,7 +20,7 @@ import * as os from 'os'; import * as path from 'path'; import { TimeoutSettings } from '../../common/timeoutSettings'; -import { PipeTransport } from '../../protocol/transport'; +import { PipeTransport } from '../../utils/pipeTransport'; import { createGuid, getPackageManagerExecCommand, isUnderTest, makeWaitForNextTask } from '../../utils'; import { RecentLogsCollector } from '../../utils/debugLogger'; import { debug } from '../../utilsBundle'; diff --git a/packages/playwright-core/src/server/artifact.ts b/packages/playwright-core/src/server/artifact.ts index 26b97d4d56..703e2d9e89 100644 --- a/packages/playwright-core/src/server/artifact.ts +++ b/packages/playwright-core/src/server/artifact.ts @@ -19,7 +19,7 @@ import * as fs from 'fs'; import { assert } from '../utils'; import { TargetClosedError } from './errors'; import { SdkObject } from './instrumentation'; -import { ManualPromise } from '../utils/manualPromise'; +import { ManualPromise } from '../utils/isomorphic/manualPromise'; type SaveCallback = (localPath: string, error?: Error) => Promise; type CancelCallback = () => Promise; diff --git a/packages/playwright-core/src/server/chromium/chromium.ts b/packages/playwright-core/src/server/chromium/chromium.ts index ff5c4a826c..7c520aa213 100644 --- a/packages/playwright-core/src/server/chromium/chromium.ts +++ b/packages/playwright-core/src/server/chromium/chromium.ts @@ -26,7 +26,7 @@ import { TimeoutSettings } from '../../common/timeoutSettings'; import { debugMode, headersArrayToObject, headersObjectToArray, } from '../../utils'; import { wrapInASCIIBox } from '../utils/ascii'; import { RecentLogsCollector } from '../../utils/debugLogger'; -import { ManualPromise } from '../../utils/manualPromise'; +import { ManualPromise } from '../../utils/isomorphic/manualPromise'; import { fetchData } from '../utils/network'; import { getUserAgent } from '../../utils/userAgent'; import { validateBrowserContextOptions } from '../browserContext'; diff --git a/packages/playwright-core/src/server/frames.ts b/packages/playwright-core/src/server/frames.ts index 2183d3f409..8be38f885f 100644 --- a/packages/playwright-core/src/server/frames.ts +++ b/packages/playwright-core/src/server/frames.ts @@ -32,7 +32,7 @@ import { isSessionClosedError } from './protocolError'; import { debugLogger } from '../utils/debugLogger'; import { eventsHelper } from '../utils/eventsHelper'; import { isInvalidSelectorError } from '../utils/isomorphic/selectorParser'; -import { ManualPromise } from '../utils/manualPromise'; +import { ManualPromise } from '../utils/isomorphic/manualPromise'; import type { ConsoleMessage } from './console'; import type { Dialog } from './dialog'; diff --git a/packages/playwright-core/src/server/har/harRecorder.ts b/packages/playwright-core/src/server/har/harRecorder.ts index 7cde24fa3a..94175de35c 100644 --- a/packages/playwright-core/src/server/har/harRecorder.ts +++ b/packages/playwright-core/src/server/har/harRecorder.ts @@ -20,7 +20,7 @@ import * as path from 'path'; import { Artifact } from '../artifact'; import { HarTracer } from './harTracer'; import { createGuid } from '../../utils'; -import { ManualPromise } from '../../utils/manualPromise'; +import { ManualPromise } from '../../utils/isomorphic/manualPromise'; import { yazl } from '../../zipBundle'; import type { BrowserContext } from '../browserContext'; diff --git a/packages/playwright-core/src/server/har/harTracer.ts b/packages/playwright-core/src/server/har/harTracer.ts index 0e3a66b938..d046962199 100644 --- a/packages/playwright-core/src/server/har/harTracer.ts +++ b/packages/playwright-core/src/server/har/harTracer.ts @@ -17,7 +17,7 @@ import { assert, calculateSha1, monotonicTime } from '../../utils'; import { getPlaywrightVersion, isTextualMimeType, urlMatches } from '../../utils'; import { eventsHelper } from '../../utils/eventsHelper'; -import { ManualPromise } from '../../utils/manualPromise'; +import { ManualPromise } from '../../utils/isomorphic/manualPromise'; import { mime } from '../../utilsBundle'; import { BrowserContext } from '../browserContext'; import { APIRequestContext } from '../fetch'; diff --git a/packages/playwright-core/src/server/javascript.ts b/packages/playwright-core/src/server/javascript.ts index 32ba84179e..a3d65f86a8 100644 --- a/packages/playwright-core/src/server/javascript.ts +++ b/packages/playwright-core/src/server/javascript.ts @@ -18,7 +18,7 @@ import { SdkObject } from './instrumentation'; import * as utilityScriptSource from '../generated/utilityScriptSource'; import { isUnderTest } from '../utils'; import { serializeAsCallArgument } from './isomorphic/utilityScriptSerializers'; -import { LongStandingScope } from '../utils/manualPromise'; +import { LongStandingScope } from '../utils/isomorphic/manualPromise'; import type * as dom from './dom'; import type { UtilityScript } from './injected/utilityScript'; diff --git a/packages/playwright-core/src/server/network.ts b/packages/playwright-core/src/server/network.ts index 81e23abd82..dfee496fc2 100644 --- a/packages/playwright-core/src/server/network.ts +++ b/packages/playwright-core/src/server/network.ts @@ -18,7 +18,7 @@ import { assert } from '../utils'; import { BrowserContext } from './browserContext'; import { APIRequestContext } from './fetch'; import { SdkObject } from './instrumentation'; -import { ManualPromise } from '../utils/manualPromise'; +import { ManualPromise } from '../utils/isomorphic/manualPromise'; import type * as contexts from './browserContext'; import type * as frames from './frames'; diff --git a/packages/playwright-core/src/server/page.ts b/packages/playwright-core/src/server/page.ts index ac7f6dfd81..730f1210de 100644 --- a/packages/playwright-core/src/server/page.ts +++ b/packages/playwright-core/src/server/page.ts @@ -34,7 +34,7 @@ import { asLocator } from '../utils'; import { getComparator } from './utils/comparators'; import { debugLogger } from '../utils/debugLogger'; import { isInvalidSelectorError } from '../utils/isomorphic/selectorParser'; -import { ManualPromise } from '../utils/manualPromise'; +import { ManualPromise } from '../utils/isomorphic/manualPromise'; import type { Artifact } from './artifact'; import type * as dom from './dom'; diff --git a/packages/playwright-core/src/server/progress.ts b/packages/playwright-core/src/server/progress.ts index 1b18089233..9766c66ebd 100644 --- a/packages/playwright-core/src/server/progress.ts +++ b/packages/playwright-core/src/server/progress.ts @@ -16,7 +16,7 @@ import { TimeoutError } from './errors'; import { assert, monotonicTime } from '../utils'; -import { ManualPromise } from '../utils/manualPromise'; +import { ManualPromise } from '../utils/isomorphic/manualPromise'; import type { CallMetadata, Instrumentation, SdkObject } from './instrumentation'; import type { Progress as CommonProgress } from '../common/progress'; diff --git a/packages/playwright-core/src/server/recorder/contextRecorder.ts b/packages/playwright-core/src/server/recorder/contextRecorder.ts index 5cc3e9abae..cede7bb28a 100644 --- a/packages/playwright-core/src/server/recorder/contextRecorder.ts +++ b/packages/playwright-core/src/server/recorder/contextRecorder.ts @@ -19,7 +19,7 @@ import { EventEmitter } from 'events'; import { RecorderCollection } from './recorderCollection'; import * as recorderSource from '../../generated/pollingRecorderSource'; import { eventsHelper, monotonicTime, quoteCSSAttributeValue } from '../../utils'; -import { raceAgainstDeadline } from '../../utils/timeoutRunner'; +import { raceAgainstDeadline } from '../../utils/isomorphic/timeoutRunner'; import { BrowserContext } from '../browserContext'; import { languageSet } from '../codegen/languages'; import { Frame } from '../frames'; diff --git a/packages/playwright-core/src/server/recorder/recorderCollection.ts b/packages/playwright-core/src/server/recorder/recorderCollection.ts index 1780502d7d..454fa05b90 100644 --- a/packages/playwright-core/src/server/recorder/recorderCollection.ts +++ b/packages/playwright-core/src/server/recorder/recorderCollection.ts @@ -19,7 +19,7 @@ import { EventEmitter } from 'events'; import { performAction } from './recorderRunner'; import { collapseActions } from './recorderUtils'; import { isUnderTest } from '../../utils/debug'; -import { monotonicTime } from '../../utils/time'; +import { monotonicTime } from '../../utils/isomorphic/time'; import type { Signal } from '../../../../recorder/src/actions'; import type { Frame } from '../frames'; diff --git a/packages/playwright-core/src/server/registry/browserFetcher.ts b/packages/playwright-core/src/server/registry/browserFetcher.ts index e7ffda483f..16cab16db1 100644 --- a/packages/playwright-core/src/server/registry/browserFetcher.ts +++ b/packages/playwright-core/src/server/registry/browserFetcher.ts @@ -21,7 +21,7 @@ import * as os from 'os'; import * as path from 'path'; import { debugLogger } from '../../utils/debugLogger'; -import { ManualPromise } from '../../utils/manualPromise'; +import { ManualPromise } from '../../utils/isomorphic/manualPromise'; import { getUserAgent } from '../../utils/userAgent'; import { colors, progress as ProgressBar } from '../../utilsBundle'; import { existsAsync } from '../utils/fileUtils'; diff --git a/packages/playwright-core/src/server/registry/oopDownloadBrowserMain.ts b/packages/playwright-core/src/server/registry/oopDownloadBrowserMain.ts index ef6348aab2..bda904f47a 100644 --- a/packages/playwright-core/src/server/registry/oopDownloadBrowserMain.ts +++ b/packages/playwright-core/src/server/registry/oopDownloadBrowserMain.ts @@ -17,7 +17,7 @@ import * as fs from 'fs'; import * as path from 'path'; -import { ManualPromise } from '../../utils/manualPromise'; +import { ManualPromise } from '../../utils/isomorphic/manualPromise'; import { httpRequest } from '../utils/network'; import { extract } from '../../zipBundle'; diff --git a/packages/playwright-core/src/server/screenshotter.ts b/packages/playwright-core/src/server/screenshotter.ts index 88870b8900..b32f51a6de 100644 --- a/packages/playwright-core/src/server/screenshotter.ts +++ b/packages/playwright-core/src/server/screenshotter.ts @@ -17,7 +17,7 @@ import { helper } from './helper'; import { assert } from '../utils'; -import { MultiMap } from '../utils/multimap'; +import { MultiMap } from '../utils/isomorphic/multimap'; import type * as dom from './dom'; import type { Frame } from './frames'; diff --git a/packages/playwright-core/src/server/utils/DEPS.list b/packages/playwright-core/src/server/utils/DEPS.list index 53cad9639a..8d1b7a30f2 100644 --- a/packages/playwright-core/src/server/utils/DEPS.list +++ b/packages/playwright-core/src/server/utils/DEPS.list @@ -1,9 +1,9 @@ [*] ../../utils +../../utils/isomorphic ../../utilsBundle.ts ../../zipBundle.ts [comparators.ts] ./image_tools ../../third_party/pixelmatch - diff --git a/packages/playwright-core/src/server/utils/fileUtils.ts b/packages/playwright-core/src/server/utils/fileUtils.ts index 5f196963b7..0a0a95d2a1 100644 --- a/packages/playwright-core/src/server/utils/fileUtils.ts +++ b/packages/playwright-core/src/server/utils/fileUtils.ts @@ -17,7 +17,7 @@ import * as fs from 'fs'; import * as path from 'path'; -import { ManualPromise } from '../../utils/manualPromise'; +import { ManualPromise } from '../../utils/isomorphic/manualPromise'; import { yazl } from '../../zipBundle'; import type { EventEmitter } from 'events'; diff --git a/packages/playwright-core/src/server/utils/happyEyeballs.ts b/packages/playwright-core/src/server/utils/happyEyeballs.ts index ba6188f97c..a5c6087513 100644 --- a/packages/playwright-core/src/server/utils/happyEyeballs.ts +++ b/packages/playwright-core/src/server/utils/happyEyeballs.ts @@ -21,8 +21,8 @@ import * as net from 'net'; import * as tls from 'tls'; import { assert } from '../../utils/debug'; -import { ManualPromise } from '../../utils/manualPromise'; -import { monotonicTime } from '../../utils/time'; +import { ManualPromise } from '../../utils/isomorphic/manualPromise'; +import { monotonicTime } from '../../utils/isomorphic/time'; // Implementation(partial) of Happy Eyeballs 2 algorithm described in // https://www.rfc-editor.org/rfc/rfc8305 diff --git a/packages/playwright-core/src/server/utils/httpServer.ts b/packages/playwright-core/src/server/utils/httpServer.ts index ee170eca33..6308ad67fa 100644 --- a/packages/playwright-core/src/server/utils/httpServer.ts +++ b/packages/playwright-core/src/server/utils/httpServer.ts @@ -20,7 +20,7 @@ import * as path from 'path'; import { mime, wsServer } from '../../utilsBundle'; import { createGuid } from '../../utils/crypto'; import { assert } from '../../utils/debug'; -import { ManualPromise } from '../../utils/manualPromise'; +import { ManualPromise } from '../../utils/isomorphic/manualPromise'; import { createHttpServer } from './network'; import type http from 'http'; diff --git a/packages/playwright-core/src/utils.ts b/packages/playwright-core/src/utils.ts index 930acae092..0bfd82bd96 100644 --- a/packages/playwright-core/src/utils.ts +++ b/packages/playwright-core/src/utils.ts @@ -14,27 +14,28 @@ * limitations under the License. */ +export * from './utils/isomorphic/manualPromise'; +export * from './utils/isomorphic/locatorGenerators'; +export * from './utils/isomorphic/mimeType'; +export * from './utils/isomorphic/stringUtils'; +export * from './utils/isomorphic/urlMatch'; +export * from './utils/isomorphic/multimap'; +export * from './utils/isomorphic/rtti'; +export * from './utils/isomorphic/time'; +export * from './utils/isomorphic/timeoutRunner'; + export * from './utils/crypto'; export * from './utils/debug'; export * from './utils/debugLogger'; export * from './utils/env'; export * from './utils/eventsHelper'; export * from './utils/expectUtils'; -export * from './utils/headers'; +export * from './utils/isomorphic/headers'; export * from './utils/hostPlatform'; -export * from './utils/manualPromise'; -export * from './utils/isomorphic/locatorGenerators'; -export * from './utils/isomorphic/mimeType'; -export * from './utils/isomorphic/stringUtils'; -export * from './utils/isomorphic/urlMatch'; -export * from './utils/multimap'; -export * from './utils/rtti'; -export * from './utils/semaphore'; +export * from './utils/platform'; +export * from './utils/isomorphic/semaphore'; export * from './utils/stackTrace'; export * from './utils/task'; -export * from './utils/time'; -export * from './utils/timeoutRunner'; -export * from './utils/traceUtils'; export * from './utils/userAgent'; export * from './utils/zipFile'; export * from './utils/zones'; diff --git a/packages/playwright-core/src/utils/DEPS.list b/packages/playwright-core/src/utils/DEPS.list index 0e2297dfdb..8a14701d4d 100644 --- a/packages/playwright-core/src/utils/DEPS.list +++ b/packages/playwright-core/src/utils/DEPS.list @@ -1,4 +1,6 @@ [*] ./ +./isomorphic ../utilsBundle.ts ../zipBundle.ts +../utils/isomorphic \ No newline at end of file diff --git a/packages/playwright-core/src/utils/expectUtils.ts b/packages/playwright-core/src/utils/expectUtils.ts index f39af23cee..ebbdf8e867 100644 --- a/packages/playwright-core/src/utils/expectUtils.ts +++ b/packages/playwright-core/src/utils/expectUtils.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { isRegExp, isString } from './rtti'; +import { isRegExp, isString } from './isomorphic/rtti'; import type { ExpectedTextValue } from '@protocol/channels'; diff --git a/packages/playwright-core/src/utils/headers.ts b/packages/playwright-core/src/utils/isomorphic/headers.ts similarity index 100% rename from packages/playwright-core/src/utils/headers.ts rename to packages/playwright-core/src/utils/isomorphic/headers.ts diff --git a/packages/playwright-core/src/utils/manualPromise.ts b/packages/playwright-core/src/utils/isomorphic/manualPromise.ts similarity index 92% rename from packages/playwright-core/src/utils/manualPromise.ts rename to packages/playwright-core/src/utils/isomorphic/manualPromise.ts index 467b8de0db..a5034e05ec 100644 --- a/packages/playwright-core/src/utils/manualPromise.ts +++ b/packages/playwright-core/src/utils/isomorphic/manualPromise.ts @@ -14,8 +14,6 @@ * limitations under the License. */ -import { captureRawStack } from './stackTrace'; - export class ManualPromise extends Promise { private _resolve!: (t: T) => void; private _reject!: (e: Error) => void; @@ -118,3 +116,12 @@ function cloneError(error: Error, frames: string[]) { clone.stack = [error.name + ':' + error.message, ...frames].join('\n'); return clone; } + +function captureRawStack(): string[] { + const stackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 50; + const error = new Error(); + const stack = error.stack || ''; + Error.stackTraceLimit = stackTraceLimit; + return stack.split('\n'); +} diff --git a/packages/playwright-core/src/utils/multimap.ts b/packages/playwright-core/src/utils/isomorphic/multimap.ts similarity index 100% rename from packages/playwright-core/src/utils/multimap.ts rename to packages/playwright-core/src/utils/isomorphic/multimap.ts diff --git a/packages/playwright-core/src/utils/rtti.ts b/packages/playwright-core/src/utils/isomorphic/rtti.ts similarity index 95% rename from packages/playwright-core/src/utils/rtti.ts rename to packages/playwright-core/src/utils/isomorphic/rtti.ts index a18d3a450a..0bcaef0748 100644 --- a/packages/playwright-core/src/utils/rtti.ts +++ b/packages/playwright-core/src/utils/isomorphic/rtti.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -export { isString } from './isomorphic/stringUtils'; +export { isString } from './stringUtils'; export function isRegExp(obj: any): obj is RegExp { return obj instanceof RegExp || Object.prototype.toString.call(obj) === '[object RegExp]'; diff --git a/packages/playwright-core/src/utils/semaphore.ts b/packages/playwright-core/src/utils/isomorphic/semaphore.ts similarity index 100% rename from packages/playwright-core/src/utils/semaphore.ts rename to packages/playwright-core/src/utils/isomorphic/semaphore.ts diff --git a/packages/playwright-core/src/utils/sequence.ts b/packages/playwright-core/src/utils/isomorphic/sequence.ts similarity index 100% rename from packages/playwright-core/src/utils/sequence.ts rename to packages/playwright-core/src/utils/isomorphic/sequence.ts diff --git a/packages/playwright-core/src/utils/isomorphic/time.ts b/packages/playwright-core/src/utils/isomorphic/time.ts new file mode 100644 index 0000000000..625fd18805 --- /dev/null +++ b/packages/playwright-core/src/utils/isomorphic/time.ts @@ -0,0 +1,19 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function monotonicTime(): number { + return (performance.now() * 1000 | 0) / 1000; +} diff --git a/packages/playwright-core/src/utils/timeoutRunner.ts b/packages/playwright-core/src/utils/isomorphic/timeoutRunner.ts similarity index 98% rename from packages/playwright-core/src/utils/timeoutRunner.ts rename to packages/playwright-core/src/utils/isomorphic/timeoutRunner.ts index e8f128b9f8..e8016ddb49 100644 --- a/packages/playwright-core/src/utils/timeoutRunner.ts +++ b/packages/playwright-core/src/utils/isomorphic/timeoutRunner.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { monotonicTime } from '../utils'; +import { monotonicTime } from './time'; export async function raceAgainstDeadline(cb: () => Promise, deadline: number): Promise<{ result: T, timedOut: false } | { timedOut: true }> { let timer: NodeJS.Timeout | undefined; diff --git a/packages/playwright-core/src/utils/isomorphic/traceUtils.ts b/packages/playwright-core/src/utils/isomorphic/traceUtils.ts index edb1e1c660..f077cc5c4b 100644 --- a/packages/playwright-core/src/utils/isomorphic/traceUtils.ts +++ b/packages/playwright-core/src/utils/isomorphic/traceUtils.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import type { StackFrame } from '@protocol/channels'; +import type { ClientSideCallMetadata, StackFrame } from '@protocol/channels'; export type SerializedStackFrame = [number, number, number, string]; export type SerializedStack = [number, SerializedStackFrame[]]; @@ -33,3 +33,24 @@ export function parseClientSideCallMetadata(data: SerializedClientSideCallMetada } return result; } + +export function serializeClientSideCallMetadata(metadatas: ClientSideCallMetadata[]): SerializedClientSideCallMetadata { + const fileNames = new Map(); + const stacks: SerializedStack[] = []; + for (const m of metadatas) { + if (!m.stack || !m.stack.length) + continue; + const stack: SerializedStackFrame[] = []; + for (const frame of m.stack) { + let ordinal = fileNames.get(frame.file); + if (typeof ordinal !== 'number') { + ordinal = fileNames.size; + fileNames.set(frame.file, ordinal); + } + const stackFrame: SerializedStackFrame = [ordinal, frame.line || 0, frame.column || 0, frame.function || '']; + stack.push(stackFrame); + } + stacks.push([m.id, stack]); + } + return { files: [...fileNames.keys()], stacks }; +} diff --git a/packages/playwright-core/src/utils/localUtils.ts b/packages/playwright-core/src/utils/localUtils.ts index d94a7da27e..91162a0301 100644 --- a/packages/playwright-core/src/utils/localUtils.ts +++ b/packages/playwright-core/src/utils/localUtils.ts @@ -20,11 +20,12 @@ import * as path from 'path'; import { removeFolders } from './fileUtils'; import { HarBackend } from './harBackend'; -import { ManualPromise } from './manualPromise'; +import { ManualPromise } from './isomorphic/manualPromise'; import { ZipFile } from './zipFile'; import { yauzl, yazl } from '../zipBundle'; -import { serializeClientSideCallMetadata } from '../utils'; -import { assert, calculateSha1 } from '../utils'; +import { serializeClientSideCallMetadata } from '../utils/isomorphic/traceUtils'; +import { assert } from '../utils/debug'; +import { calculateSha1 } from '../utils/crypto'; import type { Platform } from './platform'; import type * as channels from '@protocol/channels'; diff --git a/packages/playwright-core/src/protocol/transport.ts b/packages/playwright-core/src/utils/pipeTransport.ts similarity index 95% rename from packages/playwright-core/src/protocol/transport.ts rename to packages/playwright-core/src/utils/pipeTransport.ts index e647100c63..64b1d80e8f 100644 --- a/packages/playwright-core/src/protocol/transport.ts +++ b/packages/playwright-core/src/utils/pipeTransport.ts @@ -14,18 +14,18 @@ * limitations under the License. */ -import { makeWaitForNextTask } from '../utils'; +import { makeWaitForNextTask } from './task'; -export interface WritableStream { +interface WritableStream { write(data: Buffer): void; } -export interface ReadableStream { +interface ReadableStream { on(event: 'data', callback: (b: Buffer) => void): void; on(event: 'close', callback: () => void): void; } -export interface ClosableStream { +interface ClosableStream { close(): void; } diff --git a/packages/playwright-core/src/utils/stackTrace.ts b/packages/playwright-core/src/utils/stackTrace.ts index fb97115035..d3331698d1 100644 --- a/packages/playwright-core/src/utils/stackTrace.ts +++ b/packages/playwright-core/src/utils/stackTrace.ts @@ -17,15 +17,13 @@ import * as path from 'path'; import { colors } from '../utilsBundle'; -import { findRepeatedSubsequences } from './sequence'; -import { StackUtils } from './stackUtils'; +import { findRepeatedSubsequences } from './isomorphic/sequence'; +import { parseStackFrame } from './stackUtils'; import type { StackFrame } from '@protocol/channels'; -const stackUtils = new StackUtils(); - export function parseStackTraceLine(line: string): StackFrame | null { - const frame = stackUtils.parseLine(line); + const frame = parseStackFrame(line); if (!frame) return null; if (!process.env.PWDEBUGIMPL && (frame.file?.startsWith('internal') || frame.file?.startsWith('node:'))) diff --git a/packages/playwright-core/src/utils/stackUtils.ts b/packages/playwright-core/src/utils/stackUtils.ts index 0be4675a86..024b6fe8d0 100644 --- a/packages/playwright-core/src/utils/stackUtils.ts +++ b/packages/playwright-core/src/utils/stackUtils.ts @@ -35,84 +35,82 @@ type StackData = { evalFile?: string | undefined; }; -export class StackUtils { - parseLine(line: string) { - const match = line && line.match(re); - if (!match) - return null; +export function parseStackFrame(line: string): StackData | null { + const match = line && line.match(re); + if (!match) + return null; - const ctor = match[1] === 'new'; - let fname = match[2]; - const evalOrigin = match[3]; - const evalFile = match[4]; - const evalLine = Number(match[5]); - const evalCol = Number(match[6]); - let file = match[7]; - const lnum = match[8]; - const col = match[9]; - const native = match[10] === 'native'; - const closeParen = match[11] === ')'; - let method; + const ctor = match[1] === 'new'; + let fname = match[2]; + const evalOrigin = match[3]; + const evalFile = match[4]; + const evalLine = Number(match[5]); + const evalCol = Number(match[6]); + let file = match[7]; + const lnum = match[8]; + const col = match[9]; + const native = match[10] === 'native'; + const closeParen = match[11] === ')'; + let method; - const res: StackData = {}; + const res: StackData = {}; - if (lnum) - res.line = Number(lnum); + if (lnum) + res.line = Number(lnum); - if (col) - res.column = Number(col); + if (col) + res.column = Number(col); - if (closeParen && file) { - // make sure parens are balanced - // if we have a file like "asdf) [as foo] (xyz.js", then odds are - // that the fname should be += " (asdf) [as foo]" and the file - // should be just "xyz.js" - // walk backwards from the end to find the last unbalanced ( - let closes = 0; - for (let i = file.length - 1; i > 0; i--) { - if (file.charAt(i) === ')') { - closes++; - } else if (file.charAt(i) === '(' && file.charAt(i - 1) === ' ') { - closes--; - if (closes === -1 && file.charAt(i - 1) === ' ') { - const before = file.slice(0, i - 1); - const after = file.slice(i + 1); - file = after; - fname += ` (${before}`; - break; - } + if (closeParen && file) { + // make sure parens are balanced + // if we have a file like "asdf) [as foo] (xyz.js", then odds are + // that the fname should be += " (asdf) [as foo]" and the file + // should be just "xyz.js" + // walk backwards from the end to find the last unbalanced ( + let closes = 0; + for (let i = file.length - 1; i > 0; i--) { + if (file.charAt(i) === ')') { + closes++; + } else if (file.charAt(i) === '(' && file.charAt(i - 1) === ' ') { + closes--; + if (closes === -1 && file.charAt(i - 1) === ' ') { + const before = file.slice(0, i - 1); + const after = file.slice(i + 1); + file = after; + fname += ` (${before}`; + break; } } } - - if (fname) { - const methodMatch = fname.match(methodRe); - if (methodMatch) { - fname = methodMatch[1]; - method = methodMatch[2]; - } - } - - setFile(res, file); - - if (ctor) - res.isConstructor = true; - - if (evalOrigin) { - res.evalOrigin = evalOrigin; - res.evalLine = evalLine; - res.evalColumn = evalCol; - res.evalFile = evalFile && evalFile.replace(/\\/g, '/'); - } - - if (native) - res.native = true; - if (fname) - res.function = fname; - if (method && fname !== method) - res.method = method; - return res; } + + if (fname) { + const methodMatch = fname.match(methodRe); + if (methodMatch) { + fname = methodMatch[1]; + method = methodMatch[2]; + } + } + + setFile(res, file); + + if (ctor) + res.isConstructor = true; + + if (evalOrigin) { + res.evalOrigin = evalOrigin; + res.evalLine = evalLine; + res.evalColumn = evalCol; + res.evalFile = evalFile && evalFile.replace(/\\/g, '/'); + } + + if (native) + res.native = true; + if (fname) + res.function = fname; + if (method && fname !== method) + res.method = method; + return res; } function setFile(result: StackData, filename: string) { diff --git a/packages/playwright-core/src/utils/time.ts b/packages/playwright-core/src/utils/time.ts deleted file mode 100644 index d00ee62e82..0000000000 --- a/packages/playwright-core/src/utils/time.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// The `process.hrtime()` returns a time from some arbitrary -// date in the past; on certain systems, this is the time from the system boot. -// The `monotonicTime()` converts this to milliseconds. -// -// For a Linux server with uptime of 36 days, the `monotonicTime()` value -// will be 36 * 86400 * 1000 = 3_110_400_000, which is larger than -// the maximum value that `setTimeout` accepts as an argument: 2_147_483_647. -// -// To make the `monotonicTime()` a reasonable value, we anchor -// it to the time of the first import of this utility. -const initialTime = process.hrtime(); - -export function monotonicTime(): number { - const [seconds, nanoseconds] = process.hrtime(initialTime); - return seconds * 1000 + (nanoseconds / 1000 | 0) / 1000; -} diff --git a/packages/playwright-core/src/utils/traceUtils.ts b/packages/playwright-core/src/utils/traceUtils.ts deleted file mode 100644 index c6ecc7988b..0000000000 --- a/packages/playwright-core/src/utils/traceUtils.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import type { SerializedClientSideCallMetadata, SerializedStack, SerializedStackFrame } from './isomorphic/traceUtils'; -import type { ClientSideCallMetadata } from '@protocol/channels'; - -export function serializeClientSideCallMetadata(metadatas: ClientSideCallMetadata[]): SerializedClientSideCallMetadata { - const fileNames = new Map(); - const stacks: SerializedStack[] = []; - for (const m of metadatas) { - if (!m.stack || !m.stack.length) - continue; - const stack: SerializedStackFrame[] = []; - for (const frame of m.stack) { - let ordinal = fileNames.get(frame.file); - if (typeof ordinal !== 'number') { - ordinal = fileNames.size; - fileNames.set(frame.file, ordinal); - } - const stackFrame: SerializedStackFrame = [ordinal, frame.line || 0, frame.column || 0, frame.function || '']; - stack.push(stackFrame); - } - stacks.push([m.id, stack]); - } - return { files: [...fileNames.keys()], stacks }; -} diff --git a/packages/playwright/src/util.ts b/packages/playwright/src/util.ts index aa575710e5..803aa73f6b 100644 --- a/packages/playwright/src/util.ts +++ b/packages/playwright/src/util.ts @@ -19,9 +19,7 @@ import * as path from 'path'; import * as url from 'url'; import util from 'util'; -import { sanitizeForFilePath } from 'playwright-core/lib/utils'; -import { calculateSha1, formatCallLog, isRegExp, isString, stringifyStackFrames } from 'playwright-core/lib/utils'; -import { parseStackTraceLine } from 'playwright-core/lib/utils'; +import { parseStackTraceLine, sanitizeForFilePath, calculateSha1, formatCallLog, isRegExp, isString, stringifyStackFrames } from 'playwright-core/lib/utils'; import { debug, mime, minimatch } from 'playwright-core/lib/utilsBundle'; import type { Location } from './../types/testReporter'; diff --git a/tests/library/events/remove-all-listeners-wait.spec.ts b/tests/library/events/remove-all-listeners-wait.spec.ts index 1f8dcc8dd0..e5b4bf2dc5 100644 --- a/tests/library/events/remove-all-listeners-wait.spec.ts +++ b/tests/library/events/remove-all-listeners-wait.spec.ts @@ -15,7 +15,7 @@ * limitations under the License. */ -import { ManualPromise } from '../../../packages/playwright-core/lib/utils/manualPromise'; +import { ManualPromise } from '../../../packages/playwright-core/lib/utils/isomorphic/manualPromise'; import { EventEmitter } from '../../../packages/playwright-core/lib/client/eventEmitter'; import { test, expect } from '@playwright/test'; diff --git a/tests/library/unit/sequence.spec.ts b/tests/library/unit/sequence.spec.ts index 624722753e..e0decd4d84 100644 --- a/tests/library/unit/sequence.spec.ts +++ b/tests/library/unit/sequence.spec.ts @@ -16,7 +16,7 @@ import { test as it, expect } from '@playwright/test'; -import { findRepeatedSubsequences } from '../../../packages/playwright-core/lib/utils/sequence'; +import { findRepeatedSubsequences } from '../../../packages/playwright-core/lib/utils/isomorphic/sequence'; it('should return an empty array when the input is empty', () => { const input = []; diff --git a/tests/page/page-leaks.spec.ts b/tests/page/page-leaks.spec.ts index abd33e651e..90f78d83a9 100644 --- a/tests/page/page-leaks.spec.ts +++ b/tests/page/page-leaks.spec.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { MultiMap } from '../../packages/playwright-core/lib/utils/multimap'; +import { MultiMap } from '../../packages/playwright-core/lib/utils/isomorphic/multimap'; import { test, expect } from './pageTest'; function leakedJSHandles(): string { diff --git a/tests/page/page-listeners.spec.ts b/tests/page/page-listeners.spec.ts index c22be64553..495ecf36c7 100644 --- a/tests/page/page-listeners.spec.ts +++ b/tests/page/page-listeners.spec.ts @@ -15,7 +15,7 @@ * limitations under the License. */ -import { ManualPromise } from '../../packages/playwright-core/lib/utils/manualPromise'; +import { ManualPromise } from '../../packages/playwright-core/lib/utils/isomorphic/manualPromise'; import { test as it, expect } from './pageTest'; // This test is mostly for type checking, the actual tests are in the library/events. diff --git a/tests/playwright-test/ui-mode-test-progress.spec.ts b/tests/playwright-test/ui-mode-test-progress.spec.ts index f2f01a79ce..1b397f8f9a 100644 --- a/tests/playwright-test/ui-mode-test-progress.spec.ts +++ b/tests/playwright-test/ui-mode-test-progress.spec.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { ManualPromise } from '../../packages/playwright-core/lib/utils/manualPromise'; +import { ManualPromise } from '../../packages/playwright-core/lib/utils/isomorphic/manualPromise'; import { test, expect, retries, dumpTestTree } from './ui-mode-fixtures'; test.describe.configure({ mode: 'parallel', retries }); From 148af215401995f37efdef9ed0f13dcbabbe6a39 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Wed, 12 Feb 2025 10:53:03 -0800 Subject: [PATCH 09/13] chore(bidi): implement getOwnerFrame (#34755) --- .../playwright-core/src/server/bidi/bidiPage.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/playwright-core/src/server/bidi/bidiPage.ts b/packages/playwright-core/src/server/bidi/bidiPage.ts index dd2d276c18..82e57d8654 100644 --- a/packages/playwright-core/src/server/bidi/bidiPage.ts +++ b/packages/playwright-core/src/server/bidi/bidiPage.ts @@ -423,7 +423,22 @@ export class BidiPage implements PageDelegate { } async getOwnerFrame(handle: dom.ElementHandle): Promise { - throw new Error('Method not implemented.'); + // TODO: switch to utility world? + const windowHandle = await handle.evaluateHandle(node => { + const doc = node.ownerDocument ?? node as Document; + return doc.defaultView; + }); + if (!windowHandle) + return null; + if (!windowHandle._objectId) + return null; + const executionContext = toBidiExecutionContext(windowHandle._context as dom.FrameExecutionContext); + const contentWindow = await executionContext.rawCallFunction('e => e', { handle: windowHandle._objectId }); + if (contentWindow.type === 'window') { + const frameId = contentWindow.value.context; + return frameId; + } + return null; } isElementHandle(remoteObject: bidi.Script.RemoteValue): boolean { From 0bd3a99f04aa5fcb200fef8cd47ef45e45bf45e3 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Wed, 12 Feb 2025 12:28:19 -0800 Subject: [PATCH 10/13] tests: put filechooser and setInputFiles tests into separate files (#34756) --- tests/page/page-filechooser.spec.ts | 368 ++++++++++++++++++++ tests/page/page-set-input-files.spec.ts | 432 +++--------------------- 2 files changed, 416 insertions(+), 384 deletions(-) create mode 100644 tests/page/page-filechooser.spec.ts diff --git a/tests/page/page-filechooser.spec.ts b/tests/page/page-filechooser.spec.ts new file mode 100644 index 0000000000..7fc8cf5500 --- /dev/null +++ b/tests/page/page-filechooser.spec.ts @@ -0,0 +1,368 @@ +/** + * Copyright 2017 Google Inc. All rights reserved. + * Modifications copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { test, expect } from './pageTest'; +import { attachFrame } from '../config/utils'; + +import fs from 'fs'; +import formidable from 'formidable'; + +test('should upload multiple large files', async ({ page, server, isAndroid, isWebView2, mode }, testInfo) => { + test.skip(isAndroid); + test.skip(isWebView2); + test.skip(mode.startsWith('service')); + test.slow(); + + const filesCount = 10; + await page.goto(server.PREFIX + '/input/fileupload-multi.html'); + const uploadFile = testInfo.outputPath('50MB_1.zip'); + const str = 'A'.repeat(1024); + const stream = fs.createWriteStream(uploadFile); + // 49 is close to the actual limit + for (let i = 0; i < 49 * 1024; i++) { + await new Promise((fulfill, reject) => { + stream.write(str, err => { + if (err) + reject(err); + else + fulfill(); + }); + }); + } + await new Promise(f => stream.end(f)); + const input = page.locator('input[type="file"]'); + const uploadFiles = [uploadFile]; + for (let i = 2; i <= filesCount; i++) { + const dstFile = testInfo.outputPath(`50MB_${i}.zip`); + fs.copyFileSync(uploadFile, dstFile); + uploadFiles.push(dstFile); + } + const fileChooserPromise = page.waitForEvent('filechooser'); + await input.click(); + const fileChooser = await fileChooserPromise; + await fileChooser.setFiles(uploadFiles); + const filesLen = await page.evaluate('document.getElementsByTagName("input")[0].files.length'); + expect(fileChooser.isMultiple()).toBe(true); + expect(filesLen).toEqual(filesCount); + await Promise.all(uploadFiles.map(path => fs.promises.unlink(path))); +}); + +test('should emit event once', async ({ page, server }) => { + await page.setContent(``); + const [chooser] = await Promise.all([ + new Promise(f => page.once('filechooser', f)), + page.click('input'), + ]); + expect(chooser).toBeTruthy(); +}); + +test('should emit event via prepend', async ({ page, server }) => { + await page.setContent(``); + const [chooser] = await Promise.all([ + new Promise(f => page.prependListener('filechooser', f)), + page.click('input'), + ]); + expect(chooser).toBeTruthy(); +}); + +test('should emit event for iframe', async ({ page, server }) => { + const frame = await attachFrame(page, 'frame1', server.EMPTY_PAGE); + await frame.setContent(``); + const [chooser] = await Promise.all([ + new Promise(f => page.once('filechooser', f)), + frame.click('input'), + ]); + expect(chooser).toBeTruthy(); +}); + +test('should emit event on/off', async ({ page, server }) => { + await page.setContent(``); + const [chooser] = await Promise.all([ + new Promise(f => { + const listener = chooser => { + page.off('filechooser', listener); + f(chooser); + }; + page.on('filechooser', listener); + }), + page.click('input'), + ]); + expect(chooser).toBeTruthy(); +}); + +test('should emit event addListener/removeListener', async ({ page, server }) => { + await page.setContent(``); + const [chooser] = await Promise.all([ + new Promise(f => { + const listener = chooser => { + page.removeListener('filechooser', listener); + f(chooser); + }; + page.addListener('filechooser', listener); + }), + page.click('input'), + ]); + expect(chooser).toBeTruthy(); +}); + +test('should work when file input is attached to DOM', async ({ page, server }) => { + await page.setContent(``); + const [chooser] = await Promise.all([ + page.waitForEvent('filechooser'), + page.click('input'), + ]); + expect(chooser).toBeTruthy(); +}); + +test('should work when file input is not attached to DOM', async ({ page, asset }) => { + const [, content] = await Promise.all([ + page.waitForEvent('filechooser').then(chooser => chooser.setFiles(asset('file-to-upload.txt'))), + page.evaluate(async () => { + const el = document.createElement('input'); + el.type = 'file'; + el.click(); + await new Promise(x => el.oninput = x); + const reader = new FileReader(); + const promise = new Promise(fulfill => reader.onload = fulfill); + reader.readAsText(el.files[0]); + return promise.then(() => reader.result); + }), + ]); + expect(content).toBe('contents of the file'); +}); + +test('should not throw when filechooser belongs to iframe', async ({ page, server, browserName }) => { + await page.goto(server.PREFIX + '/frames/one-frame.html'); + const frame = page.mainFrame().childFrames()[0]; + await frame.setContent(` +
Click me
+ + `); + await Promise.all([ + page.waitForEvent('filechooser'), + frame.click('div') + ]); + await page.waitForFunction(() => (window as any).__done); +}); + +test('should not throw when frame is detached immediately', async ({ page, server }) => { + await page.goto(server.PREFIX + '/frames/one-frame.html'); + const frame = page.mainFrame().childFrames()[0]; + await frame.setContent(` +
Click me
+ + `); + page.on('filechooser', () => {}); // To ensure we handle file choosers. + await frame.click('div'); + await page.waitForFunction(() => (window as any).__done); +}); + +test('should respect timeout', async ({ page, playwright }) => { + let error = null; + await page.waitForEvent('filechooser', { timeout: 1 }).catch(e => error = e); + expect(error).toBeInstanceOf(playwright.errors.TimeoutError); +}); + +test('should respect default timeout when there is no custom timeout', async ({ page, playwright }) => { + page.setDefaultTimeout(1); + let error = null; + await page.waitForEvent('filechooser').catch(e => error = e); + expect(error).toBeInstanceOf(playwright.errors.TimeoutError); +}); + +test('should prioritize exact timeout over default timeout', async ({ page, playwright }) => { + page.setDefaultTimeout(0); + let error = null; + await page.waitForEvent('filechooser', { timeout: 1 }).catch(e => error = e); + expect(error).toBeInstanceOf(playwright.errors.TimeoutError); +}); + +test('should work with no timeout', async ({ page, server }) => { + const [chooser] = await Promise.all([ + page.waitForEvent('filechooser', { timeout: 0 }), + page.evaluate(() => window.builtinSetTimeout(() => { + const el = document.createElement('input'); + el.type = 'file'; + el.click(); + }, 50)) + ]); + expect(chooser).toBeTruthy(); +}); + +test('should return the same file chooser when there are many watchdogs simultaneously', async ({ page, server }) => { + await page.setContent(``); + const [fileChooser1, fileChooser2] = await Promise.all([ + page.waitForEvent('filechooser'), + page.waitForEvent('filechooser'), + page.$eval('input', input => input.click()), + ]); + expect(fileChooser1 === fileChooser2).toBe(true); +}); + +test('should accept single file', async ({ page, asset }) => { + await page.setContent(``); + const [fileChooser] = await Promise.all([ + page.waitForEvent('filechooser'), + page.click('input'), + ]); + expect(fileChooser.page()).toBe(page); + expect(fileChooser.element()).toBeTruthy(); + await fileChooser.setFiles(asset('file-to-upload.txt')); + expect(await page.$eval('input', input => input.files.length)).toBe(1); + expect(await page.$eval('input', input => input.files[0].name)).toBe('file-to-upload.txt'); +}); + +// @see https://github.com/microsoft/playwright/issues/4704 +test('should not trim big uploaded files', async ({ page, server }) => { + + let files: Record; + server.setRoute('/upload', async (req, res) => { + const form = new formidable.IncomingForm(); + form.parse(req, function(err, fields, f) { + files = f as Record; + res.end(); + }); + }); + await page.goto(server.EMPTY_PAGE); + + const DATA_SIZE = Math.pow(2, 20); + await Promise.all([ + page.evaluate(async size => { + const body = new FormData(); + body.set('file', new Blob([new Uint8Array(size)])); + await fetch('/upload', { method: 'POST', body }); + }, DATA_SIZE), + server.waitForRequest('/upload'), + ]); + expect(files.file.size).toBe(DATA_SIZE); +}); + +test('should be able to read selected file', async ({ page, asset }) => { + await page.setContent(``); + const [, content] = await Promise.all([ + page.waitForEvent('filechooser').then(fileChooser => fileChooser.setFiles(asset('file-to-upload.txt'))), + page.$eval('input', async picker => { + picker.click(); + await new Promise(x => picker.oninput = x); + const reader = new FileReader(); + const promise = new Promise(fulfill => reader.onload = fulfill); + reader.readAsText(picker.files[0]); + return promise.then(() => reader.result); + }), + ]); + expect(content).toBe('contents of the file'); +}); + +test('should be able to reset selected files with empty file list', async ({ page, asset }) => { + await page.setContent(``); + const [, fileLength1] = await Promise.all([ + page.waitForEvent('filechooser').then(fileChooser => fileChooser.setFiles(asset('file-to-upload.txt'))), + page.$eval('input', async picker => { + picker.click(); + await new Promise(x => picker.oninput = x); + return picker.files.length; + }), + ]); + expect(fileLength1).toBe(1); + const [, fileLength2] = await Promise.all([ + page.waitForEvent('filechooser').then(fileChooser => fileChooser.setFiles([])), + page.$eval('input', async picker => { + picker.click(); + await new Promise(x => picker.oninput = x); + return picker.files.length; + }), + ]); + expect(fileLength2).toBe(0); +}); + +test('should work for single file pick', async ({ page, server }) => { + await page.setContent(``); + const [fileChooser] = await Promise.all([ + page.waitForEvent('filechooser'), + page.click('input'), + ]); + expect(fileChooser.isMultiple()).toBe(false); +}); + +test('should work for "multiple"', async ({ page, server }) => { + await page.setContent(``); + const [fileChooser] = await Promise.all([ + page.waitForEvent('filechooser'), + page.click('input'), + ]); + expect(fileChooser.isMultiple()).toBe(true); +}); + +test('should work for "webkitdirectory"', async ({ page, server }) => { + await page.setContent(``); + const [fileChooser] = await Promise.all([ + page.waitForEvent('filechooser'), + page.click('input'), + ]); + expect(fileChooser.isMultiple()).toBe(true); +}); + +test('should emit event after navigation', async ({ page, server, browserName, browserMajorVersion }) => { + test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/11375' }); + test.skip(browserName === 'chromium' && browserMajorVersion < 99); + + const logs = []; + page.on('filechooser', () => logs.push('filechooser')); + await page.goto(server.PREFIX + '/empty.html'); + await page.setContent(``); + await Promise.all([ + page.waitForEvent('filechooser'), + page.click('input'), + ]); + await page.goto(server.CROSS_PROCESS_PREFIX + '/empty.html'); + await page.setContent(``); + await Promise.all([ + page.waitForEvent('filechooser'), + page.click('input'), + ]); + expect(logs).toEqual(['filechooser', 'filechooser']); +}); + +test('should trigger listener added before navigation', async ({ page, server, browserMajorVersion, isElectron }) => { + test.skip(isElectron && browserMajorVersion <= 98); + // Add listener before cross process navigation. + const chooserPromise = new Promise(f => page.once('filechooser', f)); + await page.goto(server.PREFIX + '/empty.html'); + await page.goto(server.CROSS_PROCESS_PREFIX + '/empty.html'); + await page.setContent(``); + const [chooser] = await Promise.all([ + chooserPromise, + page.click('input'), + ]); + expect(chooser).toBeTruthy(); +}); diff --git a/tests/page/page-set-input-files.spec.ts b/tests/page/page-set-input-files.spec.ts index eaf1316f5c..9129a6ee4f 100644 --- a/tests/page/page-set-input-files.spec.ts +++ b/tests/page/page-set-input-files.spec.ts @@ -15,14 +15,13 @@ * limitations under the License. */ -import { test as it, expect } from './pageTest'; -import { attachFrame } from '../config/utils'; +import { test, expect } from './pageTest'; import path from 'path'; import fs from 'fs'; import formidable from 'formidable'; -it('should upload the file', async ({ page, server, asset }) => { +test('should upload the file', async ({ page, server, asset }) => { await page.goto(server.PREFIX + '/input/fileupload.html'); const filePath = path.relative(process.cwd(), asset('file-to-upload.txt')); const input = await page.$('input'); @@ -36,13 +35,13 @@ it('should upload the file', async ({ page, server, asset }) => { }, input)).toBe('contents of the file'); }); -it('should upload a folder', async ({ page, server, browserName, headless, browserMajorVersion, isAndroid, macVersion, isMac }) => { - it.skip(isAndroid); - it.skip(browserName === 'webkit' && isMac && macVersion <= 12, 'WebKit on macOS-12 is frozen'); +test('should upload a folder', async ({ page, server, browserName, headless, browserMajorVersion, isAndroid, macVersion, isMac }) => { + test.skip(isAndroid); + test.skip(browserName === 'webkit' && isMac && macVersion <= 12, 'WebKit on macOS-12 is frozen'); await page.goto(server.PREFIX + '/input/folderupload.html'); const input = await page.$('input'); - const dir = path.join(it.info().outputDir, 'file-upload-test'); + const dir = path.join(test.info().outputDir, 'file-upload-test'); { await fs.promises.mkdir(dir, { recursive: true }); await fs.promises.writeFile(path.join(dir, 'file1.txt'), 'file1 content'); @@ -69,13 +68,13 @@ it('should upload a folder', async ({ page, server, browserName, headless, brows } }); -it('should upload a folder and throw for multiple directories', async ({ page, server, isAndroid, browserName, macVersion, isMac }) => { - it.skip(isAndroid); - it.skip(browserName === 'webkit' && isMac && macVersion <= 12, 'WebKit on macOS-12 is frozen'); +test('should upload a folder and throw for multiple directories', async ({ page, server, isAndroid, browserName, macVersion, isMac }) => { + test.skip(isAndroid); + test.skip(browserName === 'webkit' && isMac && macVersion <= 12, 'WebKit on macOS-12 is frozen'); await page.goto(server.PREFIX + '/input/folderupload.html'); const input = await page.$('input'); - const dir = path.join(it.info().outputDir, 'file-upload-test'); + const dir = path.join(test.info().outputDir, 'file-upload-test'); { await fs.promises.mkdir(path.join(dir, 'folder1'), { recursive: true }); await fs.promises.writeFile(path.join(dir, 'folder1', 'file1.txt'), 'file1 content'); @@ -88,13 +87,13 @@ it('should upload a folder and throw for multiple directories', async ({ page, s ])).rejects.toThrow('Multiple directories are not supported'); }); -it('should throw if a directory and files are passed', async ({ page, server, isAndroid, browserName, macVersion, isMac }) => { - it.skip(isAndroid); - it.skip(browserName === 'webkit' && isMac && macVersion <= 12, 'WebKit on macOS-12 is frozen'); +test('should throw if a directory and files are passed', async ({ page, server, isAndroid, browserName, macVersion, isMac }) => { + test.skip(isAndroid); + test.skip(browserName === 'webkit' && isMac && macVersion <= 12, 'WebKit on macOS-12 is frozen'); await page.goto(server.PREFIX + '/input/folderupload.html'); const input = await page.$('input'); - const dir = path.join(it.info().outputDir, 'file-upload-test'); + const dir = path.join(test.info().outputDir, 'file-upload-test'); { await fs.promises.mkdir(path.join(dir, 'folder1'), { recursive: true }); await fs.promises.writeFile(path.join(dir, 'folder1', 'file1.txt'), 'file1 content'); @@ -105,13 +104,13 @@ it('should throw if a directory and files are passed', async ({ page, server, is ])).rejects.toThrow('File paths must be all files or a single directory'); }); -it('should throw when uploading a folder in a normal file upload input', async ({ page, server, isAndroid, browserName, macVersion, isMac }) => { - it.skip(isAndroid); - it.skip(browserName === 'webkit' && isMac && macVersion <= 12, 'WebKit on macOS-12 is frozen'); +test('should throw when uploading a folder in a normal file upload input', async ({ page, server, isAndroid, browserName, macVersion, isMac }) => { + test.skip(isAndroid); + test.skip(browserName === 'webkit' && isMac && macVersion <= 12, 'WebKit on macOS-12 is frozen'); await page.goto(server.PREFIX + '/input/fileupload.html'); const input = await page.$('input'); - const dir = path.join(it.info().outputDir, 'file-upload-test'); + const dir = path.join(test.info().outputDir, 'file-upload-test'); { await fs.promises.mkdir(path.join(dir), { recursive: true }); await fs.promises.writeFile(path.join(dir, 'file1.txt'), 'file1 content'); @@ -119,17 +118,17 @@ it('should throw when uploading a folder in a normal file upload input', async ( await expect(input.setInputFiles(dir)).rejects.toThrow('File input does not support directories, pass individual files instead'); }); -it('should throw when uploading a file in a directory upload input', async ({ page, server, isAndroid, asset, browserName, macVersion, isMac }) => { - it.skip(isAndroid); - it.skip(browserName === 'webkit' && isMac && macVersion <= 12, 'WebKit on macOS-12 is frozen'); +test('should throw when uploading a file in a directory upload input', async ({ page, server, isAndroid, asset, browserName, macVersion, isMac }) => { + test.skip(isAndroid); + test.skip(browserName === 'webkit' && isMac && macVersion <= 12, 'WebKit on macOS-12 is frozen'); await page.goto(server.PREFIX + '/input/folderupload.html'); const input = await page.$('input'); await expect(input.setInputFiles(asset('file to upload.txt'))).rejects.toThrow('[webkitdirectory] input requires passing a path to a directory'); }); -it('should upload a file after popup', async ({ page, server, asset }) => { - it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/29923' }); +test('should upload a file after popup', async ({ page, server, asset }) => { + test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/29923' }); await page.goto(server.PREFIX + '/input/fileupload.html'); { const [popup] = await Promise.all([ @@ -144,11 +143,11 @@ it('should upload a file after popup', async ({ page, server, asset }) => { expect(await page.evaluate(e => e.files[0].name, input)).toBe('file-to-upload.txt'); }); -it('should upload large file', async ({ page, server, isAndroid, isWebView2, mode }, testInfo) => { - it.skip(isAndroid); - it.skip(isWebView2); - it.skip(mode.startsWith('service')); - it.slow(); +test('should upload large file', async ({ page, server, isAndroid, isWebView2, mode }, testInfo) => { + test.skip(isAndroid); + test.skip(isWebView2); + test.skip(mode.startsWith('service')); + test.slow(); await page.goto(server.PREFIX + '/input/fileupload.html'); const uploadFile = testInfo.outputPath('200MB.zip'); @@ -194,7 +193,7 @@ it('should upload large file', async ({ page, server, isAndroid, isWebView2, mod await Promise.all([uploadFile, file1.filepath].map(fs.promises.unlink)); }); -it('should throw an error if the file does not exist', async ({ page, server, asset }) => { +test('should throw an error if the file does not exist', async ({ page, server, asset }) => { await page.goto(server.PREFIX + '/input/fileupload.html'); const input = await page.$('input'); const error = await input.setInputFiles('i actually do not exist.txt').catch(e => e); @@ -202,51 +201,11 @@ it('should throw an error if the file does not exist', async ({ page, server, as expect(error.message).toContain('i actually do not exist.txt'); }); -it('should upload multiple large files', async ({ page, server, isAndroid, isWebView2, mode }, testInfo) => { - it.skip(isAndroid); - it.skip(isWebView2); - it.skip(mode.startsWith('service')); - it.slow(); - - const filesCount = 10; - await page.goto(server.PREFIX + '/input/fileupload-multi.html'); - const uploadFile = testInfo.outputPath('50MB_1.zip'); - const str = 'A'.repeat(1024); - const stream = fs.createWriteStream(uploadFile); - // 49 is close to the actual limit - for (let i = 0; i < 49 * 1024; i++) { - await new Promise((fulfill, reject) => { - stream.write(str, err => { - if (err) - reject(err); - else - fulfill(); - }); - }); - } - await new Promise(f => stream.end(f)); - const input = page.locator('input[type="file"]'); - const uploadFiles = [uploadFile]; - for (let i = 2; i <= filesCount; i++) { - const dstFile = testInfo.outputPath(`50MB_${i}.zip`); - fs.copyFileSync(uploadFile, dstFile); - uploadFiles.push(dstFile); - } - const fileChooserPromise = page.waitForEvent('filechooser'); - await input.click(); - const fileChooser = await fileChooserPromise; - await fileChooser.setFiles(uploadFiles); - const filesLen = await page.evaluate('document.getElementsByTagName("input")[0].files.length'); - expect(fileChooser.isMultiple()).toBe(true); - expect(filesLen).toEqual(filesCount); - await Promise.all(uploadFiles.map(path => fs.promises.unlink(path))); -}); - -it('should upload large file with relative path', async ({ page, server, isAndroid, isWebView2, mode }, testInfo) => { - it.skip(isAndroid); - it.skip(isWebView2); - it.skip(mode.startsWith('service')); - it.slow(); +test('should upload large file with relative path', async ({ page, server, isAndroid, isWebView2, mode }, testInfo) => { + test.skip(isAndroid); + test.skip(isWebView2); + test.skip(mode.startsWith('service')); + test.slow(); await page.goto(server.PREFIX + '/input/fileupload.html'); const uploadFile = testInfo.outputPath('200MB.zip'); @@ -294,8 +253,8 @@ it('should upload large file with relative path', async ({ page, server, isAndro await Promise.all([uploadFile, file1.filepath].map(fs.promises.unlink)); }); -it('should upload the file with spaces in name', async ({ page, server, asset }) => { - it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/17451' }); +test('should upload the file with spaces in name', async ({ page, server, asset }) => { + test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/17451' }); await page.goto(server.PREFIX + '/input/fileupload.html'); const filePath = path.relative(process.cwd(), asset('file to upload.txt')); const input = await page.$('input'); @@ -310,14 +269,14 @@ it('should upload the file with spaces in name', async ({ page, server, asset }) }); -it('should work @smoke', async ({ page, asset }) => { +test('should work @smoke', async ({ page, asset }) => { await page.setContent(``); await page.setInputFiles('input', asset('file-to-upload.txt')); expect(await page.$eval('input', input => input.files.length)).toBe(1); expect(await page.$eval('input', input => input.files[0].name)).toBe('file-to-upload.txt'); }); -it('should set from memory', async ({ page }) => { +test('should set from memory', async ({ page }) => { await page.setContent(``); await page.setInputFiles('input', { name: 'test.txt', @@ -328,133 +287,7 @@ it('should set from memory', async ({ page }) => { expect(await page.$eval('input', input => input.files[0].name)).toBe('test.txt'); }); -it('should emit event once', async ({ page, server }) => { - await page.setContent(``); - const [chooser] = await Promise.all([ - new Promise(f => page.once('filechooser', f)), - page.click('input'), - ]); - expect(chooser).toBeTruthy(); -}); - -it('should emit event via prepend', async ({ page, server }) => { - await page.setContent(``); - const [chooser] = await Promise.all([ - new Promise(f => page.prependListener('filechooser', f)), - page.click('input'), - ]); - expect(chooser).toBeTruthy(); -}); - -it('should emit event for iframe', async ({ page, server }) => { - const frame = await attachFrame(page, 'frame1', server.EMPTY_PAGE); - await frame.setContent(``); - const [chooser] = await Promise.all([ - new Promise(f => page.once('filechooser', f)), - frame.click('input'), - ]); - expect(chooser).toBeTruthy(); -}); - -it('should emit event on/off', async ({ page, server }) => { - await page.setContent(``); - const [chooser] = await Promise.all([ - new Promise(f => { - const listener = chooser => { - page.off('filechooser', listener); - f(chooser); - }; - page.on('filechooser', listener); - }), - page.click('input'), - ]); - expect(chooser).toBeTruthy(); -}); - -it('should emit event addListener/removeListener', async ({ page, server }) => { - await page.setContent(``); - const [chooser] = await Promise.all([ - new Promise(f => { - const listener = chooser => { - page.removeListener('filechooser', listener); - f(chooser); - }; - page.addListener('filechooser', listener); - }), - page.click('input'), - ]); - expect(chooser).toBeTruthy(); -}); - -it('should work when file input is attached to DOM', async ({ page, server }) => { - await page.setContent(``); - const [chooser] = await Promise.all([ - page.waitForEvent('filechooser'), - page.click('input'), - ]); - expect(chooser).toBeTruthy(); -}); - -it('should work when file input is not attached to DOM', async ({ page, asset }) => { - const [, content] = await Promise.all([ - page.waitForEvent('filechooser').then(chooser => chooser.setFiles(asset('file-to-upload.txt'))), - page.evaluate(async () => { - const el = document.createElement('input'); - el.type = 'file'; - el.click(); - await new Promise(x => el.oninput = x); - const reader = new FileReader(); - const promise = new Promise(fulfill => reader.onload = fulfill); - reader.readAsText(el.files[0]); - return promise.then(() => reader.result); - }), - ]); - expect(content).toBe('contents of the file'); -}); - -it('should not throw when filechooser belongs to iframe', async ({ page, server, browserName }) => { - await page.goto(server.PREFIX + '/frames/one-frame.html'); - const frame = page.mainFrame().childFrames()[0]; - await frame.setContent(` -
Click me
- - `); - await Promise.all([ - page.waitForEvent('filechooser'), - frame.click('div') - ]); - await page.waitForFunction(() => (window as any).__done); -}); - -it('should not throw when frame is detached immediately', async ({ page, server }) => { - await page.goto(server.PREFIX + '/frames/one-frame.html'); - const frame = page.mainFrame().childFrames()[0]; - await frame.setContent(` -
Click me
- - `); - page.on('filechooser', () => {}); // To ensure we handle file choosers. - await frame.click('div'); - await page.waitForFunction(() => (window as any).__done); -}); - -it('should work with CSP', async ({ page, server, asset }) => { +test('should work with CSP', async ({ page, server, asset }) => { server.setCSP('/empty.html', 'default-src "none"'); await page.goto(server.EMPTY_PAGE); await page.setContent(``); @@ -463,62 +296,7 @@ it('should work with CSP', async ({ page, server, asset }) => { expect(await page.$eval('input', input => input.files[0].name)).toBe('file-to-upload.txt'); }); -it('should respect timeout', async ({ page, playwright }) => { - let error = null; - await page.waitForEvent('filechooser', { timeout: 1 }).catch(e => error = e); - expect(error).toBeInstanceOf(playwright.errors.TimeoutError); -}); - -it('should respect default timeout when there is no custom timeout', async ({ page, playwright }) => { - page.setDefaultTimeout(1); - let error = null; - await page.waitForEvent('filechooser').catch(e => error = e); - expect(error).toBeInstanceOf(playwright.errors.TimeoutError); -}); - -it('should prioritize exact timeout over default timeout', async ({ page, playwright }) => { - page.setDefaultTimeout(0); - let error = null; - await page.waitForEvent('filechooser', { timeout: 1 }).catch(e => error = e); - expect(error).toBeInstanceOf(playwright.errors.TimeoutError); -}); - -it('should work with no timeout', async ({ page, server }) => { - const [chooser] = await Promise.all([ - page.waitForEvent('filechooser', { timeout: 0 }), - page.evaluate(() => window.builtinSetTimeout(() => { - const el = document.createElement('input'); - el.type = 'file'; - el.click(); - }, 50)) - ]); - expect(chooser).toBeTruthy(); -}); - -it('should return the same file chooser when there are many watchdogs simultaneously', async ({ page, server }) => { - await page.setContent(``); - const [fileChooser1, fileChooser2] = await Promise.all([ - page.waitForEvent('filechooser'), - page.waitForEvent('filechooser'), - page.$eval('input', input => input.click()), - ]); - expect(fileChooser1 === fileChooser2).toBe(true); -}); - -it('should accept single file', async ({ page, asset }) => { - await page.setContent(``); - const [fileChooser] = await Promise.all([ - page.waitForEvent('filechooser'), - page.click('input'), - ]); - expect(fileChooser.page()).toBe(page); - expect(fileChooser.element()).toBeTruthy(); - await fileChooser.setFiles(asset('file-to-upload.txt')); - expect(await page.$eval('input', input => input.files.length)).toBe(1); - expect(await page.$eval('input', input => input.files[0].name)).toBe('file-to-upload.txt'); -}); - -it('should detect mime type', async ({ page, server, asset }) => { +test('should detect mime type', async ({ page, server, asset }) => { let files: Record; server.setRoute('/upload', async (req, res) => { @@ -553,7 +331,7 @@ it('should detect mime type', async ({ page, server, asset }) => { }); // @see https://github.com/microsoft/playwright/issues/4704 -it('should not trim big uploaded files', async ({ page, server }) => { +test('should not trim big uploaded files', async ({ page, server }) => { let files: Record; server.setRoute('/upload', async (req, res) => { @@ -577,59 +355,7 @@ it('should not trim big uploaded files', async ({ page, server }) => { expect(files.file.size).toBe(DATA_SIZE); }); -it('should be able to read selected file', async ({ page, asset }) => { - await page.setContent(``); - const [, content] = await Promise.all([ - page.waitForEvent('filechooser').then(fileChooser => fileChooser.setFiles(asset('file-to-upload.txt'))), - page.$eval('input', async picker => { - picker.click(); - await new Promise(x => picker.oninput = x); - const reader = new FileReader(); - const promise = new Promise(fulfill => reader.onload = fulfill); - reader.readAsText(picker.files[0]); - return promise.then(() => reader.result); - }), - ]); - expect(content).toBe('contents of the file'); -}); - -it('should be able to reset selected files with empty file list', async ({ page, asset }) => { - await page.setContent(``); - const [, fileLength1] = await Promise.all([ - page.waitForEvent('filechooser').then(fileChooser => fileChooser.setFiles(asset('file-to-upload.txt'))), - page.$eval('input', async picker => { - picker.click(); - await new Promise(x => picker.oninput = x); - return picker.files.length; - }), - ]); - expect(fileLength1).toBe(1); - const [, fileLength2] = await Promise.all([ - page.waitForEvent('filechooser').then(fileChooser => fileChooser.setFiles([])), - page.$eval('input', async picker => { - picker.click(); - await new Promise(x => picker.oninput = x); - return picker.files.length; - }), - ]); - expect(fileLength2).toBe(0); -}); - -it('should not accept multiple files for single-file input', async ({ page, asset }) => { - await page.setContent(``); - const [fileChooser] = await Promise.all([ - page.waitForEvent('filechooser'), - page.click('input'), - ]); - let error = null; - await fileChooser.setFiles([ - asset('file-to-upload.txt'), - asset('pptr.png') - ]).catch(e => error = e); - expect(error).not.toBe(null); -}); - -it('should emit input and change events', async ({ page, asset }) => { +test('should emit input and change events', async ({ page, asset }) => { const events = []; await page.exposeFunction('eventHandled', e => events.push(e)); await page.setContent(` @@ -644,8 +370,8 @@ it('should emit input and change events', async ({ page, asset }) => { expect(events[1].type).toBe('change'); }); -it('input event.composed should be true and cross shadow dom boundary', async ({ page, server, asset }) => { - it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/28726' }); +test('input event.composed should be true and cross shadow dom boundary', async ({ page, server, asset }) => { + test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/28726' }); await page.goto(server.EMPTY_PAGE); await page.setContent(`