This repository has been archived by the owner on Oct 26, 2023. It is now read-only.
forked from kingland/go-v8
-
Notifications
You must be signed in to change notification settings - Fork 3
/
v8_script_test.go
106 lines (86 loc) · 2.22 KB
/
v8_script_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
package v8
import (
"fmt"
"io/ioutil"
"runtime"
"testing"
)
func TestReturnValue(t *testing.T) {
template := engine.NewObjectTemplate()
template.Bind("Call", func() *Value {
val := engine.NewObject()
obj := val.ToObject()
obj.SetProperty("name", engine.NewString("test object"))
obj.SetProperty("id", engine.NewInteger(1234))
return val
})
engine.NewContext(template).Scope(func(cs ContextScope) {
script := engine.Compile([]byte(`
a = Call();
if (a.name != "test object" || a.id != 1234) {
{};
} else {
a;
}
`), nil)
retVal := cs.Run(script)
if !retVal.IsObject() {
t.Fatalf("expected object")
}
retObj := retVal.ToObject()
if !retObj.HasProperty("name") || retObj.GetProperty("name").ToString() != "test object" ||
!retObj.HasProperty("id") || retObj.GetProperty("id").ToNumber() != 1234 {
t.Fatalf("value should be %q not %q", "{\"name\":\"test object\",\"id\":1234}", string(ToJSON(retVal)))
}
})
runtime.GC()
}
func TestTypescript(t *testing.T) {
code, err := ioutil.ReadFile("./typescript.js")
if err != nil {
t.Errorf("Read typescript file failed: %s\n", err)
}
template := engine.NewObjectTemplate()
engine.NewContext(template).Scope(func(cs ContextScope) {
script1 := engine.Compile(code, nil)
cs.Run(script1)
script2 := engine.Compile([]byte(`"use strict";
function _go_transpile(source) {
var result = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } });
return result.outputText;
}`), nil)
cs.Run(script2)
script3 := engine.Compile([]byte(`
f = _go_transpile;
`), nil)
value := cs.Run(script3)
if value.IsFunction() == false {
t.Fatal("value not a function")
}
result := value.ToFunction().Call(
engine.NewString(
`class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");`))
fmt.Println(result)
result = value.ToFunction().Call(engine.NewString(
`class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}`))
fmt.Println(result)
})
runtime.GC()
}