mihomo/common/picker/picker_test.go

42 lines
923 B
Go
Raw Normal View History

2018-12-05 21:13:29 +08:00
package picker
import (
"context"
"testing"
"time"
2023-08-26 21:19:53 +08:00
"github.com/samber/lo"
"github.com/stretchr/testify/assert"
2018-12-05 21:13:29 +08:00
)
2022-04-24 02:07:57 +08:00
func sleepAndSend[T any](ctx context.Context, delay int, input T) func() (T, error) {
return func() (T, error) {
2019-07-02 19:18:03 +08:00
timer := time.NewTimer(time.Millisecond * time.Duration(delay))
select {
case <-timer.C:
return input, nil
case <-ctx.Done():
2023-08-26 21:19:53 +08:00
return lo.Empty[T](), ctx.Err()
2019-07-02 19:18:03 +08:00
}
}
2018-12-05 21:13:29 +08:00
}
func TestPicker_Basic(t *testing.T) {
2022-04-24 02:07:57 +08:00
picker, ctx := WithContext[int](context.Background())
2019-07-02 19:18:03 +08:00
picker.Go(sleepAndSend(ctx, 30, 2))
picker.Go(sleepAndSend(ctx, 20, 1))
2018-12-05 21:13:29 +08:00
2019-07-02 19:18:03 +08:00
number := picker.Wait()
assert.NotNil(t, number)
2022-04-24 02:07:57 +08:00
assert.Equal(t, number, 1)
2018-12-05 21:13:29 +08:00
}
func TestPicker_Timeout(t *testing.T) {
2022-04-24 02:07:57 +08:00
picker, ctx := WithTimeout[int](context.Background(), time.Millisecond*5)
2019-07-02 19:18:03 +08:00
picker.Go(sleepAndSend(ctx, 20, 1))
2018-12-05 21:13:29 +08:00
2019-07-02 19:18:03 +08:00
number := picker.Wait()
2023-08-26 21:19:53 +08:00
assert.Equal(t, number, lo.Empty[int]())
2020-04-16 18:31:40 +08:00
assert.NotNil(t, picker.Error())
}