-
Notifications
You must be signed in to change notification settings - Fork 0
/
option.go
88 lines (76 loc) · 2.14 KB
/
option.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
package assert
import (
"fmt"
"testing"
)
type options struct {
messageTransforms []func(msg string) string
report ReportFunc
}
func buildOptions(tb testing.TB, opts []Option) *options { //nolint:thelper // It's not a test helper.
o := &options{
report: tb.Fatal,
}
for _, opt := range opts {
opt(o)
}
return o
}
// Option is an option for an assertion.
type Option func(*options)
// Lazy returns an [Option] that defers the evaluation of the option.
//
// It helps to reduce allocations when the option is not used.
func Lazy(f func() Option) Option {
return func(o *options) {
f()(o)
}
}
// Options returns an [Option] that combines several options.
func Options(opts ...Option) Option {
return func(o *options) {
for _, opt := range opts {
opt(o)
}
}
}
// MessageTransform returns an [Option] that adds a message transform function.
// The function is called before the ReportFunc.
// If several function are added, they're called in order.
func MessageTransform(f func(msg string) string) Option {
return func(o *options) {
o.messageTransforms = append(o.messageTransforms, f)
}
}
// Message returns an [Option] that sets the message.
func Message(msg string) Option {
return MessageTransform(func(_ string) string {
return msg
})
}
// Messagef returns an [Option] that sets the formatted message.
func Messagef(format string, args ...any) Option {
return MessageTransform(func(_ string) string {
return fmt.Sprintf(format, args...)
})
}
// MessageWrap returns an [Option] that wraps the message.
// The final message is "<msg>: <original message>".
func MessageWrap(msg string) Option {
return MessageTransform(func(wrappedMsg string) string {
return msg + ": " + wrappedMsg
})
}
// MessageWrapf returns an [Option] that wraps the message.
// The final message is "<format msg>: <original message>".
func MessageWrapf(format string, args ...any) Option {
return MessageTransform(func(wrappedMsg string) string {
return fmt.Sprintf(format, args...) + ": " + wrappedMsg
})
}
// Report returns an [Option] that sets the report function.
func Report(f ReportFunc) Option {
return func(o *options) {
o.report = f
}
}