api-app-spec.ts 65 KB

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