-
Notifications
You must be signed in to change notification settings - Fork 19
/
error_context_test.go
110 lines (85 loc) · 2.47 KB
/
error_context_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 emperror
import (
"reflect"
"testing"
"emperror.dev/errors"
)
func TestWith(t *testing.T) {
err := errors.New("error")
kvs := []interface{}{"a", 123}
err = With(err, kvs...)
kvs[1] = 0 // With should copy its key values
ctx := Context(err)
if got, want := ctx[0], "a"; got != want {
t.Errorf("context value does not match the expected one\nactual: %s\nexpected: %s", got, want)
}
if got, want := ctx[1], 123; got != want {
t.Errorf("context value does not match the expected one\nactual: %s\nexpected: %d", got, want)
}
if got, want := err.Error(), "error"; got != want {
t.Errorf("error does not match the expected one\nactual: %s\nexpected: %s", got, want)
}
}
func TestWith_Multiple(t *testing.T) {
err := errors.New("")
err = With(With(err, "a", 123), "b", 321)
ctx := Context(err)
if got, want := ctx[0], "a"; got != want {
t.Errorf("context value does not match the expected one\nactual: %s\nexpected: %s", got, want)
}
if got, want := ctx[1], 123; got != want {
t.Errorf("context value does not match the expected one\nactual: %s\nexpected: %d", got, want)
}
if got, want := ctx[2], "b"; got != want {
t.Errorf("context value does not match the expected one\nactual: %s\nexpected: %s", got, want)
}
if got, want := ctx[3], 321; got != want {
t.Errorf("context value does not match the expected one\nactual: %s\nexpected: %d", got, want)
}
}
func TestContextor_MissingValue(t *testing.T) {
err := errors.New("")
err = With(With(err, "k0"), "k1")
ctx := Context(err)
if got, want := len(ctx), 4; got != want {
t.Fatalf("context does not have the required length\nactual: %d\nexpected: %d", got, want)
}
for i := 1; i < 4; i += 2 {
if ctx[i] != nil {
t.Errorf("context value %d is expected to be nil\nactual: %v", i, ctx[i])
}
}
}
func TestContext(t *testing.T) {
err := With(
errors.WithMessage(
With(
errors.Wrap(
With(
errors.New("error"),
"key", "value",
),
"wrapped error",
),
"key2", "value2",
),
"another wrapped error",
),
"key3", "value3",
)
expected := []interface{}{
"key", "value",
"key2", "value2",
"key3", "value3",
}
actual := Context(err)
if got, want := actual, expected; !reflect.DeepEqual(got, want) {
t.Errorf("context does not match the expected one\nactual: %v\nexpected: %v", got, want)
}
}
func TestWith_NilError(t *testing.T) {
err := With(nil)
if err != nil {
t.Errorf("error is expected to be nil\nactual: %v", err)
}
}