api-app-spec.ts 64 KB

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