-
Notifications
You must be signed in to change notification settings - Fork 157
/
Copy pathtest.go
85 lines (71 loc) · 1.94 KB
/
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
package test
import (
"bytes"
"encoding"
"errors"
"fmt"
"strings"
"testing"
)
// ReportError reports an error if got is different from want.
func ReportError(t testing.TB, got, want interface{}, inputs ...interface{}) {
b := &strings.Builder{}
fmt.Fprint(b, "\n")
for i, in := range inputs {
fmt.Fprintf(b, "in[%v]: %v\n", i, in)
}
fmt.Fprintf(b, "got: %v\nwant: %v", got, want)
t.Helper()
t.Fatal(b.String())
}
// CheckOk fails the test if result == false.
func CheckOk(result bool, msg string, t testing.TB) {
t.Helper()
if !result {
t.Fatal(msg)
}
}
// checkErr fails on error condition. mustFail indicates whether err is expected
// to be nil or not.
func checkErr(t testing.TB, err error, mustFail bool, msg string) {
t.Helper()
if err != nil && !mustFail {
t.Fatalf("msg: %v\nerr: %v", msg, err)
}
if err == nil && mustFail {
t.Fatalf("msg: %v\nerr: %v", msg, err)
}
}
// CheckNoErr fails if err !=nil. Print msg as an error message.
func CheckNoErr(t testing.TB, err error, msg string) { t.Helper(); checkErr(t, err, false, msg) }
// CheckIsErr fails if err ==nil. Print msg as an error message.
func CheckIsErr(t testing.TB, err error, msg string) { t.Helper(); checkErr(t, err, true, msg) }
// CheckPanic returns true if call to function 'f' caused panic.
func CheckPanic(f func()) error {
hasPanicked := errors.New("no panic detected")
defer func() {
if r := recover(); r != nil {
hasPanicked = nil
}
}()
f()
return hasPanicked
}
func CheckMarshal(
t *testing.T,
x, y interface {
encoding.BinaryMarshaler
encoding.BinaryUnmarshaler
},
) {
t.Helper()
want, err := x.MarshalBinary()
CheckNoErr(t, err, fmt.Sprintf("cannot marshal %T = %v", x, x))
err = y.UnmarshalBinary(want)
CheckNoErr(t, err, fmt.Sprintf("cannot unmarshal %T from %x", y, want))
got, err := y.MarshalBinary()
CheckNoErr(t, err, fmt.Sprintf("cannot marshal %T = %v", y, y))
if !bytes.Equal(got, want) {
ReportError(t, got, want, x, y)
}
}