UNPKG

module-sandbox

Version:

A v8 isolate sandbox with require support

54 lines (47 loc) 1.82 kB
const p = require('path') const test = require('tape') const Sandbox = require('..') const SIMPLE_EXAMPLE_PATH = p.join(__dirname, '..', 'examples', 'simple', 'index.js') const SIMPLE_EXPORTS_EXAMPLE_PATH = p.join(__dirname, '..', 'examples', 'simple-exports', 'index.js') const HOSTCALLS_EXAMPLE_PATH = p.join(__dirname, '..', 'examples', 'hostcalls', 'index.js') const REQUIRE_OVERRIDES_EXAMPLE_PATH = p.join(__dirname, '..', 'examples', 'require-override', 'index.js') test('can run simple example', async t => { const machine = new Sandbox(SIMPLE_EXAMPLE_PATH) await machine.ready() await machine.close() t.end() }) test('can call exported functions on a simple example', async t => { const machine = new Sandbox(SIMPLE_EXPORTS_EXAMPLE_PATH) await machine.ready() t.same(await machine.rpc.add(1, 2), 3) t.same(await machine.rpc.mult(3, 4), 12) t.same(await machine.rpc.mult(3, 4, 2), 24) t.same(await machine.rpc.add(3, 2, 10), 15) t.same(await machine.rpc.arrays.double([1, 2, 3, 4]), [2, 4, 6, 8]) t.same(await machine.rpc.objects.greet({ name: 'tester' }), { hello: 'tester and world' }) await machine.close() t.end() }) test('can provide and call hostcalls', async t => { const machine = new Sandbox(HOSTCALLS_EXAMPLE_PATH, { hostcalls: { getPrefix: (_, name) => `${name}'s greeting:` } }) await machine.ready() t.same(await machine.rpc.hello('tester'), 'tester\'s greeting: hello tester') await machine.close() t.end() }) test('can override requires', async t => { const machine = new Sandbox(REQUIRE_OVERRIDES_EXAMPLE_PATH, { requires: { 'other-module': p.join(p.dirname(REQUIRE_OVERRIDES_EXAMPLE_PATH), 'other.js') } }) await machine.ready() t.same(await machine.rpc.hello(), 'hello world') await machine.close() t.end() })