| |
| package dataloader |
|
|
| import ( |
| "context" |
| "sync" |
| "testing" |
| "time" |
|
|
| "github.com/stretchr/testify/require" |
| ) |
|
|
| |
| func TestFetcher_FetchOne(t *testing.T) { |
| type example struct{ ID string } |
| l := &Fetcher[string, example]{ |
| MaxBatch: 10, |
| Delay: time.Millisecond, |
| IDFunc: func(v example) string { return v.ID }, |
| FetchFunc: func(context.Context, []string) ([]example, error) { return []example{{ID: "foo"}}, nil }, |
| } |
|
|
| res, err := l.FetchOne(context.Background(), "foo") |
| require.NoError(t, err) |
| require.Equal(t, "foo", res.ID) |
| } |
|
|
| |
| |
| func TestFetcher_FetchOne_Int(t *testing.T) { |
| type example struct{ ID int64 } |
| l := &Fetcher[int64, example]{ |
| MaxBatch: 10, |
| Delay: time.Millisecond, |
| IDFunc: func(v example) int64 { return v.ID }, |
| FetchFunc: func(context.Context, []int64) ([]example, error) { return []example{{ID: 42}}, nil }, |
| } |
|
|
| res, err := l.FetchOne(context.Background(), 42) |
| require.NoError(t, err) |
| require.NotNil(t, res) |
| require.Equal(t, int64(42), res.ID) |
| } |
|
|
| |
| |
| func TestFetcher_FetchOne_Extra(t *testing.T) { |
| type example struct{ id string } |
| l := &Fetcher[string, example]{ |
| MaxBatch: 10, |
| Delay: time.Millisecond, |
| IDFunc: func(v example) string { return v.id }, |
| FetchFunc: func(context.Context, []string) ([]example, error) { return []example{{id: "bar"}}, nil }, |
| } |
| ctx, done := context.WithTimeout(context.Background(), time.Second) |
| defer done() |
|
|
| res, err := l.FetchOne(ctx, "foo") |
| require.NoError(t, err) |
| require.Nil(t, res) |
| } |
|
|
| |
| |
| func TestFetcher_MaxBatch(t *testing.T) { |
| type example struct{ ID string } |
|
|
| var mx sync.Mutex |
| var batchSizes []int |
| l := &Fetcher[string, example]{ |
| MaxBatch: 3, |
| Delay: time.Millisecond, |
| IDFunc: func(v example) string { return v.ID }, |
| FetchFunc: func(ctx context.Context, ids []string) ([]example, error) { |
| mx.Lock() |
| batchSizes = append(batchSizes, len(ids)) |
| mx.Unlock() |
| var results []example |
| for _, id := range ids { |
| results = append(results, example{ID: id}) |
| } |
| return results, nil |
| }, |
| } |
|
|
| ctx := context.Background() |
|
|
| |
| type result struct { |
| res *example |
| err error |
| } |
| results := make(chan result, 7) |
|
|
| for i := 0; i < 7; i++ { |
| go func(id string) { |
| res, err := l.FetchOne(ctx, id) |
| results <- result{res, err} |
| }(string(rune('a' + i))) |
| } |
|
|
| |
| for i := 0; i < 7; i++ { |
| r := <-results |
| require.NoError(t, r.err) |
| require.NotNil(t, r.res) |
| } |
|
|
| |
| time.Sleep(10 * time.Millisecond) |
|
|
| |
| for _, size := range batchSizes { |
| require.LessOrEqual(t, size, 3, "Batch size should not exceed MaxBatch") |
| } |
|
|
| |
| require.GreaterOrEqual(t, len(batchSizes), 3, "Should have created multiple batches") |
| } |
|
|