electron/spec-main/api-app-spec.ts

1568 lines
51 KiB
TypeScript
Raw Normal View History

2020-03-20 20:28:31 +00:00
import { expect } from 'chai';
import * as cp from 'child_process';
import * as https from 'https';
import * as http from 'http';
import * as net from 'net';
import * as fs from 'fs';
import * as path from 'path';
import { app, BrowserWindow, Menu, session } from 'electron/main';
2020-03-20 20:28:31 +00:00
import { emittedOnce } from './events-helpers';
import { closeWindow, closeAllWindows } from './window-helpers';
import { ifdescribe } from './spec-helpers';
2019-11-01 20:37:02 +00:00
import split = require('split')
2020-03-20 20:28:31 +00:00
const features = process.electronBinding('features');
2016-03-25 19:57:17 +00:00
2020-03-20 20:28:31 +00:00
const fixturesPath = path.resolve(__dirname, '../spec/fixtures');
describe('electron module', () => {
it('does not expose internal modules to require', () => {
expect(() => {
2020-03-20 20:28:31 +00:00
require('clipboard');
}).to.throw(/Cannot find module 'clipboard'/);
});
2016-05-23 20:12:02 +00:00
describe('require("electron")', () => {
it('always returns the internal electron module', () => {
2020-03-20 20:28:31 +00:00
require('electron');
});
});
});
2016-03-25 19:57:17 +00:00
describe('app module', () => {
2020-03-20 20:28:31 +00:00
let server: https.Server;
let secureUrl: string;
const certPath = path.join(fixturesPath, 'certificates');
2016-12-02 17:34:16 +00:00
Fix some flaky tests in CI (#12153) * Guard whole InitPrefs with ScopedAllowIO Saw a crash: 0 0x7f8d2f7d918d base::debug::StackTrace::StackTrace() 1 0x7f8d2f7d755c base::debug::StackTrace::StackTrace() 2 0x7f8d2f867caa logging::LogMessage::~LogMessage() 3 0x7f8d2fa157c7 base::ThreadRestrictions::AssertIOAllowed() 4 0x7f8d2f83453a base::OpenFile() 5 0x7f8d2f82a967 base::ReadFileToStringWithMaxSize() 6 0x7f8d2f82ad44 base::ReadFileToString() 7 0x7f8d2f846f73 JSONFileValueDeserializer::ReadFileToString() 8 0x7f8d2f84738c JSONFileValueDeserializer::Deserialize() 9 0x7f8d35a5d1f6 <unknown> 10 0x7f8d35a5c217 JsonPrefStore::ReadPrefs() 11 0x7f8d35a87d3e PrefService::InitFromStorage() 12 0x7f8d35a87c60 PrefService::PrefService() 13 0x7f8d35a91a10 PrefServiceFactory::Create() 14 0x000000e86e1b brightray::BrowserContext::InitPrefs() 15 0x000000c2bd64 atom::AtomBrowserContext::AtomBrowserContext() 16 0x000000c320db atom::AtomBrowserContext::From() 17 0x000000b4b8b5 atom::api::Session::FromPartition() * Fix done being called twice in setInterval test The callback passed to browser process is called asyncly, so it is possible that multiple callbacks has already been scheduled before we can clearInternval. * Fix failing test when dir name has special chars The pdfSource is not escaped while parsedURL.search is. * Call done with Error instead of string * Fix crash caused by not removing input observer Solve crash: 0 libcontent.dylib content::RenderWidgetHostImpl::DispatchInputEventWithLatencyInfo(blink::WebInputEvent const&, ui::LatencyInfo*) + 214 1 libcontent.dylib content::RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo(blink::WebMouseEvent const&, ui::LatencyInfo const&) + 1350 2 libcontent.dylib content::RenderWidgetHostViewMac::ProcessMouseEvent(blink::WebMouseEvent const&, ui::LatencyInfo const&) + 44 3 libcontent.dylib content::RenderWidgetHostInputEventRouter::RouteMouseEvent(content::RenderWidgetHostViewBase*, blink::WebMouseEvent*, ui::LatencyInfo const&) + 1817 * Print detailed error * Run tests after server is ready
2018-03-07 05:40:27 +00:00
before((done) => {
2016-12-02 17:34:16 +00:00
const options = {
key: fs.readFileSync(path.join(certPath, 'server.key')),
cert: fs.readFileSync(path.join(certPath, 'server.pem')),
ca: [
fs.readFileSync(path.join(certPath, 'rootCA.pem')),
fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
],
requestCert: true,
rejectUnauthorized: false
2020-03-20 20:28:31 +00:00
};
2016-12-02 17:34:16 +00:00
server = https.createServer(options, (req, res) => {
if ((req as any).client.authorized) {
2020-03-20 20:28:31 +00:00
res.writeHead(200);
res.end('<title>authorized</title>');
2016-12-02 17:34:16 +00:00
} else {
2020-03-20 20:28:31 +00:00
res.writeHead(401);
res.end('<title>denied</title>');
2016-12-02 17:34:16 +00:00
}
2020-03-20 20:28:31 +00:00
});
2016-12-02 17:34:16 +00:00
server.listen(0, '127.0.0.1', () => {
2020-03-20 20:28:31 +00:00
const port = (server.address() as net.AddressInfo).port;
secureUrl = `https://127.0.0.1:${port}`;
done();
});
});
2016-12-02 17:34:16 +00:00
after(done => {
2020-03-20 20:28:31 +00:00
server.close(() => done());
});
2016-12-02 17:34:16 +00:00
describe('app.getVersion()', () => {
it('returns the version field of package.json', () => {
2020-03-20 20:28:31 +00:00
expect(app.getVersion()).to.equal('0.1.0');
});
});
2016-03-25 19:57:17 +00:00
describe('app.setVersion(version)', () => {
it('overrides the version', () => {
2020-03-20 20:28:31 +00:00
expect(app.getVersion()).to.equal('0.1.0');
app.setVersion('test-version');
2020-03-20 20:28:31 +00:00
expect(app.getVersion()).to.equal('test-version');
app.setVersion('0.1.0');
});
});
2016-03-25 19:57:17 +00:00
describe('app name APIs', () => {
it('with properties', () => {
it('returns the name field of package.json', () => {
2020-03-20 20:28:31 +00:00
expect(app.name).to.equal('Electron Test Main');
});
it('overrides the name', () => {
2020-03-20 20:28:31 +00:00
expect(app.name).to.equal('Electron Test Main');
app.name = 'test-name';
2020-03-20 20:28:31 +00:00
expect(app.name).to.equal('test-name');
app.name = 'Electron Test Main';
});
});
it('with functions', () => {
it('returns the name field of package.json', () => {
2020-03-20 20:28:31 +00:00
expect(app.getName()).to.equal('Electron Test Main');
});
2016-03-25 19:57:17 +00:00
it('overrides the name', () => {
2020-03-20 20:28:31 +00:00
expect(app.getName()).to.equal('Electron Test Main');
app.setName('test-name');
2020-03-20 20:28:31 +00:00
expect(app.getName()).to.equal('test-name');
app.setName('Electron Test Main');
});
});
});
2016-03-25 19:57:17 +00:00
describe('app.getLocale()', () => {
it('should not be empty', () => {
2020-03-20 20:28:31 +00:00
expect(app.getLocale()).to.not.equal('');
});
});
2016-03-25 19:57:17 +00:00
describe('app.getLocaleCountryCode()', () => {
it('should be empty or have length of two', () => {
2020-03-20 20:28:31 +00:00
let expectedLength = 2;
2019-10-30 23:38:21 +00:00
if (process.platform === 'linux') {
// Linux CI machines have no locale.
2020-03-20 20:28:31 +00:00
expectedLength = 0;
}
2020-03-20 20:28:31 +00:00
expect(app.getLocaleCountryCode()).to.be.a('string').and.have.lengthOf(expectedLength);
});
});
describe('app.isPackaged', () => {
it('should be false durings tests', () => {
2020-03-20 20:28:31 +00:00
expect(app.isPackaged).to.equal(false);
});
});
2019-10-30 23:38:21 +00:00
ifdescribe(process.platform === 'darwin')('app.isInApplicationsFolder()', () => {
it('should be false during tests', () => {
2020-03-20 20:28:31 +00:00
expect(app.isInApplicationsFolder()).to.equal(false);
});
});
describe('app.exit(exitCode)', () => {
2020-03-20 20:28:31 +00:00
let appProcess: cp.ChildProcess | null = null;
2016-03-25 19:57:17 +00:00
afterEach(() => {
2020-03-20 20:28:31 +00:00
if (appProcess) appProcess.kill();
});
2016-03-25 19:57:17 +00:00
2018-08-26 13:54:51 +00:00
it('emits a process exit event with the code', async () => {
2020-03-20 20:28:31 +00:00
const appPath = path.join(fixturesPath, 'api', 'quit-app');
const electronPath = process.execPath;
let output = '';
2020-03-20 20:28:31 +00:00
appProcess = cp.spawn(electronPath, [appPath]);
if (appProcess && appProcess.stdout) {
2020-03-20 20:28:31 +00:00
appProcess.stdout.on('data', data => { output += data; });
}
2020-03-20 20:28:31 +00:00
const [code] = await emittedOnce(appProcess, 'exit');
2018-08-26 13:54:51 +00:00
if (process.platform !== 'win32') {
2020-03-20 20:28:31 +00:00
expect(output).to.include('Exit event with code: 123');
2018-08-26 13:54:51 +00:00
}
2020-03-20 20:28:31 +00:00
expect(code).to.equal(123);
});
it('closes all windows', async function () {
2020-03-20 20:28:31 +00:00
const appPath = path.join(fixturesPath, 'api', 'exit-closes-all-windows-app');
const electronPath = process.execPath;
2020-03-20 20:28:31 +00:00
appProcess = cp.spawn(electronPath, [appPath]);
const [code, signal] = await emittedOnce(appProcess, 'exit');
2018-08-26 13:54:51 +00:00
2020-03-20 20:28:31 +00:00
expect(signal).to.equal(null, 'exit signal should be null, if you see this please tag @MarshallOfSound');
expect(code).to.equal(123, 'exit code should be 123, if you see this please tag @MarshallOfSound');
});
2018-01-11 22:50:35 +00:00
2018-08-26 13:54:51 +00:00
it('exits gracefully', async function () {
if (!['darwin', 'linux'].includes(process.platform)) {
2020-03-20 20:28:31 +00:00
this.skip();
return;
2018-01-11 22:50:35 +00:00
}
2020-03-20 20:28:31 +00:00
const electronPath = process.execPath;
const appPath = path.join(fixturesPath, 'api', 'singleton');
appProcess = cp.spawn(electronPath, [appPath]);
// Singleton will send us greeting data to let us know it's running.
// After that, ask it to exit gracefully and confirm that it does.
if (appProcess && appProcess.stdout) {
2020-03-20 20:28:31 +00:00
appProcess.stdout.on('data', () => appProcess!.kill());
}
2020-03-20 20:28:31 +00:00
const [code, signal] = await emittedOnce(appProcess, 'exit');
2018-08-26 13:54:51 +00:00
2020-03-20 20:28:31 +00:00
const message = `code:\n${code}\nsignal:\n${signal}`;
expect(code).to.equal(0, message);
expect(signal).to.equal(null, message);
});
});
ifdescribe(process.platform === 'darwin')('app.setActivationPolicy', () => {
it('throws an error on invalid application policies', () => {
expect(() => {
2020-03-20 20:28:31 +00:00
app.setActivationPolicy('terrible' as any);
}).to.throw(/Invalid activation policy: must be one of 'regular', 'accessory', or 'prohibited'/);
});
});
describe('app.requestSingleInstanceLock', () => {
it('prevents the second launch of app', function (done) {
2020-03-20 20:28:31 +00:00
this.timeout(120000);
const appPath = path.join(fixturesPath, 'api', 'singleton');
const first = cp.spawn(process.execPath, [appPath]);
first.once('exit', code => {
2020-03-20 20:28:31 +00:00
expect(code).to.equal(0);
});
// Start second app when received output.
first.stdout.once('data', () => {
2020-03-20 20:28:31 +00:00
const second = cp.spawn(process.execPath, [appPath]);
second.once('exit', code => {
2020-03-20 20:28:31 +00:00
expect(code).to.equal(1);
done();
});
});
});
it('passes arguments to the second-instance event', async () => {
2020-03-20 20:28:31 +00:00
const appPath = path.join(fixturesPath, 'api', 'singleton');
const first = cp.spawn(process.execPath, [appPath]);
const firstExited = emittedOnce(first, 'exit');
// Wait for the first app to boot.
2020-03-20 20:28:31 +00:00
const firstStdoutLines = first.stdout.pipe(split());
while ((await emittedOnce(firstStdoutLines, 'data')).toString() !== 'started') {
// wait.
}
2020-03-20 20:28:31 +00:00
const data2Promise = emittedOnce(firstStdoutLines, 'data');
const secondInstanceArgs = [process.execPath, appPath, '--some-switch', 'some-arg'];
const second = cp.spawn(secondInstanceArgs[0], secondInstanceArgs.slice(1));
const [code2] = await emittedOnce(second, 'exit');
expect(code2).to.equal(1);
const [code1] = await firstExited;
expect(code1).to.equal(0);
const data2 = (await data2Promise)[0].toString('ascii');
const secondInstanceArgsReceived: string[] = JSON.parse(data2.toString('ascii'));
const expected = process.platform === 'win32'
? [process.execPath, '--some-switch', '--allow-file-access-from-files', appPath, 'some-arg']
2020-03-20 20:28:31 +00:00
: secondInstanceArgs;
expect(secondInstanceArgsReceived).to.eql(expected,
2020-03-20 20:28:31 +00:00
`expected ${JSON.stringify(expected)} but got ${data2.toString('ascii')}`);
});
});
describe('app.relaunch', () => {
2020-03-20 20:28:31 +00:00
let server: net.Server | null = null;
const socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\electron-app-relaunch' : '/tmp/electron-app-relaunch';
2016-06-03 03:12:20 +00:00
beforeEach(done => {
2016-06-29 16:37:10 +00:00
fs.unlink(socketPath, () => {
2020-03-20 20:28:31 +00:00
server = net.createServer();
server.listen(socketPath);
done();
});
});
2016-06-03 03:12:20 +00:00
afterEach((done) => {
server!.close(() => {
2016-06-03 03:12:20 +00:00
if (process.platform === 'win32') {
2020-03-20 20:28:31 +00:00
done();
2016-06-03 03:12:20 +00:00
} else {
2020-03-20 20:28:31 +00:00
fs.unlink(socketPath, () => done());
2016-06-03 03:12:20 +00:00
}
2020-03-20 20:28:31 +00:00
});
});
2016-06-03 03:12:20 +00:00
it('relaunches the app', function (done) {
2020-03-20 20:28:31 +00:00
this.timeout(120000);
2020-03-20 20:28:31 +00:00
let state = 'none';
server!.once('error', error => done(error));
server!.on('connection', client => {
client.once('data', data => {
2016-06-03 03:12:20 +00:00
if (String(data) === 'false' && state === 'none') {
2020-03-20 20:28:31 +00:00
state = 'first-launch';
2016-06-03 03:12:20 +00:00
} else if (String(data) === 'true' && state === 'first-launch') {
2020-03-20 20:28:31 +00:00
done();
2016-06-03 03:12:20 +00:00
} else {
2020-03-20 20:28:31 +00:00
done(`Unexpected state: ${state}`);
2016-06-03 03:12:20 +00:00
}
2020-03-20 20:28:31 +00:00
});
});
2016-06-03 03:12:20 +00:00
2020-03-20 20:28:31 +00:00
const appPath = path.join(fixturesPath, 'api', 'relaunch');
cp.spawn(process.execPath, [appPath]);
});
});
2016-06-03 03:12:20 +00:00
describe('app.setUserActivity(type, userInfo)', () => {
before(function () {
if (process.platform !== 'darwin') {
2020-03-20 20:28:31 +00:00
this.skip();
}
2020-03-20 20:28:31 +00:00
});
it('sets the current activity', () => {
2020-03-20 20:28:31 +00:00
app.setUserActivity('com.electron.testActivity', { testData: '123' });
expect(app.getCurrentActivityType()).to.equal('com.electron.testActivity');
});
});
describe('certificate-error event', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
it('is emitted when visiting a server with a self-signed cert', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.loadURL(secureUrl);
await emittedOnce(app, 'certificate-error');
});
});
// xdescribe('app.importCertificate', () => {
// let w = null
// before(function () {
// if (process.platform !== 'linux') {
// this.skip()
// }
// })
// afterEach(() => closeWindow(w).then(() => { w = null }))
// it('can import certificate into platform cert store', done => {
// const options = {
// certificate: path.join(certPath, 'client.p12'),
// password: 'electron'
// }
// w = new BrowserWindow({
// show: false,
// webPreferences: {
// nodeIntegration: true
// }
// })
// w.webContents.on('did-finish-load', () => {
// expect(w.webContents.getTitle()).to.equal('authorized')
// done()
// })
// ipcRenderer.once('select-client-certificate', (event, webContentsId, list) => {
// expect(webContentsId).to.equal(w.webContents.id)
// expect(list).to.have.lengthOf(1)
// expect(list[0]).to.deep.equal({
// issuerName: 'Intermediate CA',
// subjectName: 'Client Cert',
// issuer: { commonName: 'Intermediate CA' },
// subject: { commonName: 'Client Cert' }
// })
// event.sender.send('client-certificate-response', list[0])
// })
// app.importCertificate(options, result => {
// expect(result).toNotExist()
// ipcRenderer.sendSync('set-client-certificate-option', false)
// w.loadURL(secureUrl)
// })
// })
// })
2016-04-18 16:23:44 +00:00
describe('BrowserWindow events', () => {
2020-03-20 20:28:31 +00:00
let w: BrowserWindow = null as any;
2020-03-20 20:28:31 +00:00
afterEach(() => closeWindow(w).then(() => { w = null as any; }));
2016-03-25 19:57:17 +00:00
it('should emit browser-window-focus event when window is focused', (done) => {
app.once('browser-window-focus', (e, window) => {
2020-03-20 20:28:31 +00:00
expect(w.id).to.equal(window.id);
done();
});
w = new BrowserWindow({ show: false });
w.emit('focus');
});
2016-03-25 19:57:17 +00:00
it('should emit browser-window-blur event when window is blured', (done) => {
app.once('browser-window-blur', (e, window) => {
2020-03-20 20:28:31 +00:00
expect(w.id).to.equal(window.id);
done();
});
w = new BrowserWindow({ show: false });
w.emit('blur');
});
2016-03-25 19:57:17 +00:00
it('should emit browser-window-created event when window is created', (done) => {
app.once('browser-window-created', (e, window) => {
setImmediate(() => {
2020-03-20 20:28:31 +00:00
expect(w.id).to.equal(window.id);
done();
});
});
w = new BrowserWindow({ show: false });
});
2016-06-13 16:05:04 +00:00
it('should emit web-contents-created event when a webContents is created', (done) => {
app.once('web-contents-created', (e, webContents) => {
setImmediate(() => {
2020-03-20 20:28:31 +00:00
expect(w.webContents.id).to.equal(webContents.id);
done();
});
});
w = new BrowserWindow({ show: false });
});
2019-11-01 20:37:02 +00:00
it('should emit renderer-process-crashed event when renderer crashes', async function () {
// FIXME: re-enable this test on win32.
2020-03-20 20:28:31 +00:00
if (process.platform === 'win32') { return this.skip(); }
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true
}
2020-03-20 20:28:31 +00:00
});
await w.loadURL('about:blank');
2020-03-20 20:28:31 +00:00
const promise = emittedOnce(app, 'renderer-process-crashed');
w.webContents.executeJavaScript('process.crash()');
2020-03-20 20:28:31 +00:00
const [, webContents] = await promise;
expect(webContents).to.equal(w.webContents);
});
it('should emit render-process-gone event when renderer crashes', async function () {
// FIXME: re-enable this test on win32.
if (process.platform === 'win32') { return this.skip(); }
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true
}
});
await w.loadURL('about:blank');
const promise = emittedOnce(app, 'render-process-gone');
w.webContents.executeJavaScript('process.crash()');
const [, webContents, details] = await promise;
expect(webContents).to.equal(w.webContents);
expect(details.reason).to.be.oneOf(['crashed', 'abnormal-exit']);
});
ifdescribe(features.isDesktopCapturerEnabled())('desktopCapturer module filtering', () => {
it('should emit desktop-capturer-get-sources event when desktopCapturer.getSources() is invoked', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true
}
2020-03-20 20:28:31 +00:00
});
await w.loadURL('about:blank');
2020-03-20 20:28:31 +00:00
const promise = emittedOnce(app, 'desktop-capturer-get-sources');
w.webContents.executeJavaScript('require(\'electron\').desktopCapturer.getSources({ types: [\'screen\'] })');
2020-03-20 20:28:31 +00:00
const [, webContents] = await promise;
expect(webContents).to.equal(w.webContents);
});
});
ifdescribe(features.isRemoteModuleEnabled())('remote module filtering', () => {
it('should emit remote-require event when remote.require() is invoked', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true
}
2020-03-20 20:28:31 +00:00
});
await w.loadURL('about:blank');
2020-03-20 20:28:31 +00:00
const promise = emittedOnce(app, 'remote-require');
w.webContents.executeJavaScript('require(\'electron\').remote.require(\'test\')');
2020-03-20 20:28:31 +00:00
const [, webContents, moduleName] = await promise;
expect(webContents).to.equal(w.webContents);
expect(moduleName).to.equal('test');
});
it('should emit remote-get-global event when remote.getGlobal() is invoked', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true
}
2020-03-20 20:28:31 +00:00
});
await w.loadURL('about:blank');
2020-03-20 20:28:31 +00:00
const promise = emittedOnce(app, 'remote-get-global');
w.webContents.executeJavaScript('require(\'electron\').remote.getGlobal(\'test\')');
2020-03-20 20:28:31 +00:00
const [, webContents, globalName] = await promise;
expect(webContents).to.equal(w.webContents);
expect(globalName).to.equal('test');
});
it('should emit remote-get-builtin event when remote.getBuiltin() is invoked', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true
}
2020-03-20 20:28:31 +00:00
});
await w.loadURL('about:blank');
2020-03-20 20:28:31 +00:00
const promise = emittedOnce(app, 'remote-get-builtin');
w.webContents.executeJavaScript('require(\'electron\').remote.app');
2020-03-20 20:28:31 +00:00
const [, webContents, moduleName] = await promise;
expect(webContents).to.equal(w.webContents);
expect(moduleName).to.equal('app');
});
it('should emit remote-get-current-window event when remote.getCurrentWindow() is invoked', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true
}
2020-03-20 20:28:31 +00:00
});
await w.loadURL('about:blank');
2020-03-20 20:28:31 +00:00
const promise = emittedOnce(app, 'remote-get-current-window');
w.webContents.executeJavaScript('{ require(\'electron\').remote.getCurrentWindow() }');
2020-03-20 20:28:31 +00:00
const [, webContents] = await promise;
expect(webContents).to.equal(w.webContents);
});
it('should emit remote-get-current-web-contents event when remote.getCurrentWebContents() is invoked', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true
}
2020-03-20 20:28:31 +00:00
});
await w.loadURL('about:blank');
2020-03-20 20:28:31 +00:00
const promise = emittedOnce(app, 'remote-get-current-web-contents');
w.webContents.executeJavaScript('{ require(\'electron\').remote.getCurrentWebContents() }');
2020-03-20 20:28:31 +00:00
const [, webContents] = await promise;
expect(webContents).to.equal(w.webContents);
});
});
});
2019-04-25 22:44:54 +00:00
describe('app.badgeCount', () => {
const platformIsNotSupported =
(process.platform === 'win32') ||
2020-03-20 20:28:31 +00:00
(process.platform === 'linux' && !app.isUnityRunning());
const platformIsSupported = !platformIsNotSupported;
2020-03-20 20:28:31 +00:00
const expectedBadgeCount = 42;
2020-03-20 20:28:31 +00:00
after(() => { app.badgeCount = 0; });
describe('on supported platform', () => {
it('with properties', () => {
it('sets a badge count', function () {
2020-03-20 20:28:31 +00:00
if (platformIsNotSupported) return this.skip();
2020-03-20 20:28:31 +00:00
app.badgeCount = expectedBadgeCount;
expect(app.badgeCount).to.equal(expectedBadgeCount);
});
});
it('with functions', () => {
it('sets a badge count', function () {
2020-03-20 20:28:31 +00:00
if (platformIsNotSupported) return this.skip();
2020-03-20 20:28:31 +00:00
app.setBadgeCount(expectedBadgeCount);
expect(app.getBadgeCount()).to.equal(expectedBadgeCount);
});
});
});
describe('on unsupported platform', () => {
it('with properties', () => {
it('does not set a badge count', function () {
2020-03-20 20:28:31 +00:00
if (platformIsSupported) return this.skip();
2020-03-20 20:28:31 +00:00
app.badgeCount = 9999;
expect(app.badgeCount).to.equal(0);
});
});
it('with functions', () => {
it('does not set a badge count)', function () {
2020-03-20 20:28:31 +00:00
if (platformIsSupported) return this.skip();
2020-03-20 20:28:31 +00:00
app.setBadgeCount(9999);
expect(app.getBadgeCount()).to.equal(0);
});
});
});
});
2016-07-06 20:34:14 +00:00
describe('app.get/setLoginItemSettings API', function () {
2020-03-20 20:28:31 +00:00
const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
const processStartArgs = [
'--processStart', `"${path.basename(process.execPath)}"`,
'--process-start-args', '"--hidden"'
2020-03-20 20:28:31 +00:00
];
before(function () {
2020-03-20 20:28:31 +00:00
if (process.platform === 'linux' || process.mas) this.skip();
});
beforeEach(() => {
2020-03-20 20:28:31 +00:00
app.setLoginItemSettings({ openAtLogin: false });
app.setLoginItemSettings({ openAtLogin: false, path: updateExe, args: processStartArgs });
});
afterEach(() => {
2020-03-20 20:28:31 +00:00
app.setLoginItemSettings({ openAtLogin: false });
app.setLoginItemSettings({ openAtLogin: false, path: updateExe, args: processStartArgs });
});
2016-07-06 20:34:14 +00:00
it('sets and returns the app as a login item', done => {
2020-03-20 20:28:31 +00:00
app.setLoginItemSettings({ openAtLogin: true });
2019-01-31 17:59:32 +00:00
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: true,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false
2020-03-20 20:28:31 +00:00
});
done();
});
it('adds a login item that loads in hidden mode', done => {
2020-03-20 20:28:31 +00:00
app.setLoginItemSettings({ openAtLogin: true, openAsHidden: true });
2019-01-31 17:59:32 +00:00
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: true,
openAsHidden: process.platform === 'darwin' && !process.mas, // Only available on macOS
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false
2020-03-20 20:28:31 +00:00
});
done();
});
it('correctly sets and unsets the LoginItem', function () {
2020-03-20 20:28:31 +00:00
expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
2020-03-20 20:28:31 +00:00
app.setLoginItemSettings({ openAtLogin: true });
expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
2020-03-20 20:28:31 +00:00
app.setLoginItemSettings({ openAtLogin: false });
expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
});
it('correctly sets and unsets the LoginItem as hidden', function () {
2020-03-20 20:28:31 +00:00
if (process.platform !== 'darwin') this.skip();
2020-03-20 20:28:31 +00:00
expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
expect(app.getLoginItemSettings().openAsHidden).to.equal(false);
2020-03-20 20:28:31 +00:00
app.setLoginItemSettings({ openAtLogin: true, openAsHidden: true });
expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
expect(app.getLoginItemSettings().openAsHidden).to.equal(true);
2020-03-20 20:28:31 +00:00
app.setLoginItemSettings({ openAtLogin: true, openAsHidden: false });
expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
expect(app.getLoginItemSettings().openAsHidden).to.equal(false);
});
it('allows you to pass a custom executable and arguments', function () {
2020-03-20 20:28:31 +00:00
if (process.platform !== 'win32') this.skip();
2020-03-20 20:28:31 +00:00
app.setLoginItemSettings({ openAtLogin: true, path: updateExe, args: processStartArgs });
2020-03-20 20:28:31 +00:00
expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
expect(app.getLoginItemSettings({
path: updateExe,
args: processStartArgs
2020-03-20 20:28:31 +00:00
}).openAtLogin).to.equal(true);
});
});
ifdescribe(process.platform !== 'linux')('accessibilitySupportEnabled property', () => {
it('with properties', () => {
it('can set accessibility support enabled', () => {
2020-03-20 20:28:31 +00:00
expect(app.accessibilitySupportEnabled).to.eql(false);
2020-03-20 20:28:31 +00:00
app.accessibilitySupportEnabled = true;
expect(app.accessibilitySupportEnabled).to.eql(true);
});
});
it('with functions', () => {
it('can set accessibility support enabled', () => {
2020-03-20 20:28:31 +00:00
expect(app.isAccessibilitySupportEnabled()).to.eql(false);
2020-03-20 20:28:31 +00:00
app.setAccessibilitySupportEnabled(true);
expect(app.isAccessibilitySupportEnabled()).to.eql(true);
});
});
});
2016-10-06 16:57:25 +00:00
describe('getAppPath', () => {
it('works for directories with package.json', async () => {
2020-03-20 20:28:31 +00:00
const { appPath } = await runTestApp('app-path');
expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path'));
});
it('works for directories with index.js', async () => {
2020-03-20 20:28:31 +00:00
const { appPath } = await runTestApp('app-path/lib');
expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
});
it('works for files without extension', async () => {
2020-03-20 20:28:31 +00:00
const { appPath } = await runTestApp('app-path/lib/index');
expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
});
it('works for files', async () => {
2020-03-20 20:28:31 +00:00
const { appPath } = await runTestApp('app-path/lib/index.js');
expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
});
});
describe('getPath(name)', () => {
it('returns paths that exist', () => {
const paths = [
fs.existsSync(app.getPath('exe')),
fs.existsSync(app.getPath('home')),
fs.existsSync(app.getPath('temp'))
2020-03-20 20:28:31 +00:00
];
expect(paths).to.deep.equal([true, true, true]);
});
2016-10-06 16:57:25 +00:00
it('throws an error when the name is invalid', () => {
expect(() => {
2020-03-20 20:28:31 +00:00
app.getPath('does-not-exist' as any);
}).to.throw(/Failed to get 'does-not-exist' path/);
});
2016-10-06 16:57:25 +00:00
it('returns the overridden path', () => {
2020-03-20 20:28:31 +00:00
app.setPath('music', __dirname);
expect(app.getPath('music')).to.equal(__dirname);
});
if (process.platform === 'win32') {
it('gets the folder for recent files', () => {
const recent = app.getPath('recent');
// We expect that one of our test machines have overriden this
// to be something crazy, it'll always include the word "Recent"
// unless people have been registry-hacking like crazy
expect(recent).to.include('Recent');
});
it('can override the recent files path', () => {
app.setPath('recent', 'C:\\fake-path');
expect(app.getPath('recent')).to.equal('C:\\fake-path');
});
}
2020-03-20 20:28:31 +00:00
});
2016-12-02 17:34:16 +00:00
describe('setPath(name, path)', () => {
it('throws when a relative path is passed', () => {
2020-03-20 20:28:31 +00:00
const badPath = 'hey/hi/hello';
expect(() => {
2020-03-20 20:28:31 +00:00
app.setPath('music', badPath);
}).to.throw(/Path must be absolute/);
});
it('does not create a new directory by default', () => {
2020-03-20 20:28:31 +00:00
const badPath = path.join(__dirname, 'music');
2020-03-20 20:28:31 +00:00
expect(fs.existsSync(badPath)).to.be.false();
app.setPath('music', badPath);
expect(fs.existsSync(badPath)).to.be.false();
2020-03-20 20:28:31 +00:00
expect(() => { app.getPath(badPath as any); }).to.throw();
});
});
describe('setAppLogsPath(path)', () => {
it('throws when a relative path is passed', () => {
2020-03-20 20:28:31 +00:00
const badPath = 'hey/hi/hello';
expect(() => {
2020-03-20 20:28:31 +00:00
app.setAppLogsPath(badPath);
}).to.throw(/Path must be absolute/);
});
});
2017-10-23 07:54:38 +00:00
describe('select-client-certificate event', () => {
2020-03-20 20:28:31 +00:00
let w: BrowserWindow;
2016-12-02 17:34:16 +00:00
before(function () {
if (process.platform === 'linux') {
2020-03-20 20:28:31 +00:00
this.skip();
}
2020-03-20 20:28:31 +00:00
session.fromPartition('empty-certificate').setCertificateVerifyProc((req, cb) => { cb(0); });
});
beforeEach(() => {
2016-12-02 17:34:16 +00:00
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
2016-12-02 17:34:16 +00:00
partition: 'empty-certificate'
}
2020-03-20 20:28:31 +00:00
});
});
2016-12-02 17:34:16 +00:00
2020-03-20 20:28:31 +00:00
afterEach(() => closeWindow(w).then(() => { w = null as any; }));
2016-12-02 17:34:16 +00:00
2020-03-20 20:28:31 +00:00
after(() => session.fromPartition('empty-certificate').setCertificateVerifyProc(null));
it('can respond with empty certificate list', async () => {
app.once('select-client-certificate', function (event, webContents, url, list, callback) {
2020-03-20 20:28:31 +00:00
console.log('select-client-certificate emitted');
event.preventDefault();
callback();
});
await w.webContents.loadURL(secureUrl);
expect(w.webContents.getTitle()).to.equal('denied');
});
});
2017-02-02 16:11:34 +00:00
describe('setAsDefaultProtocolClient(protocol, path, args)', () => {
2020-03-20 20:28:31 +00:00
const protocol = 'electron-test';
const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
2017-02-02 16:11:34 +00:00
const processStartArgs = [
'--processStart', `"${path.basename(process.execPath)}"`,
'--process-start-args', '"--hidden"'
2020-03-20 20:28:31 +00:00
];
2017-02-02 16:11:34 +00:00
2020-03-20 20:28:31 +00:00
let Winreg: any;
let classesKey: any;
before(function () {
if (process.platform !== 'win32') {
2020-03-20 20:28:31 +00:00
this.skip();
} else {
2020-03-20 20:28:31 +00:00
Winreg = require('winreg');
classesKey = new Winreg({
hive: Winreg.HKCU,
key: '\\Software\\Classes\\'
2020-03-20 20:28:31 +00:00
});
}
2020-03-20 20:28:31 +00:00
});
after(function (done) {
if (process.platform !== 'win32') {
2020-03-20 20:28:31 +00:00
done();
} else {
const protocolKey = new Winreg({
hive: Winreg.HKCU,
key: `\\Software\\Classes\\${protocol}`
2020-03-20 20:28:31 +00:00
});
// The last test leaves the registry dirty,
// delete the protocol key for those of us who test at home
2020-03-20 20:28:31 +00:00
protocolKey.destroy(() => done());
2017-12-05 21:20:34 +00:00
}
2020-03-20 20:28:31 +00:00
});
2017-02-02 16:11:34 +00:00
beforeEach(() => {
2020-03-20 20:28:31 +00:00
app.removeAsDefaultProtocolClient(protocol);
app.removeAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
});
2017-02-02 16:11:34 +00:00
afterEach(() => {
2020-03-20 20:28:31 +00:00
app.removeAsDefaultProtocolClient(protocol);
expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
2020-03-20 20:28:31 +00:00
app.removeAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(false);
});
2017-02-02 16:11:34 +00:00
it('sets the app as the default protocol client', () => {
2020-03-20 20:28:31 +00:00
expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
app.setAsDefaultProtocolClient(protocol);
expect(app.isDefaultProtocolClient(protocol)).to.equal(true);
});
2017-02-02 16:11:34 +00:00
it('allows a custom path and args to be specified', () => {
2020-03-20 20:28:31 +00:00
expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(false);
app.setAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
2020-03-20 20:28:31 +00:00
expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(true);
expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
});
it('creates a registry entry for the protocol class', (done) => {
2020-03-20 20:28:31 +00:00
app.setAsDefaultProtocolClient(protocol);
2017-12-05 19:38:19 +00:00
classesKey.keys((error: Error, keys: any[]) => {
2020-03-20 20:28:31 +00:00
if (error) throw error;
2017-12-05 19:38:19 +00:00
2020-03-20 20:28:31 +00:00
const exists = !!keys.find(key => key.key.includes(protocol));
expect(exists).to.equal(true);
2020-03-20 20:28:31 +00:00
done();
});
});
it('completely removes a registry entry for the protocol class', (done) => {
2020-03-20 20:28:31 +00:00
app.setAsDefaultProtocolClient(protocol);
app.removeAsDefaultProtocolClient(protocol);
2017-12-05 19:38:19 +00:00
classesKey.keys((error: Error, keys: any[]) => {
2020-03-20 20:28:31 +00:00
if (error) throw error;
2017-12-05 19:38:19 +00:00
2020-03-20 20:28:31 +00:00
const exists = !!keys.find(key => key.key.includes(protocol));
expect(exists).to.equal(false);
2017-12-05 19:38:19 +00:00
2020-03-20 20:28:31 +00:00
done();
});
});
it('only unsets a class registry key if it contains other data', (done) => {
2020-03-20 20:28:31 +00:00
app.setAsDefaultProtocolClient(protocol);
const protocolKey = new Winreg({
hive: Winreg.HKCU,
key: `\\Software\\Classes\\${protocol}`
2020-03-20 20:28:31 +00:00
});
protocolKey.set('test-value', 'REG_BINARY', '123', () => {
2020-03-20 20:28:31 +00:00
app.removeAsDefaultProtocolClient(protocol);
classesKey.keys((error: Error, keys: any[]) => {
2020-03-20 20:28:31 +00:00
if (error) throw error;
2017-12-05 19:38:19 +00:00
2020-03-20 20:28:31 +00:00
const exists = !!keys.find(key => key.key.includes(protocol));
expect(exists).to.equal(true);
2017-12-05 19:38:19 +00:00
2020-03-20 20:28:31 +00:00
done();
});
});
});
it('sets the default client such that getApplicationNameForProtocol returns Electron', () => {
2020-03-20 20:28:31 +00:00
app.setAsDefaultProtocolClient(protocol);
expect(app.getApplicationNameForProtocol(`${protocol}://`)).to.equal('Electron');
});
});
describe('getApplicationNameForProtocol()', () => {
it('returns application names for common protocols', function () {
// We can't expect particular app names here, but these protocols should
// at least have _something_ registered. Except on our Linux CI
// environment apparently.
if (process.platform === 'linux') {
2020-03-20 20:28:31 +00:00
this.skip();
}
const protocols = [
'http://',
'https://'
2020-03-20 20:28:31 +00:00
];
protocols.forEach((protocol) => {
2020-03-20 20:28:31 +00:00
expect(app.getApplicationNameForProtocol(protocol)).to.not.equal('');
});
});
it('returns an empty string for a bogus protocol', () => {
2020-03-20 20:28:31 +00:00
expect(app.getApplicationNameForProtocol('bogus-protocol://')).to.equal('');
});
});
describe('isDefaultProtocolClient()', () => {
it('returns false for a bogus protocol', () => {
2020-03-20 20:28:31 +00:00
expect(app.isDefaultProtocolClient('bogus-protocol://')).to.equal(false);
});
});
2016-11-06 10:59:17 +00:00
describe('app launch through uri', () => {
before(function () {
if (process.platform !== 'win32') {
2020-03-20 20:28:31 +00:00
this.skip();
}
2020-03-20 20:28:31 +00:00
});
it('does not launch for argument following a URL', done => {
2020-03-20 20:28:31 +00:00
const appPath = path.join(fixturesPath, 'api', 'quit-app');
// App should exit with non 123 code.
2020-03-20 20:28:31 +00:00
const first = cp.spawn(process.execPath, [appPath, 'electron-test:?', 'abc']);
first.once('exit', code => {
2020-03-20 20:28:31 +00:00
expect(code).to.not.equal(123);
done();
});
});
it('launches successfully for argument following a file path', done => {
2020-03-20 20:28:31 +00:00
const appPath = path.join(fixturesPath, 'api', 'quit-app');
// App should exit with code 123.
2020-03-20 20:28:31 +00:00
const first = cp.spawn(process.execPath, [appPath, 'e:\\abc', 'abc']);
first.once('exit', code => {
2020-03-20 20:28:31 +00:00
expect(code).to.equal(123);
done();
});
});
it('launches successfully for multiple URIs following --', done => {
2020-03-20 20:28:31 +00:00
const appPath = path.join(fixturesPath, 'api', 'quit-app');
// App should exit with code 123.
2020-03-20 20:28:31 +00:00
const first = cp.spawn(process.execPath, [appPath, '--', 'http://electronjs.org', 'electron-test://testdata']);
first.once('exit', code => {
2020-03-20 20:28:31 +00:00
expect(code).to.equal(123);
done();
});
});
});
2019-10-30 23:38:21 +00:00
// FIXME Get these specs running on Linux CI
ifdescribe(process.platform !== 'linux')('getFileIcon() API', () => {
2020-03-20 20:28:31 +00:00
const iconPath = path.join(__dirname, 'fixtures/assets/icon.ico');
2016-11-06 10:59:17 +00:00
const sizes = {
small: 16,
normal: 32,
2017-02-07 19:20:27 +00:00
large: process.platform === 'win32' ? 32 : 48
2020-03-20 20:28:31 +00:00
};
2016-11-06 10:59:17 +00:00
it('fetches a non-empty icon', async () => {
2020-03-20 20:28:31 +00:00
const icon = await app.getFileIcon(iconPath);
expect(icon.isEmpty()).to.equal(false);
});
2016-11-06 10:59:17 +00:00
it('fetches normal icon size by default', async () => {
2020-03-20 20:28:31 +00:00
const icon = await app.getFileIcon(iconPath);
const size = icon.getSize();
2020-03-20 20:28:31 +00:00
expect(size.height).to.equal(sizes.normal);
expect(size.width).to.equal(sizes.normal);
});
2016-11-06 10:59:17 +00:00
describe('size option', () => {
it('fetches a small icon', async () => {
2020-03-20 20:28:31 +00:00
const icon = await app.getFileIcon(iconPath, { size: 'small' });
const size = icon.getSize();
2020-03-20 20:28:31 +00:00
expect(size.height).to.equal(sizes.small);
expect(size.width).to.equal(sizes.small);
});
2016-11-06 10:59:17 +00:00
it('fetches a normal icon', async () => {
2020-03-20 20:28:31 +00:00
const icon = await app.getFileIcon(iconPath, { size: 'normal' });
const size = icon.getSize();
2020-03-20 20:28:31 +00:00
expect(size.height).to.equal(sizes.normal);
expect(size.width).to.equal(sizes.normal);
});
2016-11-06 10:59:17 +00:00
it('fetches a large icon', async () => {
2017-02-07 18:16:09 +00:00
// macOS does not support large icons
2020-03-20 20:28:31 +00:00
if (process.platform === 'darwin') return;
2017-02-07 18:16:09 +00:00
2020-03-20 20:28:31 +00:00
const icon = await app.getFileIcon(iconPath, { size: 'large' });
const size = icon.getSize();
2020-03-20 20:28:31 +00:00
expect(size.height).to.equal(sizes.large);
expect(size.width).to.equal(sizes.large);
});
});
});
describe('getAppMetrics() API', () => {
2018-06-18 04:00:17 +00:00
it('returns memory and cpu stats of all running electron processes', () => {
2020-03-20 20:28:31 +00:00
const appMetrics = app.getAppMetrics();
expect(appMetrics).to.be.an('array').and.have.lengthOf.at.least(1, 'App memory info object is not > 0');
2020-03-20 20:28:31 +00:00
const types = [];
for (const entry of appMetrics) {
2020-03-20 20:28:31 +00:00
expect(entry.pid).to.be.above(0, 'pid is not > 0');
expect(entry.type).to.be.a('string').that.does.not.equal('');
expect(entry.creationTime).to.be.a('number').that.is.greaterThan(0);
2020-03-20 20:28:31 +00:00
types.push(entry.type);
expect(entry.cpu).to.have.ownProperty('percentCPUUsage').that.is.a('number');
expect(entry.cpu).to.have.ownProperty('idleWakeupsPerSecond').that.is.a('number');
2020-03-20 20:28:31 +00:00
expect(entry.memory).to.have.property('workingSetSize').that.is.greaterThan(0);
expect(entry.memory).to.have.property('peakWorkingSetSize').that.is.greaterThan(0);
if (process.platform === 'win32') {
2020-03-20 20:28:31 +00:00
expect(entry.memory).to.have.property('privateBytes').that.is.greaterThan(0);
}
if (process.platform !== 'linux') {
2020-03-20 20:28:31 +00:00
expect(entry.sandboxed).to.be.a('boolean');
}
if (process.platform === 'win32') {
2020-03-20 20:28:31 +00:00
expect(entry.integrityLevel).to.be.a('string');
}
}
2017-05-26 15:53:26 +00:00
2017-05-26 17:10:56 +00:00
if (process.platform === 'darwin') {
2020-03-20 20:28:31 +00:00
expect(types).to.include('GPU');
2017-05-26 16:14:17 +00:00
}
2020-03-20 20:28:31 +00:00
expect(types).to.include('Browser');
});
});
2017-05-30 20:00:00 +00:00
describe('getGPUFeatureStatus() API', () => {
it('returns the graphic features statuses', () => {
2020-03-20 20:28:31 +00:00
const features = app.getGPUFeatureStatus();
expect(features).to.have.ownProperty('webgl').that.is.a('string');
expect(features).to.have.ownProperty('gpu_compositing').that.is.a('string');
});
});
2017-06-28 15:33:06 +00:00
describe('getGPUInfo() API', () => {
2020-03-20 20:28:31 +00:00
const appPath = path.join(fixturesPath, 'api', 'gpu-info.js');
const getGPUInfo = async (type: string) => {
2020-03-20 20:28:31 +00:00
const appProcess = cp.spawn(process.execPath, [appPath, type]);
let gpuInfoData = '';
let errorData = '';
appProcess.stdout.on('data', (data) => {
2020-03-20 20:28:31 +00:00
gpuInfoData += data;
});
appProcess.stderr.on('data', (data) => {
2020-03-20 20:28:31 +00:00
errorData += data;
});
const [exitCode] = await emittedOnce(appProcess, 'exit');
if (exitCode === 0) {
// return info data on successful exit
2020-03-20 20:28:31 +00:00
return JSON.parse(gpuInfoData);
} else {
// return error if not clean exit
2020-03-20 20:28:31 +00:00
return Promise.reject(new Error(errorData));
}
2020-03-20 20:28:31 +00:00
};
const verifyBasicGPUInfo = async (gpuInfo: any) => {
// Devices information is always present in the available info.
expect(gpuInfo).to.have.ownProperty('gpuDevice')
.that.is.an('array')
2020-03-20 20:28:31 +00:00
.and.does.not.equal([]);
2020-03-20 20:28:31 +00:00
const device = gpuInfo.gpuDevice[0];
expect(device).to.be.an('object')
.and.to.have.property('deviceId')
.that.is.a('number')
2020-03-20 20:28:31 +00:00
.not.lessThan(0);
};
it('succeeds with basic GPUInfo', async () => {
2020-03-20 20:28:31 +00:00
const gpuInfo = await getGPUInfo('basic');
await verifyBasicGPUInfo(gpuInfo);
});
it('succeeds with complete GPUInfo', async () => {
2020-03-20 20:28:31 +00:00
const completeInfo = await getGPUInfo('complete');
if (process.platform === 'linux') {
// For linux and macOS complete info is same as basic info
2020-03-20 20:28:31 +00:00
await verifyBasicGPUInfo(completeInfo);
const basicInfo = await getGPUInfo('basic');
expect(completeInfo).to.deep.equal(basicInfo);
} else {
// Gl version is present in the complete info.
expect(completeInfo).to.have.ownProperty('auxAttributes')
2020-03-20 20:28:31 +00:00
.that.is.an('object');
if (completeInfo.gpuDevice.active) {
expect(completeInfo.auxAttributes).to.have.ownProperty('glVersion')
.that.is.a('string')
2020-03-20 20:28:31 +00:00
.and.does.not.equal([]);
}
}
2020-03-20 20:28:31 +00:00
});
it('fails for invalid info_type', () => {
2020-03-20 20:28:31 +00:00
const invalidType = 'invalid';
const expectedErrorMessage = "Invalid info type. Use 'basic' or 'complete'";
return expect(app.getGPUInfo(invalidType as any)).to.eventually.be.rejectedWith(expectedErrorMessage);
});
});
2018-10-10 04:32:09 +00:00
describe('sandbox options', () => {
2020-03-20 20:28:31 +00:00
let appProcess: cp.ChildProcess = null as any;
let server: net.Server = null as any;
const socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\electron-mixed-sandbox' : '/tmp/electron-mixed-sandbox';
2017-06-28 15:33:06 +00:00
beforeEach(function (done) {
if (process.platform === 'linux' && (process.arch === 'arm64' || process.arch === 'arm')) {
// Our ARM tests are run on VSTS rather than CircleCI, and the Docker
// setup on VSTS disallows syscalls that Chrome requires for setting up
// sandboxing.
// See:
// - https://docs.docker.com/engine/security/seccomp/#significant-syscalls-blocked-by-the-default-profile
// - https://chromium.googlesource.com/chromium/src/+/70.0.3538.124/sandbox/linux/services/credentials.cc#292
// - https://github.com/docker/docker-ce/blob/ba7dfc59ccfe97c79ee0d1379894b35417b40bca/components/engine/profiles/seccomp/seccomp_default.go#L497
// - https://blog.jessfraz.com/post/how-to-use-new-docker-seccomp-profiles/
//
// Adding `--cap-add SYS_ADMIN` or `--security-opt seccomp=unconfined`
// to the Docker invocation allows the syscalls that Chrome needs, but
// are probably more permissive than we'd like.
2020-03-20 20:28:31 +00:00
this.skip();
}
fs.unlink(socketPath, () => {
2020-03-20 20:28:31 +00:00
server = net.createServer();
server.listen(socketPath);
done();
});
});
afterEach(done => {
2020-03-20 20:28:31 +00:00
if (appProcess != null) appProcess.kill();
server.close(() => {
if (process.platform === 'win32') {
2020-03-20 20:28:31 +00:00
done();
} else {
2020-03-20 20:28:31 +00:00
fs.unlink(socketPath, () => done());
}
2020-03-20 20:28:31 +00:00
});
});
2017-06-28 15:33:06 +00:00
2018-10-10 04:32:09 +00:00
describe('when app.enableSandbox() is called', () => {
it('adds --enable-sandbox to all renderer processes', done => {
2020-03-20 20:28:31 +00:00
const appPath = path.join(fixturesPath, 'api', 'mixed-sandbox-app');
appProcess = cp.spawn(process.execPath, [appPath, '--app-enable-sandbox']);
2018-10-10 04:32:09 +00:00
2020-03-20 20:28:31 +00:00
server.once('error', error => { done(error); });
2018-10-10 04:32:09 +00:00
server.on('connection', client => {
client.once('data', (data) => {
2020-03-20 20:28:31 +00:00
const argv = JSON.parse(data.toString());
expect(argv.sandbox).to.include('--enable-sandbox');
expect(argv.sandbox).to.not.include('--no-sandbox');
2018-10-10 04:32:09 +00:00
2020-03-20 20:28:31 +00:00
expect(argv.noSandbox).to.include('--enable-sandbox');
expect(argv.noSandbox).to.not.include('--no-sandbox');
2018-10-10 04:32:09 +00:00
2020-03-20 20:28:31 +00:00
expect(argv.noSandboxDevtools).to.equal(true);
expect(argv.sandboxDevtools).to.equal(true);
2018-10-10 04:32:09 +00:00
2020-03-20 20:28:31 +00:00
done();
});
});
});
});
2018-10-10 04:32:09 +00:00
describe('when the app is launched with --enable-sandbox', () => {
it('adds --enable-sandbox to all renderer processes', done => {
2020-03-20 20:28:31 +00:00
const appPath = path.join(fixturesPath, 'api', 'mixed-sandbox-app');
appProcess = cp.spawn(process.execPath, [appPath, '--enable-sandbox']);
2018-10-10 04:32:09 +00:00
2020-03-20 20:28:31 +00:00
server.once('error', error => { done(error); });
2018-10-10 04:32:09 +00:00
server.on('connection', client => {
client.once('data', data => {
2020-03-20 20:28:31 +00:00
const argv = JSON.parse(data.toString());
expect(argv.sandbox).to.include('--enable-sandbox');
expect(argv.sandbox).to.not.include('--no-sandbox');
2018-10-10 04:32:09 +00:00
2020-03-20 20:28:31 +00:00
expect(argv.noSandbox).to.include('--enable-sandbox');
expect(argv.noSandbox).to.not.include('--no-sandbox');
2018-10-10 04:32:09 +00:00
2020-03-20 20:28:31 +00:00
expect(argv.noSandboxDevtools).to.equal(true);
expect(argv.sandboxDevtools).to.equal(true);
2018-10-10 04:32:09 +00:00
2020-03-20 20:28:31 +00:00
done();
});
});
});
});
});
describe('disableDomainBlockingFor3DAPIs() API', () => {
it('throws when called after app is ready', () => {
expect(() => {
2020-03-20 20:28:31 +00:00
app.disableDomainBlockingFor3DAPIs();
}).to.throw(/before app is ready/);
});
});
2020-03-20 20:28:31 +00:00
const dockDescribe = process.platform === 'darwin' ? describe : describe.skip;
dockDescribe('dock APIs', () => {
after(async () => {
2020-03-20 20:28:31 +00:00
await app.dock.show();
});
describe('dock.setMenu', () => {
it('can be retrieved via dock.getMenu', () => {
2020-03-20 20:28:31 +00:00
expect(app.dock.getMenu()).to.equal(null);
const menu = new Menu();
app.dock.setMenu(menu);
expect(app.dock.getMenu()).to.equal(menu);
});
it('keeps references to the menu', () => {
2020-03-20 20:28:31 +00:00
app.dock.setMenu(new Menu());
const v8Util = process.electronBinding('v8_util');
v8Util.requestGarbageCollectionForTesting();
});
});
describe('dock.bounce', () => {
it('should return -1 for unknown bounce type', () => {
2020-03-20 20:28:31 +00:00
expect(app.dock.bounce('bad type' as any)).to.equal(-1);
});
it('should return a positive number for informational type', () => {
2020-03-20 20:28:31 +00:00
const appHasFocus = !!BrowserWindow.getFocusedWindow();
if (!appHasFocus) {
2020-03-20 20:28:31 +00:00
expect(app.dock.bounce('informational')).to.be.at.least(0);
}
2020-03-20 20:28:31 +00:00
});
it('should return a positive number for critical type', () => {
2020-03-20 20:28:31 +00:00
const appHasFocus = !!BrowserWindow.getFocusedWindow();
if (!appHasFocus) {
2020-03-20 20:28:31 +00:00
expect(app.dock.bounce('critical')).to.be.at.least(0);
}
2020-03-20 20:28:31 +00:00
});
});
describe('dock.cancelBounce', () => {
it('should not throw', () => {
2020-03-20 20:28:31 +00:00
app.dock.cancelBounce(app.dock.bounce('critical'));
});
});
describe('dock.setBadge', () => {
after(() => {
2020-03-20 20:28:31 +00:00
app.dock.setBadge('');
});
it('should not throw', () => {
2020-03-20 20:28:31 +00:00
app.dock.setBadge('1');
});
it('should be retrievable via getBadge', () => {
2020-03-20 20:28:31 +00:00
app.dock.setBadge('test');
expect(app.dock.getBadge()).to.equal('test');
});
});
describe('dock.show', () => {
it('should not throw', () => {
return app.dock.show().then(() => {
2020-03-20 20:28:31 +00:00
expect(app.dock.isVisible()).to.equal(true);
});
});
it('returns a Promise', () => {
2020-03-20 20:28:31 +00:00
expect(app.dock.show()).to.be.a('promise');
});
it('eventually fulfills', async () => {
2020-03-20 20:28:31 +00:00
await expect(app.dock.show()).to.eventually.be.fulfilled.equal(undefined);
});
});
describe('dock.hide', () => {
it('should not throw', () => {
2020-03-20 20:28:31 +00:00
app.dock.hide();
expect(app.dock.isVisible()).to.equal(false);
});
});
});
describe('whenReady', () => {
it('returns a Promise', () => {
2020-03-20 20:28:31 +00:00
expect(app.whenReady()).to.be.a('promise');
});
2019-03-15 00:22:42 +00:00
it('becomes fulfilled if the app is already ready', async () => {
2020-03-20 20:28:31 +00:00
expect(app.isReady()).to.equal(true);
await expect(app.whenReady()).to.be.eventually.fulfilled.equal(undefined);
});
});
describe('app.applicationMenu', () => {
it('has the applicationMenu property', () => {
2020-03-20 20:28:31 +00:00
expect(app).to.have.property('applicationMenu');
});
});
describe('commandLine.hasSwitch', () => {
it('returns true when present', () => {
2020-03-20 20:28:31 +00:00
app.commandLine.appendSwitch('foobar1');
expect(app.commandLine.hasSwitch('foobar1')).to.equal(true);
});
it('returns false when not present', () => {
2020-03-20 20:28:31 +00:00
expect(app.commandLine.hasSwitch('foobar2')).to.equal(false);
});
});
describe('commandLine.hasSwitch (existing argv)', () => {
it('returns true when present', async () => {
2020-03-20 20:28:31 +00:00
const { hasSwitch } = await runTestApp('command-line', '--foobar');
expect(hasSwitch).to.equal(true);
});
it('returns false when not present', async () => {
2020-03-20 20:28:31 +00:00
const { hasSwitch } = await runTestApp('command-line');
expect(hasSwitch).to.equal(false);
});
});
describe('commandLine.getSwitchValue', () => {
it('returns the value when present', () => {
2020-03-20 20:28:31 +00:00
app.commandLine.appendSwitch('foobar', 'æøåü');
expect(app.commandLine.getSwitchValue('foobar')).to.equal('æøåü');
});
it('returns an empty string when present without value', () => {
2020-03-20 20:28:31 +00:00
app.commandLine.appendSwitch('foobar1');
expect(app.commandLine.getSwitchValue('foobar1')).to.equal('');
});
it('returns an empty string when not present', () => {
2020-03-20 20:28:31 +00:00
expect(app.commandLine.getSwitchValue('foobar2')).to.equal('');
});
});
describe('commandLine.getSwitchValue (existing argv)', () => {
it('returns the value when present', async () => {
2020-03-20 20:28:31 +00:00
const { getSwitchValue } = await runTestApp('command-line', '--foobar=test');
expect(getSwitchValue).to.equal('test');
});
it('returns an empty string when present without value', async () => {
2020-03-20 20:28:31 +00:00
const { getSwitchValue } = await runTestApp('command-line', '--foobar');
expect(getSwitchValue).to.equal('');
});
it('returns an empty string when not present', async () => {
2020-03-20 20:28:31 +00:00
const { getSwitchValue } = await runTestApp('command-line');
expect(getSwitchValue).to.equal('');
});
});
});
describe('default behavior', () => {
describe('application menu', () => {
it('creates the default menu if the app does not set it', async () => {
2020-03-20 20:28:31 +00:00
const result = await runTestApp('default-menu');
expect(result).to.equal(false);
});
it('does not create the default menu if the app sets a custom menu', async () => {
2020-03-20 20:28:31 +00:00
const result = await runTestApp('default-menu', '--custom-menu');
expect(result).to.equal(true);
});
it('does not create the default menu if the app sets a null menu', async () => {
2020-03-20 20:28:31 +00:00
const result = await runTestApp('default-menu', '--null-menu');
expect(result).to.equal(true);
});
});
describe('window-all-closed', () => {
it('quits when the app does not handle the event', async () => {
2020-03-20 20:28:31 +00:00
const result = await runTestApp('window-all-closed');
expect(result).to.equal(false);
});
it('does not quit when the app handles the event', async () => {
2020-03-20 20:28:31 +00:00
const result = await runTestApp('window-all-closed', '--handle-event');
expect(result).to.equal(true);
});
});
describe('user agent fallback', () => {
2020-03-20 20:28:31 +00:00
let initialValue: string;
before(() => {
2020-03-20 20:28:31 +00:00
initialValue = app.userAgentFallback!;
});
it('should have a reasonable default', () => {
2020-03-20 20:28:31 +00:00
expect(initialValue).to.include(`Electron/${process.versions.electron}`);
expect(initialValue).to.include(`Chrome/${process.versions.chrome}`);
});
it('should be overridable', () => {
2020-03-20 20:28:31 +00:00
app.userAgentFallback = 'test-agent/123';
expect(app.userAgentFallback).to.equal('test-agent/123');
});
it('should be restorable', () => {
2020-03-20 20:28:31 +00:00
app.userAgentFallback = 'test-agent/123';
app.userAgentFallback = '';
expect(app.userAgentFallback).to.equal(initialValue);
});
});
describe('app.allowRendererProcessReuse', () => {
it('should default to true', () => {
2020-03-20 20:28:31 +00:00
expect(app.allowRendererProcessReuse).to.equal(true);
});
it('should cause renderer processes to get new PIDs when false', async () => {
2020-03-20 20:28:31 +00:00
const output = await runTestApp('site-instance-overrides', 'false');
expect(output[0]).to.be.a('number').that.is.greaterThan(0);
expect(output[1]).to.be.a('number').that.is.greaterThan(0);
expect(output[0]).to.not.equal(output[1]);
});
it('should cause renderer processes to keep the same PID when true', async () => {
2020-03-20 20:28:31 +00:00
const output = await runTestApp('site-instance-overrides', 'true');
expect(output[0]).to.be.a('number').that.is.greaterThan(0);
expect(output[1]).to.be.a('number').that.is.greaterThan(0);
expect(output[0]).to.equal(output[1]);
});
});
describe('login event', () => {
2020-03-20 20:28:31 +00:00
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
before((done) => {
server = http.createServer((request, response) => {
if (request.headers.authorization) {
2020-03-20 20:28:31 +00:00
return response.end('ok');
}
response
.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
2020-03-20 20:28:31 +00:00
.end();
}).listen(0, '127.0.0.1', () => {
2020-03-20 20:28:31 +00:00
serverUrl = 'http://127.0.0.1:' + (server.address() as net.AddressInfo).port;
done();
});
});
it('should emit a login event on app when a WebContents hits a 401', async () => {
2020-03-20 20:28:31 +00:00
const w = new BrowserWindow({ show: false });
w.loadURL(serverUrl);
const [, webContents] = await emittedOnce(app, 'login');
expect(webContents).to.equal(w.webContents);
});
});
});
async function runTestApp (name: string, ...args: any[]) {
2020-03-20 20:28:31 +00:00
const appPath = path.join(fixturesPath, 'api', name);
const electronPath = process.execPath;
const appProcess = cp.spawn(electronPath, [appPath, ...args]);
2020-03-20 20:28:31 +00:00
let output = '';
appProcess.stdout.on('data', (data) => { output += data; });
2020-03-20 20:28:31 +00:00
await emittedOnce(appProcess.stdout, 'end');
2020-03-20 20:28:31 +00:00
return JSON.parse(output);
}