spec-runner.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. #!/usr/bin/env node
  2. const childProcess = require('child_process');
  3. const crypto = require('crypto');
  4. const fs = require('fs-extra');
  5. const { hashElement } = require('folder-hash');
  6. const path = require('path');
  7. const unknownFlags = [];
  8. require('colors');
  9. const pass = '✓'.green;
  10. const fail = '✗'.red;
  11. const args = require('minimist')(process.argv, {
  12. string: ['runners', 'target'],
  13. boolean: ['buildNativeTests', 'runTestFilesSeparately'],
  14. unknown: arg => unknownFlags.push(arg)
  15. });
  16. const unknownArgs = [];
  17. for (const flag of unknownFlags) {
  18. unknownArgs.push(flag);
  19. const onlyFlag = flag.replace(/^-+/, '');
  20. if (args[onlyFlag]) {
  21. unknownArgs.push(args[onlyFlag]);
  22. }
  23. }
  24. const utils = require('./lib/utils');
  25. const { YARN_VERSION } = require('./yarn');
  26. const BASE = path.resolve(__dirname, '../..');
  27. const NPX_CMD = process.platform === 'win32' ? 'npx.cmd' : 'npx';
  28. const runners = new Map([
  29. ['main', { description: 'Main process specs', run: runMainProcessElectronTests }],
  30. ['remote', { description: 'Remote based specs', run: runRemoteBasedElectronTests }],
  31. ['native', { description: 'Native specs', run: runNativeElectronTests }]
  32. ]);
  33. const specHashPath = path.resolve(__dirname, '../spec/.hash');
  34. let runnersToRun = null;
  35. if (args.runners !== undefined) {
  36. runnersToRun = args.runners.split(',').filter(value => value);
  37. if (!runnersToRun.every(r => [...runners.keys()].includes(r))) {
  38. console.log(`${fail} ${runnersToRun} must be a subset of [${[...runners.keys()].join(' | ')}]`);
  39. process.exit(1);
  40. }
  41. console.log('Only running:', runnersToRun);
  42. } else {
  43. console.log(`Triggering runners: ${[...runners.keys()].join(', ')}`);
  44. }
  45. async function main () {
  46. const [lastSpecHash, lastSpecInstallHash] = loadLastSpecHash();
  47. const [currentSpecHash, currentSpecInstallHash] = await getSpecHash();
  48. const somethingChanged = (currentSpecHash !== lastSpecHash) ||
  49. (lastSpecInstallHash !== currentSpecInstallHash);
  50. if (somethingChanged) {
  51. await installSpecModules(path.resolve(__dirname, '..', 'spec'));
  52. await installSpecModules(path.resolve(__dirname, '..', 'spec-main'));
  53. await getSpecHash().then(saveSpecHash);
  54. }
  55. if (!fs.existsSync(path.resolve(__dirname, '../electron.d.ts'))) {
  56. console.log('Generating electron.d.ts as it is missing');
  57. generateTypeDefinitions();
  58. }
  59. await runElectronTests();
  60. }
  61. function generateTypeDefinitions () {
  62. const { status } = childProcess.spawnSync('npm', ['run', 'create-typescript-definitions'], {
  63. cwd: path.resolve(__dirname, '..'),
  64. stdio: 'inherit',
  65. shell: true
  66. });
  67. if (status !== 0) {
  68. throw new Error(`Electron typescript definition generation failed with exit code: ${status}.`);
  69. }
  70. }
  71. function loadLastSpecHash () {
  72. return fs.existsSync(specHashPath)
  73. ? fs.readFileSync(specHashPath, 'utf8').split('\n')
  74. : [null, null];
  75. }
  76. function saveSpecHash ([newSpecHash, newSpecInstallHash]) {
  77. fs.writeFileSync(specHashPath, `${newSpecHash}\n${newSpecInstallHash}`);
  78. }
  79. async function runElectronTests () {
  80. const errors = [];
  81. const testResultsDir = process.env.ELECTRON_TEST_RESULTS_DIR;
  82. for (const [runnerId, { description, run }] of runners) {
  83. if (runnersToRun && !runnersToRun.includes(runnerId)) {
  84. console.info('\nSkipping:', description);
  85. continue;
  86. }
  87. try {
  88. console.info('\nRunning:', description);
  89. if (testResultsDir) {
  90. process.env.MOCHA_FILE = path.join(testResultsDir, `test-results-${runnerId}.xml`);
  91. }
  92. await run();
  93. } catch (err) {
  94. errors.push([runnerId, err]);
  95. }
  96. }
  97. if (errors.length !== 0) {
  98. for (const err of errors) {
  99. console.error('\n\nRunner Failed:', err[0]);
  100. console.error(err[1]);
  101. }
  102. console.log(`${fail} Electron test runners have failed`);
  103. process.exit(1);
  104. }
  105. }
  106. async function runTestUsingElectron (specDir, testName) {
  107. let exe = path.resolve(BASE, utils.getElectronExec());
  108. const runnerArgs = [`electron/${specDir}`, ...unknownArgs.slice(2)];
  109. if (process.platform === 'linux') {
  110. runnerArgs.unshift(path.resolve(__dirname, 'dbus_mock.py'), exe);
  111. exe = 'python3';
  112. }
  113. const { status, signal } = childProcess.spawnSync(exe, runnerArgs, {
  114. cwd: path.resolve(__dirname, '../..'),
  115. stdio: 'inherit'
  116. });
  117. if (status !== 0) {
  118. if (status) {
  119. const textStatus = process.platform === 'win32' ? `0x${status.toString(16)}` : status.toString();
  120. console.log(`${fail} Electron tests failed with code ${textStatus}.`);
  121. } else {
  122. console.log(`${fail} Electron tests failed with kill signal ${signal}.`);
  123. }
  124. process.exit(1);
  125. }
  126. console.log(`${pass} Electron ${testName} process tests passed.`);
  127. }
  128. const specFilter = (file) => {
  129. if (!/-spec\.[tj]s$/.test(file)) {
  130. return false;
  131. } else {
  132. return true;
  133. }
  134. };
  135. async function runTests (specDir, testName) {
  136. if (args.runTestFilesSeparately) {
  137. const getFiles = require('../spec/static/get-files');
  138. const testFiles = await getFiles(path.resolve(__dirname, `../${specDir}`), { filter: specFilter });
  139. const baseElectronDir = path.resolve(__dirname, '..');
  140. unknownArgs.splice(unknownArgs.length, 0, '--files', '');
  141. testFiles.sort().forEach(async (file) => {
  142. unknownArgs.splice((unknownArgs.length - 1), 1, path.relative(baseElectronDir, file));
  143. console.log(`Running tests for ${unknownArgs[unknownArgs.length - 1]}`);
  144. await runTestUsingElectron(specDir, testName);
  145. });
  146. } else {
  147. await runTestUsingElectron(specDir, testName);
  148. }
  149. }
  150. async function runRemoteBasedElectronTests () {
  151. await runTests('spec', 'remote');
  152. }
  153. async function runNativeElectronTests () {
  154. let testTargets = require('./native-test-targets.json');
  155. const outDir = `out/${utils.getOutDir()}`;
  156. // If native tests are being run, only one arg would be relevant
  157. if (args.target && !testTargets.includes(args.target)) {
  158. console.log(`${fail} ${args.target} must be a subset of [${[testTargets].join(', ')}]`);
  159. process.exit(1);
  160. }
  161. // Optionally build all native test targets
  162. if (args.buildNativeTests) {
  163. for (const target of testTargets) {
  164. const build = childProcess.spawnSync('ninja', ['-C', outDir, target], {
  165. cwd: path.resolve(__dirname, '../..'),
  166. stdio: 'inherit'
  167. });
  168. // Exit if test target failed to build
  169. if (build.status !== 0) {
  170. console.log(`${fail} ${target} failed to build.`);
  171. process.exit(1);
  172. }
  173. }
  174. }
  175. // If a specific target was passed, only build and run that target
  176. if (args.target) testTargets = [args.target];
  177. // Run test targets
  178. const failures = [];
  179. for (const target of testTargets) {
  180. console.info('\nRunning native test for target:', target);
  181. const testRun = childProcess.spawnSync(`./${outDir}/${target}`, {
  182. cwd: path.resolve(__dirname, '../..'),
  183. stdio: 'inherit'
  184. });
  185. // Collect failures and log at end
  186. if (testRun.status !== 0) failures.push({ target });
  187. }
  188. // Exit if any failures
  189. if (failures.length > 0) {
  190. console.log(`${fail} Electron native tests failed for the following targets: `, failures);
  191. process.exit(1);
  192. }
  193. console.log(`${pass} Electron native tests passed.`);
  194. }
  195. async function runMainProcessElectronTests () {
  196. await runTests('spec-main', 'main');
  197. }
  198. async function installSpecModules (dir) {
  199. // v8 headers use c++17 so override the gyp default of -std=c++14,
  200. // but don't clobber any other CXXFLAGS that were passed into spec-runner.js
  201. const CXXFLAGS = ['-std=c++17', process.env.CXXFLAGS].filter(x => !!x).join(' ');
  202. const nodeDir = path.resolve(BASE, `out/${utils.getOutDir({ shouldLog: true })}/gen/node_headers`);
  203. const env = Object.assign({}, process.env, {
  204. CXXFLAGS,
  205. npm_config_nodedir: nodeDir,
  206. npm_config_msvs_version: '2019',
  207. npm_config_yes: 'true'
  208. });
  209. if (fs.existsSync(path.resolve(dir, 'node_modules'))) {
  210. await fs.remove(path.resolve(dir, 'node_modules'));
  211. }
  212. const { status } = childProcess.spawnSync(NPX_CMD, [`yarn@${YARN_VERSION}`, 'install', '--frozen-lockfile'], {
  213. env,
  214. cwd: dir,
  215. stdio: 'inherit'
  216. });
  217. if (status !== 0 && !process.env.IGNORE_YARN_INSTALL_ERROR) {
  218. console.log(`${fail} Failed to yarn install in '${dir}'`);
  219. process.exit(1);
  220. }
  221. }
  222. function getSpecHash () {
  223. return Promise.all([
  224. (async () => {
  225. const hasher = crypto.createHash('SHA256');
  226. hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec/package.json')));
  227. hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec-main/package.json')));
  228. hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec/yarn.lock')));
  229. hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec-main/yarn.lock')));
  230. hasher.update(fs.readFileSync(path.resolve(__dirname, '../script/spec-runner.js')));
  231. return hasher.digest('hex');
  232. })(),
  233. (async () => {
  234. const specNodeModulesPath = path.resolve(__dirname, '../spec/node_modules');
  235. if (!fs.existsSync(specNodeModulesPath)) {
  236. return null;
  237. }
  238. const { hash } = await hashElement(specNodeModulesPath, {
  239. folders: {
  240. exclude: ['.bin']
  241. }
  242. });
  243. return hash;
  244. })()
  245. ]);
  246. }
  247. main().catch((error) => {
  248. console.error('An error occurred inside the spec runner:', error);
  249. process.exit(1);
  250. });