spec-runner.js 8.2 KB

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