Fix: urltest get fastest node ehavior (#326)

This commit is contained in:
comwrg
2019-10-12 23:29:00 +08:00
committed by Dreamacro
parent 4cd8b6f24f
commit 0cdc40beb3
5 changed files with 75 additions and 29 deletions

View File

@ -4,6 +4,8 @@ import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func sleepAndSend(ctx context.Context, delay int, input interface{}) func() (interface{}, error) {
@ -24,19 +26,41 @@ func TestPicker_Basic(t *testing.T) {
picker.Go(sleepAndSend(ctx, 20, 1))
number := picker.Wait()
if number != nil && number.(int) != 1 {
t.Error("should recv 1", number)
}
assert.NotNil(t, number)
assert.Equal(t, number.(int), 1)
}
func TestPicker_Timeout(t *testing.T) {
picker, ctx, cancel := WithTimeout(context.Background(), time.Millisecond*5)
defer cancel()
picker, ctx := WithTimeout(context.Background(), time.Millisecond*5)
picker.Go(sleepAndSend(ctx, 20, 1))
number := picker.Wait()
if number != nil {
t.Error("should recv nil")
}
assert.Nil(t, number)
}
func TestPicker_WaitWithoutAutoCancel(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*60)
defer cancel()
picker := WithoutAutoCancel(ctx)
trigger := false
picker.Go(sleepAndSend(ctx, 10, 1))
picker.Go(func() (interface{}, error) {
timer := time.NewTimer(time.Millisecond * time.Duration(30))
select {
case <-timer.C:
trigger = true
return 2, nil
case <-ctx.Done():
return nil, ctx.Err()
}
})
elm := picker.WaitWithoutCancel()
assert.NotNil(t, elm)
assert.Equal(t, elm.(int), 1)
elm = picker.Wait()
assert.True(t, trigger)
assert.Equal(t, elm.(int), 1)
}