You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/rpcx/internal/balancer/p2c/p2c_test.go

109 lines
2.2 KiB
Go

package p2c
4 years ago
import (
"context"
"fmt"
"strconv"
4 years ago
"sync"
4 years ago
"testing"
4 years ago
"time"
4 years ago
"github.com/stretchr/testify/assert"
"github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/mathx"
4 years ago
"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)
}
func TestP2cPicker_Pick(t *testing.T) {
4 years ago
tests := []struct {
name string
candidates int
}{
{
name: "single",
candidates: 1,
},
4 years ago
{
name: "two",
candidates: 2,
},
4 years ago
{
name: "multiple",
candidates: 100,
},
}
for _, test := range tests {
4 years ago
test := test
4 years ago
t.Run(test.name, func(t *testing.T) {
4 years ago
t.Parallel()
4 years ago
const total = 100000
4 years ago
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)
4 years ago
var wg sync.WaitGroup
wg.Add(total)
for i := 0; i < total; i++ {
4 years ago
_, 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")
}
4 years ago
go func() {
time.Sleep(time.Millisecond)
done(balancer.DoneInfo{
Err: err,
})
wg.Done()
}()
4 years ago
}
4 years ago
wg.Wait()
4 years ago
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) {
}
4 years ago
func (m mockClientConn) Connect() {
}