2018-12-05 21:13:29 +08:00
|
|
|
package picker
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2019-07-02 19:18:03 +08:00
|
|
|
func sleepAndSend(ctx context.Context, delay int, input interface{}) func() (interface{}, error) {
|
|
|
|
return func() (interface{}, error) {
|
|
|
|
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()
|
|
|
|
if number != nil && number.(int) != 1 {
|
|
|
|
t.Error("should recv 1", number)
|
2018-12-05 21:13:29 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestPicker_Timeout(t *testing.T) {
|
2019-07-18 00:12:01 +08:00
|
|
|
picker, ctx, cancel := WithTimeout(context.Background(), time.Millisecond*5)
|
2018-12-05 21:13:29 +08:00
|
|
|
defer cancel()
|
2019-07-18 00:12:01 +08:00
|
|
|
|
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()
|
|
|
|
if number != nil {
|
|
|
|
t.Error("should recv nil")
|
2018-12-05 21:13:29 +08:00
|
|
|
}
|
|
|
|
}
|