-
Notifications
You must be signed in to change notification settings - Fork 12
/
test.py
84 lines (68 loc) · 2.22 KB
/
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#! python3
from io import StringIO
from unittest import TestCase, main
from unittest.mock import patch
from node_vm2 import eval, VM, NodeVM, VMError, VMServer
class Main(TestCase):
def test_eval(self):
with self.subTest("one line eval"):
r = eval("'foo' + 'bar'")
self.assertEqual(r, "foobar")
with self.subTest("multiline"):
r = eval("""
var foo = x => x + 'bar';
foo('foo');
""")
self.assertEqual(r, "foobar")
def test_VM(self):
with self.subTest("create VM"):
vm = VM().create()
r = vm.run("'foo' + 'bar'")
vm.destroy()
self.assertEqual(r, "foobar")
with self.subTest("with statement"):
with VM() as vm:
r = vm.run("'foo' + 'bar'")
self.assertEqual(r, "foobar")
def test_NodeVM(self):
with self.subTest("create NodeVM"):
vm = NodeVM().create()
m = vm.run("exports.foo = 'foo'")
r = m.get_member("foo")
self.assertEqual(r, "foo")
vm.destroy()
with self.subTest("with statement"):
with NodeVM() as vm:
m = vm.run("exports.foo = 'foo'")
r = m.get_member("foo")
self.assertEqual(r, "foo")
with self.subTest("NodeVM.code()"):
with NodeVM.code("exports.foo = 'foo'") as m:
r = m.get_member("foo")
self.assertEqual(r, "foo")
def test_VMError(self):
with self.assertRaisesRegex(VMError, "foo"):
eval("throw new Error('foo')")
# doesn't inherit Error
with self.assertRaisesRegex(VMError, "foo"):
eval("throw 'foo'")
def test_console(self):
code = "exports.test = s => console.log(s)"
with NodeVM.code(code) as module:
with patch("sys.stdout", new=StringIO()) as out:
module.call_member("test", "Hello")
self.assertEqual(out.getvalue(), "Hello\n")
# redirect and event
with NodeVM.code(code, console="redirect") as module:
module.call_member("test", "Hello")
event = module.vm.event_que.get_nowait()
self.assertEqual(event["value"], "Hello")
def test_node(self):
with self.assertRaises(VMError) as cm:
with VMServer("non-exists-executable-node"):
pass
self.assertTrue("'non-exists-executable-node' is unavailable" in str(cm.exception))
def test_freeze_object(self):
result = eval("Object.freeze({foo: {}})")
self.assertEqual(result, {"foo": {}})
main()