api-app-spec.ts 67 KB

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