github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/client/grpc/pool_test.go (about) 1 // Copyright 2020 Asim Aslam 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // Original source: github.com/micro/go-micro/v3/client/grpc/grpc_pool_test.go 16 17 package grpc 18 19 import ( 20 "context" 21 "net" 22 "testing" 23 "time" 24 25 "google.golang.org/grpc" 26 pgrpc "google.golang.org/grpc" 27 pb "github.com/tickoalcantara12/micro/v3/service/client/grpc/proto" 28 ) 29 30 func testPool(t *testing.T, size int, ttl time.Duration, idle int, ms int) { 31 // setup server 32 l, err := net.Listen("tcp", ":0") 33 if err != nil { 34 t.Fatalf("failed to listen: %v", err) 35 } 36 defer l.Close() 37 38 s := pgrpc.NewServer() 39 pb.RegisterGreeterServer(s, &greeterServer{}) 40 41 go s.Serve(l) 42 defer s.Stop() 43 44 // zero pool 45 p := newPool(size, ttl, idle, ms) 46 47 for i := 0; i < 10; i++ { 48 // get a conn 49 cc, err := p.getConn(l.Addr().String(), grpc.WithInsecure()) 50 if err != nil { 51 t.Fatal(err) 52 } 53 54 rsp := pb.HelloReply{} 55 56 err = cc.Invoke(context.TODO(), "/helloworld.Greeter/SayHello", &pb.HelloRequest{Name: "John"}, &rsp) 57 if err != nil { 58 t.Fatal(err) 59 } 60 61 if rsp.Message != "Hello John" { 62 t.Fatalf("Got unexpected response %v", rsp.Message) 63 } 64 65 // release the conn 66 p.release(l.Addr().String(), cc, nil) 67 68 p.Lock() 69 if i := p.conns[l.Addr().String()].count; i > size { 70 p.Unlock() 71 t.Fatalf("pool size %d is greater than expected %d", i, size) 72 } 73 p.Unlock() 74 } 75 } 76 77 func TestGRPCPool(t *testing.T) { 78 testPool(t, 0, time.Minute, 10, 2) 79 testPool(t, 2, time.Minute, 10, 1) 80 }