spec-runner.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. #!/usr/bin/env node
  2. const { ElectronVersions, Installer } = require('@electron/fiddle-core');
  3. const chalk = require('chalk');
  4. const childProcess = require('node:child_process');
  5. const crypto = require('node:crypto');
  6. const fs = require('node:fs');
  7. const { hashElement } = require('folder-hash');
  8. const os = require('node:os');
  9. const path = require('node:path');
  10. const unknownFlags = [];
  11. const pass = chalk.green('✓');
  12. const fail = chalk.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. const env = {
  164. ...process.env,
  165. CXXFLAGS: process.env.CXXFLAGS,
  166. npm_config_msvs_version: '2019',
  167. npm_config_yes: 'true'
  168. };
  169. if (args.electronVersion) {
  170. env.npm_config_target = args.electronVersion;
  171. env.npm_config_disturl = 'https://electronjs.org/headers';
  172. env.npm_config_runtime = 'electron';
  173. env.npm_config_devdir = path.join(os.homedir(), '.electron-gyp');
  174. env.npm_config_build_from_source = 'true';
  175. const { status } = childProcess.spawnSync('npm', ['run', 'node-gyp-install', '--ensure'], {
  176. env,
  177. cwd: dir,
  178. stdio: 'inherit',
  179. shell: true
  180. });
  181. if (status !== 0) {
  182. console.log(`${fail} Failed to "npm run node-gyp-install" install in '${dir}'`);
  183. process.exit(1);
  184. }
  185. } else {
  186. env.npm_config_nodedir = path.resolve(BASE, `out/${utils.getOutDir({ shouldLog: true })}/gen/node_headers`);
  187. }
  188. if (fs.existsSync(path.resolve(dir, 'node_modules'))) {
  189. await fs.promises.rm(path.resolve(dir, 'node_modules'), { force: true, recursive: true });
  190. }
  191. const { status } = childProcess.spawnSync(NPX_CMD, [`yarn@${YARN_VERSION}`, 'install', '--frozen-lockfile'], {
  192. env,
  193. cwd: dir,
  194. stdio: 'inherit',
  195. shell: process.platform === 'win32'
  196. });
  197. if (status !== 0 && !process.env.IGNORE_YARN_INSTALL_ERROR) {
  198. console.log(`${fail} Failed to yarn install in '${dir}'`);
  199. process.exit(1);
  200. }
  201. }
  202. function getSpecHash () {
  203. return Promise.all([
  204. (async () => {
  205. const hasher = crypto.createHash('SHA256');
  206. hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec/package.json')));
  207. hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec/yarn.lock')));
  208. hasher.update(fs.readFileSync(path.resolve(__dirname, '../script/spec-runner.js')));
  209. return hasher.digest('hex');
  210. })(),
  211. (async () => {
  212. const specNodeModulesPath = path.resolve(__dirname, '../spec/node_modules');
  213. if (!fs.existsSync(specNodeModulesPath)) {
  214. return null;
  215. }
  216. const { hash } = await hashElement(specNodeModulesPath, {
  217. folders: {
  218. exclude: ['.bin']
  219. }
  220. });
  221. return hash;
  222. })()
  223. ]);
  224. }
  225. main().catch((error) => {
  226. console.error('An error occurred inside the spec runner:', error);
  227. process.exit(1);
  228. });