1
2
3
4
5
6 package assert
7
8 import (
9 "fmt"
10 "path/filepath"
11 "reflect"
12 "regexp"
13 "runtime"
14 "strings"
15 "testing"
16 )
17
18
19 const skip = 2
20
21
22
23 func Equal(t *testing.T, got, want interface{}, msg ...string) {
24 if x := equal(2, got, want, msg...); x != "" {
25 fmt.Println(x)
26 t.Fail()
27 }
28 }
29
30 func equal(skip int, got, want interface{}, msg ...string) string {
31 if !reflect.DeepEqual(got, want) {
32 return fail(skip, "got %v want %v %s", got, want, strings.Join(msg, " "))
33 }
34 return ""
35 }
36
37
38
39
40
41 func Panic(t *testing.T, fn func(), matches string) {
42 if x := doesPanic(2, fn, matches); x != "" {
43 fmt.Println(x)
44 t.Fail()
45 }
46 }
47
48 func doesPanic(skip int, fn func(), expr string) (err string) {
49 defer func() {
50 r := recover()
51 if r == nil {
52 err = fail(skip, "did not panic")
53 return
54 }
55 var v string
56 switch r.(type) {
57 case error:
58 v = r.(error).Error()
59 case string:
60 v = r.(string)
61 }
62 err = matches(skip, v, expr)
63 }()
64 fn()
65 return ""
66 }
67
68
69 func Matches(t *testing.T, value, expr string) {
70 if x := matches(2, value, expr); x != "" {
71 fmt.Println(x)
72 t.Fail()
73 }
74 }
75
76 func matches(skip int, value, expr string) string {
77 ok, err := regexp.MatchString(expr, value)
78 if err != nil {
79 return fail(skip, "invalid pattern %q. %s", expr, err)
80 }
81 if !ok {
82 return fail(skip, "got %s which does not match %s", value, expr)
83 }
84 return ""
85 }
86
87 func fail(skip int, format string, args ...interface{}) string {
88 _, file, line, _ := runtime.Caller(skip)
89 return fmt.Sprintf("\t%s:%d: %s\n", filepath.Base(file), line, fmt.Sprintf(format, args...))
90 }
91
View as plain text