@@ -8,6 +8,7 @@ package util
8
8
import (
9
9
"testing"
10
10
11
+ "github.com/cockroachdb/errors"
11
12
"github.com/stretchr/testify/require"
12
13
)
13
14
@@ -123,6 +124,46 @@ func TestMap(t *testing.T) {
123
124
}))
124
125
}
125
126
127
+ func TestMapErr (t * testing.T ) {
128
+ t .Run ("empty slice" , func (t * testing.T ) {
129
+ out , err := MapE (nil , func (i int ) (int , error ) {
130
+ require .Fail (t , "should not be called" )
131
+ return 0 , nil
132
+ })
133
+ require .NoError (t , err )
134
+ require .Equal (t , []int {}, out )
135
+ })
136
+
137
+ t .Run ("map to same type" , func (t * testing.T ) {
138
+ out , err := MapE ([]int {1 , 2 , 3 }, func (i int ) (int , error ) {
139
+ return i * 2 , nil
140
+ })
141
+ require .NoError (t , err )
142
+ require .Equal (t , []int {2 , 4 , 6 }, out )
143
+ })
144
+
145
+ t .Run ("map to different type" , func (t * testing.T ) {
146
+ out , err := MapE ([]int {1 , 2 , 3 }, func (i int ) (string , error ) {
147
+ return string (rune ('a' + i - 1 )), nil
148
+ })
149
+ require .NoError (t , err )
150
+ require .Equal (t , []string {"a" , "b" , "c" }, out )
151
+ })
152
+
153
+ t .Run ("error case" , func (t * testing.T ) {
154
+ out , err := MapE ([]int {1 , 2 , 3 }, func (i int ) (int , error ) {
155
+ if i == 2 {
156
+ return 0 , errors .New ("error on 2" )
157
+ } else if i == 3 {
158
+ require .Fail (t , "should not be called" )
159
+ }
160
+ return i * 2 , nil
161
+ })
162
+ require .Error (t , err )
163
+ require .Nil (t , out )
164
+ })
165
+ }
166
+
126
167
func TestMapFrom (t * testing.T ) {
127
168
require .Equal (t , map [int ]bool {}, MapFrom (nil , func (i int ) (int , bool ) {
128
169
require .Fail (t , "should not be called" )
0 commit comments