api-app-spec.ts 74 KB

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