spec-runner.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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'],
  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) {
  36. runnersToRun = args.runners.split(',');
  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 runRemoteBasedElectronTests () {
  107. let exe = path.resolve(BASE, utils.getElectronExec());
  108. const runnerArgs = ['electron/spec', ...unknownArgs.slice(2)];
  109. if (process.platform === 'linux') {
  110. runnerArgs.unshift(path.resolve(__dirname, 'dbus_mock.py'), exe);
  111. exe = 'python';
  112. }
  113. const { status } = childProcess.spawnSync(exe, runnerArgs, {
  114. cwd: path.resolve(__dirname, '../..'),
  115. stdio: 'inherit'
  116. });
  117. if (status !== 0) {
  118. const textStatus = process.platform === 'win32' ? `0x${status.toString(16)}` : status.toString();
  119. console.log(`${fail} Electron tests failed with code ${textStatus}.`);
  120. process.exit(1);
  121. }
  122. console.log(`${pass} Electron remote process tests passed.`);
  123. }
  124. async function runNativeElectronTests () {
  125. let testTargets = require('./native-test-targets.json');
  126. const outDir = `out/${utils.getOutDir()}`;
  127. // If native tests are being run, only one arg would be relevant
  128. if (args.target && !testTargets.includes(args.target)) {
  129. console.log(`${fail} ${args.target} must be a subset of [${[testTargets].join(', ')}]`);
  130. process.exit(1);
  131. }
  132. // Optionally build all native test targets
  133. if (args.buildNativeTests) {
  134. for (const target of testTargets) {
  135. const build = childProcess.spawnSync('ninja', ['-C', outDir, target], {
  136. cwd: path.resolve(__dirname, '../..'),
  137. stdio: 'inherit'
  138. });
  139. // Exit if test target failed to build
  140. if (build.status !== 0) {
  141. console.log(`${fail} ${target} failed to build.`);
  142. process.exit(1);
  143. }
  144. }
  145. }
  146. // If a specific target was passed, only build and run that target
  147. if (args.target) testTargets = [args.target];
  148. // Run test targets
  149. const failures = [];
  150. for (const target of testTargets) {
  151. console.info('\nRunning native test for target:', target);
  152. const testRun = childProcess.spawnSync(`./${outDir}/${target}`, {
  153. cwd: path.resolve(__dirname, '../..'),
  154. stdio: 'inherit'
  155. });
  156. // Collect failures and log at end
  157. if (testRun.status !== 0) failures.push({ target });
  158. }
  159. // Exit if any failures
  160. if (failures.length > 0) {
  161. console.log(`${fail} Electron native tests failed for the following targets: `, failures);
  162. process.exit(1);
  163. }
  164. console.log(`${pass} Electron native tests passed.`);
  165. }
  166. async function runMainProcessElectronTests () {
  167. let exe = path.resolve(BASE, utils.getElectronExec());
  168. const runnerArgs = ['electron/spec-main', ...unknownArgs.slice(2)];
  169. if (process.platform === 'linux') {
  170. runnerArgs.unshift(path.resolve(__dirname, 'dbus_mock.py'), exe);
  171. exe = 'python';
  172. }
  173. const { status, signal } = childProcess.spawnSync(exe, runnerArgs, {
  174. cwd: path.resolve(__dirname, '../..'),
  175. stdio: 'inherit'
  176. });
  177. if (status !== 0) {
  178. if (status) {
  179. const textStatus = process.platform === 'win32' ? `0x${status.toString(16)}` : status.toString();
  180. console.log(`${fail} Electron tests failed with code ${textStatus}.`);
  181. } else {
  182. console.log(`${fail} Electron tests failed with kill signal ${signal}.`);
  183. }
  184. process.exit(1);
  185. }
  186. console.log(`${pass} Electron main process tests passed.`);
  187. }
  188. async function installSpecModules (dir) {
  189. const nodeDir = path.resolve(BASE, `out/${utils.getOutDir({ shouldLog: true })}/gen/node_headers`);
  190. const env = Object.assign({}, process.env, {
  191. npm_config_nodedir: nodeDir,
  192. npm_config_msvs_version: '2019',
  193. npm_config_yes: 'true'
  194. });
  195. if (fs.existsSync(path.resolve(dir, 'node_modules'))) {
  196. await fs.remove(path.resolve(dir, 'node_modules'));
  197. }
  198. const { status } = childProcess.spawnSync(NPX_CMD, [`yarn@${YARN_VERSION}`, 'install', '--frozen-lockfile'], {
  199. env,
  200. cwd: dir,
  201. stdio: 'inherit'
  202. });
  203. if (status !== 0 && !process.env.IGNORE_YARN_INSTALL_ERROR) {
  204. console.log(`${fail} Failed to yarn install in '${dir}'`);
  205. process.exit(1);
  206. }
  207. }
  208. function getSpecHash () {
  209. return Promise.all([
  210. (async () => {
  211. const hasher = crypto.createHash('SHA256');
  212. hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec/package.json')));
  213. hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec-main/package.json')));
  214. hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec/yarn.lock')));
  215. hasher.update(fs.readFileSync(path.resolve(__dirname, '../spec-main/yarn.lock')));
  216. hasher.update(fs.readFileSync(path.resolve(__dirname, '../script/spec-runner.js')));
  217. return hasher.digest('hex');
  218. })(),
  219. (async () => {
  220. const specNodeModulesPath = path.resolve(__dirname, '../spec/node_modules');
  221. if (!fs.existsSync(specNodeModulesPath)) {
  222. return null;
  223. }
  224. const { hash } = await hashElement(specNodeModulesPath, {
  225. folders: {
  226. exclude: ['.bin']
  227. }
  228. });
  229. return hash;
  230. })()
  231. ]);
  232. }
  233. main().catch((error) => {
  234. console.error('An error occurred inside the spec runner:', error);
  235. process.exit(1);
  236. });