Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
fix: collect stdio from forked processes (#27074)
Max Schmitt4431a8366dcb
diff --git a/packages/playwright/src/common/ipc.ts b/packages/playwright/src/common/ipc.tsindex 0e5113e0eb..3310b46b3a 100644--- a/packages/playwright/src/common/ipc.ts+++ b/packages/playwright/src/common/ipc.ts@@ -14,6 +14,7 @@* limitations under the License.*/+import util from 'util';import { serializeCompilationCache } from '../transform/compilationCache';import type { FullConfigInternal } from './config';import type { ReporterDescription, TestInfoError, TestStatus } from '../../types/test';@@ -141,3 +142,11 @@ export function serializeConfig(config: FullConfigInternal): SerializedConfig {};return result;}++export function stdioChunkToParams(chunk: Uint8Array | string): TestOutputPayload {+ if (chunk instanceof Uint8Array)+ return { buffer: Buffer.from(chunk).toString('base64') };+ if (typeof chunk !== 'string')+ return { text: util.inspect(chunk) };+ return { text: chunk };+}diff --git a/packages/playwright/src/runner/loaderHost.ts b/packages/playwright/src/runner/loaderHost.tsindex 8afaa2916a..d1e94688ed 100644--- a/packages/playwright/src/runner/loaderHost.ts+++ b/packages/playwright/src/runner/loaderHost.ts@@ -58,7 +58,7 @@ export class OutOfProcessLoaderHost {}async start() {- await this._processHost.startRunner(serializeConfig(this._config), true);+ await this._processHost.startRunner(serializeConfig(this._config));}async loadTestFile(file: string, testErrors: TestError[]): Promise<Suite> {diff --git a/packages/playwright/src/runner/processHost.ts b/packages/playwright/src/runner/processHost.tsindex 60b5923ca6..689a5a1938 100644--- a/packages/playwright/src/runner/processHost.ts+++ b/packages/playwright/src/runner/processHost.ts@@ -46,11 +46,16 @@ export class ProcessHost extends EventEmitter {this._extraEnv = env;}- async startRunner(runnerParams: any, inheritStdio: boolean) {+ async startRunner(runnerParams: any, options: { onStdOut?: (chunk: Buffer | string) => void, onStdErr?: (chunk: Buffer | string) => void } = {}) {this.process = child_process.fork(require.resolve('../common/process'), {detached: false,env: { ...process.env, ...this._extraEnv },- stdio: inheritStdio ? ['ignore', 'inherit', 'inherit', 'ipc'] : ['ignore', 'ignore', process.env.PW_RUNNER_DEBUG ? 'inherit' : 'ignore', 'ipc'],+ stdio: [+ 'ignore',+ options.onStdOut ? 'pipe' : 'inherit',+ (options.onStdErr && !process.env.PW_RUNNER_DEBUG) ? 'pipe' : 'inherit',+ 'ipc',+ ],...(process.env.PW_TS_ESM_ON ? { execArgv: execArgvWithExperimentalLoaderOptions() } : {}),});this.process.on('exit', (code, signal) => {@@ -84,6 +89,11 @@ export class ProcessHost extends EventEmitter {}});+ if (options.onStdOut)+ this.process.stdout?.on('data', options.onStdOut);+ if (options.onStdErr)+ this.process.stderr?.on('data', options.onStdErr);+await new Promise<void>((resolve, reject) => {this.process!.once('exit', (code, signal) => reject(new Error(`process exited with code "${code}" and signal "${signal}" before it became ready`)));this.once('ready', () => resolve());diff --git a/packages/playwright/src/runner/workerHost.ts b/packages/playwright/src/runner/workerHost.tsindex 4a71a6af01..e2c0444dbe 100644--- a/packages/playwright/src/runner/workerHost.ts+++ b/packages/playwright/src/runner/workerHost.ts@@ -17,6 +17,7 @@import fs from 'fs';import path from 'path';import type { TestGroup } from './testGroups';+import { stdioChunkToParams } from '../common/ipc';import type { RunPayload, SerializedConfig, WorkerInitParams } from '../common/ipc';import { ProcessHost } from './processHost';import { artifactsFolderName } from '../isomorphic/folders';@@ -54,7 +55,10 @@ export class WorkerHost extends ProcessHost {async start() {await fs.promises.mkdir(this._params.artifactsDir, { recursive: true });- await this.startRunner(this._params, false);+ await this.startRunner(this._params, {+ onStdOut: chunk => this.emit('stdOut', stdioChunkToParams(chunk)),+ onStdErr: chunk => this.emit('stdErr', stdioChunkToParams(chunk)),+ });}override async stop(didFail?: boolean) {diff --git a/packages/playwright/src/worker/workerMain.ts b/packages/playwright/src/worker/workerMain.tsindex 5d5b7efd1c..cb1c5e5225 100644--- a/packages/playwright/src/worker/workerMain.ts+++ b/packages/playwright/src/worker/workerMain.ts@@ -15,9 +15,8 @@*/import { colors, rimraf } from 'playwright-core/lib/utilsBundle';-import util from 'util';import { debugTest, formatLocation, relativeFilePath, serializeError } from '../util';-import type { TestBeginPayload, TestEndPayload, RunPayload, DonePayload, WorkerInitParams, TeardownErrorsPayload, TestOutputPayload } from '../common/ipc';+import { type TestBeginPayload, type TestEndPayload, type RunPayload, type DonePayload, type WorkerInitParams, type TeardownErrorsPayload, stdioChunkToParams } from '../common/ipc';import { setCurrentTestInfo, setIsWorkerProcess } from '../common/globals';import { ConfigLoader } from '../common/configLoader';import type { Suite, TestCase } from '../common/test';@@ -76,20 +75,14 @@ export class WorkerMain extends ProcessRunner {process.on('unhandledRejection', reason => this.unhandledError(reason));process.on('uncaughtException', error => this.unhandledError(error));process.stdout.write = (chunk: string | Buffer) => {- const outPayload: TestOutputPayload = {- ...chunkToParams(chunk)- };- this.dispatchEvent('stdOut', outPayload);+ this.dispatchEvent('stdOut', stdioChunkToParams(chunk));this._currentTest?._tracing.appendStdioToTrace('stdout', chunk);return true;};if (!process.env.PW_RUNNER_DEBUG) {process.stderr.write = (chunk: string | Buffer) => {- const outPayload: TestOutputPayload = {- ...chunkToParams(chunk)- };- this.dispatchEvent('stdErr', outPayload);+ this.dispatchEvent('stdErr', stdioChunkToParams(chunk));this._currentTest?._tracing.appendStdioToTrace('stderr', chunk);return true;};@@ -652,12 +645,4 @@ function formatTestTitle(test: TestCase, projectName: string) {return `${projectTitle}${location} › ${titles.join(' › ')}`;}-function chunkToParams(chunk: Uint8Array | string, encoding?: BufferEncoding): { text?: string, buffer?: string } {- if (chunk instanceof Uint8Array)- return { buffer: Buffer.from(chunk).toString('base64') };- if (typeof chunk !== 'string')- return { text: util.inspect(chunk) };- return { text: chunk };-}-export const create = (params: WorkerInitParams) => new WorkerMain(params);diff --git a/tests/playwright-test/exit-code.spec.ts b/tests/playwright-test/exit-code.spec.tsindex 65a26cd90a..661385c950 100644--- a/tests/playwright-test/exit-code.spec.ts+++ b/tests/playwright-test/exit-code.spec.ts@@ -40,6 +40,30 @@ test('should collect stdio', async ({ runInlineTest }) => {expect(stderr).toEqual([{ text: 'stderr text' }, { buffer: Buffer.from('stderr buffer').toString('base64') }]);});+test('should collect stdio from forked process', async ({ runInlineTest }) => {+ const { exitCode, report } = await runInlineTest({+ 'stdio.spec.js': `+ import { test } from '@playwright/test';+ import { fork } from 'child_process';+ test('stdio', async () => {+ const child = fork('fork.js');+ await new Promise((resolve) => child.on('exit', (code) => resolve(code)));+ });+ `,+ 'fork.js': `+ process.stdout.write('stdout text');+ process.stdout.write(Buffer.from('stdout buffer'));+ process.stderr.write('stderr text');+ process.stderr.write(Buffer.from('stderr buffer'));+ `+ });+ expect(exitCode).toBe(0);+ const testResult = report.suites[0].specs[0].tests[0].results[0];+ const { stdout, stderr } = testResult;+ expect(stdout.map(e => Buffer.from((e as any).buffer, 'base64').toString()).join('')).toEqual('stdout textstdout buffer');+ expect(stderr.map(e => Buffer.from((e as any).buffer, 'base64').toString()).join('')).toEqual('stderr textstderr buffer');+});+test('should work with not defined errors', async ({ runInlineTest }) => {const result = await runInlineTest({'is-not-defined-error.spec.ts': `