forked from vadv/gopher-lua-libs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testutil.go
90 lines (77 loc) · 2.06 KB
/
testutil.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
package tests
import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
lua "github.com/yuin/gopher-lua"
"strings"
"testing"
)
type PreloadFunc func(L *lua.LState)
const (
TType = "testing.T"
)
func tLua(L *lua.LState, t *testing.T) *lua.LUserData {
ud := L.NewUserData()
ud.Value = t
L.SetMetatable(ud, L.GetTypeMetatable(TType))
return ud
}
func checkT(L *lua.LState, n int) *testing.T {
ud := L.CheckUserData(n)
if v, ok := ud.Value.(*testing.T); ok {
return v
}
L.ArgError(n, "testing.T expected")
return nil
}
func tRun(L *lua.LState) int {
t := checkT(L, 1)
name := L.CheckString(2)
function := L.CheckFunction(3)
L.Pop(L.GetTop())
t.Run(name, func(t *testing.T) {
L.Push(function)
L.Push(tLua(L, t))
assert.NoError(t, L.PCall(1, 0, nil))
})
return 0
}
func registerTType(L *lua.LState) {
mt := L.NewTypeMetatable(TType)
index := L.SetFuncs(L.NewTable(), map[string]lua.LGFunction{
"Run": tRun,
})
L.SetField(mt, "__index", index)
L.SetGlobal(TType, mt)
}
//RunLuaTestFile fires up a new state, registers the *testing.T and invokes all methods starting with Test.
// This allows the lua test files to operate similar to go tests - see shellescape/test/test_api.lua
func RunLuaTestFile(t *testing.T, preload PreloadFunc, filename string) (numTests int) {
L := lua.NewState()
defer L.Close()
registerTType(L)
require.NotNil(t, preload)
preload(L)
L.SetGlobal("t", tLua(L, t))
require.NoError(t, L.DoFile(filename))
L.G.Global.ForEach(func(key lua.LValue, value lua.LValue) {
keyStr := lua.LVAsString(key)
if strings.HasPrefix(keyStr, "Test") && value.Type() == lua.LTFunction {
t.Run(keyStr, func(t *testing.T) {
numTests++
L.Push(value)
L.Push(tLua(L, t))
assert.NoError(t, L.PCall(1, 0, nil))
})
}
})
return
}
//SeveralPreloadFuncs combines several PreloadFuncs to one such as when tests want to preload theirs + inspect
func SeveralPreloadFuncs(preloadFuncs ...PreloadFunc) PreloadFunc {
return func(L *lua.LState) {
for _, preloadFunc := range preloadFuncs {
preloadFunc(L)
}
}
}