forked from pingcap/errcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgroup_test.go
72 lines (59 loc) · 2.15 KB
/
group_test.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
package errcode_test
import (
"reflect"
"testing"
"github.com/gregwebs/errcode"
"github.com/gregwebs/errors"
)
type MultiErrors struct{ Multi []error }
func (e MultiErrors) Error() string {
return "MultiErrors"
}
func (e MultiErrors) Unwrap() []error {
return e.Multi
}
var _ error = MultiErrors{}
func AssertLength[Any any](t *testing.T, slice []Any, expected int) {
if len(slice) != expected {
t.Helper()
t.Errorf("expected length %d, got: %d. %v", expected, len(slice), slice)
}
}
func TestErrorCodes(t *testing.T) {
codes := errcode.ErrorCodes(nil)
AssertLength(t, codes, 0)
codes = errcode.ErrorCodes(errors.New("no codes"))
AssertLength(t, codes, 0)
codes = errcode.ErrorCodes(MinimalError{})
AssertLength(t, codes, 1)
code := errcode.NewInvalidInputErr(errors.New("inner invalid input"))
codes = errcode.ErrorCodes(code)
AssertLength(t, codes, 1)
code = errcode.NewInvalidInputErr(MinimalError{})
codes = errcode.ErrorCodes(code)
AssertLength(t, codes, 1)
}
func TestErrorCodeChain(t *testing.T) {
AssertCodeChain(t, errors.New("nil"), nil)
code := MinimalError{}
// AssertCodeChain(t, code, code)
ann := errors.Wrap(code, "added annotation")
AssertCodeChain(t, ann, errcode.ChainContext{Top: ann, ErrorCode: code})
ann2 := errors.Wrap(ann, "another annotation")
AssertCodeChain(t, ann2, errcode.ChainContext{Top: ann2, ErrorCode: code})
code2 := MinimalError{}
// horizontal composition
multiCode := errcode.Combine(code, code2)
annMultiCode := errors.Wrap(multiCode, "multi ann")
AssertCodeChain(t, annMultiCode, errcode.ChainContext{Top: annMultiCode, ErrorCode: multiCode})
multiErr := MultiErrors{Multi: []error{errors.New("ignore"), annMultiCode}}
AssertCodeChain(t, multiErr, errcode.ChainContext{Top: multiErr, ErrorCode: errcode.ChainContext{Top: annMultiCode, ErrorCode: multiCode}})
// TODO: vertical composition
}
func AssertCodeChain(t *testing.T, input error, expected errcode.ErrorCode) {
t.Helper()
output := errcode.CodeChain(input)
if !reflect.DeepEqual(output, expected) {
t.Errorf("ErrorCodeChain expected type %T value %#v%v\n got type %T value %#v%v", expected, expected, expected, output, output, output)
}
}