1
1
// Package assert is a helper package for test assertions.
2
+ //
3
+ // On failure, every assertion will fatal the test.
4
+ //
5
+ // The name parameter is available in each assertion for easier debugging.
2
6
package assert // import "cdr.dev/slog/sloggers/slogtest/assert"
3
7
4
8
import (
9
+ "strings"
5
10
"testing"
6
11
7
12
"cdr.dev/slog"
@@ -24,8 +29,6 @@ func Equal(t testing.TB, exp, act interface{}, name string) {
24
29
}
25
30
26
31
// Success asserts err == nil.
27
- //
28
- // If err isn't nil, it will fatal the test with the error.
29
32
func Success (t testing.TB , err error , name string ) {
30
33
slog .Helper ()
31
34
if err != nil {
@@ -37,9 +40,39 @@ func Success(t testing.TB, err error, name string) {
37
40
}
38
41
39
42
// True asserts act == true.
40
- //
41
- // If act isn't true, it will fatal the test.
42
43
func True (t testing.TB , act bool , name string ) {
43
44
slog .Helper ()
44
45
Equal (t , true , act , name )
45
46
}
47
+
48
+ // Error asserts err != nil.
49
+ func Error (t testing.TB , err error , name string ) {
50
+ slog .Helper ()
51
+ if err == nil {
52
+ slogtest .Fatal (t , "expected error" ,
53
+ slog .F ("name" , name ),
54
+ )
55
+ }
56
+ }
57
+
58
+ // ErrorContains asserts err != nil and err.Error() contains sub.
59
+ //
60
+ // The match will be case insensitive.
61
+ func ErrorContains (t testing.TB , err error , sub , name string ) {
62
+ slog .Helper ()
63
+ Error (t , err , name )
64
+ errs := err .Error ()
65
+ if ! stringContainsFold (errs , sub ) {
66
+ slogtest .Fatal (t , "unexpected error string" ,
67
+ slog .F ("name" , name ),
68
+ slog .F ("error_string" , errs ),
69
+ slog .F ("expected_substring" , sub ),
70
+ )
71
+ }
72
+ }
73
+
74
+ func stringContainsFold (errs , sub string ) bool {
75
+ errs = strings .ToLower (errs )
76
+ sub = strings .ToLower (sub )
77
+ return strings .Contains (errs , sub )
78
+ }
0 commit comments