Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

fix(git): do not hang when git fetch stalls on a credential prompt (#42639)

Pavel Feldmanaafd6e7debec
diff --git a/packages/playwright-core/src/server/registry/dependencies.ts b/packages/playwright-core/src/server/registry/dependencies.ts
index 8d0b47911a..f472aaa3c9 100644
--- a/packages/playwright-core/src/server/registry/dependencies.ts
+++ b/packages/playwright-core/src/server/registry/dependencies.ts
@@ -21,7 +21,7 @@ import path from 'path';
import { wrapInASCIIBox } from '@utils/ascii';
import { hostPlatform, isOfficiallySupportedPlatform } from '@utils/hostPlatform';
-import { spawnAsync } from '@utils/spawnAsync';
+import { spawnAsync } from '@utils/processLauncher';
import { getPlaywrightVersion } from '../userAgent';
import { deps } from './nativeDeps';
diff --git a/packages/playwright-core/src/server/registry/index.ts b/packages/playwright-core/src/server/registry/index.ts
index 077fd78ebf..36fad71b97 100644
--- a/packages/playwright-core/src/server/registry/index.ts
+++ b/packages/playwright-core/src/server/registry/index.ts
@@ -24,7 +24,7 @@ import { wrapInASCIIBox } from '@utils/ascii';
import { debugLogger } from '@utils/debugLogger';
import { shortPlatform, hostPlatform, isOfficiallySupportedPlatform } from '@utils/hostPlatform';
import { NET_DEFAULT_TIMEOUT } from '@utils/network';
-import { spawnAsync } from '@utils/spawnAsync';
+import { spawnAsync } from '@utils/processLauncher';
import { canAccessFile, existsAsync, removeFolders } from '@utils/fileUtils';
import { calculateSha1 } from '@utils/crypto';
import { getAsBooleanFromENV, getFromENV, getPackageManagerExecCommand } from '@utils/env';
diff --git a/packages/playwright-core/src/server/webkit/webkit.ts b/packages/playwright-core/src/server/webkit/webkit.ts
index d4df20b828..3ab0f3ea6d 100644
--- a/packages/playwright-core/src/server/webkit/webkit.ts
+++ b/packages/playwright-core/src/server/webkit/webkit.ts
@@ -19,7 +19,7 @@ import path from 'path';
import { ManualPromise } from '@isomorphic/manualPromise';
import { wrapInASCIIBox } from '@utils/ascii';
-import { spawnAsync } from '@utils/spawnAsync';
+import { spawnAsync } from '@utils/processLauncher';
import { kBrowserCloseMessageId } from './wkConnection';
import { Browser } from '../browser';
import { BrowserType, kNoXServerRunningError } from '../browserType';
diff --git a/packages/playwright/src/plugins/gitCommitInfoPlugin.ts b/packages/playwright/src/plugins/gitCommitInfoPlugin.ts
index cd63dc5eb7..b025690f8a 100644
--- a/packages/playwright/src/plugins/gitCommitInfoPlugin.ts
+++ b/packages/playwright/src/plugins/gitCommitInfoPlugin.ts
@@ -16,8 +16,7 @@
import * as fs from 'fs';
-import { monotonicTime } from '@isomorphic/time';
-import { spawnAsync } from '@utils/spawnAsync';
+import { spawnAsync } from '@utils/processLauncher';
import type { TestRunnerPlugin } from './';
import type { FullConfig } from '../../types/testReporter';
@@ -195,13 +194,14 @@ async function gitDiff(gitDir: string, ci?: CIInfo): Promise<string | undefined>
async function runGit(args: string[], cwd: string): Promise<string | undefined> {
debug(`running "git ${args.join(' ')}"`);
- const start = monotonicTime();
- const result = await spawnAsync(
- 'git',
- args,
- { stdio: 'pipe', cwd, timeout: GIT_OPERATIONS_TIMEOUT_MS }
- );
- if (monotonicTime() - start > GIT_OPERATIONS_TIMEOUT_MS) {
+ // Fail fast instead of blocking in a credential prompt that nobody can answer on CI.
+ const result = await spawnAsync('git', ['-c', 'credential.interactive=false', ...args], {
+ stdio: 'pipe',
+ cwd,
+ timeout: GIT_OPERATIONS_TIMEOUT_MS,
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
+ });
+ if (result.timedOut) {
print(`timeout of ${GIT_OPERATIONS_TIMEOUT_MS}ms exceeded while running "git ${args.join(' ')}"`);
return;
}
diff --git a/packages/playwright/src/runner/processHost.ts b/packages/playwright/src/runner/processHost.ts
index b812b70024..ea3b589aab 100644
--- a/packages/playwright/src/runner/processHost.ts
+++ b/packages/playwright/src/runner/processHost.ts
@@ -21,6 +21,7 @@ import debug from 'debug';
import { assert } from '@isomorphic/assert';
import { monotonicTime, timeOrigin } from '@isomorphic/time';
import { raceAgainstDeadline } from '@isomorphic/timeoutRunner';
+import { killProcessTree } from '@utils/processLauncher';
import type { ipc, processRunner } from '../common';
@@ -193,17 +194,8 @@ export class ProcessHost extends EventEmitter {
}
private _forceKill() {
- const pid = this.process?.pid;
- if (!pid)
- return;
- try {
- if (process.platform === 'win32')
- child_process.spawnSync(`taskkill /pid ${pid} /T /F`, { shell: true });
- else
- process.kill(pid, 'SIGKILL');
- } catch {
- // The process may have already exited.
- }
+ if (this.process?.pid)
+ killProcessTree(this.process.pid);
}
didSendStop() {
diff --git a/packages/utils/index.ts b/packages/utils/index.ts
index 4a1588658d..5231fef6e5 100644
--- a/packages/utils/index.ts
+++ b/packages/utils/index.ts
@@ -31,7 +31,6 @@ export * from './processLauncher';
export * from './profiler';
export * from './serializedFS';
export * from './socksProxy';
-export * from './spawnAsync';
export * from './stackTrace';
export * from './stringWidth';
export * from './wsServer';
diff --git a/packages/utils/processLauncher.ts b/packages/utils/processLauncher.ts
index f865dda5aa..662ac482d6 100644
--- a/packages/utils/processLauncher.ts
+++ b/packages/utils/processLauncher.ts
@@ -22,6 +22,8 @@ import * as readline from 'readline';
import { removeFolders } from './fileUtils';
import { isUnderTest } from './debug';
+import type { SpawnOptions } from 'child_process';
+
export type LaunchProcessOptions = {
command: string,
args?: string[],
@@ -232,16 +234,10 @@ export async function launchProcess(options: LaunchProcessOptions): Promise<Laun
options.log(`[pid=${spawnedProcess.pid}] <will force kill>`);
// Force kill the browser.
try {
- if (process.platform === 'win32') {
- const taskkillProcess = childProcess.spawnSync(`taskkill /pid ${spawnedProcess.pid} /T /F`, { shell: true, windowsHide: true });
- const [stdout, stderr] = [taskkillProcess.stdout.toString(), taskkillProcess.stderr.toString()];
- if (stdout)
- options.log(`[pid=${spawnedProcess.pid}] taskkill stdout: ${stdout}`);
- if (stderr)
- options.log(`[pid=${spawnedProcess.pid}] taskkill stderr: ${stderr}`);
- } else {
+ if (process.platform === 'win32')
+ killProcessTree(spawnedProcess.pid);
+ else
process.kill(-spawnedProcess.pid, 'SIGKILL');
- }
} catch (e) {
options.log(`[pid=${spawnedProcess.pid}] exception while trying to kill process: ${e}`);
// the process might have already stopped
@@ -272,6 +268,45 @@ export async function launchProcess(options: LaunchProcessOptions): Promise<Laun
return { launchedProcess: spawnedProcess, gracefullyClose, kill: killAndWait };
}
+export function killProcessTree(pid: number) {
+ try {
+ if (process.platform === 'win32')
+ childProcess.spawnSync(`taskkill /pid ${pid} /T /F`, { shell: true, windowsHide: true });
+ else
+ process.kill(pid, 'SIGKILL');
+ } catch {
+ // The process may have already exited.
+ }
+}
+
+export function spawnAsync(cmd: string, args: string[], options: SpawnOptions = {}): Promise<{stdout: string, stderr: string, code: number | null, error?: Error, timedOut?: boolean}> {
+ const { timeout, ...spawnOptions } = options;
+ const child = childProcess.spawn(cmd, args, { windowsHide: true, ...spawnOptions });
+
+ return new Promise(resolve => {
+ let stdout = '';
+ let stderr = '';
+ if (child.stdout)
+ child.stdout.on('data', data => stdout += data.toString());
+ if (child.stderr)
+ child.stderr.on('data', data => stderr += data.toString());
+ // Node's timeout only kills the direct child; 'close' never fires while grandchildren hold the stdio pipes.
+ const timer = timeout ? setTimeout(() => {
+ if (child.pid)
+ killProcessTree(child.pid);
+ resolve({ stdout, stderr, code: null, timedOut: true });
+ }, timeout) : undefined;
+ child.on('close', code => {
+ clearTimeout(timer);
+ resolve({ stdout, stderr, code });
+ });
+ child.on('error', error => {
+ clearTimeout(timer);
+ resolve({ stdout, stderr, code: 0, error });
+ });
+ });
+}
+
export function envArrayToObject(env: { name: string, value: string }[]): NodeJS.ProcessEnv {
const result: NodeJS.ProcessEnv = {};
for (const { name, value } of env)
diff --git a/packages/utils/spawnAsync.ts b/packages/utils/spawnAsync.ts
deleted file mode 100644
index c3bb8f086c..0000000000
--- a/packages/utils/spawnAsync.ts
+++ /dev/null
@@ -1,36 +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 { spawn } from 'child_process';
-
-import type { SpawnOptions } from 'child_process';
-
-export function spawnAsync(cmd: string, args: string[], options: SpawnOptions = {}): Promise<{stdout: string, stderr: string, code: number | null, error?: Error}> {
- const process = spawn(cmd, args, Object.assign({ windowsHide: true }, options));
-
- 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/tests/playwright-test/reporter-html.spec.ts b/tests/playwright-test/reporter-html.spec.ts
index 5a0b7f59c8..5bc4740eaa 100644
--- a/tests/playwright-test/reporter-html.spec.ts
+++ b/tests/playwright-test/reporter-html.spec.ts
@@ -3372,6 +3372,42 @@ for (const useIntermediateMergeReport of [true, false] as const) {
expect(isShallow.trim()).toBe('false');
});
+ test('should not hang when git fetch stalls', async ({ runInlineTest, writeFiles, useIntermediateMergeReport }) => {
+ test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/42630' });
+ test.skip(useIntermediateMergeReport, 'plugin output is not available in merge report');
+ const files = {
+ 'playwright.config.ts': `export default {}`,
+ 'example.spec.ts': `
+ import { test, expect } from '@playwright/test';
+ test('sample', async ({}) => { expect(2).toBe(2); });
+ `,
+ 'hang.js': `
+ require('fs').writeFileSync(__filename + '.pid', String(process.pid));
+ setTimeout(() => {}, 120_000);
+ `,
+ };
+ const baseDir = await writeFiles(files);
+ await initGitRepo(baseDir);
+ await execGit(baseDir, ['remote', 'add', 'origin', 'ssh://example.com/repo.git']);
+ const hangScript = path.join(baseDir, 'hang.js');
+ const sshCommand = [process.execPath, hangScript].map(p => JSON.stringify(p.replace(/\\/g, '/'))).join(' ');
+ await execGit(baseDir, ['config', '--local', 'core.sshCommand', sshCommand]);
+ await execGit(baseDir, ['config', '--local', 'ssh.variant', 'ssh']);
+
+ const result = await runInlineTest({}, { reporter: 'dot' }, {
+ PLAYWRIGHT_HTML_OPEN: 'never',
+ ...(await ghaPullRequestEnv(baseDir, '1'.repeat(40))),
+ });
+ try {
+ process.kill(+await fs.promises.readFile(hangScript + '.pid', 'utf8'), 'SIGKILL');
+ } catch {
+ }
+
+ expect(result.exitCode).toBe(0);
+ expect(result.output).toContain('timeout of 3000ms exceeded while running "git fetch origin');
+ expect(result.report.config.metadata.gitDiff).toBeUndefined();
+ });
+
test('should include snapshot when page wasnt closed', async ({ runInlineTest, showReport, page }) => {
const result = await runInlineTest({
'example.spec.ts': `