test: migrate node specs to main (#35212)

This commit is contained in:
Jeremy Rose 2022-08-04 17:20:17 -07:00 коммит произвёл GitHub
Родитель b9fea0d2d2
Коммит 4cfdef0ffd
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
5 изменённых файлов: 517 добавлений и 482 удалений

Просмотреть файл

@ -4,14 +4,16 @@ import * as fs from 'fs';
import * as path from 'path';
import * as util from 'util';
import { emittedOnce } from './events-helpers';
import { ifdescribe, ifit } from './spec-helpers';
import { getRemoteContext, ifdescribe, ifit, itremote, useRemoteContext } from './spec-helpers';
import { webContents, WebContents } from 'electron/main';
import { EventEmitter } from 'stream';
const features = process._linkedBinding('electron_common_features');
const mainFixturesPath = path.resolve(__dirname, 'fixtures');
describe('node feature', () => {
const fixtures = path.join(__dirname, '..', 'spec', 'fixtures');
describe('child_process', () => {
describe('child_process.fork', () => {
it('Works in browser process', async () => {
@ -24,6 +26,132 @@ describe('node feature', () => {
});
});
ifdescribe(features.isRunAsNodeEnabled())('child_process in renderer', () => {
useRemoteContext();
describe('child_process.fork', () => {
itremote('works in current process', async (fixtures: string) => {
const child = require('child_process').fork(require('path').join(fixtures, 'module', 'ping.js'));
const message = new Promise<any>(resolve => child.once('message', resolve));
child.send('message');
const msg = await message;
expect(msg).to.equal('message');
}, [fixtures]);
itremote('preserves args', async (fixtures: string) => {
const args = ['--expose_gc', '-test', '1'];
const child = require('child_process').fork(require('path').join(fixtures, 'module', 'process_args.js'), args);
const message = new Promise<any>(resolve => child.once('message', resolve));
child.send('message');
const msg = await message;
expect(args).to.deep.equal(msg.slice(2));
}, [fixtures]);
itremote('works in forked process', async (fixtures: string) => {
const child = require('child_process').fork(require('path').join(fixtures, 'module', 'fork_ping.js'));
const message = new Promise<any>(resolve => child.once('message', resolve));
child.send('message');
const msg = await message;
expect(msg).to.equal('message');
}, [fixtures]);
itremote('works in forked process when options.env is specified', async (fixtures: string) => {
const child = require('child_process').fork(require('path').join(fixtures, 'module', 'fork_ping.js'), [], {
path: process.env.PATH
});
const message = new Promise<any>(resolve => child.once('message', resolve));
child.send('message');
const msg = await message;
expect(msg).to.equal('message');
}, [fixtures]);
itremote('has String::localeCompare working in script', async (fixtures: string) => {
const child = require('child_process').fork(require('path').join(fixtures, 'module', 'locale-compare.js'));
const message = new Promise<any>(resolve => child.once('message', resolve));
child.send('message');
const msg = await message;
expect(msg).to.deep.equal([0, -1, 1]);
}, [fixtures]);
itremote('has setImmediate working in script', async (fixtures: string) => {
const child = require('child_process').fork(require('path').join(fixtures, 'module', 'set-immediate.js'));
const message = new Promise<any>(resolve => child.once('message', resolve));
child.send('message');
const msg = await message;
expect(msg).to.equal('ok');
}, [fixtures]);
itremote('pipes stdio', async (fixtures: string) => {
const child = require('child_process').fork(require('path').join(fixtures, 'module', 'process-stdout.js'), { silent: true });
let data = '';
child.stdout.on('data', (chunk: any) => {
data += String(chunk);
});
const code = await new Promise<any>(resolve => child.once('close', resolve));
expect(code).to.equal(0);
expect(data).to.equal('pipes stdio');
}, [fixtures]);
itremote('works when sending a message to a process forked with the --eval argument', async () => {
const source = "process.on('message', (message) => { process.send(message) })";
const forked = require('child_process').fork('--eval', [source]);
const message = new Promise(resolve => forked.once('message', resolve));
forked.send('hello');
const msg = await message;
expect(msg).to.equal('hello');
});
it('has the electron version in process.versions', async () => {
const source = 'process.send(process.versions)';
const forked = require('child_process').fork('--eval', [source]);
const message = await new Promise(resolve => forked.once('message', resolve));
expect(message)
.to.have.own.property('electron')
.that.is.a('string')
.and.matches(/^\d+\.\d+\.\d+(\S*)?$/);
});
});
describe('child_process.spawn', () => {
itremote('supports spawning Electron as a node process via the ELECTRON_RUN_AS_NODE env var', async (fixtures: string) => {
const child = require('child_process').spawn(process.execPath, [require('path').join(fixtures, 'module', 'run-as-node.js')], {
env: {
ELECTRON_RUN_AS_NODE: true
}
});
let output = '';
child.stdout.on('data', (data: any) => {
output += data;
});
try {
await new Promise(resolve => child.stdout.once('close', resolve));
expect(JSON.parse(output)).to.deep.equal({
stdoutType: 'pipe',
processType: 'undefined',
window: 'undefined'
});
} finally {
child.kill();
}
}, [fixtures]);
});
describe('child_process.exec', () => {
ifit(process.platform === 'linux')('allows executing a setuid binary from non-sandboxed renderer', async () => {
// Chrome uses prctl(2) to set the NO_NEW_PRIVILEGES flag on Linux (see
// https://github.com/torvalds/linux/blob/40fde647cc/Documentation/userspace-api/no_new_privs.rst).
// We disable this for unsandboxed processes, which the renderer tests
// are running in. If this test fails with an error like 'effective uid
// is not 0', then it's likely that our patch to prevent the flag from
// being set has become ineffective.
const w = await getRemoteContext();
const stdout = await w.webContents.executeJavaScript('require(\'child_process\').execSync(\'sudo --help\')');
expect(stdout).to.not.be.empty();
});
});
});
it('does not hang when using the fs module in the renderer process', async () => {
const appPath = path.join(mainFixturesPath, 'apps', 'libuv-hang', 'main.js');
const appProcess = childProcess.spawn(process.execPath, [appPath], {
@ -62,6 +190,344 @@ describe('node feature', () => {
interval = setInterval(clear, 10);
});
});
const suspendListeners = (emitter: EventEmitter, eventName: string, callback: (...args: any[]) => void) => {
const listeners = emitter.listeners(eventName) as ((...args: any[]) => void)[];
emitter.removeAllListeners(eventName);
emitter.once(eventName, (...args) => {
emitter.removeAllListeners(eventName);
listeners.forEach((listener) => {
emitter.on(eventName, listener);
});
// eslint-disable-next-line standard/no-callback-literal
callback(...args);
});
};
describe('error thrown in main process node context', () => {
it('gets emitted as a process uncaughtException event', async () => {
fs.readFile(__filename, () => {
throw new Error('hello');
});
const result = await new Promise(resolve => suspendListeners(process, 'uncaughtException', (error) => {
resolve(error.message);
}));
expect(result).to.equal('hello');
});
});
describe('promise rejection in main process node context', () => {
it('gets emitted as a process unhandledRejection event', async () => {
fs.readFile(__filename, () => {
Promise.reject(new Error('hello'));
});
const result = await new Promise(resolve => suspendListeners(process, 'unhandledRejection', (error) => {
resolve(error.message);
}));
expect(result).to.equal('hello');
});
});
});
describe('contexts in renderer', () => {
useRemoteContext();
describe('setTimeout in fs callback', () => {
itremote('does not crash', async (filename: string) => {
await new Promise(resolve => require('fs').readFile(filename, () => {
setTimeout(resolve, 0);
}));
}, [__filename]);
});
describe('error thrown in renderer process node context', () => {
itremote('gets emitted as a process uncaughtException event', async (filename: string) => {
const error = new Error('boo!');
require('fs').readFile(filename, () => {
throw error;
});
await new Promise<void>((resolve, reject) => {
process.once('uncaughtException', (thrown) => {
try {
expect(thrown).to.equal(error);
resolve();
} catch (e) {
reject(e);
}
});
});
}, [__filename]);
});
describe('URL handling in the renderer process', () => {
itremote('can successfully handle WHATWG URLs constructed by Blink', (fixtures: string) => {
const url = new URL('file://' + require('path').resolve(fixtures, 'pages', 'base-page.html'));
expect(() => {
require('fs').createReadStream(url);
}).to.not.throw();
}, [fixtures]);
});
describe('setTimeout called under blink env in renderer process', () => {
itremote('can be scheduled in time', async () => {
await new Promise(resolve => setTimeout(resolve, 10));
});
itremote('works from the timers module', async () => {
await new Promise(resolve => require('timers').setTimeout(resolve, 10));
});
});
describe('setInterval called under blink env in renderer process', () => {
itremote('can be scheduled in time', async () => {
await new Promise<void>(resolve => {
const id = setInterval(() => {
clearInterval(id);
resolve();
}, 10);
});
});
itremote('can be scheduled in time from timers module', async () => {
const { setInterval, clearInterval } = require('timers');
await new Promise<void>(resolve => {
const id = setInterval(() => {
clearInterval(id);
resolve();
}, 10);
});
});
});
});
describe('message loop in renderer', () => {
useRemoteContext();
describe('process.nextTick', () => {
itremote('emits the callback', () => new Promise(resolve => process.nextTick(resolve)));
itremote('works in nested calls', () =>
new Promise(resolve => {
process.nextTick(() => {
process.nextTick(() => process.nextTick(resolve));
});
}));
});
describe('setImmediate', () => {
itremote('emits the callback', () => new Promise(resolve => setImmediate(resolve)));
itremote('works in nested calls', () => new Promise(resolve => {
setImmediate(() => {
setImmediate(() => setImmediate(resolve));
});
}));
});
});
ifdescribe(features.isRunAsNodeEnabled() && process.platform === 'darwin')('net.connect', () => {
itremote('emit error when connect to a socket path without listeners', async (fixtures: string) => {
const socketPath = require('path').join(require('os').tmpdir(), 'electron-test.sock');
const script = require('path').join(fixtures, 'module', 'create_socket.js');
const child = require('child_process').fork(script, [socketPath]);
const code = await new Promise(resolve => child.once('exit', resolve));
expect(code).to.equal(0);
const client = require('net').connect(socketPath);
const error = await new Promise<any>(resolve => client.once('error', resolve));
expect(error.code).to.equal('ECONNREFUSED');
}, [fixtures]);
});
describe('Buffer', () => {
useRemoteContext();
itremote('can be created from WebKit external string', () => {
const p = document.createElement('p');
p.innerText = '闲云潭影日悠悠,物换星移几度秋';
const b = Buffer.from(p.innerText);
expect(b.toString()).to.equal('闲云潭影日悠悠,物换星移几度秋');
expect(Buffer.byteLength(p.innerText)).to.equal(45);
});
itremote('correctly parses external one-byte UTF8 string', () => {
const p = document.createElement('p');
p.innerText = 'Jøhänñéß';
const b = Buffer.from(p.innerText);
expect(b.toString()).to.equal('Jøhänñéß');
expect(Buffer.byteLength(p.innerText)).to.equal(13);
});
itremote('does not crash when creating large Buffers', () => {
let buffer = Buffer.from(new Array(4096).join(' '));
expect(buffer.length).to.equal(4095);
buffer = Buffer.from(new Array(4097).join(' '));
expect(buffer.length).to.equal(4096);
});
itremote('does not crash for crypto operations', () => {
const crypto = require('crypto');
const data = 'lG9E+/g4JmRmedDAnihtBD4Dfaha/GFOjd+xUOQI05UtfVX3DjUXvrS98p7kZQwY3LNhdiFo7MY5rGft8yBuDhKuNNag9vRx/44IuClDhdQ=';
const key = 'q90K9yBqhWZnAMCMTOJfPQ==';
const cipherText = '{"error_code":114,"error_message":"Tham số không hợp lệ","data":null}';
for (let i = 0; i < 10000; ++i) {
const iv = Buffer.from('0'.repeat(32), 'hex');
const input = Buffer.from(data, 'base64');
const decipher = crypto.createDecipheriv('aes-128-cbc', Buffer.from(key, 'base64'), iv);
const result = Buffer.concat([decipher.update(input), decipher.final()]).toString('utf8');
expect(cipherText).to.equal(result);
}
});
itremote('does not crash when using crypto.diffieHellman() constructors', () => {
const crypto = require('crypto');
crypto.createDiffieHellman('abc');
crypto.createDiffieHellman('abc', 2);
// Needed to test specific DiffieHellman ctors.
// eslint-disable-next-line no-octal
crypto.createDiffieHellman('abc', Buffer.from([2]));
// eslint-disable-next-line no-octal
crypto.createDiffieHellman('abc', '123');
});
itremote('does not crash when calling crypto.createPrivateKey() with an unsupported algorithm', () => {
const crypto = require('crypto');
const ed448 = {
crv: 'Ed448',
x: 'KYWcaDwgH77xdAwcbzOgvCVcGMy9I6prRQBhQTTdKXUcr-VquTz7Fd5adJO0wT2VHysF3bk3kBoA',
d: 'UhC3-vN5vp_g9PnTknXZgfXUez7Xvw-OfuJ0pYkuwzpYkcTvacqoFkV_O05WMHpyXkzH9q2wzx5n',
kty: 'OKP'
};
expect(() => {
crypto.createPrivateKey({ key: ed448, format: 'jwk' });
}).to.throw(/Invalid JWK data/);
});
});
describe('process.stdout', () => {
useRemoteContext();
itremote('does not throw an exception when accessed', () => {
expect(() => process.stdout).to.not.throw();
});
itremote('does not throw an exception when calling write()', () => {
expect(() => {
process.stdout.write('test');
}).to.not.throw();
});
// TODO: figure out why process.stdout.isTTY is true on Darwin but not Linux/Win.
ifdescribe(process.platform !== 'darwin')('isTTY', () => {
itremote('should be undefined in the renderer process', function () {
expect(process.stdout.isTTY).to.be.undefined();
});
});
});
describe('process.stdin', () => {
useRemoteContext();
itremote('does not throw an exception when accessed', () => {
expect(() => process.stdin).to.not.throw();
});
itremote('returns null when read from', () => {
expect(process.stdin.read()).to.be.null();
});
});
describe('process.version', () => {
itremote('should not have -pre', () => {
expect(process.version.endsWith('-pre')).to.be.false();
});
});
describe('vm.runInNewContext', () => {
itremote('should not crash', () => {
require('vm').runInNewContext('');
});
});
describe('crypto', () => {
useRemoteContext();
itremote('should list the ripemd160 hash in getHashes', () => {
expect(require('crypto').getHashes()).to.include('ripemd160');
});
itremote('should be able to create a ripemd160 hash and use it', () => {
const hash = require('crypto').createHash('ripemd160');
hash.update('electron-ripemd160');
expect(hash.digest('hex')).to.equal('fa7fec13c624009ab126ebb99eda6525583395fe');
});
itremote('should list aes-{128,256}-cfb in getCiphers', () => {
expect(require('crypto').getCiphers()).to.include.members(['aes-128-cfb', 'aes-256-cfb']);
});
itremote('should be able to create an aes-128-cfb cipher', () => {
require('crypto').createCipheriv('aes-128-cfb', '0123456789abcdef', '0123456789abcdef');
});
itremote('should be able to create an aes-256-cfb cipher', () => {
require('crypto').createCipheriv('aes-256-cfb', '0123456789abcdef0123456789abcdef', '0123456789abcdef');
});
itremote('should be able to create a bf-{cbc,cfb,ecb} ciphers', () => {
require('crypto').createCipheriv('bf-cbc', Buffer.from('0123456789abcdef'), Buffer.from('01234567'));
require('crypto').createCipheriv('bf-cfb', Buffer.from('0123456789abcdef'), Buffer.from('01234567'));
require('crypto').createCipheriv('bf-ecb', Buffer.from('0123456789abcdef'), Buffer.from('01234567'));
});
itremote('should list des-ede-cbc in getCiphers', () => {
expect(require('crypto').getCiphers()).to.include('des-ede-cbc');
});
itremote('should be able to create an des-ede-cbc cipher', () => {
const key = Buffer.from('0123456789abcdeff1e0d3c2b5a49786', 'hex');
const iv = Buffer.from('fedcba9876543210', 'hex');
require('crypto').createCipheriv('des-ede-cbc', key, iv);
});
itremote('should not crash when getting an ECDH key', () => {
const ecdh = require('crypto').createECDH('prime256v1');
expect(ecdh.generateKeys()).to.be.an.instanceof(Buffer);
expect(ecdh.getPrivateKey()).to.be.an.instanceof(Buffer);
});
itremote('should not crash when generating DH keys or fetching DH fields', () => {
const dh = require('crypto').createDiffieHellman('modp15');
expect(dh.generateKeys()).to.be.an.instanceof(Buffer);
expect(dh.getPublicKey()).to.be.an.instanceof(Buffer);
expect(dh.getPrivateKey()).to.be.an.instanceof(Buffer);
expect(dh.getPrime()).to.be.an.instanceof(Buffer);
expect(dh.getGenerator()).to.be.an.instanceof(Buffer);
});
itremote('should not crash when creating an ECDH cipher', () => {
const crypto = require('crypto');
const dh = crypto.createECDH('prime256v1');
dh.generateKeys();
dh.setPrivateKey(dh.getPrivateKey());
});
});
itremote('includes the electron version in process.versions', () => {
expect(process.versions)
.to.have.own.property('electron')
.that.is.a('string')
.and.matches(/^\d+\.\d+\.\d+(\S*)?$/);
});
itremote('includes the chrome version in process.versions', () => {
expect(process.versions)
.to.have.own.property('chrome')
.that.is.a('string')
.and.matches(/^\d+\.\d+\.\d+\.\d+$/);
});
describe('NODE_OPTIONS', () => {
@ -113,8 +579,9 @@ describe('node feature', () => {
child.kill();
});
const appPath = path.join(fixtures, 'module', 'noop.js');
const env = { ...process.env, NODE_OPTIONS: '--use-openssl-ca' };
child = childProcess.spawn(process.execPath, ['--enable-logging'], { env });
child = childProcess.spawn(process.execPath, ['--enable-logging', appPath], { env });
let output = '';
const cleanup = () => {

Просмотреть файл

@ -3,6 +3,8 @@ import * as path from 'path';
import * as http from 'http';
import * as v8 from 'v8';
import { SuiteFunction, TestFunction } from 'mocha';
import { BrowserWindow } from 'electron/main';
import { AssertionError } from 'chai';
const addOnly = <T>(fn: Function): T => {
const wrapped = (...args: any[]) => {
@ -145,3 +147,45 @@ export async function repeatedly<T> (
if (+new Date() - begin > timeLimit) { throw new Error(`repeatedly timed out (limit=${timeLimit})`); }
}
}
async function makeRemoteContext (opts?: any) {
const { webPreferences, ...rest } = opts ?? {};
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, ...webPreferences }, ...rest });
await w.loadURL('about:blank');
return w;
}
const remoteContext: BrowserWindow[] = [];
export async function getRemoteContext () {
if (remoteContext.length) { return remoteContext[0]; }
const w = await makeRemoteContext();
defer(() => w.close());
return w;
}
export function useRemoteContext (opts?: any) {
before(async () => {
remoteContext.unshift(await makeRemoteContext(opts));
});
after(() => {
const w = remoteContext.shift();
w!.close();
});
}
export async function itremote (name: string, fn: Function, args?: any[]) {
it(name, async () => {
const w = await getRemoteContext();
const { ok, message } = await w.webContents.executeJavaScript(`(async () => {
try {
const chai_1 = require('chai')
chai_1.use(require('dirty-chai'))
await (${fn})(...${JSON.stringify(args ?? [])})
return {ok: true};
} catch (e) {
return {ok: false, message: e.message}
}
})()`);
if (!ok) { throw new AssertionError(message); }
});
}

Просмотреть файл

@ -3,8 +3,8 @@ import * as url from 'url';
import { BrowserWindow, session, ipcMain, app, WebContents } from 'electron/main';
import { closeAllWindows } from './window-helpers';
import { emittedOnce, emittedUntil } from './events-helpers';
import { ifit, delay, defer } from './spec-helpers';
import { AssertionError, expect } from 'chai';
import { ifit, delay, defer, itremote, useRemoteContext } from './spec-helpers';
import { expect } from 'chai';
import * as http from 'http';
import { AddressInfo } from 'net';
@ -50,24 +50,6 @@ async function loadWebViewAndWaitForMessage (w: WebContents, attributes: Record<
return message;
};
async function itremote (name: string, fn: Function, args?: any[]) {
it(name, async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, webviewTag: true } });
defer(() => w.close());
w.loadURL('about:blank');
const { ok, message } = await w.webContents.executeJavaScript(`(async () => {
try {
const chai_1 = require('chai')
await (${fn})(...${JSON.stringify(args ?? [])})
return {ok: true};
} catch (e) {
return {ok: false, message: e.message}
}
})()`);
if (!ok) { throw new AssertionError(message); }
});
}
describe('<webview> tag', function () {
const fixtures = path.join(__dirname, '..', 'spec', 'fixtures');
const blankPageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'blank.html')).toString();
@ -1105,6 +1087,7 @@ describe('<webview> tag', function () {
});
describe('preload attribute', () => {
useRemoteContext({ webPreferences: { webviewTag: true } });
it('loads the script before other scripts in window', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload.js`,
@ -1431,6 +1414,7 @@ describe('<webview> tag', function () {
});
describe('events', () => {
useRemoteContext({ webPreferences: { webviewTag: true } });
let w: WebContents;
before(async () => {
const window = new BrowserWindow({

Просмотреть файл

@ -1,451 +0,0 @@
const ChildProcess = require('child_process');
const { expect } = require('chai');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { ipcRenderer } = require('electron');
const features = process._linkedBinding('electron_common_features');
const { emittedOnce } = require('./events-helpers');
const { ifit } = require('./spec-helpers');
describe('node feature', () => {
const fixtures = path.join(__dirname, 'fixtures');
describe('child_process', () => {
beforeEach(function () {
if (!features.isRunAsNodeEnabled()) {
this.skip();
}
});
describe('child_process.fork', () => {
it('works in current process', async () => {
const child = ChildProcess.fork(path.join(fixtures, 'module', 'ping.js'));
const message = emittedOnce(child, 'message');
child.send('message');
const [msg] = await message;
expect(msg).to.equal('message');
});
it('preserves args', async () => {
const args = ['--expose_gc', '-test', '1'];
const child = ChildProcess.fork(path.join(fixtures, 'module', 'process_args.js'), args);
const message = emittedOnce(child, 'message');
child.send('message');
const [msg] = await message;
expect(args).to.deep.equal(msg.slice(2));
});
it('works in forked process', async () => {
const child = ChildProcess.fork(path.join(fixtures, 'module', 'fork_ping.js'));
const message = emittedOnce(child, 'message');
child.send('message');
const [msg] = await message;
expect(msg).to.equal('message');
});
it('works in forked process when options.env is specified', async () => {
const child = ChildProcess.fork(path.join(fixtures, 'module', 'fork_ping.js'), [], {
path: process.env.PATH
});
const message = emittedOnce(child, 'message');
child.send('message');
const [msg] = await message;
expect(msg).to.equal('message');
});
it('has String::localeCompare working in script', async () => {
const child = ChildProcess.fork(path.join(fixtures, 'module', 'locale-compare.js'));
const message = emittedOnce(child, 'message');
child.send('message');
const [msg] = await message;
expect(msg).to.deep.equal([0, -1, 1]);
});
it('has setImmediate working in script', async () => {
const child = ChildProcess.fork(path.join(fixtures, 'module', 'set-immediate.js'));
const message = emittedOnce(child, 'message');
child.send('message');
const [msg] = await message;
expect(msg).to.equal('ok');
});
it('pipes stdio', async () => {
const child = ChildProcess.fork(path.join(fixtures, 'module', 'process-stdout.js'), { silent: true });
let data = '';
child.stdout.on('data', (chunk) => {
data += String(chunk);
});
const [code] = await emittedOnce(child, 'close');
expect(code).to.equal(0);
expect(data).to.equal('pipes stdio');
});
it('works when sending a message to a process forked with the --eval argument', async () => {
const source = "process.on('message', (message) => { process.send(message) })";
const forked = ChildProcess.fork('--eval', [source]);
const message = emittedOnce(forked, 'message');
forked.send('hello');
const [msg] = await message;
expect(msg).to.equal('hello');
});
it('has the electron version in process.versions', async () => {
const source = 'process.send(process.versions)';
const forked = ChildProcess.fork('--eval', [source]);
const [message] = await emittedOnce(forked, 'message');
expect(message)
.to.have.own.property('electron')
.that.is.a('string')
.and.matches(/^\d+\.\d+\.\d+(\S*)?$/);
});
});
describe('child_process.spawn', () => {
let child;
afterEach(() => {
if (child != null) child.kill();
});
it('supports spawning Electron as a node process via the ELECTRON_RUN_AS_NODE env var', async () => {
child = ChildProcess.spawn(process.execPath, [path.join(__dirname, 'fixtures', 'module', 'run-as-node.js')], {
env: {
ELECTRON_RUN_AS_NODE: true
}
});
let output = '';
child.stdout.on('data', data => {
output += data;
});
await emittedOnce(child.stdout, 'close');
expect(JSON.parse(output)).to.deep.equal({
stdoutType: 'pipe',
processType: 'undefined',
window: 'undefined'
});
});
});
describe('child_process.exec', () => {
(process.platform === 'linux' ? it : it.skip)('allows executing a setuid binary from non-sandboxed renderer', () => {
// Chrome uses prctl(2) to set the NO_NEW_PRIVILEGES flag on Linux (see
// https://github.com/torvalds/linux/blob/40fde647cc/Documentation/userspace-api/no_new_privs.rst).
// We disable this for unsandboxed processes, which the renderer tests
// are running in. If this test fails with an error like 'effective uid
// is not 0', then it's likely that our patch to prevent the flag from
// being set has become ineffective.
const stdout = ChildProcess.execSync('sudo --help');
expect(stdout).to.not.be.empty();
});
});
});
describe('contexts', () => {
describe('setTimeout in fs callback', () => {
it('does not crash', (done) => {
fs.readFile(__filename, () => {
setTimeout(done, 0);
});
});
});
describe('error thrown in renderer process node context', () => {
it('gets emitted as a process uncaughtException event', (done) => {
const error = new Error('boo!');
const listeners = process.listeners('uncaughtException');
process.removeAllListeners('uncaughtException');
process.on('uncaughtException', (thrown) => {
try {
expect(thrown).to.equal(error);
done();
} catch (e) {
done(e);
} finally {
process.removeAllListeners('uncaughtException');
listeners.forEach((listener) => process.on('uncaughtException', listener));
}
});
fs.readFile(__filename, () => {
throw error;
});
});
});
describe('URL handling in the renderer process', () => {
it('can successfully handle WHATWG URLs constructed by Blink', () => {
const url = new URL('file://' + path.resolve(fixtures, 'pages', 'base-page.html'));
expect(() => {
fs.createReadStream(url);
}).to.not.throw();
});
});
describe('error thrown in main process node context', () => {
it('gets emitted as a process uncaughtException event', () => {
const error = ipcRenderer.sendSync('handle-uncaught-exception', 'hello');
expect(error).to.equal('hello');
});
});
describe('promise rejection in main process node context', () => {
it('gets emitted as a process unhandledRejection event', () => {
const error = ipcRenderer.sendSync('handle-unhandled-rejection', 'hello');
expect(error).to.equal('hello');
});
});
describe('setTimeout called under blink env in renderer process', () => {
it('can be scheduled in time', (done) => {
setTimeout(done, 10);
});
it('works from the timers module', (done) => {
require('timers').setTimeout(done, 10);
});
});
describe('setInterval called under blink env in renderer process', () => {
it('can be scheduled in time', (done) => {
const id = setInterval(() => {
clearInterval(id);
done();
}, 10);
});
it('can be scheduled in time from timers module', (done) => {
const { setInterval, clearInterval } = require('timers');
const id = setInterval(() => {
clearInterval(id);
done();
}, 10);
});
});
});
describe('message loop', () => {
describe('process.nextTick', () => {
it('emits the callback', (done) => process.nextTick(done));
it('works in nested calls', (done) => {
process.nextTick(() => {
process.nextTick(() => process.nextTick(done));
});
});
});
describe('setImmediate', () => {
it('emits the callback', (done) => setImmediate(done));
it('works in nested calls', (done) => {
setImmediate(() => {
setImmediate(() => setImmediate(done));
});
});
});
});
describe('net.connect', () => {
before(function () {
if (!features.isRunAsNodeEnabled() || process.platform !== 'darwin') {
this.skip();
}
});
it('emit error when connect to a socket path without listeners', async () => {
const socketPath = path.join(os.tmpdir(), 'atom-shell-test.sock');
const script = path.join(fixtures, 'module', 'create_socket.js');
const child = ChildProcess.fork(script, [socketPath]);
const [code] = await emittedOnce(child, 'exit');
expect(code).to.equal(0);
const client = require('net').connect(socketPath);
const [error] = await emittedOnce(client, 'error');
expect(error.code).to.equal('ECONNREFUSED');
});
});
describe('Buffer', () => {
it('can be created from WebKit external string', () => {
const p = document.createElement('p');
p.innerText = '闲云潭影日悠悠,物换星移几度秋';
const b = Buffer.from(p.innerText);
expect(b.toString()).to.equal('闲云潭影日悠悠,物换星移几度秋');
expect(Buffer.byteLength(p.innerText)).to.equal(45);
});
it('correctly parses external one-byte UTF8 string', () => {
const p = document.createElement('p');
p.innerText = 'Jøhänñéß';
const b = Buffer.from(p.innerText);
expect(b.toString()).to.equal('Jøhänñéß');
expect(Buffer.byteLength(p.innerText)).to.equal(13);
});
it('does not crash when creating large Buffers', () => {
let buffer = Buffer.from(new Array(4096).join(' '));
expect(buffer.length).to.equal(4095);
buffer = Buffer.from(new Array(4097).join(' '));
expect(buffer.length).to.equal(4096);
});
it('does not crash for crypto operations', () => {
const crypto = require('crypto');
const data = 'lG9E+/g4JmRmedDAnihtBD4Dfaha/GFOjd+xUOQI05UtfVX3DjUXvrS98p7kZQwY3LNhdiFo7MY5rGft8yBuDhKuNNag9vRx/44IuClDhdQ=';
const key = 'q90K9yBqhWZnAMCMTOJfPQ==';
const cipherText = '{"error_code":114,"error_message":"Tham số không hợp lệ","data":null}';
for (let i = 0; i < 10000; ++i) {
const iv = Buffer.from('0'.repeat(32), 'hex');
const input = Buffer.from(data, 'base64');
const decipher = crypto.createDecipheriv('aes-128-cbc', Buffer.from(key, 'base64'), iv);
const result = Buffer.concat([decipher.update(input), decipher.final()]).toString('utf8');
expect(cipherText).to.equal(result);
}
});
it('does not crash when using crypto.diffieHellman() constructors', () => {
const crypto = require('crypto');
crypto.createDiffieHellman('abc');
crypto.createDiffieHellman('abc', 2);
// Needed to test specific DiffieHellman ctors.
// eslint-disable-next-line no-octal
crypto.createDiffieHellman('abc', Buffer.from([02]));
// eslint-disable-next-line no-octal
crypto.createDiffieHellman('abc', '123');
});
it('does not crash when calling crypto.createPrivateKey() with an unsupported algorithm', () => {
const crypto = require('crypto');
const ed448 = {
crv: 'Ed448',
x: 'KYWcaDwgH77xdAwcbzOgvCVcGMy9I6prRQBhQTTdKXUcr-VquTz7Fd5adJO0wT2VHysF3bk3kBoA',
d: 'UhC3-vN5vp_g9PnTknXZgfXUez7Xvw-OfuJ0pYkuwzpYkcTvacqoFkV_O05WMHpyXkzH9q2wzx5n',
kty: 'OKP'
};
expect(() => {
crypto.createPrivateKey({ key: ed448, format: 'jwk' });
}).to.throw(/Invalid JWK data/);
});
});
describe('process.stdout', () => {
it('does not throw an exception when accessed', () => {
expect(() => process.stdout).to.not.throw();
});
it('does not throw an exception when calling write()', () => {
expect(() => {
process.stdout.write('test');
}).to.not.throw();
});
// TODO: figure out why process.stdout.isTTY is true on Darwin but not Linux/Win.
ifit(process.platform !== 'darwin')('isTTY should be undefined in the renderer process', function () {
expect(process.stdout.isTTY).to.be.undefined();
});
});
describe('process.stdin', () => {
it('does not throw an exception when accessed', () => {
expect(() => process.stdin).to.not.throw();
});
it('returns null when read from', () => {
expect(process.stdin.read()).to.be.null();
});
});
describe('process.version', () => {
it('should not have -pre', () => {
expect(process.version.endsWith('-pre')).to.be.false();
});
});
describe('vm.runInNewContext', () => {
it('should not crash', () => {
require('vm').runInNewContext('');
});
});
describe('crypto', () => {
it('should list the ripemd160 hash in getHashes', () => {
expect(require('crypto').getHashes()).to.include('ripemd160');
});
it('should be able to create a ripemd160 hash and use it', () => {
const hash = require('crypto').createHash('ripemd160');
hash.update('electron-ripemd160');
expect(hash.digest('hex')).to.equal('fa7fec13c624009ab126ebb99eda6525583395fe');
});
it('should list aes-{128,256}-cfb in getCiphers', () => {
expect(require('crypto').getCiphers()).to.include.members(['aes-128-cfb', 'aes-256-cfb']);
});
it('should be able to create an aes-128-cfb cipher', () => {
require('crypto').createCipheriv('aes-128-cfb', '0123456789abcdef', '0123456789abcdef');
});
it('should be able to create an aes-256-cfb cipher', () => {
require('crypto').createCipheriv('aes-256-cfb', '0123456789abcdef0123456789abcdef', '0123456789abcdef');
});
it('should be able to create a bf-{cbc,cfb,ecb} ciphers', () => {
require('crypto').createCipheriv('bf-cbc', Buffer.from('0123456789abcdef'), Buffer.from('01234567'));
require('crypto').createCipheriv('bf-cfb', Buffer.from('0123456789abcdef'), Buffer.from('01234567'));
require('crypto').createCipheriv('bf-ecb', Buffer.from('0123456789abcdef'), Buffer.from('01234567'));
});
it('should list des-ede-cbc in getCiphers', () => {
expect(require('crypto').getCiphers()).to.include('des-ede-cbc');
});
it('should be able to create an des-ede-cbc cipher', () => {
const key = Buffer.from('0123456789abcdeff1e0d3c2b5a49786', 'hex');
const iv = Buffer.from('fedcba9876543210', 'hex');
require('crypto').createCipheriv('des-ede-cbc', key, iv);
});
it('should not crash when getting an ECDH key', () => {
const ecdh = require('crypto').createECDH('prime256v1');
expect(ecdh.generateKeys()).to.be.an.instanceof(Buffer);
expect(ecdh.getPrivateKey()).to.be.an.instanceof(Buffer);
});
it('should not crash when generating DH keys or fetching DH fields', () => {
const dh = require('crypto').createDiffieHellman('modp15');
expect(dh.generateKeys()).to.be.an.instanceof(Buffer);
expect(dh.getPublicKey()).to.be.an.instanceof(Buffer);
expect(dh.getPrivateKey()).to.be.an.instanceof(Buffer);
expect(dh.getPrime()).to.be.an.instanceof(Buffer);
expect(dh.getGenerator()).to.be.an.instanceof(Buffer);
});
it('should not crash when creating an ECDH cipher', () => {
const crypto = require('crypto');
const dh = crypto.createECDH('prime256v1');
dh.generateKeys();
dh.setPrivateKey(dh.getPrivateKey());
});
});
it('includes the electron version in process.versions', () => {
expect(process.versions)
.to.have.own.property('electron')
.that.is.a('string')
.and.matches(/^\d+\.\d+\.\d+(\S*)?$/);
});
it('includes the chrome version in process.versions', () => {
expect(process.versions)
.to.have.own.property('chrome')
.that.is.a('string')
.and.matches(/^\d+\.\d+\.\d+\.\d+$/);
});
});

Просмотреть файл

@ -147,15 +147,6 @@ app.whenReady().then(async function () {
});
});
ipcMain.on('handle-uncaught-exception', (event, message) => {
suspendListeners(process, 'uncaughtException', (error) => {
event.returnValue = error.message;
});
fs.readFile(__filename, () => {
throw new Error(message);
});
});
ipcMain.on('handle-unhandled-rejection', (event, message) => {
suspendListeners(process, 'unhandledRejection', (error) => {
event.returnValue = error.message;