-
Notifications
You must be signed in to change notification settings - Fork 0
/
toast.go
151 lines (126 loc) · 2.4 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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
package toast
import (
"errors"
"fmt"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
var (
FailNow = true
format = fmt.Sprintf
)
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 Toaster interface {
FailNow()
Log(args ...interface{})
Error(args ...interface{})
}
type T struct {
T Toaster
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 FromB(t *testing.B) *T {
return &T{t, FailNow, false}
}
func From(t Toaster) *T {
return &T{t, FailNow, false}
}
func (t *T) log(s string) {
t.T.Log(s)
}
func (t *T) logErr(s string) {
f := t.T.Error
if t.mock {
f = t.T.Log
}
f(s)
}
func (t *T) Error(i ...interface{}) {
t.logErr(msg("", i...))
if t.FailNow {
t.T.FailNow()
}
}
func (t *T) CheckErr(err error) {
if err != nil {
t.logErr(msg("", err))
if t.FailNow {
t.T.FailNow()
}
}
}
func (t *T) ExpectErr(err, expect error) {
if !errors.Is(err, expect) {
t.logErr(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.logErr(msg("should have panicked", i...))
if t.FailNow {
t.T.FailNow()
}
}
func (t *T) Wrap(init, test, cleanup func(t Toaster)) {
if init != nil {
init(t.T)
}
if cleanup != nil {
defer func() { cleanup(t.T) }()
}
test(t.T)
}
func (t *T) TimeIt(name string, f func()) {
timer := time.Now()
f()
t.log(msg("", "Time", format("%s:", name), time.Since(timer).String()))
}
func (t *T) Assert(condition bool, i ...interface{}) {
if !condition {
t.logErr(msg(assertFailMsg, i...))
if t.FailNow {
t.T.FailNow()
}
}
}