api-app-spec.ts 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969
  1. import { assert, expect } from 'chai';
  2. import * as cp from 'child_process';
  3. import * as https from 'https';
  4. import * as http from 'http';
  5. import * as net from 'net';
  6. import * as fs from 'fs';
  7. import * as path from 'path';
  8. import { promisify } from 'util';
  9. import { app, BrowserWindow, Menu, session, net as electronNet } from 'electron/main';
  10. import { emittedOnce } from './events-helpers';
  11. import { closeWindow, closeAllWindows } from './window-helpers';
  12. import { ifdescribe, ifit, waitUntil } from './spec-helpers';
  13. import split = require('split')
  14. const fixturesPath = path.resolve(__dirname, '../spec/fixtures');
  15. describe('electron module', () => {
  16. it('does not expose internal modules to require', () => {
  17. expect(() => {
  18. require('clipboard');
  19. }).to.throw(/Cannot find module 'clipboard'/);
  20. });
  21. describe('require("electron")', () => {
  22. it('always returns the internal electron module', () => {
  23. require('electron');
  24. });
  25. });
  26. });
  27. describe('app module', () => {
  28. let server: https.Server;
  29. let secureUrl: string;
  30. const certPath = path.join(fixturesPath, 'certificates');
  31. before((done) => {
  32. const options = {
  33. key: fs.readFileSync(path.join(certPath, 'server.key')),
  34. cert: fs.readFileSync(path.join(certPath, 'server.pem')),
  35. ca: [
  36. fs.readFileSync(path.join(certPath, 'rootCA.pem')),
  37. fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
  38. ],
  39. requestCert: true,
  40. rejectUnauthorized: false
  41. };
  42. server = https.createServer(options, (req, res) => {
  43. if ((req as any).client.authorized) {
  44. res.writeHead(200);
  45. res.end('<title>authorized</title>');
  46. } else {
  47. res.writeHead(401);
  48. res.end('<title>denied</title>');
  49. }
  50. });
  51. server.listen(0, '127.0.0.1', () => {
  52. const port = (server.address() as net.AddressInfo).port;
  53. secureUrl = `https://127.0.0.1:${port}`;
  54. done();
  55. });
  56. });
  57. after(done => {
  58. server.close(() => done());
  59. });
  60. describe('app.getVersion()', () => {
  61. it('returns the version field of package.json', () => {
  62. expect(app.getVersion()).to.equal('0.1.0');
  63. });
  64. });
  65. describe('app.setVersion(version)', () => {
  66. it('overrides the version', () => {
  67. expect(app.getVersion()).to.equal('0.1.0');
  68. app.setVersion('test-version');
  69. expect(app.getVersion()).to.equal('test-version');
  70. app.setVersion('0.1.0');
  71. });
  72. });
  73. describe('app name APIs', () => {
  74. it('with properties', () => {
  75. it('returns the name field of package.json', () => {
  76. expect(app.name).to.equal('Electron Test Main');
  77. });
  78. it('overrides the name', () => {
  79. expect(app.name).to.equal('Electron Test Main');
  80. app.name = 'electron-test-name';
  81. expect(app.name).to.equal('electron-test-name');
  82. app.name = 'Electron Test Main';
  83. });
  84. });
  85. it('with functions', () => {
  86. it('returns the name field of package.json', () => {
  87. expect(app.getName()).to.equal('Electron Test Main');
  88. });
  89. it('overrides the name', () => {
  90. expect(app.getName()).to.equal('Electron Test Main');
  91. app.setName('electron-test-name');
  92. expect(app.getName()).to.equal('electron-test-name');
  93. app.setName('Electron Test Main');
  94. });
  95. });
  96. });
  97. describe('app.getLocale()', () => {
  98. it('should not be empty', () => {
  99. expect(app.getLocale()).to.not.equal('');
  100. });
  101. });
  102. describe('app.getLocaleCountryCode()', () => {
  103. it('should be empty or have length of two', () => {
  104. const localeCountryCode = app.getLocaleCountryCode();
  105. expect(localeCountryCode).to.be.a('string');
  106. expect(localeCountryCode.length).to.be.oneOf([0, 2]);
  107. });
  108. });
  109. describe('app.isPackaged', () => {
  110. it('should be false durings tests', () => {
  111. expect(app.isPackaged).to.equal(false);
  112. });
  113. });
  114. ifdescribe(process.platform === 'darwin')('app.isInApplicationsFolder()', () => {
  115. it('should be false during tests', () => {
  116. expect(app.isInApplicationsFolder()).to.equal(false);
  117. });
  118. });
  119. describe('app.exit(exitCode)', () => {
  120. let appProcess: cp.ChildProcess | null = null;
  121. afterEach(() => {
  122. if (appProcess) appProcess.kill();
  123. });
  124. it('emits a process exit event with the code', async () => {
  125. const appPath = path.join(fixturesPath, 'api', 'quit-app');
  126. const electronPath = process.execPath;
  127. let output = '';
  128. appProcess = cp.spawn(electronPath, [appPath]);
  129. if (appProcess && appProcess.stdout) {
  130. appProcess.stdout.on('data', data => { output += data; });
  131. }
  132. const [code] = await emittedOnce(appProcess, 'exit');
  133. if (process.platform !== 'win32') {
  134. expect(output).to.include('Exit event with code: 123');
  135. }
  136. expect(code).to.equal(123);
  137. });
  138. it('closes all windows', async function () {
  139. const appPath = path.join(fixturesPath, 'api', 'exit-closes-all-windows-app');
  140. const electronPath = process.execPath;
  141. appProcess = cp.spawn(electronPath, [appPath]);
  142. const [code, signal] = await emittedOnce(appProcess, 'exit');
  143. expect(signal).to.equal(null, 'exit signal should be null, if you see this please tag @MarshallOfSound');
  144. expect(code).to.equal(123, 'exit code should be 123, if you see this please tag @MarshallOfSound');
  145. });
  146. it('exits gracefully', async function () {
  147. if (!['darwin', 'linux'].includes(process.platform)) {
  148. this.skip();
  149. return;
  150. }
  151. const electronPath = process.execPath;
  152. const appPath = path.join(fixturesPath, 'api', 'singleton');
  153. appProcess = cp.spawn(electronPath, [appPath]);
  154. // Singleton will send us greeting data to let us know it's running.
  155. // After that, ask it to exit gracefully and confirm that it does.
  156. if (appProcess && appProcess.stdout) {
  157. appProcess.stdout.on('data', () => appProcess!.kill());
  158. }
  159. const [code, signal] = await emittedOnce(appProcess, 'exit');
  160. const message = `code:\n${code}\nsignal:\n${signal}`;
  161. expect(code).to.equal(0, message);
  162. expect(signal).to.equal(null, message);
  163. });
  164. });
  165. ifdescribe(process.platform === 'darwin')('app.setActivationPolicy', () => {
  166. it('throws an error on invalid application policies', () => {
  167. expect(() => {
  168. app.setActivationPolicy('terrible' as any);
  169. }).to.throw(/Invalid activation policy: must be one of 'regular', 'accessory', or 'prohibited'/);
  170. });
  171. });
  172. describe('app.requestSingleInstanceLock', () => {
  173. interface SingleInstanceLockTestArgs {
  174. args: string[];
  175. expectedAdditionalData: unknown;
  176. expectedAck: unknown;
  177. }
  178. it('prevents the second launch of app', async function () {
  179. this.timeout(60000);
  180. const appPath = path.join(fixturesPath, 'api', 'singleton');
  181. const first = cp.spawn(process.execPath, [appPath]);
  182. const firstExited = emittedOnce(first, 'exit');
  183. await emittedOnce(first.stdout, 'data');
  184. // Start second app when received output.
  185. const second = cp.spawn(process.execPath, [appPath]);
  186. const secondExited = emittedOnce(second, 'exit');
  187. const [code2] = await secondExited;
  188. expect(code2).to.equal(1);
  189. const [code1] = await firstExited;
  190. expect(code1).to.equal(0);
  191. });
  192. it('returns true when setting non-existent user data folder', async function () {
  193. const appPath = path.join(fixturesPath, 'api', 'singleton-userdata');
  194. const instance = cp.spawn(process.execPath, [appPath]);
  195. const [code] = await emittedOnce(instance, 'exit');
  196. expect(code).to.equal(0);
  197. });
  198. async function testArgumentPassing (testArgs: SingleInstanceLockTestArgs) {
  199. const appPath = path.join(fixturesPath, 'api', 'singleton-data');
  200. const first = cp.spawn(process.execPath, [appPath, ...testArgs.args]);
  201. const firstExited = emittedOnce(first, 'exit');
  202. // Wait for the first app to boot.
  203. const firstStdoutLines = first.stdout.pipe(split());
  204. while ((await emittedOnce(firstStdoutLines, 'data')).toString() !== 'started') {
  205. // wait.
  206. }
  207. const additionalDataPromise = emittedOnce(firstStdoutLines, 'data');
  208. const secondInstanceArgs = [process.execPath, appPath, ...testArgs.args, '--some-switch', 'some-arg'];
  209. const second = cp.spawn(secondInstanceArgs[0], secondInstanceArgs.slice(1));
  210. const secondExited = emittedOnce(second, 'exit');
  211. const secondStdoutLines = second.stdout.pipe(split());
  212. let ackData;
  213. while ((ackData = await emittedOnce(secondStdoutLines, 'data'))[0].toString().length === 0) {
  214. // This isn't valid data.
  215. }
  216. const [code2] = await secondExited;
  217. expect(code2).to.equal(1);
  218. const [code1] = await firstExited;
  219. expect(code1).to.equal(0);
  220. const dataFromSecondInstance = await additionalDataPromise;
  221. const [args, additionalData] = dataFromSecondInstance[0].toString('ascii').split('||');
  222. const secondInstanceArgsReceived: string[] = JSON.parse(args.toString('ascii'));
  223. const secondInstanceDataReceived = JSON.parse(additionalData.toString('ascii'));
  224. const dataAckReceived = JSON.parse(ackData[0].toString('ascii'));
  225. // Ensure secondInstanceArgs is a subset of secondInstanceArgsReceived
  226. for (const arg of secondInstanceArgs) {
  227. expect(secondInstanceArgsReceived).to.include(arg,
  228. `argument ${arg} is missing from received second args`);
  229. }
  230. expect(secondInstanceDataReceived).to.be.deep.equal(testArgs.expectedAdditionalData,
  231. `received data ${JSON.stringify(secondInstanceDataReceived)} is not equal to expected data ${JSON.stringify(testArgs.expectedAdditionalData)}.`);
  232. expect(dataAckReceived).to.be.deep.equal(testArgs.expectedAck,
  233. `received data ${JSON.stringify(dataAckReceived)} is not equal to expected data ${JSON.stringify(testArgs.expectedAck)}.`);
  234. }
  235. const expectedAdditionalData = {
  236. level: 1,
  237. testkey: 'testvalue1',
  238. inner: {
  239. level: 2,
  240. testkey: 'testvalue2'
  241. }
  242. };
  243. const expectedAck = {
  244. level: 1,
  245. testkey: 'acktestvalue1',
  246. inner: {
  247. level: 2,
  248. testkey: 'acktestvalue2'
  249. }
  250. };
  251. it('passes arguments to the second-instance event with no additional data', async () => {
  252. await testArgumentPassing({
  253. args: [],
  254. expectedAdditionalData: null,
  255. expectedAck: null
  256. });
  257. });
  258. it('passes arguments to the second-instance event', async () => {
  259. await testArgumentPassing({
  260. args: ['--send-data'],
  261. expectedAdditionalData,
  262. expectedAck: null
  263. });
  264. });
  265. it('gets back an ack after preventing default', async () => {
  266. await testArgumentPassing({
  267. args: ['--send-ack', '--prevent-default'],
  268. expectedAdditionalData: null,
  269. expectedAck
  270. });
  271. });
  272. it('is able to send back empty ack after preventing default', async () => {
  273. await testArgumentPassing({
  274. args: ['--prevent-default'],
  275. expectedAdditionalData: null,
  276. expectedAck: null
  277. });
  278. });
  279. it('sends and receives data', async () => {
  280. await testArgumentPassing({
  281. args: ['--send-ack', '--prevent-default', '--send-data'],
  282. expectedAdditionalData,
  283. expectedAck
  284. });
  285. });
  286. it('sends and receives numerical data', async () => {
  287. await testArgumentPassing({
  288. args: ['--send-ack', '--ack-content=1', '--prevent-default', '--send-data', '--data-content=2'],
  289. expectedAdditionalData: 2,
  290. expectedAck: 1
  291. });
  292. });
  293. it('sends and receives string data', async () => {
  294. await testArgumentPassing({
  295. args: ['--send-ack', '--ack-content="ack"', '--prevent-default', '--send-data', '--data-content="data"'],
  296. expectedAdditionalData: 'data',
  297. expectedAck: 'ack'
  298. });
  299. });
  300. it('sends and receives boolean data', async () => {
  301. await testArgumentPassing({
  302. args: ['--send-ack', '--ack-content=true', '--prevent-default', '--send-data', '--data-content=false'],
  303. expectedAdditionalData: false,
  304. expectedAck: true
  305. });
  306. });
  307. it('sends and receives array data', async () => {
  308. await testArgumentPassing({
  309. args: ['--send-ack', '--ack-content=[1, 2, 3]', '--prevent-default', '--send-data', '--data-content=[2, 3, 4]'],
  310. expectedAdditionalData: [2, 3, 4],
  311. expectedAck: [1, 2, 3]
  312. });
  313. });
  314. it('sends and receives mixed array data', async () => {
  315. await testArgumentPassing({
  316. args: ['--send-ack', '--ack-content=["1", true, 3]', '--prevent-default', '--send-data', '--data-content=["2", false, 4]'],
  317. expectedAdditionalData: ['2', false, 4],
  318. expectedAck: ['1', true, 3]
  319. });
  320. });
  321. it('sends and receives null data', async () => {
  322. await testArgumentPassing({
  323. args: ['--send-ack', '--ack-content=null', '--prevent-default', '--send-data', '--data-content=null'],
  324. expectedAdditionalData: null,
  325. expectedAck: null
  326. });
  327. });
  328. it('cannot send or receive undefined data', async () => {
  329. try {
  330. await testArgumentPassing({
  331. args: ['--send-ack', '--ack-content="undefined"', '--prevent-default', '--send-data', '--data-content="undefined"'],
  332. expectedAdditionalData: undefined,
  333. expectedAck: undefined
  334. });
  335. assert(false);
  336. } catch (e) {
  337. // This is expected.
  338. }
  339. });
  340. });
  341. describe('app.relaunch', () => {
  342. let server: net.Server | null = null;
  343. const socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\electron-app-relaunch' : '/tmp/electron-app-relaunch';
  344. beforeEach(done => {
  345. fs.unlink(socketPath, () => {
  346. server = net.createServer();
  347. server.listen(socketPath);
  348. done();
  349. });
  350. });
  351. afterEach((done) => {
  352. server!.close(() => {
  353. if (process.platform === 'win32') {
  354. done();
  355. } else {
  356. fs.unlink(socketPath, () => done());
  357. }
  358. });
  359. });
  360. it('relaunches the app', function (done) {
  361. this.timeout(120000);
  362. let state = 'none';
  363. server!.once('error', error => done(error));
  364. server!.on('connection', client => {
  365. client.once('data', data => {
  366. if (String(data) === 'false' && state === 'none') {
  367. state = 'first-launch';
  368. } else if (String(data) === 'true' && state === 'first-launch') {
  369. done();
  370. } else {
  371. done(`Unexpected state: "${state}", data: "${data}"`);
  372. }
  373. });
  374. });
  375. const appPath = path.join(fixturesPath, 'api', 'relaunch');
  376. const child = cp.spawn(process.execPath, [appPath]);
  377. child.stdout.on('data', (c) => console.log(c.toString()));
  378. child.stderr.on('data', (c) => console.log(c.toString()));
  379. child.on('exit', (code, signal) => {
  380. if (code !== 0) {
  381. console.log(`Process exited with code "${code}" signal "${signal}"`);
  382. }
  383. });
  384. });
  385. });
  386. describe('app.setUserActivity(type, userInfo)', () => {
  387. before(function () {
  388. if (process.platform !== 'darwin') {
  389. this.skip();
  390. }
  391. });
  392. it('sets the current activity', () => {
  393. app.setUserActivity('com.electron.testActivity', { testData: '123' });
  394. expect(app.getCurrentActivityType()).to.equal('com.electron.testActivity');
  395. });
  396. });
  397. describe('certificate-error event', () => {
  398. afterEach(closeAllWindows);
  399. it('is emitted when visiting a server with a self-signed cert', async () => {
  400. const w = new BrowserWindow({ show: false });
  401. w.loadURL(secureUrl);
  402. await emittedOnce(app, 'certificate-error');
  403. });
  404. describe('when denied', () => {
  405. before(() => {
  406. app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
  407. callback(false);
  408. });
  409. });
  410. after(() => {
  411. app.removeAllListeners('certificate-error');
  412. });
  413. it('causes did-fail-load', async () => {
  414. const w = new BrowserWindow({ show: false });
  415. w.loadURL(secureUrl);
  416. await emittedOnce(w.webContents, 'did-fail-load');
  417. });
  418. });
  419. });
  420. // xdescribe('app.importCertificate', () => {
  421. // let w = null
  422. // before(function () {
  423. // if (process.platform !== 'linux') {
  424. // this.skip()
  425. // }
  426. // })
  427. // afterEach(() => closeWindow(w).then(() => { w = null }))
  428. // it('can import certificate into platform cert store', done => {
  429. // const options = {
  430. // certificate: path.join(certPath, 'client.p12'),
  431. // password: 'electron'
  432. // }
  433. // w = new BrowserWindow({
  434. // show: false,
  435. // webPreferences: {
  436. // nodeIntegration: true
  437. // }
  438. // })
  439. // w.webContents.on('did-finish-load', () => {
  440. // expect(w.webContents.getTitle()).to.equal('authorized')
  441. // done()
  442. // })
  443. // ipcRenderer.once('select-client-certificate', (event, webContentsId, list) => {
  444. // expect(webContentsId).to.equal(w.webContents.id)
  445. // expect(list).to.have.lengthOf(1)
  446. // expect(list[0]).to.deep.equal({
  447. // issuerName: 'Intermediate CA',
  448. // subjectName: 'Client Cert',
  449. // issuer: { commonName: 'Intermediate CA' },
  450. // subject: { commonName: 'Client Cert' }
  451. // })
  452. // event.sender.send('client-certificate-response', list[0])
  453. // })
  454. // app.importCertificate(options, result => {
  455. // expect(result).toNotExist()
  456. // ipcRenderer.sendSync('set-client-certificate-option', false)
  457. // w.loadURL(secureUrl)
  458. // })
  459. // })
  460. // })
  461. describe('BrowserWindow events', () => {
  462. let w: BrowserWindow = null as any;
  463. afterEach(() => closeWindow(w).then(() => { w = null as any; }));
  464. it('should emit browser-window-focus event when window is focused', async () => {
  465. const emitted = emittedOnce(app, 'browser-window-focus');
  466. w = new BrowserWindow({ show: false });
  467. w.emit('focus');
  468. const [, window] = await emitted;
  469. expect(window.id).to.equal(w.id);
  470. });
  471. it('should emit browser-window-blur event when window is blured', async () => {
  472. const emitted = emittedOnce(app, 'browser-window-blur');
  473. w = new BrowserWindow({ show: false });
  474. w.emit('blur');
  475. const [, window] = await emitted;
  476. expect(window.id).to.equal(w.id);
  477. });
  478. it('should emit browser-window-created event when window is created', async () => {
  479. const emitted = emittedOnce(app, 'browser-window-created');
  480. w = new BrowserWindow({ show: false });
  481. const [, window] = await emitted;
  482. expect(window.id).to.equal(w.id);
  483. });
  484. it('should emit web-contents-created event when a webContents is created', async () => {
  485. const emitted = emittedOnce(app, 'web-contents-created');
  486. w = new BrowserWindow({ show: false });
  487. const [, webContents] = await emitted;
  488. expect(webContents.id).to.equal(w.webContents.id);
  489. });
  490. // FIXME: re-enable this test on win32.
  491. ifit(process.platform !== 'win32')('should emit renderer-process-crashed event when renderer crashes', async () => {
  492. w = new BrowserWindow({
  493. show: false,
  494. webPreferences: {
  495. nodeIntegration: true,
  496. contextIsolation: false
  497. }
  498. });
  499. await w.loadURL('about:blank');
  500. const emitted = emittedOnce(app, 'renderer-process-crashed');
  501. w.webContents.executeJavaScript('process.crash()');
  502. const [, webContents] = await emitted;
  503. expect(webContents).to.equal(w.webContents);
  504. });
  505. // FIXME: re-enable this test on win32.
  506. ifit(process.platform !== 'win32')('should emit render-process-gone event when renderer crashes', async () => {
  507. w = new BrowserWindow({
  508. show: false,
  509. webPreferences: {
  510. nodeIntegration: true,
  511. contextIsolation: false
  512. }
  513. });
  514. await w.loadURL('about:blank');
  515. const emitted = emittedOnce(app, 'render-process-gone');
  516. w.webContents.executeJavaScript('process.crash()');
  517. const [, webContents, details] = await emitted;
  518. expect(webContents).to.equal(w.webContents);
  519. expect(details.reason).to.be.oneOf(['crashed', 'abnormal-exit']);
  520. });
  521. });
  522. describe('app.badgeCount', () => {
  523. const platformIsNotSupported =
  524. (process.platform === 'win32') ||
  525. (process.platform === 'linux' && !app.isUnityRunning());
  526. const expectedBadgeCount = 42;
  527. after(() => { app.badgeCount = 0; });
  528. ifdescribe(!platformIsNotSupported)('on supported platform', () => {
  529. describe('with properties', () => {
  530. it('sets a badge count', function () {
  531. app.badgeCount = expectedBadgeCount;
  532. expect(app.badgeCount).to.equal(expectedBadgeCount);
  533. });
  534. });
  535. describe('with functions', () => {
  536. it('sets a numerical badge count', function () {
  537. app.setBadgeCount(expectedBadgeCount);
  538. expect(app.getBadgeCount()).to.equal(expectedBadgeCount);
  539. });
  540. it('sets an non numeric (dot) badge count', function () {
  541. app.setBadgeCount();
  542. // Badge count should be zero when non numeric (dot) is requested
  543. expect(app.getBadgeCount()).to.equal(0);
  544. });
  545. });
  546. });
  547. ifdescribe(process.platform !== 'win32' && platformIsNotSupported)('on unsupported platform', () => {
  548. describe('with properties', () => {
  549. it('does not set a badge count', function () {
  550. app.badgeCount = 9999;
  551. expect(app.badgeCount).to.equal(0);
  552. });
  553. });
  554. describe('with functions', () => {
  555. it('does not set a badge count)', function () {
  556. app.setBadgeCount(9999);
  557. expect(app.getBadgeCount()).to.equal(0);
  558. });
  559. });
  560. });
  561. });
  562. ifdescribe(process.platform !== 'linux' && !process.mas)('app.get/setLoginItemSettings API', function () {
  563. const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
  564. const processStartArgs = [
  565. '--processStart', `"${path.basename(process.execPath)}"`,
  566. '--process-start-args', '"--hidden"'
  567. ];
  568. const regAddArgs = [
  569. 'ADD',
  570. 'HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run',
  571. '/v',
  572. 'additionalEntry',
  573. '/t',
  574. 'REG_BINARY',
  575. '/f',
  576. '/d'
  577. ];
  578. beforeEach(() => {
  579. app.setLoginItemSettings({ openAtLogin: false });
  580. app.setLoginItemSettings({ openAtLogin: false, path: updateExe, args: processStartArgs });
  581. app.setLoginItemSettings({ name: 'additionalEntry', openAtLogin: false });
  582. });
  583. afterEach(() => {
  584. app.setLoginItemSettings({ openAtLogin: false });
  585. app.setLoginItemSettings({ openAtLogin: false, path: updateExe, args: processStartArgs });
  586. app.setLoginItemSettings({ name: 'additionalEntry', openAtLogin: false });
  587. });
  588. ifit(process.platform !== 'win32')('sets and returns the app as a login item', function () {
  589. app.setLoginItemSettings({ openAtLogin: true });
  590. expect(app.getLoginItemSettings()).to.deep.equal({
  591. openAtLogin: true,
  592. openAsHidden: false,
  593. wasOpenedAtLogin: false,
  594. wasOpenedAsHidden: false,
  595. restoreState: false
  596. });
  597. });
  598. ifit(process.platform === 'win32')('sets and returns the app as a login item (windows)', function () {
  599. app.setLoginItemSettings({ openAtLogin: true, enabled: true });
  600. expect(app.getLoginItemSettings()).to.deep.equal({
  601. openAtLogin: true,
  602. openAsHidden: false,
  603. wasOpenedAtLogin: false,
  604. wasOpenedAsHidden: false,
  605. restoreState: false,
  606. executableWillLaunchAtLogin: true,
  607. launchItems: [{
  608. name: 'electron.app.Electron',
  609. path: process.execPath,
  610. args: [],
  611. scope: 'user',
  612. enabled: true
  613. }]
  614. });
  615. app.setLoginItemSettings({ openAtLogin: false });
  616. app.setLoginItemSettings({ openAtLogin: true, enabled: false });
  617. expect(app.getLoginItemSettings()).to.deep.equal({
  618. openAtLogin: true,
  619. openAsHidden: false,
  620. wasOpenedAtLogin: false,
  621. wasOpenedAsHidden: false,
  622. restoreState: false,
  623. executableWillLaunchAtLogin: false,
  624. launchItems: [{
  625. name: 'electron.app.Electron',
  626. path: process.execPath,
  627. args: [],
  628. scope: 'user',
  629. enabled: false
  630. }]
  631. });
  632. });
  633. ifit(process.platform !== 'win32')('adds a login item that loads in hidden mode', function () {
  634. app.setLoginItemSettings({ openAtLogin: true, openAsHidden: true });
  635. expect(app.getLoginItemSettings()).to.deep.equal({
  636. openAtLogin: true,
  637. openAsHidden: process.platform === 'darwin' && !process.mas, // Only available on macOS
  638. wasOpenedAtLogin: false,
  639. wasOpenedAsHidden: false,
  640. restoreState: false
  641. });
  642. });
  643. ifit(process.platform === 'win32')('adds a login item that loads in hidden mode (windows)', function () {
  644. app.setLoginItemSettings({ openAtLogin: true, openAsHidden: true });
  645. expect(app.getLoginItemSettings()).to.deep.equal({
  646. openAtLogin: true,
  647. openAsHidden: false,
  648. wasOpenedAtLogin: false,
  649. wasOpenedAsHidden: false,
  650. restoreState: false,
  651. executableWillLaunchAtLogin: true,
  652. launchItems: [{
  653. name: 'electron.app.Electron',
  654. path: process.execPath,
  655. args: [],
  656. scope: 'user',
  657. enabled: true
  658. }]
  659. });
  660. });
  661. it('correctly sets and unsets the LoginItem', function () {
  662. expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
  663. app.setLoginItemSettings({ openAtLogin: true });
  664. expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
  665. app.setLoginItemSettings({ openAtLogin: false });
  666. expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
  667. });
  668. it('correctly sets and unsets the LoginItem as hidden', function () {
  669. if (process.platform !== 'darwin') this.skip();
  670. expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
  671. expect(app.getLoginItemSettings().openAsHidden).to.equal(false);
  672. app.setLoginItemSettings({ openAtLogin: true, openAsHidden: true });
  673. expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
  674. expect(app.getLoginItemSettings().openAsHidden).to.equal(true);
  675. app.setLoginItemSettings({ openAtLogin: true, openAsHidden: false });
  676. expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
  677. expect(app.getLoginItemSettings().openAsHidden).to.equal(false);
  678. });
  679. ifit(process.platform === 'win32')('allows you to pass a custom executable and arguments', function () {
  680. app.setLoginItemSettings({ openAtLogin: true, path: updateExe, args: processStartArgs, enabled: true });
  681. expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
  682. const openAtLoginTrueEnabledTrue = app.getLoginItemSettings({
  683. path: updateExe,
  684. args: processStartArgs
  685. });
  686. expect(openAtLoginTrueEnabledTrue.openAtLogin).to.equal(true);
  687. expect(openAtLoginTrueEnabledTrue.executableWillLaunchAtLogin).to.equal(true);
  688. app.setLoginItemSettings({ openAtLogin: true, path: updateExe, args: processStartArgs, enabled: false });
  689. const openAtLoginTrueEnabledFalse = app.getLoginItemSettings({
  690. path: updateExe,
  691. args: processStartArgs
  692. });
  693. expect(openAtLoginTrueEnabledFalse.openAtLogin).to.equal(true);
  694. expect(openAtLoginTrueEnabledFalse.executableWillLaunchAtLogin).to.equal(false);
  695. app.setLoginItemSettings({ openAtLogin: false, path: updateExe, args: processStartArgs, enabled: false });
  696. const openAtLoginFalseEnabledFalse = app.getLoginItemSettings({
  697. path: updateExe,
  698. args: processStartArgs
  699. });
  700. expect(openAtLoginFalseEnabledFalse.openAtLogin).to.equal(false);
  701. expect(openAtLoginFalseEnabledFalse.executableWillLaunchAtLogin).to.equal(false);
  702. });
  703. ifit(process.platform === 'win32')('allows you to pass a custom name', function () {
  704. app.setLoginItemSettings({ openAtLogin: true });
  705. app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: false });
  706. expect(app.getLoginItemSettings()).to.deep.equal({
  707. openAtLogin: true,
  708. openAsHidden: false,
  709. wasOpenedAtLogin: false,
  710. wasOpenedAsHidden: false,
  711. restoreState: false,
  712. executableWillLaunchAtLogin: true,
  713. launchItems: [{
  714. name: 'additionalEntry',
  715. path: process.execPath,
  716. args: [],
  717. scope: 'user',
  718. enabled: false
  719. }, {
  720. name: 'electron.app.Electron',
  721. path: process.execPath,
  722. args: [],
  723. scope: 'user',
  724. enabled: true
  725. }]
  726. });
  727. app.setLoginItemSettings({ openAtLogin: false, name: 'additionalEntry' });
  728. expect(app.getLoginItemSettings()).to.deep.equal({
  729. openAtLogin: true,
  730. openAsHidden: false,
  731. wasOpenedAtLogin: false,
  732. wasOpenedAsHidden: false,
  733. restoreState: false,
  734. executableWillLaunchAtLogin: true,
  735. launchItems: [{
  736. name: 'electron.app.Electron',
  737. path: process.execPath,
  738. args: [],
  739. scope: 'user',
  740. enabled: true
  741. }]
  742. });
  743. });
  744. ifit(process.platform === 'win32')('finds launch items independent of args', function () {
  745. app.setLoginItemSettings({ openAtLogin: true, args: ['arg1'] });
  746. app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: false, args: ['arg2'] });
  747. expect(app.getLoginItemSettings()).to.deep.equal({
  748. openAtLogin: false,
  749. openAsHidden: false,
  750. wasOpenedAtLogin: false,
  751. wasOpenedAsHidden: false,
  752. restoreState: false,
  753. executableWillLaunchAtLogin: true,
  754. launchItems: [{
  755. name: 'additionalEntry',
  756. path: process.execPath,
  757. args: ['arg2'],
  758. scope: 'user',
  759. enabled: false
  760. }, {
  761. name: 'electron.app.Electron',
  762. path: process.execPath,
  763. args: ['arg1'],
  764. scope: 'user',
  765. enabled: true
  766. }]
  767. });
  768. });
  769. ifit(process.platform === 'win32')('finds launch items independent of path quotation or casing', function () {
  770. const expectation = {
  771. openAtLogin: false,
  772. openAsHidden: false,
  773. wasOpenedAtLogin: false,
  774. wasOpenedAsHidden: false,
  775. restoreState: false,
  776. executableWillLaunchAtLogin: true,
  777. launchItems: [{
  778. name: 'additionalEntry',
  779. path: 'C:\\electron\\myapp.exe',
  780. args: ['arg1'],
  781. scope: 'user',
  782. enabled: true
  783. }]
  784. };
  785. app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: true, path: 'C:\\electron\\myapp.exe', args: ['arg1'] });
  786. expect(app.getLoginItemSettings({ path: '"C:\\electron\\MYAPP.exe"' })).to.deep.equal(expectation);
  787. app.setLoginItemSettings({ openAtLogin: false, name: 'additionalEntry' });
  788. app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: true, path: '"C:\\electron\\MYAPP.exe"', args: ['arg1'] });
  789. expect(app.getLoginItemSettings({ path: 'C:\\electron\\myapp.exe' })).to.deep.equal({
  790. ...expectation,
  791. launchItems: [
  792. {
  793. name: 'additionalEntry',
  794. path: 'C:\\electron\\MYAPP.exe',
  795. args: ['arg1'],
  796. scope: 'user',
  797. enabled: true
  798. }
  799. ]
  800. });
  801. });
  802. ifit(process.platform === 'win32')('detects disabled by TaskManager', async function () {
  803. app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: true, args: ['arg1'] });
  804. const appProcess = cp.spawn('reg', [...regAddArgs, '030000000000000000000000']);
  805. await emittedOnce(appProcess, 'exit');
  806. expect(app.getLoginItemSettings()).to.deep.equal({
  807. openAtLogin: false,
  808. openAsHidden: false,
  809. wasOpenedAtLogin: false,
  810. wasOpenedAsHidden: false,
  811. restoreState: false,
  812. executableWillLaunchAtLogin: false,
  813. launchItems: [{
  814. name: 'additionalEntry',
  815. path: process.execPath,
  816. args: ['arg1'],
  817. scope: 'user',
  818. enabled: false
  819. }]
  820. });
  821. });
  822. ifit(process.platform === 'win32')('detects enabled by TaskManager', async function () {
  823. const expectation = {
  824. openAtLogin: false,
  825. openAsHidden: false,
  826. wasOpenedAtLogin: false,
  827. wasOpenedAsHidden: false,
  828. restoreState: false,
  829. executableWillLaunchAtLogin: true,
  830. launchItems: [{
  831. name: 'additionalEntry',
  832. path: process.execPath,
  833. args: ['arg1'],
  834. scope: 'user',
  835. enabled: true
  836. }]
  837. };
  838. app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: false, args: ['arg1'] });
  839. let appProcess = cp.spawn('reg', [...regAddArgs, '020000000000000000000000']);
  840. await emittedOnce(appProcess, 'exit');
  841. expect(app.getLoginItemSettings()).to.deep.equal(expectation);
  842. app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: false, args: ['arg1'] });
  843. appProcess = cp.spawn('reg', [...regAddArgs, '000000000000000000000000']);
  844. await emittedOnce(appProcess, 'exit');
  845. expect(app.getLoginItemSettings()).to.deep.equal(expectation);
  846. });
  847. });
  848. ifdescribe(process.platform !== 'linux')('accessibilitySupportEnabled property', () => {
  849. it('with properties', () => {
  850. it('can set accessibility support enabled', () => {
  851. expect(app.accessibilitySupportEnabled).to.eql(false);
  852. app.accessibilitySupportEnabled = true;
  853. expect(app.accessibilitySupportEnabled).to.eql(true);
  854. });
  855. });
  856. it('with functions', () => {
  857. it('can set accessibility support enabled', () => {
  858. expect(app.isAccessibilitySupportEnabled()).to.eql(false);
  859. app.setAccessibilitySupportEnabled(true);
  860. expect(app.isAccessibilitySupportEnabled()).to.eql(true);
  861. });
  862. });
  863. });
  864. describe('getAppPath', () => {
  865. it('works for directories with package.json', async () => {
  866. const { appPath } = await runTestApp('app-path');
  867. expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path'));
  868. });
  869. it('works for directories with index.js', async () => {
  870. const { appPath } = await runTestApp('app-path/lib');
  871. expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
  872. });
  873. it('works for files without extension', async () => {
  874. const { appPath } = await runTestApp('app-path/lib/index');
  875. expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
  876. });
  877. it('works for files', async () => {
  878. const { appPath } = await runTestApp('app-path/lib/index.js');
  879. expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
  880. });
  881. });
  882. describe('getPath(name)', () => {
  883. it('returns paths that exist', () => {
  884. const paths = [
  885. fs.existsSync(app.getPath('exe')),
  886. fs.existsSync(app.getPath('home')),
  887. fs.existsSync(app.getPath('temp'))
  888. ];
  889. expect(paths).to.deep.equal([true, true, true]);
  890. });
  891. it('throws an error when the name is invalid', () => {
  892. expect(() => {
  893. app.getPath('does-not-exist' as any);
  894. }).to.throw(/Failed to get 'does-not-exist' path/);
  895. });
  896. it('returns the overridden path', () => {
  897. app.setPath('music', __dirname);
  898. expect(app.getPath('music')).to.equal(__dirname);
  899. });
  900. if (process.platform === 'win32') {
  901. it('gets the folder for recent files', () => {
  902. const recent = app.getPath('recent');
  903. // We expect that one of our test machines have overriden this
  904. // to be something crazy, it'll always include the word "Recent"
  905. // unless people have been registry-hacking like crazy
  906. expect(recent).to.include('Recent');
  907. });
  908. it('can override the recent files path', () => {
  909. app.setPath('recent', 'C:\\fake-path');
  910. expect(app.getPath('recent')).to.equal('C:\\fake-path');
  911. });
  912. }
  913. it('uses the app name in getPath(userData)', () => {
  914. expect(app.getPath('userData')).to.include(app.name);
  915. });
  916. });
  917. describe('setPath(name, path)', () => {
  918. it('throws when a relative path is passed', () => {
  919. const badPath = 'hey/hi/hello';
  920. expect(() => {
  921. app.setPath('music', badPath);
  922. }).to.throw(/Path must be absolute/);
  923. });
  924. it('does not create a new directory by default', () => {
  925. const badPath = path.join(__dirname, 'music');
  926. expect(fs.existsSync(badPath)).to.be.false();
  927. app.setPath('music', badPath);
  928. expect(fs.existsSync(badPath)).to.be.false();
  929. expect(() => { app.getPath(badPath as any); }).to.throw();
  930. });
  931. });
  932. describe('setAppLogsPath(path)', () => {
  933. it('throws when a relative path is passed', () => {
  934. const badPath = 'hey/hi/hello';
  935. expect(() => {
  936. app.setAppLogsPath(badPath);
  937. }).to.throw(/Path must be absolute/);
  938. });
  939. });
  940. describe('select-client-certificate event', () => {
  941. let w: BrowserWindow;
  942. before(function () {
  943. if (process.platform === 'linux') {
  944. this.skip();
  945. }
  946. session.fromPartition('empty-certificate').setCertificateVerifyProc((req, cb) => { cb(0); });
  947. });
  948. beforeEach(() => {
  949. w = new BrowserWindow({
  950. show: false,
  951. webPreferences: {
  952. nodeIntegration: true,
  953. partition: 'empty-certificate'
  954. }
  955. });
  956. });
  957. afterEach(() => closeWindow(w).then(() => { w = null as any; }));
  958. after(() => session.fromPartition('empty-certificate').setCertificateVerifyProc(null));
  959. it('can respond with empty certificate list', async () => {
  960. app.once('select-client-certificate', function (event, webContents, url, list, callback) {
  961. console.log('select-client-certificate emitted');
  962. event.preventDefault();
  963. callback();
  964. });
  965. await w.webContents.loadURL(secureUrl);
  966. expect(w.webContents.getTitle()).to.equal('denied');
  967. });
  968. });
  969. describe('setAsDefaultProtocolClient(protocol, path, args)', () => {
  970. const protocol = 'electron-test';
  971. const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
  972. const processStartArgs = [
  973. '--processStart', `"${path.basename(process.execPath)}"`,
  974. '--process-start-args', '"--hidden"'
  975. ];
  976. let Winreg: any;
  977. let classesKey: any;
  978. before(function () {
  979. if (process.platform !== 'win32') {
  980. this.skip();
  981. } else {
  982. Winreg = require('winreg');
  983. classesKey = new Winreg({
  984. hive: Winreg.HKCU,
  985. key: '\\Software\\Classes\\'
  986. });
  987. }
  988. });
  989. after(function (done) {
  990. if (process.platform !== 'win32') {
  991. done();
  992. } else {
  993. const protocolKey = new Winreg({
  994. hive: Winreg.HKCU,
  995. key: `\\Software\\Classes\\${protocol}`
  996. });
  997. // The last test leaves the registry dirty,
  998. // delete the protocol key for those of us who test at home
  999. protocolKey.destroy(() => done());
  1000. }
  1001. });
  1002. beforeEach(() => {
  1003. app.removeAsDefaultProtocolClient(protocol);
  1004. app.removeAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
  1005. });
  1006. afterEach(() => {
  1007. app.removeAsDefaultProtocolClient(protocol);
  1008. expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
  1009. app.removeAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
  1010. expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(false);
  1011. });
  1012. it('sets the app as the default protocol client', () => {
  1013. expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
  1014. app.setAsDefaultProtocolClient(protocol);
  1015. expect(app.isDefaultProtocolClient(protocol)).to.equal(true);
  1016. });
  1017. it('allows a custom path and args to be specified', () => {
  1018. expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(false);
  1019. app.setAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
  1020. expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(true);
  1021. expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
  1022. });
  1023. it('creates a registry entry for the protocol class', async () => {
  1024. app.setAsDefaultProtocolClient(protocol);
  1025. const keys = await promisify(classesKey.keys).call(classesKey) as any[];
  1026. const exists = !!keys.find(key => key.key.includes(protocol));
  1027. expect(exists).to.equal(true);
  1028. });
  1029. it('completely removes a registry entry for the protocol class', async () => {
  1030. app.setAsDefaultProtocolClient(protocol);
  1031. app.removeAsDefaultProtocolClient(protocol);
  1032. const keys = await promisify(classesKey.keys).call(classesKey) as any[];
  1033. const exists = !!keys.find(key => key.key.includes(protocol));
  1034. expect(exists).to.equal(false);
  1035. });
  1036. it('only unsets a class registry key if it contains other data', async () => {
  1037. app.setAsDefaultProtocolClient(protocol);
  1038. const protocolKey = new Winreg({
  1039. hive: Winreg.HKCU,
  1040. key: `\\Software\\Classes\\${protocol}`
  1041. });
  1042. await promisify(protocolKey.set).call(protocolKey, 'test-value', 'REG_BINARY', '123');
  1043. app.removeAsDefaultProtocolClient(protocol);
  1044. const keys = await promisify(classesKey.keys).call(classesKey) as any[];
  1045. const exists = !!keys.find(key => key.key.includes(protocol));
  1046. expect(exists).to.equal(true);
  1047. });
  1048. it('sets the default client such that getApplicationNameForProtocol returns Electron', () => {
  1049. app.setAsDefaultProtocolClient(protocol);
  1050. expect(app.getApplicationNameForProtocol(`${protocol}://`)).to.equal('Electron');
  1051. });
  1052. });
  1053. describe('getApplicationNameForProtocol()', () => {
  1054. it('returns application names for common protocols', function () {
  1055. // We can't expect particular app names here, but these protocols should
  1056. // at least have _something_ registered. Except on our Linux CI
  1057. // environment apparently.
  1058. if (process.platform === 'linux') {
  1059. this.skip();
  1060. }
  1061. const protocols = [
  1062. 'http://',
  1063. 'https://'
  1064. ];
  1065. protocols.forEach((protocol) => {
  1066. expect(app.getApplicationNameForProtocol(protocol)).to.not.equal('');
  1067. });
  1068. });
  1069. it('returns an empty string for a bogus protocol', () => {
  1070. expect(app.getApplicationNameForProtocol('bogus-protocol://')).to.equal('');
  1071. });
  1072. });
  1073. ifdescribe(process.platform !== 'linux')('getApplicationInfoForProtocol()', () => {
  1074. it('returns promise rejection for a bogus protocol', async function () {
  1075. await expect(
  1076. app.getApplicationInfoForProtocol('bogus-protocol://')
  1077. ).to.eventually.be.rejectedWith(
  1078. 'Unable to retrieve installation path to app'
  1079. );
  1080. });
  1081. it('returns resolved promise with appPath, displayName and icon', async function () {
  1082. const appInfo = await app.getApplicationInfoForProtocol('https://');
  1083. expect(appInfo.path).not.to.be.undefined();
  1084. expect(appInfo.name).not.to.be.undefined();
  1085. expect(appInfo.icon).not.to.be.undefined();
  1086. });
  1087. });
  1088. describe('isDefaultProtocolClient()', () => {
  1089. it('returns false for a bogus protocol', () => {
  1090. expect(app.isDefaultProtocolClient('bogus-protocol://')).to.equal(false);
  1091. });
  1092. });
  1093. ifdescribe(process.platform === 'win32')('app launch through uri', () => {
  1094. it('does not launch for argument following a URL', async () => {
  1095. const appPath = path.join(fixturesPath, 'api', 'quit-app');
  1096. // App should exit with non 123 code.
  1097. const first = cp.spawn(process.execPath, [appPath, 'electron-test:?', 'abc']);
  1098. const [code] = await emittedOnce(first, 'exit');
  1099. expect(code).to.not.equal(123);
  1100. });
  1101. it('launches successfully for argument following a file path', async () => {
  1102. const appPath = path.join(fixturesPath, 'api', 'quit-app');
  1103. // App should exit with code 123.
  1104. const first = cp.spawn(process.execPath, [appPath, 'e:\\abc', 'abc']);
  1105. const [code] = await emittedOnce(first, 'exit');
  1106. expect(code).to.equal(123);
  1107. });
  1108. it('launches successfully for multiple URIs following --', async () => {
  1109. const appPath = path.join(fixturesPath, 'api', 'quit-app');
  1110. // App should exit with code 123.
  1111. const first = cp.spawn(process.execPath, [appPath, '--', 'http://electronjs.org', 'electron-test://testdata']);
  1112. const [code] = await emittedOnce(first, 'exit');
  1113. expect(code).to.equal(123);
  1114. });
  1115. });
  1116. // FIXME Get these specs running on Linux CI
  1117. ifdescribe(process.platform !== 'linux')('getFileIcon() API', () => {
  1118. const iconPath = path.join(__dirname, 'fixtures/assets/icon.ico');
  1119. const sizes = {
  1120. small: 16,
  1121. normal: 32,
  1122. large: process.platform === 'win32' ? 32 : 48
  1123. };
  1124. it('fetches a non-empty icon', async () => {
  1125. const icon = await app.getFileIcon(iconPath);
  1126. expect(icon.isEmpty()).to.equal(false);
  1127. });
  1128. it('fetches normal icon size by default', async () => {
  1129. const icon = await app.getFileIcon(iconPath);
  1130. const size = icon.getSize();
  1131. expect(size.height).to.equal(sizes.normal);
  1132. expect(size.width).to.equal(sizes.normal);
  1133. });
  1134. describe('size option', () => {
  1135. it('fetches a small icon', async () => {
  1136. const icon = await app.getFileIcon(iconPath, { size: 'small' });
  1137. const size = icon.getSize();
  1138. expect(size.height).to.equal(sizes.small);
  1139. expect(size.width).to.equal(sizes.small);
  1140. });
  1141. it('fetches a normal icon', async () => {
  1142. const icon = await app.getFileIcon(iconPath, { size: 'normal' });
  1143. const size = icon.getSize();
  1144. expect(size.height).to.equal(sizes.normal);
  1145. expect(size.width).to.equal(sizes.normal);
  1146. });
  1147. it('fetches a large icon', async () => {
  1148. // macOS does not support large icons
  1149. if (process.platform === 'darwin') return;
  1150. const icon = await app.getFileIcon(iconPath, { size: 'large' });
  1151. const size = icon.getSize();
  1152. expect(size.height).to.equal(sizes.large);
  1153. expect(size.width).to.equal(sizes.large);
  1154. });
  1155. });
  1156. });
  1157. describe('getAppMetrics() API', () => {
  1158. it('returns memory and cpu stats of all running electron processes', () => {
  1159. const appMetrics = app.getAppMetrics();
  1160. expect(appMetrics).to.be.an('array').and.have.lengthOf.at.least(1, 'App memory info object is not > 0');
  1161. const types = [];
  1162. for (const entry of appMetrics) {
  1163. expect(entry.pid).to.be.above(0, 'pid is not > 0');
  1164. expect(entry.type).to.be.a('string').that.does.not.equal('');
  1165. expect(entry.creationTime).to.be.a('number').that.is.greaterThan(0);
  1166. types.push(entry.type);
  1167. expect(entry.cpu).to.have.ownProperty('percentCPUUsage').that.is.a('number');
  1168. expect(entry.cpu).to.have.ownProperty('idleWakeupsPerSecond').that.is.a('number');
  1169. expect(entry.memory).to.have.property('workingSetSize').that.is.greaterThan(0);
  1170. expect(entry.memory).to.have.property('peakWorkingSetSize').that.is.greaterThan(0);
  1171. if (entry.type === 'Utility' || entry.type === 'GPU') {
  1172. expect(entry.serviceName).to.be.a('string').that.does.not.equal('');
  1173. }
  1174. if (entry.type === 'Utility') {
  1175. expect(entry).to.have.property('name').that.is.a('string');
  1176. }
  1177. if (process.platform === 'win32') {
  1178. expect(entry.memory).to.have.property('privateBytes').that.is.greaterThan(0);
  1179. }
  1180. if (process.platform !== 'linux') {
  1181. expect(entry.sandboxed).to.be.a('boolean');
  1182. }
  1183. if (process.platform === 'win32') {
  1184. expect(entry.integrityLevel).to.be.a('string');
  1185. }
  1186. }
  1187. if (process.platform === 'darwin') {
  1188. expect(types).to.include('GPU');
  1189. }
  1190. expect(types).to.include('Browser');
  1191. });
  1192. });
  1193. describe('getGPUFeatureStatus() API', () => {
  1194. it('returns the graphic features statuses', () => {
  1195. const features = app.getGPUFeatureStatus();
  1196. expect(features).to.have.ownProperty('webgl').that.is.a('string');
  1197. expect(features).to.have.ownProperty('gpu_compositing').that.is.a('string');
  1198. });
  1199. });
  1200. // FIXME https://github.com/electron/electron/issues/24224
  1201. ifdescribe(process.platform !== 'linux')('getGPUInfo() API', () => {
  1202. const appPath = path.join(fixturesPath, 'api', 'gpu-info.js');
  1203. const getGPUInfo = async (type: string) => {
  1204. const appProcess = cp.spawn(process.execPath, [appPath, type]);
  1205. let gpuInfoData = '';
  1206. let errorData = '';
  1207. appProcess.stdout.on('data', (data) => {
  1208. gpuInfoData += data;
  1209. });
  1210. appProcess.stderr.on('data', (data) => {
  1211. errorData += data;
  1212. });
  1213. const [exitCode] = await emittedOnce(appProcess, 'exit');
  1214. if (exitCode === 0) {
  1215. try {
  1216. const [, json] = /HERE COMES THE JSON: (.+) AND THERE IT WAS/.exec(gpuInfoData)!;
  1217. // return info data on successful exit
  1218. return JSON.parse(json);
  1219. } catch (e) {
  1220. console.error('Failed to interpret the following as JSON:');
  1221. console.error(gpuInfoData);
  1222. throw e;
  1223. }
  1224. } else {
  1225. // return error if not clean exit
  1226. return Promise.reject(new Error(errorData));
  1227. }
  1228. };
  1229. const verifyBasicGPUInfo = async (gpuInfo: any) => {
  1230. // Devices information is always present in the available info.
  1231. expect(gpuInfo).to.have.ownProperty('gpuDevice')
  1232. .that.is.an('array')
  1233. .and.does.not.equal([]);
  1234. const device = gpuInfo.gpuDevice[0];
  1235. expect(device).to.be.an('object')
  1236. .and.to.have.property('deviceId')
  1237. .that.is.a('number')
  1238. .not.lessThan(0);
  1239. };
  1240. it('succeeds with basic GPUInfo', async () => {
  1241. const gpuInfo = await getGPUInfo('basic');
  1242. await verifyBasicGPUInfo(gpuInfo);
  1243. });
  1244. it('succeeds with complete GPUInfo', async () => {
  1245. const completeInfo = await getGPUInfo('complete');
  1246. if (process.platform === 'linux') {
  1247. // For linux and macOS complete info is same as basic info
  1248. await verifyBasicGPUInfo(completeInfo);
  1249. const basicInfo = await getGPUInfo('basic');
  1250. expect(completeInfo).to.deep.equal(basicInfo);
  1251. } else {
  1252. // Gl version is present in the complete info.
  1253. expect(completeInfo).to.have.ownProperty('auxAttributes')
  1254. .that.is.an('object');
  1255. if (completeInfo.gpuDevice.active) {
  1256. expect(completeInfo.auxAttributes).to.have.ownProperty('glVersion')
  1257. .that.is.a('string')
  1258. .and.does.not.equal([]);
  1259. }
  1260. }
  1261. });
  1262. it('fails for invalid info_type', () => {
  1263. const invalidType = 'invalid';
  1264. const expectedErrorMessage = "Invalid info type. Use 'basic' or 'complete'";
  1265. return expect(app.getGPUInfo(invalidType as any)).to.eventually.be.rejectedWith(expectedErrorMessage);
  1266. });
  1267. });
  1268. describe('sandbox options', () => {
  1269. let appProcess: cp.ChildProcess = null as any;
  1270. let server: net.Server = null as any;
  1271. const socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\electron-mixed-sandbox' : '/tmp/electron-mixed-sandbox';
  1272. beforeEach(function (done) {
  1273. if (process.platform === 'linux' && (process.arch === 'arm64' || process.arch === 'arm')) {
  1274. // Our ARM tests are run on VSTS rather than CircleCI, and the Docker
  1275. // setup on VSTS disallows syscalls that Chrome requires for setting up
  1276. // sandboxing.
  1277. // See:
  1278. // - https://docs.docker.com/engine/security/seccomp/#significant-syscalls-blocked-by-the-default-profile
  1279. // - https://chromium.googlesource.com/chromium/src/+/70.0.3538.124/sandbox/linux/services/credentials.cc#292
  1280. // - https://github.com/docker/docker-ce/blob/ba7dfc59ccfe97c79ee0d1379894b35417b40bca/components/engine/profiles/seccomp/seccomp_default.go#L497
  1281. // - https://blog.jessfraz.com/post/how-to-use-new-docker-seccomp-profiles/
  1282. //
  1283. // Adding `--cap-add SYS_ADMIN` or `--security-opt seccomp=unconfined`
  1284. // to the Docker invocation allows the syscalls that Chrome needs, but
  1285. // are probably more permissive than we'd like.
  1286. this.skip();
  1287. }
  1288. fs.unlink(socketPath, () => {
  1289. server = net.createServer();
  1290. server.listen(socketPath);
  1291. done();
  1292. });
  1293. });
  1294. afterEach(done => {
  1295. if (appProcess != null) appProcess.kill();
  1296. server.close(() => {
  1297. if (process.platform === 'win32') {
  1298. done();
  1299. } else {
  1300. fs.unlink(socketPath, () => done());
  1301. }
  1302. });
  1303. });
  1304. describe('when app.enableSandbox() is called', () => {
  1305. it('adds --enable-sandbox to all renderer processes', done => {
  1306. const appPath = path.join(fixturesPath, 'api', 'mixed-sandbox-app');
  1307. appProcess = cp.spawn(process.execPath, [appPath, '--app-enable-sandbox'], { stdio: 'inherit' });
  1308. server.once('error', error => { done(error); });
  1309. server.on('connection', client => {
  1310. client.once('data', (data) => {
  1311. const argv = JSON.parse(data.toString());
  1312. expect(argv.sandbox).to.include('--enable-sandbox');
  1313. expect(argv.sandbox).to.not.include('--no-sandbox');
  1314. expect(argv.noSandbox).to.include('--enable-sandbox');
  1315. expect(argv.noSandbox).to.not.include('--no-sandbox');
  1316. expect(argv.noSandboxDevtools).to.equal(true);
  1317. expect(argv.sandboxDevtools).to.equal(true);
  1318. done();
  1319. });
  1320. });
  1321. });
  1322. });
  1323. describe('when the app is launched with --enable-sandbox', () => {
  1324. it('adds --enable-sandbox to all renderer processes', done => {
  1325. const appPath = path.join(fixturesPath, 'api', 'mixed-sandbox-app');
  1326. appProcess = cp.spawn(process.execPath, [appPath, '--enable-sandbox'], { stdio: 'inherit' });
  1327. server.once('error', error => { done(error); });
  1328. server.on('connection', client => {
  1329. client.once('data', data => {
  1330. const argv = JSON.parse(data.toString());
  1331. expect(argv.sandbox).to.include('--enable-sandbox');
  1332. expect(argv.sandbox).to.not.include('--no-sandbox');
  1333. expect(argv.noSandbox).to.include('--enable-sandbox');
  1334. expect(argv.noSandbox).to.not.include('--no-sandbox');
  1335. expect(argv.noSandboxDevtools).to.equal(true);
  1336. expect(argv.sandboxDevtools).to.equal(true);
  1337. done();
  1338. });
  1339. });
  1340. });
  1341. });
  1342. });
  1343. describe('disableDomainBlockingFor3DAPIs() API', () => {
  1344. it('throws when called after app is ready', () => {
  1345. expect(() => {
  1346. app.disableDomainBlockingFor3DAPIs();
  1347. }).to.throw(/before app is ready/);
  1348. });
  1349. });
  1350. ifdescribe(process.platform === 'darwin')('app hide and show API', () => {
  1351. describe('app.isHidden', () => {
  1352. it('returns true when the app is hidden', async () => {
  1353. app.hide();
  1354. await expect(
  1355. waitUntil(() => app.isHidden())
  1356. ).to.eventually.be.fulfilled();
  1357. });
  1358. it('returns false when the app is shown', async () => {
  1359. app.show();
  1360. await expect(
  1361. waitUntil(() => !app.isHidden())
  1362. ).to.eventually.be.fulfilled();
  1363. });
  1364. });
  1365. });
  1366. const dockDescribe = process.platform === 'darwin' ? describe : describe.skip;
  1367. dockDescribe('dock APIs', () => {
  1368. after(async () => {
  1369. await app.dock.show();
  1370. });
  1371. describe('dock.setMenu', () => {
  1372. it('can be retrieved via dock.getMenu', () => {
  1373. expect(app.dock.getMenu()).to.equal(null);
  1374. const menu = new Menu();
  1375. app.dock.setMenu(menu);
  1376. expect(app.dock.getMenu()).to.equal(menu);
  1377. });
  1378. it('keeps references to the menu', () => {
  1379. app.dock.setMenu(new Menu());
  1380. const v8Util = process._linkedBinding('electron_common_v8_util');
  1381. v8Util.requestGarbageCollectionForTesting();
  1382. });
  1383. });
  1384. describe('dock.setIcon', () => {
  1385. it('throws a descriptive error for a bad icon path', () => {
  1386. const badPath = path.resolve('I', 'Do', 'Not', 'Exist');
  1387. expect(() => {
  1388. app.dock.setIcon(badPath);
  1389. }).to.throw(/Failed to load image from path (.+)/);
  1390. });
  1391. });
  1392. describe('dock.bounce', () => {
  1393. it('should return -1 for unknown bounce type', () => {
  1394. expect(app.dock.bounce('bad type' as any)).to.equal(-1);
  1395. });
  1396. it('should return a positive number for informational type', () => {
  1397. const appHasFocus = !!BrowserWindow.getFocusedWindow();
  1398. if (!appHasFocus) {
  1399. expect(app.dock.bounce('informational')).to.be.at.least(0);
  1400. }
  1401. });
  1402. it('should return a positive number for critical type', () => {
  1403. const appHasFocus = !!BrowserWindow.getFocusedWindow();
  1404. if (!appHasFocus) {
  1405. expect(app.dock.bounce('critical')).to.be.at.least(0);
  1406. }
  1407. });
  1408. });
  1409. describe('dock.cancelBounce', () => {
  1410. it('should not throw', () => {
  1411. app.dock.cancelBounce(app.dock.bounce('critical'));
  1412. });
  1413. });
  1414. describe('dock.setBadge', () => {
  1415. after(() => {
  1416. app.dock.setBadge('');
  1417. });
  1418. it('should not throw', () => {
  1419. app.dock.setBadge('1');
  1420. });
  1421. it('should be retrievable via getBadge', () => {
  1422. app.dock.setBadge('test');
  1423. expect(app.dock.getBadge()).to.equal('test');
  1424. });
  1425. });
  1426. describe('dock.hide', () => {
  1427. it('should not throw', () => {
  1428. app.dock.hide();
  1429. expect(app.dock.isVisible()).to.equal(false);
  1430. });
  1431. });
  1432. // Note that dock.show tests should run after dock.hide tests, to work
  1433. // around a bug of macOS.
  1434. // See https://github.com/electron/electron/pull/25269 for more.
  1435. describe('dock.show', () => {
  1436. it('should not throw', () => {
  1437. return app.dock.show().then(() => {
  1438. expect(app.dock.isVisible()).to.equal(true);
  1439. });
  1440. });
  1441. it('returns a Promise', () => {
  1442. expect(app.dock.show()).to.be.a('promise');
  1443. });
  1444. it('eventually fulfills', async () => {
  1445. await expect(app.dock.show()).to.eventually.be.fulfilled.equal(undefined);
  1446. });
  1447. });
  1448. });
  1449. describe('whenReady', () => {
  1450. it('returns a Promise', () => {
  1451. expect(app.whenReady()).to.be.a('promise');
  1452. });
  1453. it('becomes fulfilled if the app is already ready', async () => {
  1454. expect(app.isReady()).to.equal(true);
  1455. await expect(app.whenReady()).to.be.eventually.fulfilled.equal(undefined);
  1456. });
  1457. });
  1458. describe('app.applicationMenu', () => {
  1459. it('has the applicationMenu property', () => {
  1460. expect(app).to.have.property('applicationMenu');
  1461. });
  1462. });
  1463. describe('commandLine.hasSwitch', () => {
  1464. it('returns true when present', () => {
  1465. app.commandLine.appendSwitch('foobar1');
  1466. expect(app.commandLine.hasSwitch('foobar1')).to.equal(true);
  1467. });
  1468. it('returns false when not present', () => {
  1469. expect(app.commandLine.hasSwitch('foobar2')).to.equal(false);
  1470. });
  1471. });
  1472. describe('commandLine.hasSwitch (existing argv)', () => {
  1473. it('returns true when present', async () => {
  1474. const { hasSwitch } = await runTestApp('command-line', '--foobar');
  1475. expect(hasSwitch).to.equal(true);
  1476. });
  1477. it('returns false when not present', async () => {
  1478. const { hasSwitch } = await runTestApp('command-line');
  1479. expect(hasSwitch).to.equal(false);
  1480. });
  1481. });
  1482. describe('commandLine.getSwitchValue', () => {
  1483. it('returns the value when present', () => {
  1484. app.commandLine.appendSwitch('foobar', 'æøåü');
  1485. expect(app.commandLine.getSwitchValue('foobar')).to.equal('æøåü');
  1486. });
  1487. it('returns an empty string when present without value', () => {
  1488. app.commandLine.appendSwitch('foobar1');
  1489. expect(app.commandLine.getSwitchValue('foobar1')).to.equal('');
  1490. });
  1491. it('returns an empty string when not present', () => {
  1492. expect(app.commandLine.getSwitchValue('foobar2')).to.equal('');
  1493. });
  1494. });
  1495. describe('commandLine.getSwitchValue (existing argv)', () => {
  1496. it('returns the value when present', async () => {
  1497. const { getSwitchValue } = await runTestApp('command-line', '--foobar=test');
  1498. expect(getSwitchValue).to.equal('test');
  1499. });
  1500. it('returns an empty string when present without value', async () => {
  1501. const { getSwitchValue } = await runTestApp('command-line', '--foobar');
  1502. expect(getSwitchValue).to.equal('');
  1503. });
  1504. it('returns an empty string when not present', async () => {
  1505. const { getSwitchValue } = await runTestApp('command-line');
  1506. expect(getSwitchValue).to.equal('');
  1507. });
  1508. });
  1509. describe('commandLine.removeSwitch', () => {
  1510. it('no-ops a non-existent switch', async () => {
  1511. expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
  1512. app.commandLine.removeSwitch('foobar3');
  1513. expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
  1514. });
  1515. it('removes an existing switch', async () => {
  1516. app.commandLine.appendSwitch('foobar3', 'test');
  1517. expect(app.commandLine.hasSwitch('foobar3')).to.equal(true);
  1518. app.commandLine.removeSwitch('foobar3');
  1519. expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
  1520. });
  1521. });
  1522. ifdescribe(process.platform === 'darwin')('app.setSecureKeyboardEntryEnabled', () => {
  1523. it('changes Secure Keyboard Entry is enabled', () => {
  1524. app.setSecureKeyboardEntryEnabled(true);
  1525. expect(app.isSecureKeyboardEntryEnabled()).to.equal(true);
  1526. app.setSecureKeyboardEntryEnabled(false);
  1527. expect(app.isSecureKeyboardEntryEnabled()).to.equal(false);
  1528. });
  1529. });
  1530. describe('configureHostResolver', () => {
  1531. after(() => {
  1532. // Returns to the default configuration.
  1533. app.configureHostResolver({});
  1534. });
  1535. it('fails on bad arguments', () => {
  1536. expect(() => {
  1537. (app.configureHostResolver as any)();
  1538. }).to.throw();
  1539. expect(() => {
  1540. app.configureHostResolver({
  1541. secureDnsMode: 'notAValidValue' as any
  1542. });
  1543. }).to.throw();
  1544. expect(() => {
  1545. app.configureHostResolver({
  1546. secureDnsServers: [123 as any]
  1547. });
  1548. }).to.throw();
  1549. });
  1550. it('affects dns lookup behavior', async () => {
  1551. // 1. resolve a domain name to check that things are working
  1552. await expect(new Promise((resolve, reject) => {
  1553. electronNet.request({
  1554. method: 'HEAD',
  1555. url: 'https://www.electronjs.org'
  1556. }).on('response', resolve)
  1557. .on('error', reject)
  1558. .end();
  1559. })).to.eventually.be.fulfilled();
  1560. // 2. change the host resolver configuration to something that will
  1561. // always fail
  1562. app.configureHostResolver({
  1563. secureDnsMode: 'secure',
  1564. secureDnsServers: ['https://127.0.0.1:1234']
  1565. });
  1566. // 3. check that resolving domain names now fails
  1567. await expect(new Promise((resolve, reject) => {
  1568. electronNet.request({
  1569. method: 'HEAD',
  1570. // Needs to be a slightly different domain to above, otherwise the
  1571. // response will come from the cache.
  1572. url: 'https://electronjs.org'
  1573. }).on('response', resolve)
  1574. .on('error', reject)
  1575. .end();
  1576. })).to.eventually.be.rejectedWith(/ERR_NAME_NOT_RESOLVED/);
  1577. });
  1578. });
  1579. });
  1580. describe('default behavior', () => {
  1581. describe('application menu', () => {
  1582. it('creates the default menu if the app does not set it', async () => {
  1583. const result = await runTestApp('default-menu');
  1584. expect(result).to.equal(false);
  1585. });
  1586. it('does not create the default menu if the app sets a custom menu', async () => {
  1587. const result = await runTestApp('default-menu', '--custom-menu');
  1588. expect(result).to.equal(true);
  1589. });
  1590. it('does not create the default menu if the app sets a null menu', async () => {
  1591. const result = await runTestApp('default-menu', '--null-menu');
  1592. expect(result).to.equal(true);
  1593. });
  1594. });
  1595. describe('window-all-closed', () => {
  1596. afterEach(closeAllWindows);
  1597. it('quits when the app does not handle the event', async () => {
  1598. const result = await runTestApp('window-all-closed');
  1599. expect(result).to.equal(false);
  1600. });
  1601. it('does not quit when the app handles the event', async () => {
  1602. const result = await runTestApp('window-all-closed', '--handle-event');
  1603. expect(result).to.equal(true);
  1604. });
  1605. it('should omit closed windows from getAllWindows', async () => {
  1606. const w = new BrowserWindow({ show: false });
  1607. const len = new Promise(resolve => {
  1608. app.on('window-all-closed', () => {
  1609. resolve(BrowserWindow.getAllWindows().length);
  1610. });
  1611. });
  1612. w.close();
  1613. expect(await len).to.equal(0);
  1614. });
  1615. });
  1616. describe('user agent fallback', () => {
  1617. let initialValue: string;
  1618. before(() => {
  1619. initialValue = app.userAgentFallback!;
  1620. });
  1621. it('should have a reasonable default', () => {
  1622. expect(initialValue).to.include(`Electron/${process.versions.electron}`);
  1623. expect(initialValue).to.include(`Chrome/${process.versions.chrome}`);
  1624. });
  1625. it('should be overridable', () => {
  1626. app.userAgentFallback = 'test-agent/123';
  1627. expect(app.userAgentFallback).to.equal('test-agent/123');
  1628. });
  1629. it('should be restorable', () => {
  1630. app.userAgentFallback = 'test-agent/123';
  1631. app.userAgentFallback = '';
  1632. expect(app.userAgentFallback).to.equal(initialValue);
  1633. });
  1634. });
  1635. describe('login event', () => {
  1636. afterEach(closeAllWindows);
  1637. let server: http.Server;
  1638. let serverUrl: string;
  1639. before((done) => {
  1640. server = http.createServer((request, response) => {
  1641. if (request.headers.authorization) {
  1642. return response.end('ok');
  1643. }
  1644. response
  1645. .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
  1646. .end();
  1647. }).listen(0, '127.0.0.1', () => {
  1648. serverUrl = 'http://127.0.0.1:' + (server.address() as net.AddressInfo).port;
  1649. done();
  1650. });
  1651. });
  1652. it('should emit a login event on app when a WebContents hits a 401', async () => {
  1653. const w = new BrowserWindow({ show: false });
  1654. w.loadURL(serverUrl);
  1655. const [, webContents] = await emittedOnce(app, 'login');
  1656. expect(webContents).to.equal(w.webContents);
  1657. });
  1658. });
  1659. describe('running under ARM64 translation', () => {
  1660. it('does not throw an error', () => {
  1661. if (process.platform === 'darwin' || process.platform === 'win32') {
  1662. expect(app.runningUnderARM64Translation).not.to.be.undefined();
  1663. expect(() => {
  1664. return app.runningUnderARM64Translation;
  1665. }).not.to.throw();
  1666. } else {
  1667. expect(app.runningUnderARM64Translation).to.be.undefined();
  1668. }
  1669. });
  1670. });
  1671. });
  1672. async function runTestApp (name: string, ...args: any[]) {
  1673. const appPath = path.join(fixturesPath, 'api', name);
  1674. const electronPath = process.execPath;
  1675. const appProcess = cp.spawn(electronPath, [appPath, ...args]);
  1676. let output = '';
  1677. appProcess.stdout.on('data', (data) => { output += data; });
  1678. await emittedOnce(appProcess.stdout, 'end');
  1679. return JSON.parse(output);
  1680. }