api-app-spec.ts 59 KB

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