micro-client-grpc/grpc_pool_test.go

66 lines
1.3 KiB
Go
Raw Normal View History

2019-06-03 18:44:43 +01:00
package grpc
import (
"context"
2019-06-03 18:44:43 +01:00
"net"
"testing"
"time"
pb "github.com/unistack-org/micro-client-grpc/proto"
2019-06-03 18:44:43 +01:00
"google.golang.org/grpc"
pgrpc "google.golang.org/grpc"
)
func testPool(t *testing.T, size int, ttl time.Duration, idle int, ms int) {
2019-06-03 18:44:43 +01:00
// setup server
l, err := net.Listen("tcp", ":0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer l.Close()
ctx := context.Background()
2019-06-03 18:44:43 +01:00
s := pgrpc.NewServer()
pb.RegisterTestServer(s, &testServer{})
2019-06-03 18:44:43 +01:00
go s.Serve(l)
defer s.Stop()
// zero pool
p := newPool(size, ttl, idle, ms)
2019-06-03 18:44:43 +01:00
for i := 0; i < 10; i++ {
// get a conn
cc, err := p.getConn(ctx, l.Addr().String(), grpc.WithInsecure())
2019-06-03 18:44:43 +01:00
if err != nil {
t.Fatal(err)
}
rsp := pb.Response{}
2019-06-03 18:44:43 +01:00
err = cc.Invoke(context.TODO(), "/helloworld.Test/CallNative", &pb.Request{Name: "John"}, &rsp)
2019-06-03 18:44:43 +01:00
if err != nil {
t.Fatal(err)
}
if rsp.Msg != "Hello John" {
t.Fatalf("Got unexpected response %v", rsp.Msg)
2019-06-03 18:44:43 +01:00
}
// release the conn
p.release(l.Addr().String(), cc, nil)
p.Lock()
if i := p.conns[l.Addr().String()].count; i > size {
2019-06-03 18:44:43 +01:00
p.Unlock()
t.Fatalf("pool size %d is greater than expected %d", i, size)
}
p.Unlock()
}
}
func TestGRPCPool(t *testing.T) {
testPool(t, 0, time.Minute, 10, 2)
testPool(t, 2, time.Minute, 10, 1)
2019-06-03 18:44:43 +01:00
}