api-app-spec.ts 62 KB

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