api-app-spec.ts 62 KB

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