clash/common/picker/picker_test.go

42 lines
923 B
Go
Raw Normal View History

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