api-app-spec.ts 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205
  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. 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 = fs.readJsonSync(path.join(appPath, 'package.json')).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.removeSync(userDataPath);
  986. fs.removeSync(tempBrowserDataPath);
  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. // Our ARM tests are run on VSTS rather than CircleCI, and the Docker
  1336. // setup on VSTS disallows syscalls that Chrome requires for setting up
  1337. // sandboxing.
  1338. // See:
  1339. // - https://docs.docker.com/engine/security/seccomp/#significant-syscalls-blocked-by-the-default-profile
  1340. // - https://chromium.googlesource.com/chromium/src/+/70.0.3538.124/sandbox/linux/services/credentials.cc#292
  1341. // - https://github.com/docker/docker-ce/blob/ba7dfc59ccfe97c79ee0d1379894b35417b40bca/components/engine/profiles/seccomp/seccomp_default.go#L497
  1342. // - https://blog.jessfraz.com/post/how-to-use-new-docker-seccomp-profiles/
  1343. //
  1344. // Adding `--cap-add SYS_ADMIN` or `--security-opt seccomp=unconfined`
  1345. // to the Docker invocation allows the syscalls that Chrome needs, but
  1346. // are probably more permissive than we'd like.
  1347. let appProcess: cp.ChildProcess = null as any;
  1348. let server: net.Server = null as any;
  1349. const socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\electron-mixed-sandbox' : '/tmp/electron-mixed-sandbox';
  1350. beforeEach(function (done) {
  1351. fs.unlink(socketPath, () => {
  1352. server = net.createServer();
  1353. server.listen(socketPath);
  1354. done();
  1355. });
  1356. });
  1357. afterEach(done => {
  1358. if (appProcess != null) appProcess.kill();
  1359. if (server) {
  1360. server.close(() => {
  1361. if (process.platform === 'win32') {
  1362. done();
  1363. } else {
  1364. fs.unlink(socketPath, () => done());
  1365. }
  1366. });
  1367. } else {
  1368. done();
  1369. }
  1370. });
  1371. describe('when app.enableSandbox() is called', () => {
  1372. it('adds --enable-sandbox to all renderer processes', done => {
  1373. const appPath = path.join(fixturesPath, 'api', 'mixed-sandbox-app');
  1374. appProcess = cp.spawn(process.execPath, [appPath, '--app-enable-sandbox'], { stdio: 'inherit' });
  1375. server.once('error', error => { done(error); });
  1376. server.on('connection', client => {
  1377. client.once('data', (data) => {
  1378. const argv = JSON.parse(data.toString());
  1379. expect(argv.sandbox).to.include('--enable-sandbox');
  1380. expect(argv.sandbox).to.not.include('--no-sandbox');
  1381. expect(argv.noSandbox).to.include('--enable-sandbox');
  1382. expect(argv.noSandbox).to.not.include('--no-sandbox');
  1383. expect(argv.noSandboxDevtools).to.equal(true);
  1384. expect(argv.sandboxDevtools).to.equal(true);
  1385. done();
  1386. });
  1387. });
  1388. });
  1389. });
  1390. describe('when the app is launched with --enable-sandbox', () => {
  1391. it('adds --enable-sandbox to all renderer processes', done => {
  1392. const appPath = path.join(fixturesPath, 'api', 'mixed-sandbox-app');
  1393. appProcess = cp.spawn(process.execPath, [appPath, '--enable-sandbox'], { stdio: 'inherit' });
  1394. server.once('error', error => { done(error); });
  1395. server.on('connection', client => {
  1396. client.once('data', data => {
  1397. const argv = JSON.parse(data.toString());
  1398. expect(argv.sandbox).to.include('--enable-sandbox');
  1399. expect(argv.sandbox).to.not.include('--no-sandbox');
  1400. expect(argv.noSandbox).to.include('--enable-sandbox');
  1401. expect(argv.noSandbox).to.not.include('--no-sandbox');
  1402. expect(argv.noSandboxDevtools).to.equal(true);
  1403. expect(argv.sandboxDevtools).to.equal(true);
  1404. done();
  1405. });
  1406. });
  1407. });
  1408. });
  1409. });
  1410. describe('disableDomainBlockingFor3DAPIs() API', () => {
  1411. it('throws when called after app is ready', () => {
  1412. expect(() => {
  1413. app.disableDomainBlockingFor3DAPIs();
  1414. }).to.throw(/before app is ready/);
  1415. });
  1416. });
  1417. ifdescribe(process.platform === 'darwin')('app hide and show API', () => {
  1418. describe('app.isHidden', () => {
  1419. it('returns true when the app is hidden', async () => {
  1420. app.hide();
  1421. await expect(
  1422. waitUntil(() => app.isHidden())
  1423. ).to.eventually.be.fulfilled();
  1424. });
  1425. it('returns false when the app is shown', async () => {
  1426. app.show();
  1427. await expect(
  1428. waitUntil(() => !app.isHidden())
  1429. ).to.eventually.be.fulfilled();
  1430. });
  1431. });
  1432. });
  1433. ifdescribe(process.platform === 'darwin')('dock APIs', () => {
  1434. after(async () => {
  1435. await app.dock.show();
  1436. });
  1437. describe('dock.setMenu', () => {
  1438. it('can be retrieved via dock.getMenu', () => {
  1439. expect(app.dock.getMenu()).to.equal(null);
  1440. const menu = new Menu();
  1441. app.dock.setMenu(menu);
  1442. expect(app.dock.getMenu()).to.equal(menu);
  1443. });
  1444. it('keeps references to the menu', () => {
  1445. app.dock.setMenu(new Menu());
  1446. const v8Util = process._linkedBinding('electron_common_v8_util');
  1447. v8Util.requestGarbageCollectionForTesting();
  1448. });
  1449. });
  1450. describe('dock.setIcon', () => {
  1451. it('throws a descriptive error for a bad icon path', () => {
  1452. const badPath = path.resolve('I', 'Do', 'Not', 'Exist');
  1453. expect(() => {
  1454. app.dock.setIcon(badPath);
  1455. }).to.throw(/Failed to load image from path (.+)/);
  1456. });
  1457. });
  1458. describe('dock.bounce', () => {
  1459. it('should return -1 for unknown bounce type', () => {
  1460. expect(app.dock.bounce('bad type' as any)).to.equal(-1);
  1461. });
  1462. it('should return a positive number for informational type', () => {
  1463. const appHasFocus = !!BrowserWindow.getFocusedWindow();
  1464. if (!appHasFocus) {
  1465. expect(app.dock.bounce('informational')).to.be.at.least(0);
  1466. }
  1467. });
  1468. it('should return a positive number for critical type', () => {
  1469. const appHasFocus = !!BrowserWindow.getFocusedWindow();
  1470. if (!appHasFocus) {
  1471. expect(app.dock.bounce('critical')).to.be.at.least(0);
  1472. }
  1473. });
  1474. });
  1475. describe('dock.cancelBounce', () => {
  1476. it('should not throw', () => {
  1477. app.dock.cancelBounce(app.dock.bounce('critical'));
  1478. });
  1479. });
  1480. describe('dock.setBadge', () => {
  1481. after(() => {
  1482. app.dock.setBadge('');
  1483. });
  1484. it('should not throw', () => {
  1485. app.dock.setBadge('1');
  1486. });
  1487. it('should be retrievable via getBadge', () => {
  1488. app.dock.setBadge('test');
  1489. expect(app.dock.getBadge()).to.equal('test');
  1490. });
  1491. });
  1492. describe('dock.hide', () => {
  1493. it('should not throw', () => {
  1494. app.dock.hide();
  1495. expect(app.dock.isVisible()).to.equal(false);
  1496. });
  1497. });
  1498. // Note that dock.show tests should run after dock.hide tests, to work
  1499. // around a bug of macOS.
  1500. // See https://github.com/electron/electron/pull/25269 for more.
  1501. describe('dock.show', () => {
  1502. it('should not throw', () => {
  1503. return app.dock.show().then(() => {
  1504. expect(app.dock.isVisible()).to.equal(true);
  1505. });
  1506. });
  1507. it('returns a Promise', () => {
  1508. expect(app.dock.show()).to.be.a('promise');
  1509. });
  1510. it('eventually fulfills', async () => {
  1511. await expect(app.dock.show()).to.eventually.be.fulfilled.equal(undefined);
  1512. });
  1513. });
  1514. });
  1515. describe('whenReady', () => {
  1516. it('returns a Promise', () => {
  1517. expect(app.whenReady()).to.be.a('promise');
  1518. });
  1519. it('becomes fulfilled if the app is already ready', async () => {
  1520. expect(app.isReady()).to.equal(true);
  1521. await expect(app.whenReady()).to.be.eventually.fulfilled.equal(undefined);
  1522. });
  1523. });
  1524. describe('app.applicationMenu', () => {
  1525. it('has the applicationMenu property', () => {
  1526. expect(app).to.have.property('applicationMenu');
  1527. });
  1528. });
  1529. describe('commandLine.hasSwitch', () => {
  1530. it('returns true when present', () => {
  1531. app.commandLine.appendSwitch('foobar1');
  1532. expect(app.commandLine.hasSwitch('foobar1')).to.equal(true);
  1533. });
  1534. it('returns false when not present', () => {
  1535. expect(app.commandLine.hasSwitch('foobar2')).to.equal(false);
  1536. });
  1537. });
  1538. describe('commandLine.hasSwitch (existing argv)', () => {
  1539. it('returns true when present', async () => {
  1540. const { hasSwitch } = await runTestApp('command-line', '--foobar');
  1541. expect(hasSwitch).to.equal(true);
  1542. });
  1543. it('returns false when not present', async () => {
  1544. const { hasSwitch } = await runTestApp('command-line');
  1545. expect(hasSwitch).to.equal(false);
  1546. });
  1547. });
  1548. describe('commandLine.getSwitchValue', () => {
  1549. it('returns the value when present', () => {
  1550. app.commandLine.appendSwitch('foobar', 'æøåü');
  1551. expect(app.commandLine.getSwitchValue('foobar')).to.equal('æøåü');
  1552. });
  1553. it('returns an empty string when present without value', () => {
  1554. app.commandLine.appendSwitch('foobar1');
  1555. expect(app.commandLine.getSwitchValue('foobar1')).to.equal('');
  1556. });
  1557. it('returns an empty string when not present', () => {
  1558. expect(app.commandLine.getSwitchValue('foobar2')).to.equal('');
  1559. });
  1560. });
  1561. describe('commandLine.getSwitchValue (existing argv)', () => {
  1562. it('returns the value when present', async () => {
  1563. const { getSwitchValue } = await runTestApp('command-line', '--foobar=test');
  1564. expect(getSwitchValue).to.equal('test');
  1565. });
  1566. it('returns an empty string when present without value', async () => {
  1567. const { getSwitchValue } = await runTestApp('command-line', '--foobar');
  1568. expect(getSwitchValue).to.equal('');
  1569. });
  1570. it('returns an empty string when not present', async () => {
  1571. const { getSwitchValue } = await runTestApp('command-line');
  1572. expect(getSwitchValue).to.equal('');
  1573. });
  1574. });
  1575. describe('commandLine.removeSwitch', () => {
  1576. it('no-ops a non-existent switch', async () => {
  1577. expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
  1578. app.commandLine.removeSwitch('foobar3');
  1579. expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
  1580. });
  1581. it('removes an existing switch', async () => {
  1582. app.commandLine.appendSwitch('foobar3', 'test');
  1583. expect(app.commandLine.hasSwitch('foobar3')).to.equal(true);
  1584. app.commandLine.removeSwitch('foobar3');
  1585. expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
  1586. });
  1587. });
  1588. ifdescribe(process.platform === 'darwin')('app.setSecureKeyboardEntryEnabled', () => {
  1589. it('changes Secure Keyboard Entry is enabled', () => {
  1590. app.setSecureKeyboardEntryEnabled(true);
  1591. expect(app.isSecureKeyboardEntryEnabled()).to.equal(true);
  1592. app.setSecureKeyboardEntryEnabled(false);
  1593. expect(app.isSecureKeyboardEntryEnabled()).to.equal(false);
  1594. });
  1595. });
  1596. describe('configureHostResolver', () => {
  1597. after(() => {
  1598. // Returns to the default configuration.
  1599. app.configureHostResolver({});
  1600. });
  1601. it('fails on bad arguments', () => {
  1602. expect(() => {
  1603. (app.configureHostResolver as any)();
  1604. }).to.throw();
  1605. expect(() => {
  1606. app.configureHostResolver({
  1607. secureDnsMode: 'notAValidValue' as any
  1608. });
  1609. }).to.throw();
  1610. expect(() => {
  1611. app.configureHostResolver({
  1612. secureDnsServers: [123 as any]
  1613. });
  1614. }).to.throw();
  1615. });
  1616. it('affects dns lookup behavior', async () => {
  1617. // 1. resolve a domain name to check that things are working
  1618. await expect(new Promise((resolve, reject) => {
  1619. electronNet.request({
  1620. method: 'HEAD',
  1621. url: 'https://www.electronjs.org'
  1622. }).on('response', resolve)
  1623. .on('error', reject)
  1624. .end();
  1625. })).to.eventually.be.fulfilled();
  1626. // 2. change the host resolver configuration to something that will
  1627. // always fail
  1628. app.configureHostResolver({
  1629. secureDnsMode: 'secure',
  1630. secureDnsServers: ['https://127.0.0.1:1234']
  1631. });
  1632. // 3. check that resolving domain names now fails
  1633. await expect(new Promise((resolve, reject) => {
  1634. electronNet.request({
  1635. method: 'HEAD',
  1636. // Needs to be a slightly different domain to above, otherwise the
  1637. // response will come from the cache.
  1638. url: 'https://electronjs.org'
  1639. }).on('response', resolve)
  1640. .on('error', reject)
  1641. .end();
  1642. })).to.eventually.be.rejectedWith(/ERR_NAME_NOT_RESOLVED/);
  1643. });
  1644. });
  1645. describe('about panel', () => {
  1646. it('app.setAboutPanelOptions() does not crash', () => {
  1647. app.setAboutPanelOptions({
  1648. applicationName: 'electron!!',
  1649. version: '1.2.3'
  1650. });
  1651. });
  1652. it('app.showAboutPanel() does not crash & runs asynchronously', () => {
  1653. app.showAboutPanel();
  1654. });
  1655. });
  1656. describe('app.setProxy(options)', () => {
  1657. let server: http.Server;
  1658. afterEach(async () => {
  1659. if (server) {
  1660. server.close();
  1661. }
  1662. await app.setProxy({ mode: 'direct' as const });
  1663. });
  1664. it('allows configuring proxy settings', async () => {
  1665. const config = { proxyRules: 'http=myproxy:80' };
  1666. await app.setProxy(config);
  1667. const proxy = await app.resolveProxy('http://example.com/');
  1668. expect(proxy).to.equal('PROXY myproxy:80');
  1669. });
  1670. it('allows removing the implicit bypass rules for localhost', async () => {
  1671. const config = {
  1672. proxyRules: 'http=myproxy:80',
  1673. proxyBypassRules: '<-loopback>'
  1674. };
  1675. await app.setProxy(config);
  1676. const proxy = await app.resolveProxy('http://localhost');
  1677. expect(proxy).to.equal('PROXY myproxy:80');
  1678. });
  1679. it('allows configuring proxy settings with pacScript', async () => {
  1680. server = http.createServer((req, res) => {
  1681. const pac = `
  1682. function FindProxyForURL(url, host) {
  1683. return "PROXY myproxy:8132";
  1684. }
  1685. `;
  1686. res.writeHead(200, {
  1687. 'Content-Type': 'application/x-ns-proxy-autoconfig'
  1688. });
  1689. res.end(pac);
  1690. });
  1691. const { url } = await listen(server);
  1692. {
  1693. const config = { pacScript: url };
  1694. await app.setProxy(config);
  1695. const proxy = await app.resolveProxy('https://google.com');
  1696. expect(proxy).to.equal('PROXY myproxy:8132');
  1697. }
  1698. {
  1699. const config = { mode: 'pac_script' as any, pacScript: url };
  1700. await app.setProxy(config);
  1701. const proxy = await app.resolveProxy('https://google.com');
  1702. expect(proxy).to.equal('PROXY myproxy:8132');
  1703. }
  1704. });
  1705. it('allows bypassing proxy settings', async () => {
  1706. const config = {
  1707. proxyRules: 'http=myproxy:80',
  1708. proxyBypassRules: '<local>'
  1709. };
  1710. await app.setProxy(config);
  1711. const proxy = await app.resolveProxy('http://example/');
  1712. expect(proxy).to.equal('DIRECT');
  1713. });
  1714. it('allows configuring proxy settings with mode `direct`', async () => {
  1715. const config = { mode: 'direct' as const, proxyRules: 'http=myproxy:80' };
  1716. await app.setProxy(config);
  1717. const proxy = await app.resolveProxy('http://example.com/');
  1718. expect(proxy).to.equal('DIRECT');
  1719. });
  1720. it('allows configuring proxy settings with mode `auto_detect`', async () => {
  1721. const config = { mode: 'auto_detect' as const };
  1722. await app.setProxy(config);
  1723. });
  1724. it('allows configuring proxy settings with mode `pac_script`', async () => {
  1725. const config = { mode: 'pac_script' as const };
  1726. await app.setProxy(config);
  1727. const proxy = await app.resolveProxy('http://example.com/');
  1728. expect(proxy).to.equal('DIRECT');
  1729. });
  1730. it('allows configuring proxy settings with mode `fixed_servers`', async () => {
  1731. const config = { mode: 'fixed_servers' as const, proxyRules: 'http=myproxy:80' };
  1732. await app.setProxy(config);
  1733. const proxy = await app.resolveProxy('http://example.com/');
  1734. expect(proxy).to.equal('PROXY myproxy:80');
  1735. });
  1736. it('allows configuring proxy settings with mode `system`', async () => {
  1737. const config = { mode: 'system' as const };
  1738. await app.setProxy(config);
  1739. });
  1740. it('disallows configuring proxy settings with mode `invalid`', async () => {
  1741. const config = { mode: 'invalid' as any };
  1742. await expect(app.setProxy(config)).to.eventually.be.rejectedWith(/Invalid mode/);
  1743. });
  1744. it('impacts proxy for requests made from utility process', async () => {
  1745. const utilityFixturePath = path.resolve(__dirname, 'fixtures', 'api', 'utility-process', 'api-net-spec.js');
  1746. const fn = async () => {
  1747. const urlRequest = electronNet.request('http://example.com/');
  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 proxy\n');
  1752. };
  1753. server = http.createServer((req, res) => {
  1754. res.writeHead(200);
  1755. res.end('ok from proxy\n');
  1756. });
  1757. const { port, hostname } = await listen(server);
  1758. const config = { mode: 'fixed_servers' as const, proxyRules: `http=${hostname}:${port}` };
  1759. await app.setProxy(config);
  1760. const proxy = await app.resolveProxy('http://example.com/');
  1761. expect(proxy).to.equal(`PROXY ${hostname}:${port}`);
  1762. const child = utilityProcess.fork(utilityFixturePath, [], {
  1763. execArgv: ['--expose-gc']
  1764. });
  1765. child.postMessage({ fn: `(${fn})()` });
  1766. const [data] = await once(child, 'message');
  1767. expect(data.ok).to.be.true(data.message);
  1768. // Cleanup.
  1769. const [code] = await once(child, 'exit');
  1770. expect(code).to.equal(0);
  1771. });
  1772. it('does not impact proxy for requests made from main process', async () => {
  1773. server = http.createServer((req, res) => {
  1774. res.writeHead(200);
  1775. res.end('ok from server\n');
  1776. });
  1777. const { url } = await listen(server);
  1778. const config = { mode: 'fixed_servers' as const, proxyRules: 'http=myproxy:80' };
  1779. await app.setProxy(config);
  1780. const proxy = await app.resolveProxy('http://example.com/');
  1781. expect(proxy).to.equal('PROXY myproxy:80');
  1782. const urlRequest = electronNet.request(url);
  1783. const response = await getResponse(urlRequest);
  1784. expect(response.statusCode).to.equal(200);
  1785. const message = await collectStreamBody(response);
  1786. expect(message).to.equal('ok from server\n');
  1787. });
  1788. });
  1789. });
  1790. describe('default behavior', () => {
  1791. describe('application menu', () => {
  1792. it('creates the default menu if the app does not set it', async () => {
  1793. const result = await runTestApp('default-menu');
  1794. expect(result).to.equal(false);
  1795. });
  1796. it('does not create the default menu if the app sets a custom menu', async () => {
  1797. const result = await runTestApp('default-menu', '--custom-menu');
  1798. expect(result).to.equal(true);
  1799. });
  1800. it('does not create the default menu if the app sets a null menu', async () => {
  1801. const result = await runTestApp('default-menu', '--null-menu');
  1802. expect(result).to.equal(true);
  1803. });
  1804. });
  1805. describe('window-all-closed', () => {
  1806. afterEach(closeAllWindows);
  1807. it('quits when the app does not handle the event', async () => {
  1808. const result = await runTestApp('window-all-closed');
  1809. expect(result).to.equal(false);
  1810. });
  1811. it('does not quit when the app handles the event', async () => {
  1812. const result = await runTestApp('window-all-closed', '--handle-event');
  1813. expect(result).to.equal(true);
  1814. });
  1815. it('should omit closed windows from getAllWindows', async () => {
  1816. const w = new BrowserWindow({ show: false });
  1817. const len = new Promise(resolve => {
  1818. app.on('window-all-closed', () => {
  1819. resolve(BrowserWindow.getAllWindows().length);
  1820. });
  1821. });
  1822. w.close();
  1823. expect(await len).to.equal(0);
  1824. });
  1825. });
  1826. describe('user agent fallback', () => {
  1827. let initialValue: string;
  1828. before(() => {
  1829. initialValue = app.userAgentFallback!;
  1830. });
  1831. it('should have a reasonable default', () => {
  1832. expect(initialValue).to.include(`Electron/${process.versions.electron}`);
  1833. expect(initialValue).to.include(`Chrome/${process.versions.chrome}`);
  1834. });
  1835. it('should be overridable', () => {
  1836. app.userAgentFallback = 'test-agent/123';
  1837. expect(app.userAgentFallback).to.equal('test-agent/123');
  1838. });
  1839. it('should be restorable', () => {
  1840. app.userAgentFallback = 'test-agent/123';
  1841. app.userAgentFallback = '';
  1842. expect(app.userAgentFallback).to.equal(initialValue);
  1843. });
  1844. });
  1845. describe('login event', () => {
  1846. afterEach(closeAllWindows);
  1847. let server: http.Server;
  1848. let serverUrl: string;
  1849. before(async () => {
  1850. server = http.createServer((request, response) => {
  1851. if (request.headers.authorization) {
  1852. return response.end('ok');
  1853. }
  1854. response
  1855. .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
  1856. .end();
  1857. });
  1858. serverUrl = (await listen(server)).url;
  1859. });
  1860. it('should emit a login event on app when a WebContents hits a 401', async () => {
  1861. const w = new BrowserWindow({ show: false });
  1862. w.loadURL(serverUrl);
  1863. const [, webContents] = await once(app, 'login') as [any, WebContents];
  1864. expect(webContents).to.equal(w.webContents);
  1865. });
  1866. });
  1867. describe('running under ARM64 translation', () => {
  1868. it('does not throw an error', () => {
  1869. if (process.platform === 'darwin' || process.platform === 'win32') {
  1870. expect(app.runningUnderARM64Translation).not.to.be.undefined();
  1871. expect(() => {
  1872. return app.runningUnderARM64Translation;
  1873. }).not.to.throw();
  1874. } else {
  1875. expect(app.runningUnderARM64Translation).to.be.undefined();
  1876. }
  1877. });
  1878. });
  1879. });
  1880. async function runTestApp (name: string, ...args: any[]) {
  1881. const appPath = path.join(fixturesPath, 'api', name);
  1882. const electronPath = process.execPath;
  1883. const appProcess = cp.spawn(electronPath, [appPath, ...args]);
  1884. let output = '';
  1885. appProcess.stdout.on('data', (data) => { output += data; });
  1886. await once(appProcess.stdout, 'end');
  1887. return JSON.parse(output);
  1888. }