go-zero/rpcx/internal/balancer/p2c/p2c_test.go

109 lines
2.2 KiB
Go
Raw Normal View History

2020-08-06 20:55:38 +08:00
package p2c
2020-08-07 15:28:40 +08:00
import (
"context"
"fmt"
"strconv"
2020-08-20 15:35:13 +08:00
"sync"
2020-08-07 15:28:40 +08:00
"testing"
2020-08-20 15:35:13 +08:00
"time"
2020-08-07 15:28:40 +08:00
"github.com/stretchr/testify/assert"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/mathx"
2020-08-07 15:28:40 +08:00
"google.golang.org/grpc/balancer"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/resolver"
"google.golang.org/grpc/status"
)
func init() {
logx.Disable()
}
func TestP2cPicker_PickNil(t *testing.T) {
builder := new(p2cPickerBuilder)
picker := builder.Build(nil)
_, _, err := picker.Pick(context.Background(), balancer.PickInfo{
FullMethodName: "/",
Ctx: context.Background(),
})
assert.NotNil(t, err)
}
2020-08-06 20:55:38 +08:00
func TestP2cPicker_Pick(t *testing.T) {
2020-08-07 15:28:40 +08:00
tests := []struct {
name string
candidates int
}{
{
name: "single",
candidates: 1,
},
2020-08-20 15:35:13 +08:00
{
name: "two",
candidates: 2,
},
2020-08-07 15:28:40 +08:00
{
name: "multiple",
candidates: 100,
},
}
for _, test := range tests {
2020-08-21 16:57:17 +08:00
test := test
2020-08-07 15:28:40 +08:00
t.Run(test.name, func(t *testing.T) {
2020-08-21 16:57:17 +08:00
t.Parallel()
2020-08-21 23:15:45 +08:00
2020-08-21 16:57:17 +08:00
const total = 100000
2020-08-07 15:28:40 +08:00
builder := new(p2cPickerBuilder)
ready := make(map[resolver.Address]balancer.SubConn)
for i := 0; i < test.candidates; i++ {
ready[resolver.Address{
Addr: strconv.Itoa(i),
}] = new(mockClientConn)
}
picker := builder.Build(ready)
2020-08-20 15:35:13 +08:00
var wg sync.WaitGroup
wg.Add(total)
for i := 0; i < total; i++ {
2020-08-07 15:28:40 +08:00
_, done, err := picker.Pick(context.Background(), balancer.PickInfo{
FullMethodName: "/",
Ctx: context.Background(),
})
assert.Nil(t, err)
if i%100 == 0 {
err = status.Error(codes.DeadlineExceeded, "deadline")
}
2020-08-20 15:35:13 +08:00
go func() {
time.Sleep(time.Millisecond)
done(balancer.DoneInfo{
Err: err,
})
wg.Done()
}()
2020-08-07 15:28:40 +08:00
}
2020-08-20 15:35:13 +08:00
wg.Wait()
2020-08-07 15:28:40 +08:00
dist := make(map[interface{}]int)
conns := picker.(*p2cPicker).conns
for _, conn := range conns {
dist[conn.addr.Addr] = int(conn.requests)
}
entropy := mathx.CalcEntropy(dist)
assert.True(t, entropy > .95, fmt.Sprintf("entropy is %f, less than .95", entropy))
})
}
}
type mockClientConn struct {
}
func (m mockClientConn) UpdateAddresses(addresses []resolver.Address) {
}
2020-08-06 20:55:38 +08:00
2020-08-07 15:28:40 +08:00
func (m mockClientConn) Connect() {
2020-08-06 20:55:38 +08:00
}