api-app-spec.ts 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192
  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 'node:fs';
  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 && (process.platform !== 'darwin' || process.arch === 'arm64'))('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. ifdescribe(process.platform === 'win32')('setJumpList(categories)', () => {
  863. it('throws an error when categories is not null or an array', () => {
  864. expect(() => {
  865. app.setJumpList('string' as any);
  866. }).to.throw('Argument must be null or an array of categories');
  867. });
  868. it('can get jump list settings', () => {
  869. const settings = app.getJumpListSettings();
  870. expect(settings).to.eql({ minItems: 10, removedItems: [] });
  871. });
  872. it('can set a jump list with an array of categories', () => {
  873. expect(() => {
  874. app.setJumpList([
  875. { type: 'frequent' },
  876. {
  877. items: [{
  878. type: 'task',
  879. title: 'New Project',
  880. program: process.execPath,
  881. args: '--new-project',
  882. description: 'Create a new project.'
  883. },
  884. { type: 'separator' },
  885. {
  886. type: 'task',
  887. title: 'Recover Project',
  888. program: process.execPath,
  889. args: '--recover-project',
  890. description: 'Recover Project'
  891. }]
  892. }
  893. ]);
  894. }).to.not.throw();
  895. });
  896. });
  897. describe('getAppPath', () => {
  898. it('works for directories with package.json', async () => {
  899. const { appPath } = await runTestApp('app-path');
  900. expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path'));
  901. });
  902. it('works for directories with index.js', async () => {
  903. const { appPath } = await runTestApp('app-path/lib');
  904. expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
  905. });
  906. it('works for files without extension', async () => {
  907. const { appPath } = await runTestApp('app-path/lib/index');
  908. expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
  909. });
  910. it('works for files', async () => {
  911. const { appPath } = await runTestApp('app-path/lib/index.js');
  912. expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
  913. });
  914. });
  915. describe('getPath(name)', () => {
  916. it('returns paths that exist', () => {
  917. const paths = [
  918. fs.existsSync(app.getPath('exe')),
  919. fs.existsSync(app.getPath('home')),
  920. fs.existsSync(app.getPath('temp'))
  921. ];
  922. expect(paths).to.deep.equal([true, true, true]);
  923. });
  924. it('throws an error when the name is invalid', () => {
  925. expect(() => {
  926. app.getPath('does-not-exist' as any);
  927. }).to.throw(/Failed to get 'does-not-exist' path/);
  928. });
  929. it('returns the overridden path', () => {
  930. app.setPath('music', __dirname);
  931. expect(app.getPath('music')).to.equal(__dirname);
  932. });
  933. if (process.platform === 'win32') {
  934. it('gets the folder for recent files', () => {
  935. const recent = app.getPath('recent');
  936. // We expect that one of our test machines have overridden this
  937. // to be something crazy, it'll always include the word "Recent"
  938. // unless people have been registry-hacking like crazy
  939. expect(recent).to.include('Recent');
  940. });
  941. it('can override the recent files path', () => {
  942. app.setPath('recent', 'C:\\fake-path');
  943. expect(app.getPath('recent')).to.equal('C:\\fake-path');
  944. });
  945. }
  946. it('uses the app name in getPath(userData)', () => {
  947. expect(app.getPath('userData')).to.include(app.name);
  948. });
  949. });
  950. describe('setPath(name, path)', () => {
  951. it('throws when a relative path is passed', () => {
  952. const badPath = 'hey/hi/hello';
  953. expect(() => {
  954. app.setPath('music', badPath);
  955. }).to.throw(/Path must be absolute/);
  956. });
  957. it('does not create a new directory by default', () => {
  958. const badPath = path.join(__dirname, 'music');
  959. expect(fs.existsSync(badPath)).to.be.false();
  960. app.setPath('music', badPath);
  961. expect(fs.existsSync(badPath)).to.be.false();
  962. expect(() => { app.getPath(badPath as any); }).to.throw();
  963. });
  964. describe('sessionData', () => {
  965. const appPath = path.join(__dirname, 'fixtures', 'apps', 'set-path');
  966. const appName = JSON.parse(fs.readFileSync(path.join(appPath, 'package.json'), 'utf8')).name;
  967. const userDataPath = path.join(app.getPath('appData'), appName);
  968. const tempBrowserDataPath = path.join(app.getPath('temp'), appName);
  969. const sessionFiles = [
  970. 'Preferences',
  971. 'Code Cache',
  972. 'Local Storage',
  973. 'IndexedDB',
  974. 'Service Worker'
  975. ];
  976. const hasSessionFiles = (dir: string) => {
  977. for (const file of sessionFiles) {
  978. if (!fs.existsSync(path.join(dir, file))) {
  979. return false;
  980. }
  981. }
  982. return true;
  983. };
  984. beforeEach(() => {
  985. fs.rmSync(userDataPath, { force: true, recursive: true });
  986. fs.rmSync(tempBrowserDataPath, { force: true, recursive: true });
  987. });
  988. it('writes to userData by default', () => {
  989. expect(hasSessionFiles(userDataPath)).to.equal(false);
  990. cp.spawnSync(process.execPath, [appPath]);
  991. expect(hasSessionFiles(userDataPath)).to.equal(true);
  992. });
  993. it('can be changed', () => {
  994. expect(hasSessionFiles(userDataPath)).to.equal(false);
  995. cp.spawnSync(process.execPath, [appPath, 'sessionData', tempBrowserDataPath]);
  996. expect(hasSessionFiles(userDataPath)).to.equal(false);
  997. expect(hasSessionFiles(tempBrowserDataPath)).to.equal(true);
  998. });
  999. it('changing userData affects default sessionData', () => {
  1000. expect(hasSessionFiles(userDataPath)).to.equal(false);
  1001. cp.spawnSync(process.execPath, [appPath, 'userData', tempBrowserDataPath]);
  1002. expect(hasSessionFiles(userDataPath)).to.equal(false);
  1003. expect(hasSessionFiles(tempBrowserDataPath)).to.equal(true);
  1004. });
  1005. });
  1006. });
  1007. describe('setAppLogsPath(path)', () => {
  1008. it('throws when a relative path is passed', () => {
  1009. const badPath = 'hey/hi/hello';
  1010. expect(() => {
  1011. app.setAppLogsPath(badPath);
  1012. }).to.throw(/Path must be absolute/);
  1013. });
  1014. });
  1015. ifdescribe(process.platform !== 'linux')('select-client-certificate event', () => {
  1016. let w: BrowserWindow;
  1017. before(function () {
  1018. session.fromPartition('empty-certificate').setCertificateVerifyProc((req, cb) => { cb(0); });
  1019. });
  1020. beforeEach(() => {
  1021. w = new BrowserWindow({
  1022. show: false,
  1023. webPreferences: {
  1024. nodeIntegration: true,
  1025. partition: 'empty-certificate'
  1026. }
  1027. });
  1028. });
  1029. afterEach(() => closeWindow(w).then(() => { w = null as any; }));
  1030. after(() => session.fromPartition('empty-certificate').setCertificateVerifyProc(null));
  1031. it('can respond with empty certificate list', async () => {
  1032. app.once('select-client-certificate', function (event, webContents, url, list, callback) {
  1033. console.log('select-client-certificate emitted');
  1034. event.preventDefault();
  1035. callback();
  1036. });
  1037. await w.webContents.loadURL(secureUrl);
  1038. expect(w.webContents.getTitle()).to.equal('denied');
  1039. });
  1040. });
  1041. ifdescribe(process.platform === 'win32')('setAsDefaultProtocolClient(protocol, path, args)', () => {
  1042. const protocol = 'electron-test';
  1043. const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
  1044. const processStartArgs = [
  1045. '--processStart', `"${path.basename(process.execPath)}"`,
  1046. '--process-start-args', '"--hidden"'
  1047. ];
  1048. let Winreg: any;
  1049. let classesKey: any;
  1050. before(function () {
  1051. Winreg = require('winreg');
  1052. classesKey = new Winreg({
  1053. hive: Winreg.HKCU,
  1054. key: '\\Software\\Classes\\'
  1055. });
  1056. });
  1057. after(function (done) {
  1058. if (process.platform !== 'win32') {
  1059. done();
  1060. } else {
  1061. const protocolKey = new Winreg({
  1062. hive: Winreg.HKCU,
  1063. key: `\\Software\\Classes\\${protocol}`
  1064. });
  1065. // The last test leaves the registry dirty,
  1066. // delete the protocol key for those of us who test at home
  1067. protocolKey.destroy(() => done());
  1068. }
  1069. });
  1070. beforeEach(() => {
  1071. app.removeAsDefaultProtocolClient(protocol);
  1072. app.removeAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
  1073. });
  1074. afterEach(() => {
  1075. app.removeAsDefaultProtocolClient(protocol);
  1076. expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
  1077. app.removeAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
  1078. expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(false);
  1079. });
  1080. it('sets the app as the default protocol client', () => {
  1081. expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
  1082. app.setAsDefaultProtocolClient(protocol);
  1083. expect(app.isDefaultProtocolClient(protocol)).to.equal(true);
  1084. });
  1085. it('allows a custom path and args to be specified', () => {
  1086. expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(false);
  1087. app.setAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
  1088. expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(true);
  1089. expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
  1090. });
  1091. it('creates a registry entry for the protocol class', async () => {
  1092. app.setAsDefaultProtocolClient(protocol);
  1093. const keys = await promisify(classesKey.keys).call(classesKey) as any[];
  1094. const exists = keys.some(key => key.key.includes(protocol));
  1095. expect(exists).to.equal(true);
  1096. });
  1097. it('completely removes a registry entry for the protocol class', async () => {
  1098. app.setAsDefaultProtocolClient(protocol);
  1099. app.removeAsDefaultProtocolClient(protocol);
  1100. const keys = await promisify(classesKey.keys).call(classesKey) as any[];
  1101. const exists = keys.some(key => key.key.includes(protocol));
  1102. expect(exists).to.equal(false);
  1103. });
  1104. it('only unsets a class registry key if it contains other data', async () => {
  1105. app.setAsDefaultProtocolClient(protocol);
  1106. const protocolKey = new Winreg({
  1107. hive: Winreg.HKCU,
  1108. key: `\\Software\\Classes\\${protocol}`
  1109. });
  1110. await promisify(protocolKey.set).call(protocolKey, 'test-value', 'REG_BINARY', '123');
  1111. app.removeAsDefaultProtocolClient(protocol);
  1112. const keys = await promisify(classesKey.keys).call(classesKey) as any[];
  1113. const exists = keys.some(key => key.key.includes(protocol));
  1114. expect(exists).to.equal(true);
  1115. });
  1116. it('sets the default client such that getApplicationNameForProtocol returns Electron', () => {
  1117. app.setAsDefaultProtocolClient(protocol);
  1118. expect(app.getApplicationNameForProtocol(`${protocol}://`)).to.equal('Electron');
  1119. });
  1120. });
  1121. describe('getApplicationNameForProtocol()', () => {
  1122. // TODO: Linux CI doesn't have registered http & https handlers
  1123. ifit(!(process.env.CI && process.platform === 'linux'))('returns application names for common protocols', function () {
  1124. // We can't expect particular app names here, but these protocols should
  1125. // at least have _something_ registered. Except on our Linux CI
  1126. // environment apparently.
  1127. const protocols = [
  1128. 'http://',
  1129. 'https://'
  1130. ];
  1131. for (const protocol of protocols) {
  1132. expect(app.getApplicationNameForProtocol(protocol)).to.not.equal('');
  1133. }
  1134. });
  1135. it('returns an empty string for a bogus protocol', () => {
  1136. expect(app.getApplicationNameForProtocol('bogus-protocol://')).to.equal('');
  1137. });
  1138. });
  1139. ifdescribe(process.platform !== 'linux')('getApplicationInfoForProtocol()', () => {
  1140. it('returns promise rejection for a bogus protocol', async function () {
  1141. await expect(
  1142. app.getApplicationInfoForProtocol('bogus-protocol://')
  1143. ).to.eventually.be.rejectedWith(
  1144. 'Unable to retrieve installation path to app'
  1145. );
  1146. });
  1147. it('returns resolved promise with appPath, displayName and icon', async function () {
  1148. const appInfo = await app.getApplicationInfoForProtocol('https://');
  1149. expect(appInfo.path).not.to.be.undefined();
  1150. expect(appInfo.name).not.to.be.undefined();
  1151. expect(appInfo.icon).not.to.be.undefined();
  1152. });
  1153. });
  1154. describe('isDefaultProtocolClient()', () => {
  1155. it('returns false for a bogus protocol', () => {
  1156. expect(app.isDefaultProtocolClient('bogus-protocol://')).to.equal(false);
  1157. });
  1158. });
  1159. ifdescribe(process.platform === 'win32')('app launch through uri', () => {
  1160. it('does not launch for argument following a URL', async () => {
  1161. const appPath = path.join(fixturesPath, 'api', 'quit-app');
  1162. // App should exit with non 123 code.
  1163. const first = cp.spawn(process.execPath, [appPath, 'electron-test:?', 'abc']);
  1164. const [code] = await once(first, 'exit');
  1165. expect(code).to.not.equal(123);
  1166. });
  1167. it('launches successfully for argument following a file path', async () => {
  1168. const appPath = path.join(fixturesPath, 'api', 'quit-app');
  1169. // App should exit with code 123.
  1170. const first = cp.spawn(process.execPath, [appPath, 'e:\\abc', 'abc']);
  1171. const [code] = await once(first, 'exit');
  1172. expect(code).to.equal(123);
  1173. });
  1174. it('launches successfully for multiple URIs following --', async () => {
  1175. const appPath = path.join(fixturesPath, 'api', 'quit-app');
  1176. // App should exit with code 123.
  1177. const first = cp.spawn(process.execPath, [appPath, '--', 'http://electronjs.org', 'electron-test://testdata']);
  1178. const [code] = await once(first, 'exit');
  1179. expect(code).to.equal(123);
  1180. });
  1181. });
  1182. // FIXME Get these specs running on Linux CI
  1183. ifdescribe(process.platform !== 'linux')('getFileIcon() API', () => {
  1184. const iconPath = path.join(__dirname, 'fixtures/assets/icon.ico');
  1185. const sizes = {
  1186. small: 16,
  1187. normal: 32,
  1188. large: process.platform === 'win32' ? 32 : 48
  1189. };
  1190. it('fetches a non-empty icon', async () => {
  1191. const icon = await app.getFileIcon(iconPath);
  1192. expect(icon.isEmpty()).to.equal(false);
  1193. });
  1194. it('fetches normal icon size by default', async () => {
  1195. const icon = await app.getFileIcon(iconPath);
  1196. const size = icon.getSize();
  1197. expect(size.height).to.equal(sizes.normal);
  1198. expect(size.width).to.equal(sizes.normal);
  1199. });
  1200. describe('size option', () => {
  1201. it('fetches a small icon', async () => {
  1202. const icon = await app.getFileIcon(iconPath, { size: 'small' });
  1203. const size = icon.getSize();
  1204. expect(size.height).to.equal(sizes.small);
  1205. expect(size.width).to.equal(sizes.small);
  1206. });
  1207. it('fetches a normal icon', async () => {
  1208. const icon = await app.getFileIcon(iconPath, { size: 'normal' });
  1209. const size = icon.getSize();
  1210. expect(size.height).to.equal(sizes.normal);
  1211. expect(size.width).to.equal(sizes.normal);
  1212. });
  1213. it('fetches a large icon', async () => {
  1214. // macOS does not support large icons
  1215. if (process.platform === 'darwin') return;
  1216. const icon = await app.getFileIcon(iconPath, { size: 'large' });
  1217. const size = icon.getSize();
  1218. expect(size.height).to.equal(sizes.large);
  1219. expect(size.width).to.equal(sizes.large);
  1220. });
  1221. });
  1222. });
  1223. describe('getAppMetrics() API', () => {
  1224. it('returns memory and cpu stats of all running electron processes', () => {
  1225. const appMetrics = app.getAppMetrics();
  1226. expect(appMetrics).to.be.an('array').and.have.lengthOf.at.least(1, 'App memory info object is not > 0');
  1227. const types = [];
  1228. for (const entry of appMetrics) {
  1229. expect(entry.pid).to.be.above(0, 'pid is not > 0');
  1230. expect(entry.type).to.be.a('string').that.does.not.equal('');
  1231. expect(entry.creationTime).to.be.a('number').that.is.greaterThan(0);
  1232. types.push(entry.type);
  1233. expect(entry.cpu).to.have.ownProperty('percentCPUUsage').that.is.a('number');
  1234. expect(entry.cpu).to.have.ownProperty('cumulativeCPUUsage').that.is.a('number');
  1235. expect(entry.cpu).to.have.ownProperty('idleWakeupsPerSecond').that.is.a('number');
  1236. expect(entry.memory).to.have.property('workingSetSize').that.is.greaterThan(0);
  1237. expect(entry.memory).to.have.property('peakWorkingSetSize').that.is.greaterThan(0);
  1238. if (entry.type === 'Utility' || entry.type === 'GPU') {
  1239. expect(entry.serviceName).to.be.a('string').that.does.not.equal('');
  1240. }
  1241. if (entry.type === 'Utility') {
  1242. expect(entry).to.have.property('name').that.is.a('string');
  1243. }
  1244. if (process.platform === 'win32') {
  1245. expect(entry.memory).to.have.property('privateBytes').that.is.greaterThan(0);
  1246. }
  1247. if (process.platform !== 'linux') {
  1248. expect(entry.sandboxed).to.be.a('boolean');
  1249. }
  1250. if (process.platform === 'win32') {
  1251. expect(entry.integrityLevel).to.be.a('string');
  1252. }
  1253. }
  1254. if (process.platform === 'darwin') {
  1255. expect(types).to.include('GPU');
  1256. }
  1257. expect(types).to.include('Browser');
  1258. });
  1259. });
  1260. describe('getGPUFeatureStatus() API', () => {
  1261. it('returns the graphic features statuses', () => {
  1262. const features = app.getGPUFeatureStatus();
  1263. expect(features).to.have.ownProperty('webgl').that.is.a('string');
  1264. expect(features).to.have.ownProperty('gpu_compositing').that.is.a('string');
  1265. });
  1266. });
  1267. ifdescribe(!process.env.IS_ASAN)('getGPUInfo() API', () => {
  1268. const appPath = path.join(fixturesPath, 'api', 'gpu-info.js');
  1269. const getGPUInfo = async (type: string) => {
  1270. const appProcess = cp.spawn(process.execPath, [appPath, type]);
  1271. let gpuInfoData = '';
  1272. let errorData = '';
  1273. appProcess.stdout.on('data', (data) => {
  1274. gpuInfoData += data;
  1275. });
  1276. appProcess.stderr.on('data', (data) => {
  1277. errorData += data;
  1278. });
  1279. const [exitCode] = await once(appProcess, 'exit');
  1280. if (exitCode === 0) {
  1281. try {
  1282. const [, json] = /HERE COMES THE JSON: (.+) AND THERE IT WAS/.exec(gpuInfoData)!;
  1283. // return info data on successful exit
  1284. return JSON.parse(json);
  1285. } catch (e) {
  1286. console.error('Failed to interpret the following as JSON:');
  1287. console.error(gpuInfoData);
  1288. throw e;
  1289. }
  1290. } else {
  1291. // return error if not clean exit
  1292. throw new Error(errorData);
  1293. }
  1294. };
  1295. const verifyBasicGPUInfo = async (gpuInfo: any) => {
  1296. // Devices information is always present in the available info.
  1297. expect(gpuInfo).to.have.ownProperty('gpuDevice')
  1298. .that.is.an('array')
  1299. .and.does.not.equal([]);
  1300. const device = gpuInfo.gpuDevice[0];
  1301. expect(device).to.be.an('object')
  1302. .and.to.have.property('deviceId')
  1303. .that.is.a('number')
  1304. .not.lessThan(0);
  1305. };
  1306. it('succeeds with basic GPUInfo', async () => {
  1307. const gpuInfo = await getGPUInfo('basic');
  1308. await verifyBasicGPUInfo(gpuInfo);
  1309. });
  1310. it('succeeds with complete GPUInfo', async () => {
  1311. const completeInfo = await getGPUInfo('complete');
  1312. if (process.platform === 'linux') {
  1313. // For linux and macOS complete info is same as basic info
  1314. await verifyBasicGPUInfo(completeInfo);
  1315. const basicInfo = await getGPUInfo('basic');
  1316. expect(completeInfo).to.deep.equal(basicInfo);
  1317. } else {
  1318. // Gl version is present in the complete info.
  1319. expect(completeInfo).to.have.ownProperty('auxAttributes')
  1320. .that.is.an('object');
  1321. if (completeInfo.gpuDevice.active) {
  1322. expect(completeInfo.auxAttributes).to.have.ownProperty('glVersion')
  1323. .that.is.a('string')
  1324. .and.does.not.equal([]);
  1325. }
  1326. }
  1327. });
  1328. it('fails for invalid info_type', () => {
  1329. const invalidType = 'invalid';
  1330. const expectedErrorMessage = "Invalid info type. Use 'basic' or 'complete'";
  1331. return expect(app.getGPUInfo(invalidType as any)).to.eventually.be.rejectedWith(expectedErrorMessage);
  1332. });
  1333. });
  1334. ifdescribe(!(process.platform === 'linux' && (process.arch === 'arm64' || process.arch === 'arm')))('sandbox options', () => {
  1335. let appProcess: cp.ChildProcess = null as any;
  1336. let server: net.Server = null as any;
  1337. const socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\electron-mixed-sandbox' : '/tmp/electron-mixed-sandbox';
  1338. beforeEach(function (done) {
  1339. fs.unlink(socketPath, () => {
  1340. server = net.createServer();
  1341. server.listen(socketPath);
  1342. done();
  1343. });
  1344. });
  1345. afterEach(done => {
  1346. if (appProcess != null) appProcess.kill();
  1347. if (server) {
  1348. server.close(() => {
  1349. if (process.platform === 'win32') {
  1350. done();
  1351. } else {
  1352. fs.unlink(socketPath, () => done());
  1353. }
  1354. });
  1355. } else {
  1356. done();
  1357. }
  1358. });
  1359. describe('when app.enableSandbox() is called', () => {
  1360. it('adds --enable-sandbox to all renderer processes', done => {
  1361. const appPath = path.join(fixturesPath, 'api', 'mixed-sandbox-app');
  1362. appProcess = cp.spawn(process.execPath, [appPath, '--app-enable-sandbox'], { stdio: 'inherit' });
  1363. server.once('error', error => { done(error); });
  1364. server.on('connection', client => {
  1365. client.once('data', (data) => {
  1366. const argv = JSON.parse(data.toString());
  1367. expect(argv.sandbox).to.include('--enable-sandbox');
  1368. expect(argv.sandbox).to.not.include('--no-sandbox');
  1369. expect(argv.noSandbox).to.include('--enable-sandbox');
  1370. expect(argv.noSandbox).to.not.include('--no-sandbox');
  1371. expect(argv.noSandboxDevtools).to.equal(true);
  1372. expect(argv.sandboxDevtools).to.equal(true);
  1373. done();
  1374. });
  1375. });
  1376. });
  1377. });
  1378. describe('when the app is launched with --enable-sandbox', () => {
  1379. it('adds --enable-sandbox to all renderer processes', done => {
  1380. const appPath = path.join(fixturesPath, 'api', 'mixed-sandbox-app');
  1381. appProcess = cp.spawn(process.execPath, [appPath, '--enable-sandbox'], { stdio: 'inherit' });
  1382. server.once('error', error => { done(error); });
  1383. server.on('connection', client => {
  1384. client.once('data', data => {
  1385. const argv = JSON.parse(data.toString());
  1386. expect(argv.sandbox).to.include('--enable-sandbox');
  1387. expect(argv.sandbox).to.not.include('--no-sandbox');
  1388. expect(argv.noSandbox).to.include('--enable-sandbox');
  1389. expect(argv.noSandbox).to.not.include('--no-sandbox');
  1390. expect(argv.noSandboxDevtools).to.equal(true);
  1391. expect(argv.sandboxDevtools).to.equal(true);
  1392. done();
  1393. });
  1394. });
  1395. });
  1396. });
  1397. });
  1398. describe('disableDomainBlockingFor3DAPIs() API', () => {
  1399. it('throws when called after app is ready', () => {
  1400. expect(() => {
  1401. app.disableDomainBlockingFor3DAPIs();
  1402. }).to.throw(/before app is ready/);
  1403. });
  1404. });
  1405. ifdescribe(process.platform === 'darwin')('app hide and show API', () => {
  1406. describe('app.isHidden', () => {
  1407. it('returns true when the app is hidden', async () => {
  1408. app.hide();
  1409. await expect(
  1410. waitUntil(() => app.isHidden())
  1411. ).to.eventually.be.fulfilled();
  1412. });
  1413. it('returns false when the app is shown', async () => {
  1414. app.show();
  1415. await expect(
  1416. waitUntil(() => !app.isHidden())
  1417. ).to.eventually.be.fulfilled();
  1418. });
  1419. });
  1420. });
  1421. ifdescribe(process.platform === 'darwin')('dock APIs', () => {
  1422. after(async () => {
  1423. await app.dock.show();
  1424. });
  1425. describe('dock.setMenu', () => {
  1426. it('can be retrieved via dock.getMenu', () => {
  1427. expect(app.dock.getMenu()).to.equal(null);
  1428. const menu = new Menu();
  1429. app.dock.setMenu(menu);
  1430. expect(app.dock.getMenu()).to.equal(menu);
  1431. });
  1432. it('keeps references to the menu', () => {
  1433. app.dock.setMenu(new Menu());
  1434. const v8Util = process._linkedBinding('electron_common_v8_util');
  1435. v8Util.requestGarbageCollectionForTesting();
  1436. });
  1437. });
  1438. describe('dock.setIcon', () => {
  1439. it('throws a descriptive error for a bad icon path', () => {
  1440. const badPath = path.resolve('I', 'Do', 'Not', 'Exist');
  1441. expect(() => {
  1442. app.dock.setIcon(badPath);
  1443. }).to.throw(/Failed to load image from path (.+)/);
  1444. });
  1445. });
  1446. describe('dock.bounce', () => {
  1447. it('should return -1 for unknown bounce type', () => {
  1448. expect(app.dock.bounce('bad type' as any)).to.equal(-1);
  1449. });
  1450. it('should return a positive number for informational type', () => {
  1451. const appHasFocus = !!BrowserWindow.getFocusedWindow();
  1452. if (!appHasFocus) {
  1453. expect(app.dock.bounce('informational')).to.be.at.least(0);
  1454. }
  1455. });
  1456. it('should return a positive number for critical type', () => {
  1457. const appHasFocus = !!BrowserWindow.getFocusedWindow();
  1458. if (!appHasFocus) {
  1459. expect(app.dock.bounce('critical')).to.be.at.least(0);
  1460. }
  1461. });
  1462. });
  1463. describe('dock.cancelBounce', () => {
  1464. it('should not throw', () => {
  1465. app.dock.cancelBounce(app.dock.bounce('critical'));
  1466. });
  1467. });
  1468. describe('dock.setBadge', () => {
  1469. after(() => {
  1470. app.dock.setBadge('');
  1471. });
  1472. it('should not throw', () => {
  1473. app.dock.setBadge('1');
  1474. });
  1475. it('should be retrievable via getBadge', () => {
  1476. app.dock.setBadge('test');
  1477. expect(app.dock.getBadge()).to.equal('test');
  1478. });
  1479. });
  1480. describe('dock.hide', () => {
  1481. it('should not throw', () => {
  1482. app.dock.hide();
  1483. expect(app.dock.isVisible()).to.equal(false);
  1484. });
  1485. });
  1486. // Note that dock.show tests should run after dock.hide tests, to work
  1487. // around a bug of macOS.
  1488. // See https://github.com/electron/electron/pull/25269 for more.
  1489. describe('dock.show', () => {
  1490. it('should not throw', () => {
  1491. return app.dock.show().then(() => {
  1492. expect(app.dock.isVisible()).to.equal(true);
  1493. });
  1494. });
  1495. it('returns a Promise', () => {
  1496. expect(app.dock.show()).to.be.a('promise');
  1497. });
  1498. it('eventually fulfills', async () => {
  1499. await expect(app.dock.show()).to.eventually.be.fulfilled.equal(undefined);
  1500. });
  1501. });
  1502. });
  1503. describe('whenReady', () => {
  1504. it('returns a Promise', () => {
  1505. expect(app.whenReady()).to.be.a('promise');
  1506. });
  1507. it('becomes fulfilled if the app is already ready', async () => {
  1508. expect(app.isReady()).to.equal(true);
  1509. await expect(app.whenReady()).to.be.eventually.fulfilled.equal(undefined);
  1510. });
  1511. });
  1512. describe('app.applicationMenu', () => {
  1513. it('has the applicationMenu property', () => {
  1514. expect(app).to.have.property('applicationMenu');
  1515. });
  1516. });
  1517. describe('commandLine.hasSwitch', () => {
  1518. it('returns true when present', () => {
  1519. app.commandLine.appendSwitch('foobar1');
  1520. expect(app.commandLine.hasSwitch('foobar1')).to.equal(true);
  1521. });
  1522. it('returns false when not present', () => {
  1523. expect(app.commandLine.hasSwitch('foobar2')).to.equal(false);
  1524. });
  1525. });
  1526. describe('commandLine.hasSwitch (existing argv)', () => {
  1527. it('returns true when present', async () => {
  1528. const { hasSwitch } = await runTestApp('command-line', '--foobar');
  1529. expect(hasSwitch).to.equal(true);
  1530. });
  1531. it('returns false when not present', async () => {
  1532. const { hasSwitch } = await runTestApp('command-line');
  1533. expect(hasSwitch).to.equal(false);
  1534. });
  1535. });
  1536. describe('commandLine.getSwitchValue', () => {
  1537. it('returns the value when present', () => {
  1538. app.commandLine.appendSwitch('foobar', 'æøåü');
  1539. expect(app.commandLine.getSwitchValue('foobar')).to.equal('æøåü');
  1540. });
  1541. it('returns an empty string when present without value', () => {
  1542. app.commandLine.appendSwitch('foobar1');
  1543. expect(app.commandLine.getSwitchValue('foobar1')).to.equal('');
  1544. });
  1545. it('returns an empty string when not present', () => {
  1546. expect(app.commandLine.getSwitchValue('foobar2')).to.equal('');
  1547. });
  1548. });
  1549. describe('commandLine.getSwitchValue (existing argv)', () => {
  1550. it('returns the value when present', async () => {
  1551. const { getSwitchValue } = await runTestApp('command-line', '--foobar=test');
  1552. expect(getSwitchValue).to.equal('test');
  1553. });
  1554. it('returns an empty string when present without value', async () => {
  1555. const { getSwitchValue } = await runTestApp('command-line', '--foobar');
  1556. expect(getSwitchValue).to.equal('');
  1557. });
  1558. it('returns an empty string when not present', async () => {
  1559. const { getSwitchValue } = await runTestApp('command-line');
  1560. expect(getSwitchValue).to.equal('');
  1561. });
  1562. });
  1563. describe('commandLine.removeSwitch', () => {
  1564. it('no-ops a non-existent switch', async () => {
  1565. expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
  1566. app.commandLine.removeSwitch('foobar3');
  1567. expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
  1568. });
  1569. it('removes an existing switch', async () => {
  1570. app.commandLine.appendSwitch('foobar3', 'test');
  1571. expect(app.commandLine.hasSwitch('foobar3')).to.equal(true);
  1572. app.commandLine.removeSwitch('foobar3');
  1573. expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
  1574. });
  1575. });
  1576. ifdescribe(process.platform === 'darwin')('app.setSecureKeyboardEntryEnabled', () => {
  1577. it('changes Secure Keyboard Entry is enabled', () => {
  1578. app.setSecureKeyboardEntryEnabled(true);
  1579. expect(app.isSecureKeyboardEntryEnabled()).to.equal(true);
  1580. app.setSecureKeyboardEntryEnabled(false);
  1581. expect(app.isSecureKeyboardEntryEnabled()).to.equal(false);
  1582. });
  1583. });
  1584. describe('configureHostResolver', () => {
  1585. after(() => {
  1586. // Returns to the default configuration.
  1587. app.configureHostResolver({});
  1588. });
  1589. it('fails on bad arguments', () => {
  1590. expect(() => {
  1591. (app.configureHostResolver as any)();
  1592. }).to.throw();
  1593. expect(() => {
  1594. app.configureHostResolver({
  1595. secureDnsMode: 'notAValidValue' as any
  1596. });
  1597. }).to.throw();
  1598. expect(() => {
  1599. app.configureHostResolver({
  1600. secureDnsServers: [123 as any]
  1601. });
  1602. }).to.throw();
  1603. });
  1604. it('affects dns lookup behavior', async () => {
  1605. // 1. resolve a domain name to check that things are working
  1606. await expect(new Promise((resolve, reject) => {
  1607. electronNet.request({
  1608. method: 'HEAD',
  1609. url: 'https://www.electronjs.org'
  1610. }).on('response', resolve)
  1611. .on('error', reject)
  1612. .end();
  1613. })).to.eventually.be.fulfilled();
  1614. // 2. change the host resolver configuration to something that will
  1615. // always fail
  1616. app.configureHostResolver({
  1617. secureDnsMode: 'secure',
  1618. secureDnsServers: ['https://127.0.0.1:1234']
  1619. });
  1620. // 3. check that resolving domain names now fails
  1621. await expect(new Promise((resolve, reject) => {
  1622. electronNet.request({
  1623. method: 'HEAD',
  1624. // Needs to be a slightly different domain to above, otherwise the
  1625. // response will come from the cache.
  1626. url: 'https://electronjs.org'
  1627. }).on('response', resolve)
  1628. .on('error', reject)
  1629. .end();
  1630. })).to.eventually.be.rejectedWith(/ERR_NAME_NOT_RESOLVED/);
  1631. });
  1632. });
  1633. describe('about panel', () => {
  1634. it('app.setAboutPanelOptions() does not crash', () => {
  1635. app.setAboutPanelOptions({
  1636. applicationName: 'electron!!',
  1637. version: '1.2.3'
  1638. });
  1639. });
  1640. it('app.showAboutPanel() does not crash & runs asynchronously', () => {
  1641. app.showAboutPanel();
  1642. });
  1643. });
  1644. describe('app.setProxy(options)', () => {
  1645. let server: http.Server;
  1646. afterEach(async () => {
  1647. if (server) {
  1648. server.close();
  1649. }
  1650. await app.setProxy({ mode: 'direct' as const });
  1651. });
  1652. it('allows configuring proxy settings', async () => {
  1653. const config = { proxyRules: 'http=myproxy:80' };
  1654. await app.setProxy(config);
  1655. const proxy = await app.resolveProxy('http://example.com/');
  1656. expect(proxy).to.equal('PROXY myproxy:80');
  1657. });
  1658. it('allows removing the implicit bypass rules for localhost', async () => {
  1659. const config = {
  1660. proxyRules: 'http=myproxy:80',
  1661. proxyBypassRules: '<-loopback>'
  1662. };
  1663. await app.setProxy(config);
  1664. const proxy = await app.resolveProxy('http://localhost');
  1665. expect(proxy).to.equal('PROXY myproxy:80');
  1666. });
  1667. it('allows configuring proxy settings with pacScript', async () => {
  1668. server = http.createServer((req, res) => {
  1669. const pac = `
  1670. function FindProxyForURL(url, host) {
  1671. return "PROXY myproxy:8132";
  1672. }
  1673. `;
  1674. res.writeHead(200, {
  1675. 'Content-Type': 'application/x-ns-proxy-autoconfig'
  1676. });
  1677. res.end(pac);
  1678. });
  1679. const { url } = await listen(server);
  1680. {
  1681. const config = { pacScript: url };
  1682. await app.setProxy(config);
  1683. const proxy = await app.resolveProxy('https://google.com');
  1684. expect(proxy).to.equal('PROXY myproxy:8132');
  1685. }
  1686. {
  1687. const config = { mode: 'pac_script' as any, pacScript: url };
  1688. await app.setProxy(config);
  1689. const proxy = await app.resolveProxy('https://google.com');
  1690. expect(proxy).to.equal('PROXY myproxy:8132');
  1691. }
  1692. });
  1693. it('allows bypassing proxy settings', async () => {
  1694. const config = {
  1695. proxyRules: 'http=myproxy:80',
  1696. proxyBypassRules: '<local>'
  1697. };
  1698. await app.setProxy(config);
  1699. const proxy = await app.resolveProxy('http://example/');
  1700. expect(proxy).to.equal('DIRECT');
  1701. });
  1702. it('allows configuring proxy settings with mode `direct`', async () => {
  1703. const config = { mode: 'direct' as const, proxyRules: 'http=myproxy:80' };
  1704. await app.setProxy(config);
  1705. const proxy = await app.resolveProxy('http://example.com/');
  1706. expect(proxy).to.equal('DIRECT');
  1707. });
  1708. it('allows configuring proxy settings with mode `auto_detect`', async () => {
  1709. const config = { mode: 'auto_detect' as const };
  1710. await app.setProxy(config);
  1711. });
  1712. it('allows configuring proxy settings with mode `pac_script`', async () => {
  1713. const config = { mode: 'pac_script' as const };
  1714. await app.setProxy(config);
  1715. const proxy = await app.resolveProxy('http://example.com/');
  1716. expect(proxy).to.equal('DIRECT');
  1717. });
  1718. it('allows configuring proxy settings with mode `fixed_servers`', async () => {
  1719. const config = { mode: 'fixed_servers' as const, proxyRules: 'http=myproxy:80' };
  1720. await app.setProxy(config);
  1721. const proxy = await app.resolveProxy('http://example.com/');
  1722. expect(proxy).to.equal('PROXY myproxy:80');
  1723. });
  1724. it('allows configuring proxy settings with mode `system`', async () => {
  1725. const config = { mode: 'system' as const };
  1726. await app.setProxy(config);
  1727. });
  1728. it('disallows configuring proxy settings with mode `invalid`', async () => {
  1729. const config = { mode: 'invalid' as any };
  1730. await expect(app.setProxy(config)).to.eventually.be.rejectedWith(/Invalid mode/);
  1731. });
  1732. it('impacts proxy for requests made from utility process', async () => {
  1733. const utilityFixturePath = path.resolve(__dirname, 'fixtures', 'api', 'utility-process', 'api-net-spec.js');
  1734. const fn = async () => {
  1735. const urlRequest = electronNet.request('http://example.com/');
  1736. const response = await getResponse(urlRequest);
  1737. expect(response.statusCode).to.equal(200);
  1738. const message = await collectStreamBody(response);
  1739. expect(message).to.equal('ok from proxy\n');
  1740. };
  1741. server = http.createServer((req, res) => {
  1742. res.writeHead(200);
  1743. res.end('ok from proxy\n');
  1744. });
  1745. const { port, hostname } = await listen(server);
  1746. const config = { mode: 'fixed_servers' as const, proxyRules: `http=${hostname}:${port}` };
  1747. await app.setProxy(config);
  1748. const proxy = await app.resolveProxy('http://example.com/');
  1749. expect(proxy).to.equal(`PROXY ${hostname}:${port}`);
  1750. const child = utilityProcess.fork(utilityFixturePath, [], {
  1751. execArgv: ['--expose-gc']
  1752. });
  1753. child.postMessage({ fn: `(${fn})()` });
  1754. const [data] = await once(child, 'message');
  1755. expect(data.ok).to.be.true(data.message);
  1756. // Cleanup.
  1757. const [code] = await once(child, 'exit');
  1758. expect(code).to.equal(0);
  1759. });
  1760. it('does not impact proxy for requests made from main process', async () => {
  1761. server = http.createServer((req, res) => {
  1762. res.writeHead(200);
  1763. res.end('ok from server\n');
  1764. });
  1765. const { url } = await listen(server);
  1766. const config = { mode: 'fixed_servers' as const, proxyRules: 'http=myproxy:80' };
  1767. await app.setProxy(config);
  1768. const proxy = await app.resolveProxy('http://example.com/');
  1769. expect(proxy).to.equal('PROXY myproxy:80');
  1770. const urlRequest = electronNet.request(url);
  1771. const response = await getResponse(urlRequest);
  1772. expect(response.statusCode).to.equal(200);
  1773. const message = await collectStreamBody(response);
  1774. expect(message).to.equal('ok from server\n');
  1775. });
  1776. });
  1777. });
  1778. describe('default behavior', () => {
  1779. describe('application menu', () => {
  1780. it('creates the default menu if the app does not set it', async () => {
  1781. const result = await runTestApp('default-menu');
  1782. expect(result).to.equal(false);
  1783. });
  1784. it('does not create the default menu if the app sets a custom menu', async () => {
  1785. const result = await runTestApp('default-menu', '--custom-menu');
  1786. expect(result).to.equal(true);
  1787. });
  1788. it('does not create the default menu if the app sets a null menu', async () => {
  1789. const result = await runTestApp('default-menu', '--null-menu');
  1790. expect(result).to.equal(true);
  1791. });
  1792. });
  1793. describe('window-all-closed', () => {
  1794. afterEach(closeAllWindows);
  1795. it('quits when the app does not handle the event', async () => {
  1796. const result = await runTestApp('window-all-closed');
  1797. expect(result).to.equal(false);
  1798. });
  1799. it('does not quit when the app handles the event', async () => {
  1800. const result = await runTestApp('window-all-closed', '--handle-event');
  1801. expect(result).to.equal(true);
  1802. });
  1803. it('should omit closed windows from getAllWindows', async () => {
  1804. const w = new BrowserWindow({ show: false });
  1805. const len = new Promise(resolve => {
  1806. app.on('window-all-closed', () => {
  1807. resolve(BrowserWindow.getAllWindows().length);
  1808. });
  1809. });
  1810. w.close();
  1811. expect(await len).to.equal(0);
  1812. });
  1813. });
  1814. describe('user agent fallback', () => {
  1815. let initialValue: string;
  1816. before(() => {
  1817. initialValue = app.userAgentFallback!;
  1818. });
  1819. it('should have a reasonable default', () => {
  1820. expect(initialValue).to.include(`Electron/${process.versions.electron}`);
  1821. expect(initialValue).to.include(`Chrome/${process.versions.chrome}`);
  1822. });
  1823. it('should be overridable', () => {
  1824. app.userAgentFallback = 'test-agent/123';
  1825. expect(app.userAgentFallback).to.equal('test-agent/123');
  1826. });
  1827. it('should be restorable', () => {
  1828. app.userAgentFallback = 'test-agent/123';
  1829. app.userAgentFallback = '';
  1830. expect(app.userAgentFallback).to.equal(initialValue);
  1831. });
  1832. });
  1833. describe('login event', () => {
  1834. afterEach(closeAllWindows);
  1835. let server: http.Server;
  1836. let serverUrl: string;
  1837. before(async () => {
  1838. server = http.createServer((request, response) => {
  1839. if (request.headers.authorization) {
  1840. return response.end('ok');
  1841. }
  1842. response
  1843. .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
  1844. .end();
  1845. });
  1846. serverUrl = (await listen(server)).url;
  1847. });
  1848. it('should emit a login event on app when a WebContents hits a 401', async () => {
  1849. const w = new BrowserWindow({ show: false });
  1850. w.loadURL(serverUrl);
  1851. const [, webContents] = await once(app, 'login') as [any, WebContents];
  1852. expect(webContents).to.equal(w.webContents);
  1853. });
  1854. });
  1855. describe('running under ARM64 translation', () => {
  1856. it('does not throw an error', () => {
  1857. if (process.platform === 'darwin' || process.platform === 'win32') {
  1858. expect(app.runningUnderARM64Translation).not.to.be.undefined();
  1859. expect(() => {
  1860. return app.runningUnderARM64Translation;
  1861. }).not.to.throw();
  1862. } else {
  1863. expect(app.runningUnderARM64Translation).to.be.undefined();
  1864. }
  1865. });
  1866. });
  1867. });
  1868. async function runTestApp (name: string, ...args: any[]) {
  1869. const appPath = path.join(fixturesPath, 'api', name);
  1870. const electronPath = process.execPath;
  1871. const appProcess = cp.spawn(electronPath, [appPath, ...args]);
  1872. let output = '';
  1873. appProcess.stdout.on('data', (data) => { output += data; });
  1874. await once(appProcess.stdout, 'end');
  1875. return JSON.parse(output);
  1876. }