...
1 package emperror
2
3 import (
4 "testing"
5
6 "github.com/pkg/errors"
7 )
8
9 func TestForEachCause(t *testing.T) {
10 err := errors.WithMessage(
11 errors.WithMessage(
12 errors.WithMessage(
13 errors.New("level 0"),
14 "level 1",
15 ),
16 "level 2",
17 ),
18 "level 3",
19 )
20
21 var i int
22 fn := func(err error) bool {
23 i++
24
25 return true
26 }
27
28 ForEachCause(err, fn)
29
30 if got, want := i, 4; got != want {
31 t.Errorf("error chain length does not match the expected one\nactual: %d\nexpected: %d", got, want)
32 }
33 }
34
35 func TestForEachCause_BreakTheLoop(t *testing.T) {
36 err := errors.WithMessage(
37 errors.WithMessage(
38 errors.WithMessage(
39 errors.New("level 0"),
40 "level 1",
41 ),
42 "level 2",
43 ),
44 "level 3",
45 )
46
47 var i int
48 fn := func(err error) bool {
49 i++
50
51 return !(i > 2)
52 }
53
54 ForEachCause(err, fn)
55
56 if got, want := i, 3; got != want {
57 t.Errorf("error chain length does not match the expected one\nactual: %d\nexpected: %d", got, want)
58 }
59 }
60
61 func TestForEachCause_NilError(t *testing.T) {
62 var i int
63 fn := func(err error) bool {
64 i++
65
66 return !(i > 2)
67 }
68
69 ForEachCause(nil, fn)
70
71 if got, want := i, 0; got != want {
72 t.Errorf("error chain length does not match the expected one\nactual: %d\nexpected: %d", got, want)
73 }
74 }
75
View as plain text