api-app-spec.ts 64 KB

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