api-shell-spec.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. import { shell } from 'electron/common';
  2. import { BrowserWindow, app } from 'electron/main';
  3. import { expect } from 'chai';
  4. import { execSync } from 'node:child_process';
  5. import { once } from 'node:events';
  6. import * as fs from 'node:fs';
  7. import * as http from 'node:http';
  8. import * as os from 'node:os';
  9. import * as path from 'node:path';
  10. import { ifdescribe, ifit, listen } from './lib/spec-helpers';
  11. import { closeAllWindows } from './lib/window-helpers';
  12. describe('shell module', () => {
  13. describe('shell.openExternal()', () => {
  14. let envVars: Record<string, string | undefined> = {};
  15. let server: http.Server;
  16. after(function () {
  17. this.timeout(60000);
  18. if (process.env.CI && process.platform === 'win32') {
  19. // Edge may cause issues with visibility tests, so make sure it is closed after testing.
  20. const killEdge = 'Get-Process | Where Name -Like "msedge" | Stop-Process';
  21. execSync(killEdge, { shell: 'powershell.exe' });
  22. }
  23. });
  24. beforeEach(function () {
  25. envVars = {
  26. display: process.env.DISPLAY,
  27. de: process.env.DE,
  28. browser: process.env.BROWSER
  29. };
  30. });
  31. afterEach(async () => {
  32. // reset env vars to prevent side effects
  33. if (process.platform === 'linux') {
  34. process.env.DE = envVars.de;
  35. process.env.BROWSER = envVars.browser;
  36. process.env.DISPLAY = envVars.display;
  37. }
  38. await closeAllWindows();
  39. if (server) {
  40. server.close();
  41. server = null as unknown as http.Server;
  42. }
  43. });
  44. async function urlOpened () {
  45. let url = 'http://127.0.0.1';
  46. let requestReceived: Promise<any>;
  47. if (process.platform === 'linux') {
  48. process.env.BROWSER = '/bin/true';
  49. process.env.DE = 'generic';
  50. process.env.DISPLAY = '';
  51. requestReceived = Promise.resolve();
  52. } else if (process.platform === 'darwin') {
  53. // On the Mac CI machines, Safari tries to ask for a password to the
  54. // code signing keychain we set up to test code signing (see
  55. // https://github.com/electron/electron/pull/19969#issuecomment-526278890),
  56. // so use a blur event as a crude proxy.
  57. const w = new BrowserWindow({ show: true });
  58. requestReceived = once(w, 'blur');
  59. } else {
  60. server = http.createServer((req, res) => {
  61. res.end();
  62. });
  63. url = (await listen(server)).url;
  64. requestReceived = new Promise<void>(resolve => server.on('connection', () => resolve()));
  65. }
  66. return { url, requestReceived };
  67. }
  68. it('opens an external link', async () => {
  69. const { url, requestReceived } = await urlOpened();
  70. await Promise.all<void>([
  71. shell.openExternal(url),
  72. requestReceived
  73. ]);
  74. });
  75. it('opens an external link in the renderer', async () => {
  76. const { url, requestReceived } = await urlOpened();
  77. const w = new BrowserWindow({ show: false, webPreferences: { sandbox: false, contextIsolation: false, nodeIntegration: true } });
  78. await w.loadURL('about:blank');
  79. await Promise.all<void>([
  80. w.webContents.executeJavaScript(`require("electron").shell.openExternal(${JSON.stringify(url)})`),
  81. requestReceived
  82. ]);
  83. });
  84. ifit(process.platform === 'darwin')('removes focus from the electron window after opening an external link', async () => {
  85. const url = 'http://127.0.0.1';
  86. const w = new BrowserWindow({ show: true });
  87. await once(w, 'focus');
  88. expect(w.isFocused()).to.be.true();
  89. await Promise.all<void>([
  90. shell.openExternal(url),
  91. once(w, 'blur') as Promise<any>
  92. ]);
  93. expect(w.isFocused()).to.be.false();
  94. });
  95. });
  96. describe('shell.trashItem()', () => {
  97. afterEach(closeAllWindows);
  98. it('moves an item to the trash', async () => {
  99. const dir = await fs.promises.mkdtemp(path.resolve(app.getPath('temp'), 'electron-shell-spec-'));
  100. const filename = path.join(dir, 'temp-to-be-deleted');
  101. await fs.promises.writeFile(filename, 'dummy-contents');
  102. await shell.trashItem(filename);
  103. expect(fs.existsSync(filename)).to.be.false();
  104. });
  105. it('throws when called with a nonexistent path', async () => {
  106. const filename = path.join(app.getPath('temp'), 'does-not-exist');
  107. await expect(shell.trashItem(filename)).to.eventually.be.rejected();
  108. });
  109. ifit(!(process.platform === 'win32' && process.arch === 'ia32'))('works in the renderer process', async () => {
  110. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  111. w.loadURL('about:blank');
  112. await expect(w.webContents.executeJavaScript('require(\'electron\').shell.trashItem(\'does-not-exist\')')).to.be.rejectedWith(/does-not-exist|Failed to move item|Failed to create FileOperation/);
  113. });
  114. });
  115. const shortcutOptions = {
  116. target: 'C:\\target',
  117. description: 'description',
  118. cwd: 'cwd',
  119. args: 'args',
  120. appUserModelId: 'appUserModelId',
  121. icon: 'icon',
  122. iconIndex: 1,
  123. toastActivatorClsid: '{0E3CFA27-6FEA-410B-824F-A174B6E865E5}'
  124. };
  125. ifdescribe(process.platform === 'win32')('shell.readShortcutLink(shortcutPath)', () => {
  126. it('throws when failed', () => {
  127. expect(() => {
  128. shell.readShortcutLink('not-exist');
  129. }).to.throw('Failed to read shortcut link');
  130. });
  131. const fixtures = path.resolve(__dirname, 'fixtures');
  132. it('reads all properties of a shortcut', () => {
  133. const shortcut = shell.readShortcutLink(path.join(fixtures, 'assets', 'shortcut.lnk'));
  134. expect(shortcut).to.deep.equal(shortcutOptions);
  135. });
  136. });
  137. ifdescribe(process.platform === 'win32')('shell.writeShortcutLink(shortcutPath[, operation], options)', () => {
  138. const tmpShortcut = path.join(os.tmpdir(), `${Date.now()}.lnk`);
  139. afterEach(() => {
  140. fs.unlinkSync(tmpShortcut);
  141. });
  142. it('writes the shortcut', () => {
  143. expect(shell.writeShortcutLink(tmpShortcut, { target: 'C:\\' })).to.be.true();
  144. expect(fs.existsSync(tmpShortcut)).to.be.true();
  145. });
  146. it('correctly sets the fields', () => {
  147. expect(shell.writeShortcutLink(tmpShortcut, shortcutOptions)).to.be.true();
  148. expect(shell.readShortcutLink(tmpShortcut)).to.deep.equal(shortcutOptions);
  149. });
  150. it('updates the shortcut', () => {
  151. expect(shell.writeShortcutLink(tmpShortcut, 'update', shortcutOptions)).to.be.false();
  152. expect(shell.writeShortcutLink(tmpShortcut, 'create', shortcutOptions)).to.be.true();
  153. expect(shell.readShortcutLink(tmpShortcut)).to.deep.equal(shortcutOptions);
  154. const change = { target: 'D:\\' };
  155. expect(shell.writeShortcutLink(tmpShortcut, 'update', change)).to.be.true();
  156. expect(shell.readShortcutLink(tmpShortcut)).to.deep.equal({ ...shortcutOptions, ...change });
  157. });
  158. it('replaces the shortcut', () => {
  159. expect(shell.writeShortcutLink(tmpShortcut, 'replace', shortcutOptions)).to.be.false();
  160. expect(shell.writeShortcutLink(tmpShortcut, 'create', shortcutOptions)).to.be.true();
  161. expect(shell.readShortcutLink(tmpShortcut)).to.deep.equal(shortcutOptions);
  162. const change = {
  163. target: 'D:\\',
  164. description: 'description2',
  165. cwd: 'cwd2',
  166. args: 'args2',
  167. appUserModelId: 'appUserModelId2',
  168. icon: 'icon2',
  169. iconIndex: 2,
  170. toastActivatorClsid: '{C51A3996-CAD9-4934-848B-16285D4A1496}'
  171. };
  172. expect(shell.writeShortcutLink(tmpShortcut, 'replace', change)).to.be.true();
  173. expect(shell.readShortcutLink(tmpShortcut)).to.deep.equal(change);
  174. });
  175. });
  176. });