2010-12-05 07:20:34 +08:00
|
|
|
var common = require('../common');
|
|
|
|
var assert = require('assert');
|
2010-04-17 23:18:15 +08:00
|
|
|
|
2010-11-16 10:37:27 +08:00
|
|
|
var Script = require('vm').Script;
|
2010-04-17 23:18:15 +08:00
|
|
|
|
2010-07-16 02:47:25 +08:00
|
|
|
common.debug('run a string');
|
2010-04-17 23:18:15 +08:00
|
|
|
var result = Script.runInNewContext('"passed";');
|
|
|
|
assert.equal('passed', result);
|
|
|
|
|
2010-07-16 02:47:25 +08:00
|
|
|
common.debug('thrown error');
|
2010-04-17 23:18:15 +08:00
|
|
|
assert.throws(function() {
|
|
|
|
Script.runInNewContext('throw new Error("test");');
|
|
|
|
});
|
|
|
|
|
|
|
|
hello = 5;
|
|
|
|
Script.runInNewContext('hello = 2');
|
|
|
|
assert.equal(5, hello);
|
|
|
|
|
|
|
|
|
2010-07-16 02:47:25 +08:00
|
|
|
common.debug("pass values in and out");
|
2010-04-17 23:18:15 +08:00
|
|
|
code = "foo = 1;"
|
|
|
|
+ "bar = 2;"
|
|
|
|
+ "if (baz !== 3) throw new Error('test fail');";
|
|
|
|
foo = 2;
|
|
|
|
obj = { foo : 0, baz : 3 };
|
|
|
|
var baz = Script.runInNewContext(code, obj);
|
|
|
|
assert.equal(1, obj.foo);
|
|
|
|
assert.equal(2, obj.bar);
|
|
|
|
assert.equal(2, foo);
|
|
|
|
|
2010-07-16 02:47:25 +08:00
|
|
|
common.debug("call a function by reference");
|
2010-04-17 23:18:15 +08:00
|
|
|
function changeFoo () { foo = 100 }
|
|
|
|
Script.runInNewContext("f()", { f : changeFoo });
|
|
|
|
assert.equal(foo, 100);
|
|
|
|
|
2010-07-16 02:47:25 +08:00
|
|
|
common.debug("modify an object by reference");
|
2010-04-17 23:18:15 +08:00
|
|
|
var f = { a : 1 };
|
|
|
|
Script.runInNewContext("f.a = 2", { f : f });
|
|
|
|
assert.equal(f.a, 2);
|
|
|
|
|