spec-runner.js 9.8 KB

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