-
Notifications
You must be signed in to change notification settings - Fork 0
/
stdlib-compat_test.go
110 lines (95 loc) · 2.59 KB
/
stdlib-compat_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
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
package errors_test
import (
"testing"
"github.com/TheDSCPL/minimal-errors"
"github.com/stretchr/testify/assert"
)
func TestCustomFunctionsWithStdlib(t *testing.T) {
// This test is to ensure that the custom error factories
// are compatible the stdlib errors API (errors.Is,
// errors.As, errors.Unwrap)
baseErr1 := &customError1{"base"}
baseErr2 := errors.Wrap(baseErr1, "foo")
baseErrIndependent := errors.New("independent")
// Wrap
{
err := errors.Wrap(baseErr2, "bar")
assert.Equal(t, baseErr2, errors.Unwrap(err))
assert.True(t, errors.Is(err, baseErr2))
assert.True(t, errors.Is(err, baseErr1))
var asPtrResult *customError1
var asReturn bool
assert.NotPanics(t, func() {
asReturn = errors.As(err, &asPtrResult)
})
assert.True(t, asReturn)
assert.Panics(t, func() {
asReturn = errors.As(err, &customNonError{})
})
}
// Redefine
{
err := errors.Redefine(baseErrIndependent, baseErr1)
assert.Equal(t, baseErrIndependent, errors.Unwrap(err))
assert.True(t, errors.Is(err, baseErrIndependent))
assert.False(t, errors.Is(err, baseErr1))
assert.False(t, errors.Is(err, baseErr2))
var asPtrResult *customError1
var asReturn bool
assert.NotPanics(t, func() {
asReturn = errors.As(err, &asPtrResult)
})
assert.False(t, asReturn)
assert.NotPanics(t, func() {
// will have the same underlying type as baseErrIndependent
tmp := errors.New("tmp")
asReturn = errors.As(err, &tmp)
})
assert.True(t, asReturn)
assert.Panics(t, func() {
asReturn = errors.As(err, &customNonError{})
})
}
// WithMetadata
{
err := errors.WithMetadata(baseErr2, iMeta2{})
assert.Equal(t, baseErr2, errors.Unwrap(err))
assert.True(t, errors.Is(err, baseErr1))
assert.True(t, errors.Is(err, baseErr2))
var asPtrResult *customError1
var asReturn bool
assert.NotPanics(t, func() {
asReturn = errors.As(err, &asPtrResult)
})
assert.True(t, asReturn)
assert.Panics(t, func() {
asReturn = errors.As(err, &customNonError{})
})
}
// WithCause
{
err := errors.WithCause(baseErr2, baseErrIndependent)
assert.Equal(t, baseErr2, errors.Unwrap(err))
assert.True(t, errors.Is(err, baseErr1))
assert.True(t, errors.Is(err, baseErr2))
assert.False(t, errors.Is(err, baseErrIndependent))
var asPtrResult *customError1
var asReturn bool
assert.NotPanics(t, func() {
asReturn = errors.As(err, &asPtrResult)
})
assert.True(t, asReturn)
assert.Panics(t, func() {
errors.As(err, &customNonError{})
})
}
}
type customError1 struct {
msg string
}
func (e *customError1) Error() string {
return e.msg
}
type customNonError struct {
_ string
}