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
chore: use screen for output in reporters (#37039)
Pavel Feldmane722aa99eacf
diff --git a/eslint.config.mjs b/eslint.config.mjsindex 26e7070a1f..e45ca0e78f 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -339,6 +339,8 @@ export default [message:"Please use gracefullyProcessExitDoNotHang function to exit the process.",},+ { object: "process", property: "stdout" },+ { object: "process", property: "stderr" },],},},@@ -354,13 +356,6 @@ export default [...noFloatingPromisesRules,},},- {- files: ["packages/playwright/src/reporters/**/*.ts"],- languageOptions: languageOptionsWithTsConfig,- rules: {- "no-console": "off",- },- },{files: ["packages/playwright-core/src/utils/**/*.ts",diff --git a/packages/playwright-core/src/cli/driver.ts b/packages/playwright-core/src/cli/driver.tsindex de8d94293c..f716d8efa7 100644--- a/packages/playwright-core/src/cli/driver.ts+++ b/packages/playwright-core/src/cli/driver.ts@@ -38,6 +38,7 @@ export function runDriver() {const playwright = createPlaywright({ sdkLanguage });return new PlaywrightDispatcher(rootScope, playwright);});+ // eslint-disable-next-line no-restricted-propertiesconst transport = new PipeTransport(process.stdout, process.stdin);transport.onmessage = (message: string) => dispatcherConnection.dispatch(JSON.parse(message));// Certain Language Binding JSON parsers (e.g. .NET) do not like strings with lone surrogates.diff --git a/packages/playwright-core/src/cli/program.ts b/packages/playwright-core/src/cli/program.tsindex e94d822789..5dc18774b7 100644--- a/packages/playwright-core/src/cli/program.ts+++ b/packages/playwright-core/src/cli/program.ts@@ -643,11 +643,13 @@ async function maybeSetupTestHooks(browser: Browser, closeBrowser: () => Promiserequire('playwright-core/lib/utilsBundle').debug.log = (...args: any[]) => {const line = require('util').format(...args) + '\n';logs.push(line);+ // eslint-disable-next-line no-restricted-propertiesprocess.stderr.write(line);};browser.on('disconnected', () => {const hasCrashLine = logs.some(line => line.includes('process did exit:') && !line.includes('process did exit: exitCode=0, signal=null'));if (hasCrashLine) {+ // eslint-disable-next-line no-restricted-propertiesprocess.stderr.write('Detected browser crash.\n');gracefullyProcessExitDoNotHang(1);}diff --git a/packages/playwright-core/src/outofprocess.ts b/packages/playwright-core/src/outofprocess.tsindex e2fd486414..3496c9895d 100644--- a/packages/playwright-core/src/outofprocess.ts+++ b/packages/playwright-core/src/outofprocess.ts@@ -47,6 +47,7 @@ class PlaywrightClient {},});this._driverProcess.unref();+ // eslint-disable-next-line no-restricted-propertiesthis._driverProcess.stderr!.on('data', data => process.stderr.write(data));const connection = new Connection(nodePlatform);diff --git a/packages/playwright-core/src/server/electron/electron.ts b/packages/playwright-core/src/server/electron/electron.tsindex efe830935c..8a341743bd 100644--- a/packages/playwright-core/src/server/electron/electron.ts+++ b/packages/playwright-core/src/server/electron/electron.ts@@ -292,6 +292,7 @@ export class Electron extends SdkObject {async function waitForLine(progress: Progress, process: childProcess.ChildProcess, regex: RegExp) {const promise = new ManualPromise<RegExpMatchArray>();+ // eslint-disable-next-line no-restricted-propertiesconst rl = readline.createInterface({ input: process.stderr! });const failError = new Error('Process failed to launch!');const listeners = [diff --git a/packages/playwright-core/src/server/registry/browserFetcher.ts b/packages/playwright-core/src/server/registry/browserFetcher.tsindex f912b2a2fe..acd3a52f14 100644--- a/packages/playwright-core/src/server/registry/browserFetcher.ts+++ b/packages/playwright-core/src/server/registry/browserFetcher.ts@@ -126,6 +126,7 @@ export function logPolitely(toBeLogged: string) {type OnProgressCallback = (downloadedBytes: number, totalBytes: number) => void;function getDownloadProgress(): OnProgressCallback {+ // eslint-disable-next-line no-restricted-propertiesif (process.stdout.isTTY)return getAnimatedDownloadProgress();return getBasicDownloadProgress();diff --git a/packages/playwright-core/src/server/registry/index.ts b/packages/playwright-core/src/server/registry/index.tsindex 7d03838f7f..aa32c266e1 100644--- a/packages/playwright-core/src/server/registry/index.ts+++ b/packages/playwright-core/src/server/registry/index.ts@@ -1068,6 +1068,7 @@ export class Registry {const { embedderName } = getEmbedderName();if (!getAsBooleanFromENV('CI') && !executable._isHermeticInstallation && !forceReinstall && executable.executablePath(embedderName)) {const command = buildPlaywrightCLICommand(embedderName, 'install --force ' + executable.name);+ // eslint-disable-next-line no-restricted-propertiesprocess.stderr.write('\n' + wrapInASCIIBox([`ATTENTION: "${executable.name}" is already installed on the system!`,``,@@ -1132,6 +1133,7 @@ export class Registry {async validateHostRequirementsForExecutablesIfNeeded(executables: Executable[], sdkLanguage: string) {if (getAsBooleanFromENV('PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS')) {+ // eslint-disable-next-line no-restricted-propertiesprocess.stderr.write('Skipping host requirements validation logic because `PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS` env variable is set.\n');return;}diff --git a/packages/playwright-core/src/server/trace/viewer/traceViewer.ts b/packages/playwright-core/src/server/trace/viewer/traceViewer.tsindex d23789a99f..3c367e4ad6 100644--- a/packages/playwright-core/src/server/trace/viewer/traceViewer.ts+++ b/packages/playwright-core/src/server/trace/viewer/traceViewer.ts@@ -182,8 +182,10 @@ export async function openTraceViewerApp(url: string, browserName: string, optioawait controller.run(async progress => {await context._browser._defaultContext!._loadDefaultContextAsIs(progress);- if (process.env.PWTEST_PRINT_WS_ENDPOINT)+ if (process.env.PWTEST_PRINT_WS_ENDPOINT) {+ // eslint-disable-next-line no-restricted-propertiesprocess.stderr.write('DevTools listening on: ' + context._browser.options.wsEndpoint + '\n');+ }if (!isUnderTest())await syncLocalStorageWithSettings(page, 'traceviewer');diff --git a/packages/playwright-core/src/server/utils/spawnAsync.ts b/packages/playwright-core/src/server/utils/spawnAsync.tsindex f68719d620..c3bb8f086c 100644--- a/packages/playwright-core/src/server/utils/spawnAsync.ts+++ b/packages/playwright-core/src/server/utils/spawnAsync.ts@@ -24,10 +24,12 @@ export function spawnAsync(cmd: string, args: string[], options: SpawnOptions =return new Promise(resolve => {let stdout = '';let stderr = '';+ /* eslint-disable no-restricted-properties */if (process.stdout)process.stdout.on('data', data => stdout += data.toString());if (process.stderr)process.stderr.on('data', data => stderr += data.toString());+ /* eslint-enable no-restricted-properties */process.on('close', code => resolve({ stdout, stderr, code }));process.on('error', error => resolve({ stdout, stderr, code: 0, error }));});diff --git a/packages/playwright/src/program.ts b/packages/playwright/src/program.tsindex c2f5f4540c..b57fda08bc 100644--- a/packages/playwright/src/program.ts+++ b/packages/playwright/src/program.ts@@ -234,7 +234,9 @@ async function runTestServer(opts: { [key: string]: any }) {export async function withRunnerAndMutedWrite(configFile: string | undefined, callback: (runner: Runner) => Promise<any>) {// Redefine process.stdout.write in case config decides to pollute stdio.+ // eslint-disable-next-line no-restricted-propertiesconst stdoutWrite = process.stdout.write.bind(process.stdout);+ // eslint-disable-next-line no-restricted-propertiesprocess.stdout.write = ((a: any, b: any, c: any) => process.stderr.write(a, b, c)) as any;try {const config = await loadConfigFromFile(configFile);diff --git a/packages/playwright/src/reporters/base.ts b/packages/playwright/src/reporters/base.tsindex 5a3e033ef8..d8989e8852 100644--- a/packages/playwright/src/reporters/base.ts+++ b/packages/playwright/src/reporters/base.ts@@ -59,24 +59,36 @@ export type Screen = {isTTY: boolean;ttyWidth: number;ttyHeight: number;+ stdout?: NodeJS.WriteStream;+ stderr?: NodeJS.WriteStream;+};++export type TerminalScreen = Screen & {+ stdout: NodeJS.WriteStream;+ stderr: NodeJS.WriteStream;};const DEFAULT_TTY_WIDTH = 100;const DEFAULT_TTY_HEIGHT = 40;+// eslint-disable-next-line no-restricted-properties+const originalProcessStdout = process.stdout;+// eslint-disable-next-line no-restricted-properties+const originalProcessStderr = process.stderr;+// Output goes to terminal.-export const terminalScreen: Screen = (() => {- let isTTY = !!process.stdout.isTTY;- let ttyWidth = process.stdout.columns || 0;- let ttyHeight = process.stdout.rows || 0;+export const terminalScreen: TerminalScreen = (() => {+ let isTTY = !!originalProcessStdout.isTTY;+ let ttyWidth = originalProcessStdout.columns || 0;+ let ttyHeight = originalProcessStdout.rows || 0;if (process.env.PLAYWRIGHT_FORCE_TTY === 'false' || process.env.PLAYWRIGHT_FORCE_TTY === '0') {isTTY = false;ttyWidth = 0;ttyHeight = 0;} else if (process.env.PLAYWRIGHT_FORCE_TTY === 'true' || process.env.PLAYWRIGHT_FORCE_TTY === '1') {isTTY = true;- ttyWidth = process.stdout.columns || DEFAULT_TTY_WIDTH;- ttyHeight = process.stdout.rows || DEFAULT_TTY_HEIGHT;+ ttyWidth = originalProcessStdout.columns || DEFAULT_TTY_WIDTH;+ ttyHeight = originalProcessStdout.rows || DEFAULT_TTY_HEIGHT;} else if (process.env.PLAYWRIGHT_FORCE_TTY) {isTTY = true;const sizeMatch = process.env.PLAYWRIGHT_FORCE_TTY.match(/^(\d+)x(\d+)$/);@@ -106,7 +118,9 @@ export const terminalScreen: Screen = (() => {isTTY,ttyWidth,ttyHeight,- colors+ colors,+ stdout: originalProcessStdout,+ stderr: originalProcessStderr,};})();@@ -129,7 +143,7 @@ export const internalScreen: Screen = {};export class TerminalReporter implements ReporterV2 {- screen: Screen = terminalScreen;+ screen: TerminalScreen = terminalScreen;config!: FullConfig;suite!: Suite;totalTestCount = 0;@@ -299,24 +313,24 @@ export class TerminalReporter implements ReporterV2 {}private _printFailures(failures: TestCase[]) {- console.log('');+ this.writeLine('');failures.forEach((test, index) => {- console.log(this.formatFailure(test, index + 1));+ this.writeLine(this.formatFailure(test, index + 1));});}private _printSlowTests() {const slowTests = this.getSlowTests();slowTests.forEach(([file, duration]) => {- console.log(this.screen.colors.yellow(' Slow test file: ') + file + this.screen.colors.yellow(` (${milliseconds(duration)})`));+ this.writeLine(this.screen.colors.yellow(' Slow test file: ') + file + this.screen.colors.yellow(` (${milliseconds(duration)})`));});if (slowTests.length)- console.log(this.screen.colors.yellow(' Consider running tests from slow files in parallel. See: https://playwright.dev/docs/test-parallel'));+ this.writeLine(this.screen.colors.yellow(' Consider running tests from slow files in parallel. See: https://playwright.dev/docs/test-parallel'));}private _printSummary(summary: string) {if (summary.trim())- console.log(summary);+ this.writeLine(summary);}willRetry(test: TestCase): boolean {@@ -338,6 +352,10 @@ export class TerminalReporter implements ReporterV2 {formatError(error: TestError): ErrorDetails {return formatError(this.screen, error);}++ writeLine(line?: string) {+ this.screen.stdout?.write(line ? line + '\n' : '\n');+ }}export function formatFailure(screen: Screen, config: FullConfig, test: TestCase, index?: number): string {diff --git a/packages/playwright/src/reporters/dot.ts b/packages/playwright/src/reporters/dot.tsindex b3e7b114c0..c2076147db 100644--- a/packages/playwright/src/reporters/dot.ts+++ b/packages/playwright/src/reporters/dot.ts@@ -23,52 +23,52 @@ class DotReporter extends TerminalReporter {override onBegin(suite: Suite) {super.onBegin(suite);- console.log(this.generateStartingMessage());+ this.writeLine(this.generateStartingMessage());}override onStdOut(chunk: string | Buffer, test?: TestCase, result?: TestResult) {super.onStdOut(chunk, test, result);if (!this.config.quiet)- process.stdout.write(chunk);+ this.screen.stdout.write(chunk);}override onStdErr(chunk: string | Buffer, test?: TestCase, result?: TestResult) {super.onStdErr(chunk, test, result);if (!this.config.quiet)- process.stderr.write(chunk);+ this.screen.stderr.write(chunk);}override onTestEnd(test: TestCase, result: TestResult) {super.onTestEnd(test, result);if (this._counter === 80) {- process.stdout.write('\n');+ this.screen.stdout.write('\n');this._counter = 0;}++this._counter;if (result.status === 'skipped') {- process.stdout.write(this.screen.colors.yellow('°'));+ this.screen.stdout.write(this.screen.colors.yellow('°'));return;}if (this.willRetry(test)) {- process.stdout.write(this.screen.colors.gray('×'));+ this.screen.stdout.write(this.screen.colors.gray('×'));return;}switch (test.outcome()) {- case 'expected': process.stdout.write(this.screen.colors.green('·')); break;- case 'unexpected': process.stdout.write(this.screen.colors.red(result.status === 'timedOut' ? 'T' : 'F')); break;- case 'flaky': process.stdout.write(this.screen.colors.yellow('±')); break;+ case 'expected': this.screen.stdout.write(this.screen.colors.green('·')); break;+ case 'unexpected': this.screen.stdout.write(this.screen.colors.red(result.status === 'timedOut' ? 'T' : 'F')); break;+ case 'flaky': this.screen.stdout.write(this.screen.colors.yellow('±')); break;}}override onError(error: TestError): void {super.onError(error);- console.log('\n' + this.formatError(error).message);+ this.writeLine('\n' + this.formatError(error).message);this._counter = 0;}override async onEnd(result: FullResult) {await super.onEnd(result);- process.stdout.write('\n');+ this.screen.stdout.write('\n');this.epilogue(true);}}diff --git a/packages/playwright/src/reporters/github.ts b/packages/playwright/src/reporters/github.tsindex 826981e862..ceac0d8914 100644--- a/packages/playwright/src/reporters/github.ts+++ b/packages/playwright/src/reporters/github.ts@@ -41,7 +41,8 @@ class GitHubLogger {const configs = Object.entries(options).map(([key, option]) => `${key}=${option}`).join(',');- console.log(stripAnsiEscapes(`::${type} ${configs}::${message}`));+ // eslint-disable-next-line no-restricted-properties+ process.stdout.write(stripAnsiEscapes(`::${type} ${configs}::${message}\n`));}debug(message: string, options?: GitHubLogOptions) {diff --git a/packages/playwright/src/reporters/html.ts b/packages/playwright/src/reporters/html.tsindex 98a4397705..5e92291f8b 100644--- a/packages/playwright/src/reporters/html.ts+++ b/packages/playwright/src/reporters/html.ts@@ -89,12 +89,12 @@ class HtmlReporter implements ReporterV2 {if (reportedWarnings.has(key))continue;reportedWarnings.add(key);- console.log(colors.red(`Configuration Error: HTML reporter output folder clashes with the tests output folder:`));- console.log(`+ writeLine(colors.red(`Configuration Error: HTML reporter output folder clashes with the tests output folder:`));+ writeLine(`html reporter folder: ${colors.bold(outputFolder)}test results folder: ${colors.bold(project.outputDir)}`);- console.log('');- console.log(`HTML reporter will clear its output directory prior to being generated, which will lead to the artifact loss.+ writeLine('');+ writeLine(`HTML reporter will clear its output directory prior to being generated, which will lead to the artifact loss.`);}}@@ -147,9 +147,9 @@ class HtmlReporter implements ReporterV2 {const relativeReportPath = this._outputFolder === standaloneDefaultFolder() ? '' : ' ' + path.relative(process.cwd(), this._outputFolder);const hostArg = this._host ? ` --host ${this._host}` : '';const portArg = this._port ? ` --port ${this._port}` : '';- console.log('');- console.log('To open last HTML report run:');- console.log(colors.cyan(`+ writeLine('');+ writeLine('To open last HTML report run:');+ writeLine(colors.cyan(`${packageManagerCommand} playwright show-report${relativeReportPath}${hostArg}${portArg}`));}@@ -168,7 +168,7 @@ function getHtmlReportOptionProcessEnv(): HtmlReportOpenOption | undefined {if (!htmlOpenEnv)return undefined;if (!isHtmlReportOption(htmlOpenEnv)) {- console.log(colors.red(`Configuration Error: HTML reporter Invalid value for PLAYWRIGHT_HTML_OPEN: ${htmlOpenEnv}. Valid values are: ${htmlReportOptions.join(', ')}`));+ writeLine(colors.red(`Configuration Error: HTML reporter Invalid value for PLAYWRIGHT_HTML_OPEN: ${htmlOpenEnv}. Valid values are: ${htmlReportOptions.join(', ')}`));return undefined;}return htmlOpenEnv;@@ -183,15 +183,15 @@ export async function showHTMLReport(reportFolder: string | undefined, host: strtry {assert(fs.statSync(folder).isDirectory());} catch (e) {- console.log(colors.red(`No report found at "${folder}"`));+ writeLine(colors.red(`No report found at "${folder}"`));gracefullyProcessExitDoNotHang(1);return;}const server = startHtmlReportServer(folder);await server.start({ port, host, preferredPort: port ? undefined : 9323 });let url = server.urlPrefix('human-readable');- console.log('');- console.log(colors.cyan(` Serving HTML report at ${url}. Press Ctrl+C to quit.`));+ writeLine('');+ writeLine(colors.cyan(` Serving HTML report at ${url}. Press Ctrl+C to quit.`));if (testId)url += `#?testId=${testId}`;url = url.replace('0.0.0.0', 'localhost');@@ -720,4 +720,9 @@ function createErrorCodeframe(message: string, location: Location) {);}+function writeLine(line: string) {+ // eslint-disable-next-line no-restricted-properties+ process.stdout.write(line + '\n');+}+export default HtmlReporter;diff --git a/packages/playwright/src/reporters/json.ts b/packages/playwright/src/reporters/json.tsindex fb2c0ace3d..5823746e50 100644--- a/packages/playwright/src/reporters/json.ts+++ b/packages/playwright/src/reporters/json.ts@@ -243,6 +243,7 @@ async function outputReport(report: JSONReport, resolvedOutputFile: string | undawait fs.promises.mkdir(path.dirname(resolvedOutputFile), { recursive: true });await fs.promises.writeFile(resolvedOutputFile, reportString);} else {+ // eslint-disable-next-line no-consoleconsole.log(reportString);}}diff --git a/packages/playwright/src/reporters/junit.ts b/packages/playwright/src/reporters/junit.tsindex 72d8da7c77..a5304da77a 100644--- a/packages/playwright/src/reporters/junit.ts+++ b/packages/playwright/src/reporters/junit.ts@@ -91,6 +91,7 @@ class JUnitReporter implements ReporterV2 {await fs.promises.mkdir(path.dirname(this.resolvedOutputFile), { recursive: true });await fs.promises.writeFile(this.resolvedOutputFile, reportString);} else {+ // eslint-disable-next-line no-consoleconsole.log(reportString);}}diff --git a/packages/playwright/src/reporters/line.ts b/packages/playwright/src/reporters/line.tsindex b0bf0fd6fd..3c34f22308 100644--- a/packages/playwright/src/reporters/line.ts+++ b/packages/playwright/src/reporters/line.ts@@ -28,20 +28,20 @@ class LineReporter extends TerminalReporter {super.onBegin(suite);const startingMessage = this.generateStartingMessage();if (startingMessage) {- console.log(startingMessage);- console.log();+ this.writeLine(startingMessage);+ this.writeLine();}this._didBegin = true;}override onStdOut(chunk: string | Buffer, test?: TestCase, result?: TestResult) {super.onStdOut(chunk, test, result);- this._dumpToStdio(test, chunk, process.stdout);+ this._dumpToStdio(test, chunk, this.screen.stdout);}override onStdErr(chunk: string | Buffer, test?: TestCase, result?: TestResult) {super.onStdErr(chunk, test, result);- this._dumpToStdio(test, chunk, process.stderr);+ this._dumpToStdio(test, chunk, this.screen.stderr);}private _dumpToStdio(test: TestCase | undefined, chunk: string | Buffer, stream: NodeJS.WriteStream) {@@ -58,9 +58,9 @@ class LineReporter extends TerminalReporter {stream.write(chunk);if (chunk[chunk.length - 1] !== '\n')- console.log();+ this.writeLine();- console.log();+ this.writeLine();}onTestBegin(test: TestCase, result: TestResult) {@@ -82,9 +82,9 @@ class LineReporter extends TerminalReporter {super.onTestEnd(test, result);if (!this.willRetry(test) && (test.outcome() === 'flaky' || test.outcome() === 'unexpected' || result.status === 'interrupted')) {if (!process.env.PW_TEST_DEBUG_REPORTERS)- process.stdout.write(`\u001B[1A\u001B[2K`);- console.log(this.formatFailure(test, ++this._failures));- console.log();+ this.screen.stdout.write(`\u001B[1A\u001B[2K`);+ this.writeLine(this.formatFailure(test, ++this._failures));+ this.writeLine();}}@@ -94,9 +94,9 @@ class LineReporter extends TerminalReporter {const currentRetrySuffix = result.retry ? this.screen.colors.yellow(` (retry #${result.retry})`) : '';const title = this.formatTestTitle(test, step) + currentRetrySuffix;if (process.env.PW_TEST_DEBUG_REPORTERS)- process.stdout.write(`${prefix + title}\n`);+ this.screen.stdout.write(`${prefix + title}\n`);else- process.stdout.write(`\u001B[1A\u001B[2K${prefix + this.fitToScreen(title, prefix)}\n`);+ this.screen.stdout.write(`\u001B[1A\u001B[2K${prefix + this.fitToScreen(title, prefix)}\n`);}override onError(error: TestError): void {@@ -104,14 +104,14 @@ class LineReporter extends TerminalReporter {const message = this.formatError(error).message + '\n';if (!process.env.PW_TEST_DEBUG_REPORTERS && this._didBegin)- process.stdout.write(`\u001B[1A\u001B[2K`);- process.stdout.write(message);- console.log();+ this.screen.stdout.write(`\u001B[1A\u001B[2K`);+ this.screen.stdout.write(message);+ this.writeLine();}override async onEnd(result: FullResult) {if (!process.env.PW_TEST_DEBUG_REPORTERS && this._didBegin)- process.stdout.write(`\u001B[1A\u001B[2K`);+ this.screen.stdout.write(`\u001B[1A\u001B[2K`);await super.onEnd(result);this.epilogue(false);}diff --git a/packages/playwright/src/reporters/list.ts b/packages/playwright/src/reporters/list.tsindex d494d1f56f..8f5bf4ebd2 100644--- a/packages/playwright/src/reporters/list.ts+++ b/packages/playwright/src/reporters/list.ts@@ -48,8 +48,8 @@ class ListReporter extends TerminalReporter {super.onBegin(suite);const startingMessage = this.generateStartingMessage();if (startingMessage) {- console.log(startingMessage);- console.log();+ this.writeLine(startingMessage);+ this.writeLine('');}}@@ -68,12 +68,12 @@ class ListReporter extends TerminalReporter {override onStdOut(chunk: string | Buffer, test?: TestCase, result?: TestResult) {super.onStdOut(chunk, test, result);- this._dumpToStdio(test, chunk, process.stdout);+ this._dumpToStdio(test, chunk, this.screen.stdout);}override onStdErr(chunk: string | Buffer, test?: TestCase, result?: TestResult) {super.onStdErr(chunk, test, result);- this._dumpToStdio(test, chunk, process.stderr);+ this._dumpToStdio(test, chunk, this.screen.stderr);}private getStepIndex(testIndex: string, result: TestResult, step: TestStep): string {@@ -133,7 +133,7 @@ class ListReporter extends TerminalReporter {private _maybeWriteNewLine() {if (this._needNewLine) {this._needNewLine = false;- process.stdout.write('\n');+ this.screen.stdout.write('\n');++this._lastRow;this._lastColumn = 0;}@@ -214,10 +214,10 @@ class ListReporter extends TerminalReporter {private _appendLine(text: string, prefix: string) {const line = prefix + this.fitToScreen(text, prefix);if (process.env.PW_TEST_DEBUG_REPORTERS) {- process.stdout.write('#' + this._lastRow + ' : ' + line + '\n');+ this.screen.stdout.write('#' + this._lastRow + ' : ' + line + '\n');} else {- process.stdout.write(line);- process.stdout.write('\n');+ this.screen.stdout.write(line);+ this.screen.stdout.write('\n');}++this._lastRow;this._lastColumn = 0;@@ -226,7 +226,7 @@ class ListReporter extends TerminalReporter {private _updateLine(row: number, text: string, prefix: string) {const line = prefix + this.fitToScreen(text, prefix);if (process.env.PW_TEST_DEBUG_REPORTERS)- process.stdout.write('#' + row + ' : ' + line + '\n');+ this.screen.stdout.write('#' + row + ' : ' + line + '\n');elsethis._updateLineForTTY(row, line);}@@ -234,13 +234,13 @@ class ListReporter extends TerminalReporter {private _updateLineForTTY(row: number, line: string) {// Go up if neededif (row !== this._lastRow)- process.stdout.write(`\u001B[${this._lastRow - row}A`);+ this.screen.stdout.write(`\u001B[${this._lastRow - row}A`);// Erase line, go to the start- process.stdout.write('\u001B[2K\u001B[0G');- process.stdout.write(line);+ this.screen.stdout.write('\u001B[2K\u001B[0G');+ this.screen.stdout.write(line);// Go down if needed.if (row !== this._lastRow)- process.stdout.write(`\u001B[${this._lastRow - row}E`);+ this.screen.stdout.write(`\u001B[${this._lastRow - row}E`);}private _testPrefix(index: string, statusMark: string) {@@ -258,12 +258,12 @@ class ListReporter extends TerminalReporter {this._maybeWriteNewLine();const message = this.formatError(error).message + '\n';this._updateLineCountAndNewLineFlagForOutput(message);- process.stdout.write(message);+ this.screen.stdout.write(message);}override async onEnd(result: FullResult) {await super.onEnd(result);- process.stdout.write('\n');+ this.screen.stdout.write('\n');this.epilogue(true);}}diff --git a/packages/playwright/src/reporters/listModeReporter.ts b/packages/playwright/src/reporters/listModeReporter.tsnew file mode 100644index 0000000000..2337067ed0--- /dev/null+++ b/packages/playwright/src/reporters/listModeReporter.ts@@ -0,0 +1,66 @@+/**+ * Copyright Microsoft Corporation. All rights reserved.+ *+ * 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 path from 'path';++import { formatError, terminalScreen } from './base';++import type { FullConfig, TestError } from '../../types/testReporter';+import type { Suite } from '../common/test';+import type { TerminalScreen } from './base';+import type { ReporterV2 } from './reporterV2';++class ListModeReporter implements ReporterV2 {+ private config!: FullConfig;+ private screen: TerminalScreen;++ constructor(options?: { screen?: TerminalScreen }) {+ this.screen = options?.screen ?? terminalScreen;+ }++ version(): 'v2' {+ return 'v2';+ }++ onConfigure(config: FullConfig) {+ this.config = config;+ }++ onBegin(suite: Suite): void {+ this._writeLine(`Listing tests:`);+ const tests = suite.allTests();+ const files = new Set<string>();+ for (const test of tests) {+ // root, project, file, ...describes, test+ const [, projectName, , ...titles] = test.titlePath();+ const location = `${path.relative(this.config.rootDir, test.location.file)}:${test.location.line}:${test.location.column}`;+ const projectTitle = projectName ? `[${projectName}] › ` : '';+ this._writeLine(` ${projectTitle}${location} › ${titles.join(' › ')}`);+ files.add(test.location.file);+ }+ this._writeLine(`Total: ${tests.length} ${tests.length === 1 ? 'test' : 'tests'} in ${files.size} ${files.size === 1 ? 'file' : 'files'}`);+ }++ onError(error: TestError) {+ this.screen.stderr.write('\n' + formatError(terminalScreen, error).message + '\n');+ }++ private _writeLine(line: string) {+ this.screen.stdout.write(line + '\n');+ }+}++export default ListModeReporter;diff --git a/packages/playwright/src/reporters/merge.ts b/packages/playwright/src/reporters/merge.tsindex 719cf3c567..b3f6b457ae 100644--- a/packages/playwright/src/reporters/merge.ts+++ b/packages/playwright/src/reporters/merge.ts@@ -344,6 +344,7 @@ async function sortedShardFiles(dir: string) {}function printStatusToStdout(message: string) {+ // eslint-disable-next-line no-restricted-propertiesprocess.stdout.write(`${message}\n`);}diff --git a/packages/playwright/src/reporters/multiplexer.ts b/packages/playwright/src/reporters/multiplexer.tsindex 9ecc9de0f3..2a11b93583 100644--- a/packages/playwright/src/reporters/multiplexer.ts+++ b/packages/playwright/src/reporters/multiplexer.ts@@ -101,6 +101,7 @@ async function wrapAsync<T>(callback: () => T | Promise<T>) {try {return await callback();} catch (e) {+ // eslint-disable-next-line no-consoleconsole.error('Error in reporter', e);}}@@ -109,6 +110,7 @@ function wrap(callback: () => void) {try {callback();} catch (e) {+ // eslint-disable-next-line no-consoleconsole.error('Error in reporter', e);}}diff --git a/packages/playwright/src/runner/reporters.ts b/packages/playwright/src/runner/reporters.tsindex 6fce6dbbd9..afe8a4c005 100644--- a/packages/playwright/src/runner/reporters.ts+++ b/packages/playwright/src/runner/reporters.ts@@ -14,12 +14,10 @@* limitations under the License.*/-import path from 'path';-import { calculateSha1 } from 'playwright-core/lib/utils';import { loadReporter } from './loadUtils';-import { formatError, terminalScreen } from '../reporters/base';+import { formatError } from '../reporters/base';import { BlobReporter } from '../reporters/blob';import DotReporter from '../reporters/dot';import EmptyReporter from '../reporters/empty';@@ -29,12 +27,12 @@ import JSONReporter from '../reporters/json';import JUnitReporter from '../reporters/junit';import LineReporter from '../reporters/line';import ListReporter from '../reporters/list';-import { wrapReporterAsV2 } from '../reporters/reporterV2';+import ListModeReporter from '../reporters/listModeReporter';+import { wrapReporterAsV2 } from '../reporters/reporterV2';import type { ReporterDescription } from '../../types/test';-import type { FullConfig, TestError } from '../../types/testReporter';+import type { TestError } from '../../types/testReporter';import type { BuiltInReporter, FullConfigInternal } from '../common/config';-import type { Suite } from '../common/test';import type { CommonReporterOptions, Screen } from '../reporters/base';import type { ReporterV2 } from '../reporters/reporterV2';@@ -100,7 +98,7 @@ export function createErrorCollectingReporter(screen: Screen, writeToConsole?: bonError(error: TestError) {errors.push(error);if (writeToConsole)- process.stdout.write(formatError(screen, error).message + '\n');+ screen.stderr?.write(formatError(screen, error).message + '\n');},errors: () => errors,};@@ -133,38 +131,3 @@ function computeCommandHash(config: FullConfigInternal) {parts.push(calculateSha1(JSON.stringify(command)).substring(0, 7));return parts.join('-');}--class ListModeReporter implements ReporterV2 {- private config!: FullConfig;-- version(): 'v2' {- return 'v2';- }-- onConfigure(config: FullConfig) {- this.config = config;- }-- onBegin(suite: Suite): void {- // eslint-disable-next-line no-console- console.log(`Listing tests:`);- const tests = suite.allTests();- const files = new Set<string>();- for (const test of tests) {- // root, project, file, ...describes, test- const [, projectName, , ...titles] = test.titlePath();- const location = `${path.relative(this.config.rootDir, test.location.file)}:${test.location.line}:${test.location.column}`;- const projectTitle = projectName ? `[${projectName}] › ` : '';- // eslint-disable-next-line no-console- console.log(` ${projectTitle}${location} › ${titles.join(' › ')}`);- files.add(test.location.file);- }- // eslint-disable-next-line no-console- console.log(`Total: ${tests.length} ${tests.length === 1 ? 'test' : 'tests'} in ${files.size} ${files.size === 1 ? 'file' : 'files'}`);- }-- onError(error: TestError) {- // eslint-disable-next-line no-console- console.error('\n' + formatError(terminalScreen, error).message);- }-}diff --git a/packages/playwright/src/runner/runner.ts b/packages/playwright/src/runner/runner.tsindex 22694c251e..3736b95beb 100644--- a/packages/playwright/src/runner/runner.ts+++ b/packages/playwright/src/runner/runner.ts@@ -98,7 +98,9 @@ export class Runner {// Calling process.exit() might truncate large stdout/stderr output.// See https://github.com/nodejs/node/issues/6456.// See https://github.com/nodejs/node/issues/12921+ // eslint-disable-next-line no-restricted-propertiesawait new Promise<void>(resolve => process.stdout.write('', () => resolve()));+ // eslint-disable-next-line no-restricted-propertiesawait new Promise<void>(resolve => process.stderr.write('', () => resolve()));return status;}diff --git a/packages/playwright/src/runner/testRunner.ts b/packages/playwright/src/runner/testRunner.tsindex f55b366f77..3f0f5b81c7 100644--- a/packages/playwright/src/runner/testRunner.ts+++ b/packages/playwright/src/runner/testRunner.ts@@ -118,10 +118,12 @@ export class TestRunner extends EventEmitter<TestRunnerEventMap> {}resizeTerminal(params: { cols: number, rows: number }) {+ /* eslint-disable no-restricted-properties */process.stdout.columns = params.cols;process.stdout.rows = params.rows;process.stderr.columns = params.cols;process.stderr.rows = params.rows;+ /* eslint-enable no-restricted-properties */}hasSomeBrowsers(): boolean {diff --git a/packages/playwright/src/runner/testServer.ts b/packages/playwright/src/runner/testServer.tsindex f0fc00beac..1418fddfc7 100644--- a/packages/playwright/src/runner/testServer.ts+++ b/packages/playwright/src/runner/testServer.ts@@ -35,7 +35,9 @@ import type { RecoverFromStepErrorResult, ReportEntry, TestServerInterface, Testimport type { ReporterV2 } from '../reporters/reporterV2';const originalDebugLog = debug.log;+// eslint-disable-next-line no-restricted-propertiesconst originalStdoutWrite = process.stdout.write;+// eslint-disable-next-line no-restricted-propertiesconst originalStderrWrite = process.stderr.write;class TestServer {@@ -233,6 +235,7 @@ export class TestServerDispatcher implements TestServerInterface {}async _setInterceptStdio(intercept: boolean) {+ /* eslint-disable no-restricted-properties */if (process.env.PWTEST_DEBUG)return;if (intercept) {@@ -243,19 +246,22 @@ export class TestServerDispatcher implements TestServerInterface {return (originalStderrWrite as any).apply(process.stderr, [string]);};}- process.stdout.write = (chunk: string | Buffer) => {+ const stdoutWrite = (chunk: string | Buffer) => {this._dispatchEvent('stdio', chunkToPayload('stdout', chunk));return true;};- process.stderr.write = (chunk: string | Buffer) => {+ const stderrWrite = (chunk: string | Buffer) => {this._dispatchEvent('stdio', chunkToPayload('stderr', chunk));return true;};+ process.stdout.write = stdoutWrite;+ process.stderr.write = stderrWrite;} else {debug.log = originalDebugLog;process.stdout.write = originalStdoutWrite;process.stderr.write = originalStderrWrite;}+ /* eslint-enable no-restricted-properties */}async closeGracefully() {diff --git a/packages/playwright/src/runner/watchMode.ts b/packages/playwright/src/runner/watchMode.tsindex 488a6cf888..6b3c7b405d 100644--- a/packages/playwright/src/runner/watchMode.ts+++ b/packages/playwright/src/runner/watchMode.ts@@ -35,6 +35,7 @@ import type * as reporterTypes from '../../types/testReporter';import type { ConfigLocation } from '../common/config';import type { TestServerTransport } from '../isomorphic/testServerConnection';+/* eslint-disable no-restricted-properties */class InMemoryTransport extends EventEmitter implements TestServerTransport {public readonly _send: (data: string) => void;diff --git a/packages/playwright/src/worker/workerMain.ts b/packages/playwright/src/worker/workerMain.tsindex 1fefb76a6d..0cfe0f65db 100644--- a/packages/playwright/src/worker/workerMain.ts+++ b/packages/playwright/src/worker/workerMain.ts@@ -78,6 +78,7 @@ export class WorkerMain extends ProcessRunner {process.on('unhandledRejection', reason => this.unhandledError(reason));process.on('uncaughtException', error => this.unhandledError(error));+ // eslint-disable-next-line no-restricted-propertiesprocess.stdout.write = (chunk: string | Buffer, cb?: any) => {this.dispatchEvent('stdOut', stdioChunkToParams(chunk));this._currentTest?._tracing.appendStdioToTrace('stdout', chunk);@@ -87,6 +88,7 @@ export class WorkerMain extends ProcessRunner {};if (!process.env.PW_RUNNER_DEBUG) {+ // eslint-disable-next-line no-restricted-propertiesprocess.stderr.write = (chunk: string | Buffer, cb?: any) => {this.dispatchEvent('stdErr', stdioChunkToParams(chunk));this._currentTest?._tracing.appendStdioToTrace('stderr', chunk);