forked from lazytiger/go-v8
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathv8_context_test.go
116 lines (89 loc) · 2.49 KB
/
v8_context_test.go
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package v8
import "testing"
import "runtime"
import "io/ioutil"
func Test_HelloWorld(t *testing.T) {
engine.NewContext(nil).Scope(func(cs ContextScope) {
if cs.Eval("'Hello ' + 'World!'").ToString() != "Hello World!" {
t.Fatal("result not match")
}
})
runtime.GC()
}
func Test_Context(t *testing.T) {
script1 := engine.Compile([]byte("typeof(MyTestContext) === 'undefined';"), nil)
script2 := engine.Compile([]byte("MyTestContext = 1;"), nil)
script3 := engine.Compile([]byte("MyTestContext = MyTestContext + 7;"), nil)
test_func := func(cs ContextScope) {
if !cs.Run(script1).IsTrue() {
t.Fatal(`!cs.Run(script1).IsTrue()`)
}
if cs.Run(script1).IsFalse() {
t.Fatal(`cs.Run(script1).IsFalse()`)
}
if cs.Run(script2).ToInteger() != 1 {
t.Fatal(`cs.Run(script2).ToInteger() != 1`)
}
if cs.Run(script3).ToInteger() != 8 {
t.Fatal(`cs.Run(script3).ToInteger() != 8`)
}
}
engine.NewContext(nil).Scope(func(cs ContextScope) {
t.Log("context1")
engine.NewContext(nil).Scope(test_func)
t.Log("context2")
engine.NewContext(nil).Scope(test_func)
test_func(cs)
})
functionTemplate := engine.NewFunctionTemplate(func(info FunctionCallbackInfo) {
for i := 0; i < info.Length(); i++ {
t.Log(info.Get(i).ToString())
}
}, nil)
// Test Global Template
globalTemplate := engine.NewObjectTemplate()
globalTemplate.SetAccessor("log", func(name string, info AccessorCallbackInfo) {
info.ReturnValue().Set(functionTemplate.NewFunction())
}, nil, nil, PA_None)
engine.NewContext(globalTemplate).Scope(func(cs ContextScope) {
cs.Eval(`log("Hello World!")`)
})
// Test Global Object
engine.NewContext(nil).Scope(func(cs ContextScope) {
global := cs.Global()
if !global.SetProperty("println", functionTemplate.NewFunction()) {
}
global = cs.Global()
if !global.HasProperty("println") {
t.Fatal(`!global.HasProperty("println")`)
return
}
cs.Eval(`println("Hello World!")`)
})
runtime.GC()
}
func Test_UnderscoreJS(t *testing.T) {
engine.NewContext(nil).Scope(func(cs ContextScope) {
code, err := ioutil.ReadFile("samples/underscore.js")
if err != nil {
return
}
script := engine.Compile(code, nil)
cs.Run(script)
test := []byte(`
_.find([1, 2, 3, 4, 5, 6], function(num) {
return num % 2 == 0;
});
`)
testScript := engine.Compile(test, nil)
value := cs.Run(testScript)
if value == nil || value.IsNumber() == false {
t.FailNow()
}
result := value.ToNumber()
if result != 2 {
t.FailNow()
}
})
runtime.GC()
}