test: unflake fixtures test (#2313)

Drive-by: ensure we call onkill before manually exiting the process.
This commit is contained in:
Dmitry Gozman 2020-05-20 14:58:27 -07:00 committed by GitHub
parent 9808d8bc03
commit 48440f7ed7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 170 additions and 115 deletions

View file

@ -142,6 +142,8 @@ export class Chromium extends AbstractBrowserType<CRBrowser> {
pipe: true, pipe: true,
tempDir: temporaryUserDataDir || undefined, tempDir: temporaryUserDataDir || undefined,
attemptToGracefullyClose: async () => { attemptToGracefullyClose: async () => {
if ((options as any).__testHookGracefullyClose)
await (options as any).__testHookGracefullyClose();
debugAssert(browserServer._isInitialized()); debugAssert(browserServer._isInitialized());
// We try to gracefully close to prevent crash reporting and core dumps. // We try to gracefully close to prevent crash reporting and core dumps.
// Note that it's fine to reuse the pipe transport, since // Note that it's fine to reuse the pipe transport, since

View file

@ -137,6 +137,8 @@ export class Firefox extends AbstractBrowserType<FFBrowser> {
pipe: false, pipe: false,
tempDir: temporaryProfileDir || undefined, tempDir: temporaryProfileDir || undefined,
attemptToGracefullyClose: async () => { attemptToGracefullyClose: async () => {
if ((options as any).__testHookGracefullyClose)
await (options as any).__testHookGracefullyClose();
debugAssert(browserServer._isInitialized()); debugAssert(browserServer._isInitialized());
// We try to gracefully close to prevent crash reporting and core dumps. // We try to gracefully close to prevent crash reporting and core dumps.
const transport = await WebSocketTransport.connect(browserWSEndpoint!, async transport => transport); const transport = await WebSocketTransport.connect(browserWSEndpoint!, async transport => transport);

View file

@ -111,18 +111,21 @@ export async function launchProcess(options: LaunchProcessOptions): Promise<Laun
const downloadsPath = options.omitDownloads ? '' : await mkdtempAsync(DOWNLOADS_FOLDER); const downloadsPath = options.omitDownloads ? '' : await mkdtempAsync(DOWNLOADS_FOLDER);
let processClosed = false; let processClosed = false;
const waitForProcessToClose = new Promise((fulfill, reject) => { let fulfillClose = () => {};
const waitForClose = new Promise(f => fulfillClose = f);
let fulfillCleanup = () => {};
const waitForCleanup = new Promise(f => fulfillCleanup = f);
spawnedProcess.once('exit', (exitCode, signal) => { spawnedProcess.once('exit', (exitCode, signal) => {
logger._log(browserLog, `<process did exit ${exitCode}, ${signal}>`); logger._log(browserLog, `<process did exit ${exitCode}, ${signal}>`);
processClosed = true; processClosed = true;
helper.removeEventListeners(listeners); helper.removeEventListeners(listeners);
options.onkill(exitCode, signal); options.onkill(exitCode, signal);
fulfillClose();
// Cleanup as processes exit. // Cleanup as processes exit.
Promise.all([ Promise.all([
options.omitDownloads ? Promise.resolve() : removeFolderAsync(downloadsPath), options.omitDownloads ? Promise.resolve() : removeFolderAsync(downloadsPath),
options.tempDir ? removeFolderAsync(options.tempDir) : Promise.resolve() options.tempDir ? removeFolderAsync(options.tempDir) : Promise.resolve()
]).catch((err: Error) => console.error(err)).then(fulfill); ]).catch((err: Error) => console.error(err)).then(fulfillCleanup);
});
}); });
const listeners = [ helper.addEventListener(process, 'exit', killProcess) ]; const listeners = [ helper.addEventListener(process, 'exit', killProcess) ];
@ -145,12 +148,13 @@ export async function launchProcess(options: LaunchProcessOptions): Promise<Laun
if (gracefullyClosing) { if (gracefullyClosing) {
logger._log(browserLog, `<forecefully close>`); logger._log(browserLog, `<forecefully close>`);
killProcess(); killProcess();
await waitForClose; // Ensure the process is dead and we called options.onkill.
return; return;
} }
gracefullyClosing = true; gracefullyClosing = true;
logger._log(browserLog, `<gracefully close start>`); logger._log(browserLog, `<gracefully close start>`);
await options.attemptToGracefullyClose().catch(() => killProcess()); await options.attemptToGracefullyClose().catch(() => killProcess());
await waitForProcessToClose; await waitForCleanup; // Ensure the process is dead and we have cleaned up.
logger._log(browserLog, `<gracefully close end>`); logger._log(browserLog, `<gracefully close end>`);
} }
@ -169,10 +173,12 @@ export async function launchProcess(options: LaunchProcessOptions): Promise<Laun
// the process might have already stopped // the process might have already stopped
} }
} }
// Attempt to remove temporary profile directory to avoid littering. // Attempt to remove temporary directories to avoid littering.
try { try {
if (options.tempDir) if (options.tempDir)
removeFolder.sync(options.tempDir); removeFolder.sync(options.tempDir);
if (!options.omitDownloads)
removeFolder.sync(downloadsPath);
} catch (e) { } } catch (e) { }
} }

View file

@ -125,6 +125,8 @@ export class WebKit extends AbstractBrowserType<WKBrowser> {
pipe: true, pipe: true,
tempDir: temporaryUserDataDir || undefined, tempDir: temporaryUserDataDir || undefined,
attemptToGracefullyClose: async () => { attemptToGracefullyClose: async () => {
if ((options as any).__testHookGracefullyClose)
await (options as any).__testHookGracefullyClose();
assert(transport); assert(transport);
// We try to gracefully close to prevent crash reporting and core dumps. // We try to gracefully close to prevent crash reporting and core dumps.
// Note that it's fine to reuse the pipe transport, since // Note that it's fine to reuse the pipe transport, since

View file

@ -19,57 +19,90 @@ const path = require('path');
const {spawn, execSync} = require('child_process'); const {spawn, execSync} = require('child_process');
const {FFOX, CHROMIUM, WEBKIT, WIN, LINUX} = require('./utils').testOptions(browserType); const {FFOX, CHROMIUM, WEBKIT, WIN, LINUX} = require('./utils').testOptions(browserType);
async function testSignal(state, action, exitOnClose) { class Wrapper {
const options = Object.assign({}, state.defaultBrowserOptions, { constructor(state, extraOptions) {
this._output = new Map();
this._outputCallback = new Map();
this._browserType = state.browserType;
const launchOptions = {...state.defaultBrowserOptions,
handleSIGINT: true, handleSIGINT: true,
handleSIGTERM: true, handleSIGTERM: true,
handleSIGHUP: true, handleSIGHUP: true,
executablePath: state.browserType.executablePath(), executablePath: state.browserType.executablePath(),
logger: undefined, logger: undefined,
}); };
const res = spawn('node', [path.join(__dirname, 'fixtures', 'closeme.js'), path.join(state.playwrightPath, 'index-for-dev'), state.browserType.name(), JSON.stringify(options), exitOnClose ? 'true' : '']); const options = {
let wsEndPointCallback; playwrightFile: path.join(state.playwrightPath, 'index-for-dev'),
const wsEndPointPromise = new Promise(x => wsEndPointCallback = x); browserTypeName: state.browserType.name(),
let output = ''; launchOptions,
let browserExitCode = 'none'; ...extraOptions,
let browserSignal = 'none'; };
let browserPid; this._child = spawn('node', [path.join(__dirname, 'fixtures', 'closeme.js'), JSON.stringify(options)]);
res.stdout.on('data', data => { this._child.on('error', (...args) => console.log("ERROR", ...args));
output += data.toString(); this._exitPromise = new Promise(resolve => this._child.on('exit', resolve));
// Uncomment to debug these tests.
let outputString = '';
this._child.stdout.on('data', data => {
outputString += data.toString();
// Uncomment to debug.
// console.log(data.toString()); // console.log(data.toString());
let match = output.match(/browserWS:(.+):browserWS/); let match;
if (match) while (match = outputString.match(/\(([^()]+)=>([^()]+)\)/)) {
wsEndPointCallback(match[1]); const key = match[1];
match = output.match(/browserClose:([^:]+):([^:]+):browserClose/); const value = match[2];
if (match) { this._addOutput(key, value);
browserExitCode = match[1]; outputString = outputString.substring(match.index + match[0].length);
browserSignal = match[2];
} }
match = output.match(/browserPid:([^:]+):browserPid/);
if (match)
browserPid = +match[1];
}); });
res.on('error', (...args) => console.log("ERROR", ...args)); }
const browser = await state.browserType.connect({ wsEndpoint: await wsEndPointPromise });
const promises = [ _addOutput(key, value) {
this._output.set(key, value);
const cb = this._outputCallback.get(key);
this._outputCallback.delete(key);
if (cb)
cb();
}
async out(key) {
if (!this._output.has(key))
await new Promise(f => this._outputCallback.set(key, f));
return this._output.get(key);
}
async connect() {
const wsEndpoint = await this.out('wsEndpoint');
const browser = await this._browserType.connect({ wsEndpoint });
this._exitAndDisconnectPromise = Promise.all([
this._exitPromise,
new Promise(resolve => browser.once('disconnected', resolve)), new Promise(resolve => browser.once('disconnected', resolve)),
new Promise(resolve => res.on('exit', resolve)), ]).then(([exitCode]) => exitCode);
]; }
action(res, browserPid);
const [, exitCode] = await Promise.all(promises); child() {
return { exitCode, browserSignal, browserExitCode, output }; return this._child;
}
async childExitCode() {
return await this._exitAndDisconnectPromise;
}
}
async function setup(state, options = {}) {
const wrapper = new Wrapper(state, options);
await wrapper.connect();
return wrapper;
} }
describe('Fixtures', function() { describe('Fixtures', function() {
it.slow()('should close the browser when the node process closes', async state => { it.slow()('should close the browser when the node process closes', async state => {
const result = await testSignal(state, child => { const wrapper = await setup(state);
if (WIN) if (WIN)
execSync(`taskkill /pid ${child.pid} /T /F`); execSync(`taskkill /pid ${wrapper.child().pid} /T /F`);
else else
process.kill(child.pid); process.kill(wrapper.child().pid);
}); expect(await wrapper.childExitCode()).toBe(WIN ? 1 : 0);
expect(result.exitCode).toBe(WIN ? 1 : 0);
// We might not get browser exitCode in time when killing the parent node process, // We might not get browser exitCode in time when killing the parent node process,
// so we don't check it here. // so we don't check it here.
}); });
@ -77,65 +110,70 @@ describe('Fixtures', function() {
describe.skip(WIN).skip(!HEADLESS)('signals', () => { describe.skip(WIN).skip(!HEADLESS)('signals', () => {
// Cannot reliably send signals on Windows. // Cannot reliably send signals on Windows.
it.slow()('should report browser close signal', async state => { it.slow()('should report browser close signal', async state => {
const result = await testSignal(state, (child, browserPid) => process.kill(browserPid), true); const wrapper = await setup(state);
expect(result.exitCode).toBe(0); const pid = await wrapper.out('pid');
expect(result.browserExitCode).toBe('null'); process.kill(-pid, 'SIGTERM');
expect(result.browserSignal).toBe('SIGTERM'); expect(await wrapper.out('exitCode')).toBe('null');
expect(await wrapper.out('signal')).toBe('SIGTERM');
process.kill(wrapper.child().pid);
await wrapper.childExitCode();
}); });
it.slow()('should report browser close signal 2', async state => { it.slow()('should report browser close signal 2', async state => {
const result = await testSignal(state, (child, browserPid) => process.kill(browserPid, 'SIGKILL'), true); const wrapper = await setup(state);
expect(result.exitCode).toBe(0); const pid = await wrapper.out('pid');
expect(result.browserExitCode).toBe('null'); process.kill(-pid, 'SIGKILL');
expect(result.browserSignal).toBe('SIGKILL'); expect(await wrapper.out('exitCode')).toBe('null');
expect(await wrapper.out('signal')).toBe('SIGKILL');
process.kill(wrapper.child().pid);
await wrapper.childExitCode();
}); });
it.slow()('should close the browser on SIGINT', async state => { it.slow()('should close the browser on SIGINT', async state => {
const result = await testSignal(state, child => process.kill(child.pid, 'SIGINT')); const wrapper = await setup(state);
expect(result.exitCode).toBe(130); process.kill(wrapper.child().pid, 'SIGINT');
expect(result.browserExitCode).toBe('0'); expect(await wrapper.out('exitCode')).toBe('0');
expect(result.browserSignal).toBe('null'); expect(await wrapper.out('signal')).toBe('null');
expect(await wrapper.childExitCode()).toBe(130);
}); });
it.slow()('should close the browser on SIGTERM', async state => { it.slow()('should close the browser on SIGTERM', async state => {
const result = await testSignal(state, child => process.kill(child.pid, 'SIGTERM')); const wrapper = await setup(state);
expect(result.exitCode).toBe(0); process.kill(wrapper.child().pid, 'SIGTERM');
expect(result.browserExitCode).toBe('0'); expect(await wrapper.out('exitCode')).toBe('0');
expect(result.browserSignal).toBe('null'); expect(await wrapper.out('signal')).toBe('null');
expect(await wrapper.childExitCode()).toBe(0);
}); });
it.slow()('should close the browser on SIGHUP', async state => { it.slow()('should close the browser on SIGHUP', async state => {
const result = await testSignal(state, child => process.kill(child.pid, 'SIGHUP')); const wrapper = await setup(state);
expect(result.exitCode).toBe(0); process.kill(wrapper.child().pid, 'SIGHUP');
expect(result.browserExitCode).toBe('0'); expect(await wrapper.out('exitCode')).toBe('0');
expect(result.browserSignal).toBe('null'); expect(await wrapper.out('signal')).toBe('null');
expect(await wrapper.childExitCode()).toBe(0);
}); });
it.slow()('should kill the browser on double SIGINT', async state => { it.slow()('should kill the browser on double SIGINT', async state => {
const result = await testSignal(state, child => { const wrapper = await setup(state, { stallOnClose: true });
process.kill(child.pid, 'SIGINT'); process.kill(wrapper.child().pid, 'SIGINT');
process.kill(child.pid, 'SIGINT'); await wrapper.out('stalled');
process.kill(wrapper.child().pid, 'SIGINT');
expect(await wrapper.out('exitCode')).toBe('null');
expect(await wrapper.out('signal')).toBe('SIGKILL');
expect(await wrapper.childExitCode()).toBe(130);
}); });
expect(result.exitCode).toBe(130); it.slow()('should kill the browser on SIGINT + SIGTERM', async state => {
// TODO: ideally, we would expect the SIGKILL on the browser from const wrapper = await setup(state, { stallOnClose: true });
// force kill, but that's racy with sending two signals. process.kill(wrapper.child().pid, 'SIGINT');
await wrapper.out('stalled');
process.kill(wrapper.child().pid, 'SIGTERM');
expect(await wrapper.out('exitCode')).toBe('null');
expect(await wrapper.out('signal')).toBe('SIGKILL');
expect(await wrapper.childExitCode()).toBe(0);
}); });
// TODO: flaky - https://app.circleci.com/pipelines/github/microsoft/playwright/582/workflows/b49033ce-fe20-4029-b665-13fb331f842e/jobs/579 it.slow()('should kill the browser on SIGTERM + SIGINT', async state => {
it.slow().fail(FFOX && LINUX)('should kill the browser on SIGINT + SIGTERM', async state => { const wrapper = await setup(state, { stallOnClose: true });
const result = await testSignal(state, child => { process.kill(wrapper.child().pid, 'SIGTERM');
process.kill(child.pid, 'SIGINT'); await wrapper.out('stalled');
process.kill(child.pid, 'SIGTERM'); process.kill(wrapper.child().pid, 'SIGINT');
}); expect(await wrapper.out('exitCode')).toBe('null');
expect(result.exitCode).toBe(130); expect(await wrapper.out('signal')).toBe('SIGKILL');
// TODO: ideally, we would expect the SIGKILL on the browser from expect(await wrapper.childExitCode()).toBe(130);
// force kill, but that's racy with sending two signals.
});
// TODO: flaky!
// - firefox: https://github.com/microsoft/playwright/pull/1911/checks?check_run_id=607148951
// - chromium: https://travis-ci.com/github/microsoft/playwright/builds/161356178
it.slow().fail((FFOX || CHROMIUM) && LINUX)('should kill the browser on SIGTERM + SIGINT', async state => {
const result = await testSignal(state, child => {
process.kill(child.pid, 'SIGTERM');
process.kill(child.pid, 'SIGINT');
});
expect(result.exitCode).toBe(130);
// TODO: ideally, we would expect the SIGKILL on the browser from
// force kill, but that's racy with sending two signals.
}); });
}); });
}); });

View file

@ -1,11 +1,16 @@
(async() => { (async() => {
const [, , playwrightIndex, browserType, options, exitOnClose] = process.argv; const { playwrightFile, browserTypeName, launchOptions, stallOnClose } = JSON.parse(process.argv[2]);
const browserServer = await require(playwrightIndex)[browserType].launchServer(JSON.parse(options)); if (stallOnClose) {
launchOptions.__testHookGracefullyClose = () => {
console.log(`(stalled=>true)`);
return new Promise(() => {});
};
}
const browserServer = await require(playwrightFile)[browserTypeName].launchServer(launchOptions);
browserServer.on('close', (exitCode, signal) => { browserServer.on('close', (exitCode, signal) => {
console.log(`browserClose:${exitCode}:${signal}:browserClose`); console.log(`(exitCode=>${exitCode})`);
if (exitOnClose) console.log(`(signal=>${signal})`);
process.exit(0);
}); });
console.log(`browserPid:${browserServer.process().pid}:browserPid`); console.log(`(pid=>${browserServer.process().pid})`);
console.log(`browserWS:${browserServer.wsEndpoint()}:browserWS`); console.log(`(wsEndpoint=>${browserServer.wsEndpoint()})`);
})(); })();