api-app-spec.ts 67 KB

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