electron/script/spec-runner.js

272 lines
8.6 KiB
JavaScript
Raw Normal View History

#!/usr/bin/env node
2020-03-20 20:28:31 +00:00
const childProcess = require('child_process');
const crypto = require('crypto');
const fs = require('fs-extra');
2020-03-20 20:28:31 +00:00
const { hashElement } = require('folder-hash');
const path = require('path');
const unknownFlags = [];
2020-03-20 20:28:31 +00:00
require('colors');
const pass = '✓'.green;
const fail = '✗'.red;
2019-03-13 22:09:28 +00:00
const args = require('minimist')(process.argv, {
string: ['runners', 'target'],
boolean: ['buildNativeTests'],
unknown: arg => unknownFlags.push(arg)
2020-03-20 20:28:31 +00:00
});
2020-03-20 20:28:31 +00:00
const unknownArgs = [];
for (const flag of unknownFlags) {
2020-03-20 20:28:31 +00:00
unknownArgs.push(flag);
const onlyFlag = flag.replace(/^-+/, '');
if (args[onlyFlag]) {
2020-03-20 20:28:31 +00:00
unknownArgs.push(args[onlyFlag]);
}
}
2020-03-20 20:28:31 +00:00
const utils = require('./lib/utils');
const { YARN_VERSION } = require('./yarn');
2020-03-20 20:28:31 +00:00
const BASE = path.resolve(__dirname, '../..');
const NPX_CMD = process.platform === 'win32' ? 'npx.cmd' : 'npx';
const runners = new Map([
['main', { description: 'Main process specs', run: runMainProcessElectronTests }],
['remote', { description: 'Remote based specs', run: runRemoteBasedElectronTests }],
['native', { description: 'Native specs', run: runNativeElectronTests }]
2020-03-20 20:28:31 +00:00
]);
2020-03-20 20:28:31 +00:00
const specHashPath = path.resolve(__dirname, '../spec/.hash');
2020-03-20 20:28:31 +00:00
let runnersToRun = null;
2019-03-15 00:22:42 +00:00
if (args.runners) {
2020-03-20 20:28:31 +00:00
runnersToRun = args.runners.split(',');
if (!runnersToRun.every(r => [...runners.keys()].includes(r))) {
2020-03-20 20:28:31 +00:00
console.log(`${fail} ${runnersToRun} must be a subset of [${[...runners.keys()].join(' | ')}]`);
process.exit(1);
}
2020-03-20 20:28:31 +00:00
console.log('Only running:', runnersToRun);
} else {
2020-03-20 20:28:31 +00:00
console.log(`Triggering runners: ${[...runners.keys()].join(', ')}`);
}
async function main () {
2020-03-20 20:28:31 +00:00
const [lastSpecHash, lastSpecInstallHash] = loadLastSpecHash();
const [currentSpecHash, currentSpecInstallHash] = await getSpecHash();
const somethingChanged = (currentSpecHash !== lastSpecHash) ||
2020-03-20 20:28:31 +00:00
(lastSpecInstallHash !== currentSpecInstallHash);
if (somethingChanged) {
2020-03-20 20:28:31 +00:00
await installSpecModules(path.resolve(__dirname, '..', 'spec'));
await installSpecModules(path.resolve(__dirname, '..', 'spec-main'));
await getSpecHash().then(saveSpecHash);
}
if (!fs.existsSync(path.resolve(__dirname, '../electron.d.ts'))) {
2020-03-20 20:28:31 +00:00
console.log('Generating electron.d.ts as it is missing');
generateTypeDefinitions();
}
2020-03-20 20:28:31 +00:00
await runElectronTests();
}
function generateTypeDefinitions () {
const { status } = childProcess.spawnSync('npm', ['run', 'create-typescript-definitions'], {
cwd: path.resolve(__dirname, '..'),
stdio: 'inherit',
shell: true
2020-03-20 20:28:31 +00:00
});
if (status !== 0) {
2020-03-20 20:28:31 +00:00
throw new Error(`Electron typescript definition generation failed with exit code: ${status}.`);
}
}
function loadLastSpecHash () {
return fs.existsSync(specHashPath)
? fs.readFileSync(specHashPath, 'utf8').split('\n')
2020-03-20 20:28:31 +00:00
: [null, null];
}
function saveSpecHash ([newSpecHash, newSpecInstallHash]) {
2020-03-20 20:28:31 +00:00
fs.writeFileSync(specHashPath, `${newSpecHash}\n${newSpecInstallHash}`);
}
async function runElectronTests () {
2020-03-20 20:28:31 +00:00
const errors = [];
2020-03-20 20:28:31 +00:00
const testResultsDir = process.env.ELECTRON_TEST_RESULTS_DIR;
for (const [runnerId, { description, run }] of runners) {
if (runnersToRun && !runnersToRun.includes(runnerId)) {
2020-03-20 20:28:31 +00:00
console.info('\nSkipping:', description);
continue;
}
try {
2020-03-20 20:28:31 +00:00
console.info('\nRunning:', description);
if (testResultsDir) {
2020-03-20 20:28:31 +00:00
process.env.MOCHA_FILE = path.join(testResultsDir, `test-results-${runnerId}.xml`);
}
2020-03-20 20:28:31 +00:00
await run();
} catch (err) {
2020-03-20 20:28:31 +00:00
errors.push([runnerId, err]);
}
}
if (errors.length !== 0) {
for (const err of errors) {
2020-03-20 20:28:31 +00:00
console.error('\n\nRunner Failed:', err[0]);
console.error(err[1]);
}
2020-03-20 20:28:31 +00:00
console.log(`${fail} Electron test runners have failed`);
process.exit(1);
}
}
async function runRemoteBasedElectronTests () {
2020-03-20 20:28:31 +00:00
let exe = path.resolve(BASE, utils.getElectronExec());
const runnerArgs = ['electron/spec', ...unknownArgs.slice(2)];
if (process.platform === 'linux') {
2020-03-20 20:28:31 +00:00
runnerArgs.unshift(path.resolve(__dirname, 'dbus_mock.py'), exe);
exe = 'python';
}
2019-03-13 22:09:28 +00:00
const { status } = childProcess.spawnSync(exe, runnerArgs, {
cwd: path.resolve(__dirname, '../..'),
stdio: 'inherit'
2020-03-20 20:28:31 +00:00
});
if (status !== 0) {
2020-03-20 20:28:31 +00:00
const textStatus = process.platform === 'win32' ? `0x${status.toString(16)}` : status.toString();
console.log(`${fail} Electron tests failed with code ${textStatus}.`);
process.exit(1);
}
2020-03-20 20:28:31 +00:00
console.log(`${pass} Electron remote process tests passed.`);
}
async function runNativeElectronTests () {
2020-03-20 20:28:31 +00:00
let testTargets = require('./native-test-targets.json');
const outDir = `out/${utils.getOutDir()}`;
// If native tests are being run, only one arg would be relevant
if (args.target && !testTargets.includes(args.target)) {
2020-03-20 20:28:31 +00:00
console.log(`${fail} ${args.target} must be a subset of [${[testTargets].join(', ')}]`);
process.exit(1);
}
// Optionally build all native test targets
if (args.buildNativeTests) {
for (const target of testTargets) {
const build = childProcess.spawnSync('ninja', ['-C', outDir, target], {
cwd: path.resolve(__dirname, '../..'),
stdio: 'inherit'
2020-03-20 20:28:31 +00:00
});
// Exit if test target failed to build
if (build.status !== 0) {
2020-03-20 20:28:31 +00:00
console.log(`${fail} ${target} failed to build.`);
process.exit(1);
}
}
}
// If a specific target was passed, only build and run that target
2020-03-20 20:28:31 +00:00
if (args.target) testTargets = [args.target];
// Run test targets
2020-03-20 20:28:31 +00:00
const failures = [];
for (const target of testTargets) {
2020-03-20 20:28:31 +00:00
console.info('\nRunning native test for target:', target);
const testRun = childProcess.spawnSync(`./${outDir}/${target}`, {
cwd: path.resolve(__dirname, '../..'),
stdio: 'inherit'
2020-03-20 20:28:31 +00:00
});
// Collect failures and log at end
2020-03-20 20:28:31 +00:00
if (testRun.status !== 0) failures.push({ target });
}
// Exit if any failures
if (failures.length > 0) {
2020-03-20 20:28:31 +00:00
console.log(`${fail} Electron native tests failed for the following targets: `, failures);
process.exit(1);
}
2020-03-20 20:28:31 +00:00
console.log(`${pass} Electron native tests passed.`);
}
async function runMainProcessElectronTests () {
2020-03-20 20:28:31 +00:00
let exe = path.resolve(BASE, utils.getElectronExec());
const runnerArgs = ['electron/spec-main', ...unknownArgs.slice(2)];
2019-08-28 20:54:50 +00:00
if (process.platform === 'linux') {
2020-03-20 20:28:31 +00:00
runnerArgs.unshift(path.resolve(__dirname, 'dbus_mock.py'), exe);
exe = 'python';
2019-08-28 20:54:50 +00:00
}
const { status, signal } = childProcess.spawnSync(exe, runnerArgs, {
cwd: path.resolve(__dirname, '../..'),
stdio: 'inherit'
2020-03-20 20:28:31 +00:00
});
if (status !== 0) {
if (status) {
2020-03-20 20:28:31 +00:00
const textStatus = process.platform === 'win32' ? `0x${status.toString(16)}` : status.toString();
console.log(`${fail} Electron tests failed with code ${textStatus}.`);
} else {
2020-03-20 20:28:31 +00:00
console.log(`${fail} Electron tests failed with kill signal ${signal}.`);
}
2020-03-20 20:28:31 +00:00
process.exit(1);
}
2020-03-20 20:28:31 +00:00
console.log(`${pass} Electron main process tests passed.`);
}
async function installSpecModules (dir) {
2020-03-20 20:28:31 +00:00
const nodeDir = path.resolve(BASE, `out/${utils.getOutDir({ shouldLog: true })}/gen/node_headers`);
const env = Object.assign({}, process.env, {
npm_config_nodedir: nodeDir,
npm_config_msvs_version: '2019',
npm_config_yes: 'true'
2020-03-20 20:28:31 +00:00
});
if (fs.existsSync(path.resolve(dir, 'node_modules'))) {
await fs.remove(path.resolve(dir, 'node_modules'));
}
const { status } = childProcess.spawnSync(NPX_CMD, [`yarn@${YARN_VERSION}`, 'install', '--frozen-lockfile'], {
env,
cwd: dir,
stdio: 'inherit'
2020-03-20 20:28:31 +00:00
});
if (status !== 0 && !process.env.IGNORE_YARN_INSTALL_ERROR) {
2020-03-20 20:28:31 +00:00
console.log(`${fail} Failed to yarn install in '${dir}'`);
process.exit(1);
}
}
function getSpecHash () {
return Promise.all([
(async () => {
2020-03-20 20:28:31 +00:00
const hasher = crypto.createHash('SHA256');
hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec/package.json')));
hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec-main/package.json')));
hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec/yarn.lock')));
hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec-main/yarn.lock')));
hasher.update(fs.readFileSync(path.resolve(__dirname, '../script/spec-runner.js')));
2020-03-20 20:28:31 +00:00
return hasher.digest('hex');
})(),
(async () => {
2020-03-20 20:28:31 +00:00
const specNodeModulesPath = path.resolve(__dirname, '../spec/node_modules');
if (!fs.existsSync(specNodeModulesPath)) {
2020-03-20 20:28:31 +00:00
return null;
}
const { hash } = await hashElement(specNodeModulesPath, {
folders: {
exclude: ['.bin']
}
2020-03-20 20:28:31 +00:00
});
return hash;
})()
2020-03-20 20:28:31 +00:00
]);
}
main().catch((error) => {
2020-03-20 20:28:31 +00:00
console.error('An error occurred inside the spec runner:', error);
process.exit(1);
});