-
Notifications
You must be signed in to change notification settings - Fork 0
/
toast.go
124 lines (105 loc) · 1.96 KB
/
toast.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
package toast
import (
"errors"
"fmt"
"path/filepath"
"runtime"
"strings"
"testing"
)
var (
FailNow = true
)
const (
assertFailMsg = "assertion failed"
)
func mkfmt(i ...interface{}) string {
fmt := make([]string, len(i))
for i := range fmt {
fmt[i] = "%v"
}
return strings.Join(fmt, " ")
}
func msg(or string, i ...interface{}) string {
var prefix string
_, filename, line, ok := runtime.Caller(2)
if ok {
prefix = fmt.Sprintf("\r %s:%d:", filepath.Base(filename), line)
i = append([]interface{}{prefix}, i...)
if len(i) > 1 {
return fmt.Sprintf(mkfmt(i...), i...)
}
return strings.Join([]string{prefix, or}, " ")
}
if len(i) > 0 {
return fmt.Sprintf(mkfmt(i...), i...)
}
return or
}
func AssertOrPanic(condition bool, i ...interface{}) {
if !condition {
panic(msg(assertFailMsg, i...))
}
}
type T struct {
*testing.T
FailNow bool
mock bool // to be able to test that structure without test failure
}
func FromT(t *testing.T) *T {
return &T{t, FailNow, false}
}
func (t *T) log(s string) {
f := t.T.Error
if t.mock {
f = t.T.Log
}
f(s)
}
func (t *T) Error(i ...interface{}) {
t.log(msg("", i...))
if t.FailNow {
t.T.FailNow()
}
}
func (t *T) CheckErr(err error) {
if err != nil {
t.log(msg("", err))
if t.FailNow {
t.T.FailNow()
}
}
}
func (t *T) ExpectErr(err, expect error) {
if !errors.Is(err, expect) {
t.log(msg("unexpected error", fmt.Errorf("expecting %v got %v", expect, err)))
if t.FailNow {
t.T.FailNow()
}
}
}
func (t *T) ShouldPanic(f func(), i ...interface{}) {
defer func() { recover() }()
f()
t.log(msg("should have panicked", i...))
if t.FailNow {
t.T.FailNow()
}
}
func (t *T) Wrap(init, test, cleanup func(*testing.T)) {
if init != nil {
init(t.T)
}
if cleanup != nil {
defer func() { cleanup(t.T) }()
}
test(t.T)
}
func (t *T) Assert(condition bool, i ...interface{}) {
if !condition {
t.log(msg(assertFailMsg, i...))
if t.FailNow {
t.T.FailNow()
}
}
}