api-app-spec.ts 64 KB

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