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 96 97 98 99 100 101 102 103 104 105 106 107
|
package parallel
import (
"context"
"errors"
"fmt"
"strconv"
"testing"
"github.com/bradenaw/juniper/internal/require2"
"github.com/bradenaw/juniper/iterator"
"github.com/bradenaw/juniper/stream"
)
func TestMap(t *testing.T) {
for _, parallelism := range []int{1, 2} {
t.Run(fmt.Sprintf("parallelism=%d", parallelism), func(t *testing.T) {
ints := []int{0, 1, 2, 3, 4}
strs := Map(
parallelism,
ints,
func(i int) string {
return strconv.Itoa(i)
},
)
require2.SlicesEqual(t, []string{"0", "1", "2", "3", "4"}, strs)
})
}
}
func TestMapContext(t *testing.T) {
for _, parallelism := range []int{1, 2} {
t.Run(fmt.Sprintf("parallelism=%d", parallelism), func(t *testing.T) {
ctx := context.Background()
ints := []int{0, 1, 2, 3, 4}
strs, err := MapContext(
ctx,
parallelism,
ints,
func(ctx context.Context, i int) (string, error) {
return strconv.Itoa(i), nil
},
)
require2.NoError(t, err)
require2.SlicesEqual(t, []string{"0", "1", "2", "3", "4"}, strs)
})
}
}
func TestMapIterator(t *testing.T) {
strs := MapIterator(
iterator.Counter(5),
2, // parallelism
0, // bufferSize
func(i int) string {
return strconv.Itoa(i)
},
)
require2.SlicesEqual(t, []string{"0", "1", "2", "3", "4"}, iterator.Collect(strs))
}
func TestMapStream(t *testing.T) {
strsStream := MapStream(
context.Background(),
stream.FromIterator(iterator.Counter(5)),
2, // parallelism
0, // bufferSize
func(ctx context.Context, i int) (string, error) {
return strconv.Itoa(i), nil
},
)
strs, err := stream.Collect(context.Background(), strsStream)
require2.NoError(t, err)
require2.SlicesEqual(t, []string{"0", "1", "2", "3", "4"}, strs)
}
func TestMapStreamError(t *testing.T) {
sender, receiver := stream.Pipe[int](0)
strsStream := MapStream(
context.Background(),
receiver,
2, // parallelism
0, // bufferSize
func(ctx context.Context, i int) (string, error) {
return strconv.Itoa(i), nil
},
)
oopsError := errors.New("oops")
err := sender.Send(context.Background(), 0)
require2.NoError(t, err)
err = sender.Send(context.Background(), 1)
require2.NoError(t, err)
sender.Close(oopsError)
for {
_, err := strsStream.Next(context.Background())
if err == nil {
continue
}
if err != oopsError {
t.Fatalf("%s", err)
}
break
}
}
|