Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/playwright-core/src/server/browserType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ export abstract class BrowserType extends SdkObject {
browserLogsCollector.log(message);
},
stdio: 'pipe',
waitForStdioClose: !this.getExecutableName(options).startsWith('msedge'),
tempDirectories: prepared.tempDirectories,
attemptToGracefullyClose: async () => {
if ((options as any).__testHookGracefullyClose)
Expand Down
9 changes: 7 additions & 2 deletions packages/utils/processLauncher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ export type LaunchProcessOptions = {
handleSIGTERM?: boolean,
handleSIGHUP?: boolean,
stdio: 'pipe' | 'stdin',
// Defaults to true. Set to false when a child process can spawn helpers
// that inherit stdio and outlive the child itself.
waitForStdioClose?: boolean,
tempDirectories: string[],

cwd?: string,
Expand Down Expand Up @@ -179,10 +182,11 @@ export async function launchProcess(options: LaunchProcessOptions): Promise<Laun
options.log(`[pid=${spawnedProcess.pid}][err] ` + data);
});

const waitForStdioClose = options.waitForStdioClose ?? true;
let processClosed = false;
let fulfillCleanup = () => {};
const waitForCleanup = new Promise<void>(f => fulfillCleanup = f);
spawnedProcess.once('close', (exitCode, signal) => {
const handleProcessExit = (exitCode: number | null, signal: string | null) => {
options.log(`[pid=${spawnedProcess.pid}] <process did exit: exitCode=${exitCode}, signal=${signal}>`);
processClosed = true;
gracefullyCloseSet.delete(gracefullyClose);
Expand All @@ -191,7 +195,8 @@ export async function launchProcess(options: LaunchProcessOptions): Promise<Laun
options.onExit(exitCode, signal);
// Cleanup as process exits.
cleanup().then(fulfillCleanup);
});
};
spawnedProcess.once(waitForStdioClose ? 'close' : 'exit', handleProcessExit);

addProcessHandlerIfNeeded('exit');
if (options.handleSIGINT)
Expand Down
91 changes: 91 additions & 0 deletions tests/playwright-test/process-launcher.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/**
* 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 './playwright-test-fixtures';
import fs from 'fs';
import { utils } from '../../packages/playwright-core/lib/coreBundle';

const { launchProcess } = utils;

async function launchProcessWithStdioGrandchild(pidFile: string, cleanupDir: string, waitForStdioClose: boolean) {
fs.mkdirSync(cleanupDir, { recursive: true });
let onExitCalls = 0;
const script = `
const { spawn } = require('child_process');
const fs = require('fs');
const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 30000)'], { stdio: 'inherit' });
fs.writeFileSync(process.argv[1], String(child.pid));
child.unref();
`;
const result = await launchProcess({
command: process.execPath,
args: ['-e', script, pidFile],
stdio: 'pipe',
waitForStdioClose,
tempDirectories: [cleanupDir],
attemptToGracefullyClose: async () => {},
handleSIGINT: false,
handleSIGTERM: false,
handleSIGHUP: false,
log: () => {},
onExit: () => ++onExitCalls,
});
return { ...result, onExitCalls: () => onExitCalls };
}

function killGrandchild(pidFile: string) {
if (!fs.existsSync(pidFile))
return;
const pid = +fs.readFileSync(pidFile, 'utf8');
try {
process.kill(pid, 'SIGKILL');
} catch (e) {
}
}

test('process launcher can wait for the main process exit without waiting for inherited stdio', async ({}, testInfo) => {
const pidFile = testInfo.outputPath('grandchild.pid');
const cleanupDir = testInfo.outputPath('cleanup');
const { gracefullyClose, onExitCalls } = await launchProcessWithStdioGrandchild(pidFile, cleanupDir, false);
try {
const start = Date.now();
await gracefullyClose();
expect(Date.now() - start).toBeLessThan(1000);
expect(onExitCalls()).toBe(1);
expect(fs.existsSync(cleanupDir)).toBe(false);
} finally {
killGrandchild(pidFile);
}
});

test('process launcher waits for stdio close by default', async ({}, testInfo) => {
const pidFile = testInfo.outputPath('grandchild.pid');
const cleanupDir = testInfo.outputPath('cleanup');
const { gracefullyClose, onExitCalls } = await launchProcessWithStdioGrandchild(pidFile, cleanupDir, true);
const closePromise = gracefullyClose();
try {
const closed = await Promise.race([
closePromise.then(() => true),
new Promise<boolean>(f => setTimeout(() => f(false), 1000)),
]);
expect(closed).toBe(false);
} finally {
killGrandchild(pidFile);
await closePromise;
expect(onExitCalls()).toBe(1);
expect(fs.existsSync(cleanupDir)).toBe(false);
}
});