api-app-spec.ts 59 KB

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