2021-07-21 17:01:02 +08:00
|
|
|
package batch
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
"strconv"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestBatch(t *testing.T) {
|
2022-04-24 02:07:57 +08:00
|
|
|
b, _ := New[string](context.Background())
|
2021-07-21 17:01:02 +08:00
|
|
|
|
|
|
|
now := time.Now()
|
2022-04-24 02:07:57 +08:00
|
|
|
b.Go("foo", func() (string, error) {
|
2021-07-21 17:01:02 +08:00
|
|
|
time.Sleep(time.Millisecond * 100)
|
|
|
|
return "foo", nil
|
|
|
|
})
|
2022-04-24 02:07:57 +08:00
|
|
|
b.Go("bar", func() (string, error) {
|
2021-07-21 17:01:02 +08:00
|
|
|
time.Sleep(time.Millisecond * 150)
|
|
|
|
return "bar", nil
|
|
|
|
})
|
|
|
|
result, err := b.WaitAndGetResult()
|
|
|
|
|
|
|
|
assert.Nil(t, err)
|
|
|
|
|
|
|
|
duration := time.Since(now)
|
|
|
|
assert.Less(t, duration, time.Millisecond*200)
|
|
|
|
assert.Equal(t, 2, len(result))
|
|
|
|
|
|
|
|
for k, v := range result {
|
|
|
|
assert.NoError(t, v.Err)
|
2022-04-24 02:07:57 +08:00
|
|
|
assert.Equal(t, k, v.Value)
|
2021-07-21 17:01:02 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestBatchWithConcurrencyNum(t *testing.T) {
|
2022-04-24 02:07:57 +08:00
|
|
|
b, _ := New[string](
|
2021-07-23 00:30:23 +08:00
|
|
|
context.Background(),
|
2022-04-24 02:07:57 +08:00
|
|
|
WithConcurrencyNum[string](3),
|
2021-07-21 17:01:02 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
now := time.Now()
|
|
|
|
for i := 0; i < 7; i++ {
|
|
|
|
idx := i
|
2022-04-24 02:07:57 +08:00
|
|
|
b.Go(strconv.Itoa(idx), func() (string, error) {
|
2021-07-21 17:01:02 +08:00
|
|
|
time.Sleep(time.Millisecond * 100)
|
|
|
|
return strconv.Itoa(idx), nil
|
|
|
|
})
|
|
|
|
}
|
|
|
|
result, _ := b.WaitAndGetResult()
|
|
|
|
duration := time.Since(now)
|
|
|
|
assert.Greater(t, duration, time.Millisecond*260)
|
|
|
|
assert.Equal(t, 7, len(result))
|
|
|
|
|
|
|
|
for k, v := range result {
|
|
|
|
assert.NoError(t, v.Err)
|
2022-04-24 02:07:57 +08:00
|
|
|
assert.Equal(t, k, v.Value)
|
2021-07-21 17:01:02 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestBatchContext(t *testing.T) {
|
2022-04-24 02:07:57 +08:00
|
|
|
b, ctx := New[string](context.Background())
|
2021-07-21 17:01:02 +08:00
|
|
|
|
2022-04-24 02:07:57 +08:00
|
|
|
b.Go("error", func() (string, error) {
|
2021-07-21 17:01:02 +08:00
|
|
|
time.Sleep(time.Millisecond * 100)
|
2022-04-24 02:07:57 +08:00
|
|
|
return "", errors.New("test error")
|
2021-07-21 17:01:02 +08:00
|
|
|
})
|
|
|
|
|
2022-04-24 02:07:57 +08:00
|
|
|
b.Go("ctx", func() (string, error) {
|
2021-07-21 17:01:02 +08:00
|
|
|
<-ctx.Done()
|
2022-04-24 02:07:57 +08:00
|
|
|
return "", ctx.Err()
|
2021-07-21 17:01:02 +08:00
|
|
|
})
|
|
|
|
|
|
|
|
result, err := b.WaitAndGetResult()
|
|
|
|
|
|
|
|
assert.NotNil(t, err)
|
|
|
|
assert.Equal(t, "error", err.Key)
|
|
|
|
|
|
|
|
assert.Equal(t, ctx.Err(), result["ctx"].Err)
|
|
|
|
}
|