@@ -8,6 +8,7 @@ package util
88import (
99 "testing"
1010
11+ "github.com/cockroachdb/errors"
1112 "github.com/stretchr/testify/require"
1213)
1314
@@ -123,6 +124,46 @@ func TestMap(t *testing.T) {
123124 }))
124125}
125126
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+
126167func TestMapFrom (t * testing.T ) {
127168 require .Equal (t , map [int ]bool {}, MapFrom (nil , func (i int ) (int , bool ) {
128169 require .Fail (t , "should not be called" )
0 commit comments