1package lua
2
3import (
4	"fmt"
5	"path/filepath"
6	"regexp"
7	"runtime"
8	"testing"
9)
10
11func positionString(level int) string {
12	_, file, line, _ := runtime.Caller(level + 1)
13	return fmt.Sprintf("%v:%v:", filepath.Base(file), line)
14}
15
16func errorIfNotEqual(t *testing.T, v1, v2 interface{}) {
17	if v1 != v2 {
18		t.Errorf("%v '%v' expected, but got '%v'", positionString(1), v1, v2)
19	}
20}
21
22func errorIfFalse(t *testing.T, cond bool, msg string, args ...interface{}) {
23	if !cond {
24		if len(args) > 0 {
25			t.Errorf("%v %v", positionString(1), fmt.Sprintf(msg, args...))
26		} else {
27			t.Errorf("%v %v", positionString(1), msg)
28		}
29	}
30}
31
32func errorIfNotNil(t *testing.T, v1 interface{}) {
33	if fmt.Sprint(v1) != "<nil>" {
34		t.Errorf("%v nil expected, but got '%v'", positionString(1), v1)
35	}
36}
37
38func errorIfNil(t *testing.T, v1 interface{}) {
39	if fmt.Sprint(v1) == "<nil>" {
40		t.Errorf("%v non-nil value expected, but got nil", positionString(1))
41	}
42}
43
44func errorIfScriptFail(t *testing.T, L *LState, script string) {
45	if err := L.DoString(script); err != nil {
46		t.Errorf("%v %v", positionString(1), err.Error())
47	}
48}
49
50func errorIfGFuncFail(t *testing.T, L *LState, f LGFunction) {
51	if err := L.GPCall(f, LNil); err != nil {
52		t.Errorf("%v %v", positionString(1), err.Error())
53	}
54}
55
56func errorIfScriptNotFail(t *testing.T, L *LState, script string, pattern string) {
57	if err := L.DoString(script); err != nil {
58		reg := regexp.MustCompile(pattern)
59		if len(reg.FindStringIndex(err.Error())) == 0 {
60			t.Errorf("%v error message '%v' does not contains given pattern string '%v'.", positionString(1), err.Error(), pattern)
61			return
62		}
63		return
64	}
65	t.Errorf("%v script should fail", positionString(1))
66}
67
68func errorIfGFuncNotFail(t *testing.T, L *LState, f LGFunction, pattern string) {
69	if err := L.GPCall(f, LNil); err != nil {
70		reg := regexp.MustCompile(pattern)
71		if len(reg.FindStringIndex(err.Error())) == 0 {
72			t.Errorf("%v error message '%v' does not contains given pattern string '%v'.", positionString(1), err.Error(), pattern)
73			return
74		}
75		return
76	}
77	t.Errorf("%v LGFunction should fail", positionString(1))
78}
79