mihomo/common/picker/picker_test.go

41 lines
865 B
Go
Raw Normal View History

2018-12-05 21:13:29 +08:00
package picker
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
2018-12-05 21:13:29 +08:00
)
2022-03-16 12:10:13 +08:00
func sleepAndSend(ctx context.Context, delay int, input any) func() (any, error) {
return func() (any, 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():
return nil, ctx.Err()
}
}
2018-12-05 21:13:29 +08:00
}
func TestPicker_Basic(t *testing.T) {
2019-07-02 19:18:03 +08:00
picker, ctx := WithContext(context.Background())
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)
assert.Equal(t, number.(int), 1)
2018-12-05 21:13:29 +08:00
}
func TestPicker_Timeout(t *testing.T) {
picker, ctx := WithTimeout(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()
assert.Nil(t, number)
2020-04-16 18:31:40 +08:00
assert.NotNil(t, picker.Error())
}