api-app-spec.ts 60 KB

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