forked from robertkrimen/otto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testing_test.go
137 lines (122 loc) · 2.43 KB
/
testing_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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package otto
import (
"errors"
"strings"
"testing"
"time"
"github.com/robertkrimen/otto/terst"
)
func tt(t *testing.T, arguments ...func()) {
t.Helper()
halt := errors.New("A test was taking too long")
timer := time.AfterFunc(20*time.Second, func() {
panic(halt)
})
defer func() {
timer.Stop()
}()
terst.Terst(t, arguments...)
}
func is(arguments ...interface{}) bool {
var got, expect interface{}
switch len(arguments) {
case 0, 1:
return terst.Is(arguments...)
case 2:
got, expect = arguments[0], arguments[1]
default:
got, expect = arguments[0], arguments[2]
}
switch value := got.(type) {
case Value:
if value.value != nil {
got = value.value
}
case *Error:
if value != nil {
got = value.Error()
}
if expect == nil {
// FIXME This is weird
expect = ""
}
}
if len(arguments) == 2 {
arguments[0] = got
arguments[1] = expect
} else {
arguments[0] = got
arguments[2] = expect
}
return terst.Is(arguments...)
}
func test(arguments ...interface{}) (func(string, ...interface{}) Value, *_tester) {
tester := newTester()
if len(arguments) > 0 {
tester.test(arguments[0].(string))
}
return tester.test, tester
}
type _tester struct {
vm *Otto
}
func newTester() *_tester {
return &_tester{
vm: New(),
}
}
func (self *_tester) Get(name string) (Value, error) {
return self.vm.Get(name)
}
func (self *_tester) Set(name string, value interface{}) Value {
err := self.vm.Set(name, value)
is(err, nil)
if err != nil {
terst.Caller().T().FailNow()
}
return self.vm.getValue(name)
}
func (self *_tester) Run(src interface{}) (Value, error) {
return self.vm.Run(src)
}
func (self *_tester) test(name string, expect ...interface{}) Value {
vm := self.vm
raise := false
defer func() {
if caught := recover(); caught != nil {
if exception, ok := caught.(*_exception); ok {
caught = exception.eject()
}
if raise {
if len(expect) > 0 {
is(caught, expect[0])
}
} else {
dbg("Panic, caught:", caught)
panic(caught)
}
}
}()
var value Value
var err error
if isIdentifier(name) {
value = vm.getValue(name)
} else {
source := name
index := strings.Index(source, "raise:")
if index == 0 {
raise = true
source = source[6:]
source = strings.TrimLeft(source, " ")
}
value, err = vm.runtime.cmpl_run(source, nil)
if err != nil {
panic(err)
}
}
value = value.resolve()
if len(expect) > 0 {
is(value, expect[0])
}
return value
}