blob: e2350397f957fe13e0319851d75714f188ce7755 [file] [edit]
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as fs from 'node:fs';
import type * as Yargs from 'yargs';
export function expandResponseFiles(args: string[]): string[] {
const expanded: string[] = [];
for (const arg of args) {
if (arg.startsWith('@') && arg.length > 1) {
const rspPath = arg.substring(1);
if (fs.existsSync(rspPath)) {
const content = fs.readFileSync(rspPath, 'utf-8');
const lines =
content.split(/\r?\n/).map(line => line.trim()).filter(line => line.length > 0 && !line.startsWith('#'));
for (const line of expandResponseFiles(lines)) {
expanded.push(line);
}
} else {
expanded.push(arg);
}
} else {
expanded.push(arg);
}
}
return expanded;
}
export const DiffBehaviors = {
UPDATE: 'update',
THROW: 'throw',
NO_THROW: 'no-throw',
NO_UPDATE: 'no-update',
} as const;
export type DiffBehaviors = typeof DiffBehaviors[keyof typeof DiffBehaviors];
export function asArray(value?: string|string[]): string[] {
if (!value) {
return [];
}
if (Array.isArray(value)) {
return value;
}
return [value];
}
export function normalizeForwardedOptions(unparsed: readonly string[]): string[] {
const args: string[] = [];
for (let i = 0; i < unparsed.length; i++) {
const arg = unparsed[i];
const next = unparsed[i + 1];
if (arg.startsWith('--') && arg !== '--' && !arg.includes('=') && next !== undefined && next.trim() !== '' &&
!Number.isNaN(Number(next))) {
// Mocha errors on --repeat 1 as it expects --repeat=1. We assume
// that this is the same for all args followed by a number.
args.push(`${arg}=${next}`);
i++;
} else {
args.push(arg);
}
}
return args;
}
function validateDiffBehaviors(args?: string|string[]) {
const failed = [];
for (const arg of asArray(args)) {
if (Object.values(DiffBehaviors).includes(arg as DiffBehaviors)) {
continue;
}
if (!arg.startsWith(`${DiffBehaviors.UPDATE}=`)) {
failed.push(arg);
}
}
if (failed.length > 0) {
throw new Error(
`Invalid options for --on-diff: ${failed}. Valid options are: ${Object.values(DiffBehaviors).join(', ')}`);
}
return asArray(args);
}
export interface CommandLineOptions {
debug: boolean;
headless?: boolean;
coverage: boolean;
'artifacts-dir'?: string;
'chrome-binary'?: string;
'enable-features'?: string|string[];
'disable-features'?: string|string[];
'on-diff'?: string[];
verbose: number;
shuffle: boolean;
repeat: number;
bail: boolean;
retries: number;
grep?: string;
fgrep?: string;
'invert-grep': boolean;
'cpu-throttle': number;
'shard-count': number;
'shard-number': number;
'shard-bias': number;
'expectations-file'?: string;
'force-screenshots': boolean;
'ota-username'?: string;
'ota-password'?: string;
'isolated-script-test-output'?: string;
'isolated-script-test-perf-output'?: string;
'isolated-script-test-filter'?: string|string[];
'isolated-script-test-filter-file'?: string|string[];
'dry-run': boolean;
jobs?: number;
}
export function commandLineArgs<T = Record<string, unknown>>(yargs: Yargs.Argv<T>): Yargs.Argv<T&CommandLineOptions> {
return yargs
.parserConfiguration({
'camel-case-expansion': false,
})
// TODO: add description
.command('$0 [tests..]', '')
.option('debug', {
type: 'boolean',
default: false,
desc: 'Execute tests in debug mode',
})
.option('headless', {
type: 'boolean',
desc: 'Whether to run tests headless. If unspecified, the default depends on the `debug` option',
})
.option('coverage', {
type: 'boolean',
default: false,
desc: 'Enable coverage reporting',
})
.option('artifacts-dir', {
type: 'string',
desc: 'Path to a directory to store test artifacts in (e.g. coverage reports)',
})
.option('chrome-binary', {
type: 'string',
desc: 'Path to a custom Chrome binary to run',
})
.option('enable-features', {
type: 'string',
desc: 'Comma-separated list of additional Chrome features to enable (can be repeated)',
})
.option('disable-features', {
type: 'string',
desc: 'Comma-separated list of additional Chrome features to disable (can be repeated)',
})
.option('on-diff', {
type: 'string',
coerce: validateDiffBehaviors,
choices: Object.values(DiffBehaviors),
desc: 'Define how to deal with diffs in snapshots/screenshots',
})
.option('verbose', {
alias: 'v',
type: 'count',
desc: 'Increases the log level',
})
.option('shuffle', {
type: 'boolean',
desc: 'Execute tests in random order',
default: false,
})
.option('repeat', {
alias: ['isolated-script-test-repeat'],
type: 'number',
default: 1,
desc: 'Reruns the test X number of times regardless of result',
})
.option('bail', {
alias: ['fail-fast'],
type: 'boolean',
default: false,
desc: 'Stops the test run after the first test failure',
})
.option('retries', {
alias: ['isolated-script-test-launcher-retry-limit'],
type: 'number',
desc: 'Reruns the tests if upon failure at max X number of times',
default: 0,
})
.option('grep', {
type: 'string',
conflicts: 'fgrep',
desc: 'Filter tests by name using grep',
})
.option('fgrep', {
type: 'string',
conflicts: 'grep',
desc: 'Filter tests by name using fgrep',
})
.option('invert-grep', {
type: 'boolean',
default: false,
desc: 'Invert the grep/fgrep result',
})
.option('cpu-throttle', {
type: 'number',
default: 1,
desc: 'Throttle the CPU during tests. The number provided is the multiplier used.',
})
.option('shard-count', {
type: 'number',
desc: 'Total number of shards to split the tests into.',
implies: 'shard-number',
default: Number(process.env['GTEST_TOTAL_SHARDS'] ?? 1),
})
.option('shard-number', {
type: 'number',
desc: 'The shard number to run (1-based).',
implies: 'shard-count',
default: Number(process.env['GTEST_SHARD_INDEX'] ?? 0) + 1,
})
.option('shard-bias', {
type: 'number',
desc: 'The bias to be used when calculating the sharding ' +
'hash. Biases the distribution of tests between different ' +
'shards for a given shard count. This is useful for ' +
're-sharding without changing the shard count.',
implies: ['shard-count', 'shard-number'], // shard-bias only makes sense if sharding is enabled
default: 0,
})
.option('expectations-file', {
type: 'string',
desc: 'Path to a custom TestExpectations file',
})
.option('force-screenshots', {
type: 'boolean',
default: false,
desc: 'Force running screenshot tests on non-Linux platforms',
})
.option('ota-username', {
type: 'string',
desc: 'Test account username used for Ai authentication logic in testing.',
})
.option('ota-password', {
type: 'string',
desc: 'Test account password used for Ai authentication logic in testing.',
})
.option('isolated-script-test-output', {
type: 'string',
desc: 'Path to write JSON Test Results Format v3 output to (used by Chromium Swarming).',
})
.option('isolated-script-test-perf-output', {
type: 'string',
desc: 'Path to write perf output to (passed by Chromium Swarming, unused by functional tests).',
})
.option('isolated-script-test-filter', {
type: 'string',
desc: '::-separated list of test filters (used by Chromium Swarming).',
})
.option('isolated-script-test-filter-file', {
type: 'string',
desc: 'Path to a file containing test filters (used by Chromium Swarming).',
})
.option('dry-run', {
type: 'boolean',
default: false,
desc: 'Check test IDs and print matched tests without running them',
})
.option('jobs', {
type: 'number',
desc: 'Number of parallel worker processes to use when supported by the suite',
});
}