-
Notifications
You must be signed in to change notification settings - Fork 4
/
for_each_test.go
95 lines (80 loc) · 2.41 KB
/
for_each_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
package hoff
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/require"
)
type forEachTestCase struct {
In []string
Out []string
}
var forEachTestCases = []forEachTestCase{
{
In: []string{"aaa", "bbb"},
Out: []string{"aaa", "bbb"},
},
{
In: []string{"this", "that"},
Out: []string{"this", "that"},
},
}
func TestForEach(t *testing.T) {
for _, testCase := range forEachTestCases {
// foreach does not return a value, so we need to test
// that the receiver function gets called by pushing each value to an array.
var stringSlice = make([]string, 0, len(testCase.In))
fn := func(s string) {
stringSlice = append(stringSlice, s)
}
ForEach(testCase.In, fn)
require.Equal(t, testCase.Out, stringSlice)
}
}
func TestForEachContext(t *testing.T) {
var key = contextKey("key")
for _, testCase := range forEachTestCases {
// foreach does not return a value, so we need to test
// that the receiver function gets called by pushing each value to an array.
var stringSlice = make([]string, 0, len(testCase.In))
fn := func(c context.Context, s string) {
require.Equal(t, "a_value", c.Value(key))
stringSlice = append(stringSlice, s)
}
ctx := context.WithValue(context.Background(), key, "a_value")
ForEachContext(ctx, testCase.In, fn)
require.Equal(t, testCase.Out, stringSlice)
}
}
func TestForEachContextError(t *testing.T) {
var key = contextKey("key")
input := []string{"aaa", "bbb"}
t.Run(
"success", func(t *testing.T) {
var calledInputs = make([]string, 0, len(input))
fn := func(c context.Context, s string) error {
require.Equal(t, "a_value", c.Value(key))
calledInputs = append(calledInputs, s)
return nil
}
ctx := context.WithValue(context.Background(), key, "a_value")
err := ForEachContextError(ctx, input, fn)
require.Nil(t, err)
require.Equal(t, input, calledInputs)
},
)
t.Run(
"failure", func(t *testing.T) {
var calledInputs = make([]string, 0, len(input))
fn := func(c context.Context, s string) error {
require.Equal(t, "a_value", c.Value(key))
calledInputs = append(calledInputs, s)
return errors.New("catastrophic error")
}
ctx := context.WithValue(context.Background(), key, "a_value")
err := ForEachContextError(ctx, input, fn)
require.ErrorContains(t, err, "catastrophic error")
require.Equal(t, input[0:1], calledInputs) // only first fn was called beacuse it return error
},
)
}