api-app-spec.ts 67 KB

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