-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patherrors.go
60 lines (52 loc) · 1.42 KB
/
errors.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
package testament
import (
"testing"
"github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// AssertInError returns true if the needle is found in stack, which is created
// either with pkg/errors help, the multierror or Go's error wrap. It will fall
// back to checking the contents of the needle.Error() is in haystack.Error().
func AssertInError(t *testing.T, haystack, needle error) bool {
t.Helper()
if haystack == nil || needle == nil {
t.Errorf("want %v in %v", needle, haystack)
return false
}
if errors.Is(haystack, needle) {
return true
}
contains := func() bool {
return assert.Containsf(t, haystack.Error(), needle.Error(),
"want\n\t%v\nin\n\t%v", needle, haystack,
)
}
var merr *multierror.Error
ok := errors.As(haystack, &merr)
if !ok {
return contains()
}
for _, err := range merr.Errors {
if errors.Is(err, needle) {
return true
}
}
return contains()
}
// AssertIsCode is a helper to assert the err error contains the code.
func AssertIsCode(t *testing.T, err error, code codes.Code) bool {
t.Helper()
if !assert.Error(t, err, "empty error") {
return false
}
st := status.Convert(errors.Cause(err))
if !assert.NotNil(t, st, "empty status") {
return false
}
return assert.EqualValuesf(t, code, st.Code(),
"got %q code, want %q. error: %#v", st.Code(), code, err,
)
}