summaryrefslogtreecommitdiff
path: root/pkg/errorhandling/errorhandling_test.go
blob: ec720c5e7c41f102693860c90727030745b97dc4 (plain)
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
package errorhandling

import (
	"errors"
	"fmt"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestCause(t *testing.T) {
	t.Parallel()

	for _, tc := range []struct {
		name        string
		err         func() error
		expectedErr error
	}{
		{
			name:        "nil error",
			err:         func() error { return nil },
			expectedErr: nil,
		},
		{
			name:        "equal errors",
			err:         func() error { return errors.New("foo") },
			expectedErr: errors.New("foo"),
		},
		{
			name:        "wrapped error",
			err:         func() error { return fmt.Errorf("baz: %w", fmt.Errorf("bar: %w", errors.New("foo"))) },
			expectedErr: errors.New("foo"),
		},
		{
			name: "max depth reached",
			err: func() error {
				err := errors.New("error")
				for i := 0; i <= 101; i++ {
					err = fmt.Errorf("%d: %w", i, err)
				}
				return err
			},
			expectedErr: fmt.Errorf("0: %w", errors.New("error")),
		},
	} {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			t.Parallel()
			err := Cause(tc.err())
			assert.Equal(t, tc.expectedErr, err)
		})
	}
}