2019-06-03 20:44:43 +03:00
|
|
|
package grpc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net"
|
|
|
|
"testing"
|
|
|
|
|
2020-01-30 14:39:00 +03:00
|
|
|
"github.com/micro/go-micro/v2/client"
|
|
|
|
"github.com/micro/go-micro/v2/client/selector"
|
|
|
|
"github.com/micro/go-micro/v2/registry"
|
|
|
|
"github.com/micro/go-micro/v2/registry/memory"
|
2019-06-03 20:44:43 +03:00
|
|
|
pgrpc "google.golang.org/grpc"
|
|
|
|
pb "google.golang.org/grpc/examples/helloworld/helloworld"
|
|
|
|
)
|
|
|
|
|
|
|
|
// server is used to implement helloworld.GreeterServer.
|
|
|
|
type greeterServer struct{}
|
|
|
|
|
|
|
|
// SayHello implements helloworld.GreeterServer
|
|
|
|
func (g *greeterServer) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
|
|
|
|
return &pb.HelloReply{Message: "Hello " + in.Name}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestGRPCClient(t *testing.T) {
|
|
|
|
l, err := net.Listen("tcp", ":0")
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("failed to listen: %v", err)
|
|
|
|
}
|
|
|
|
defer l.Close()
|
|
|
|
|
|
|
|
s := pgrpc.NewServer()
|
|
|
|
pb.RegisterGreeterServer(s, &greeterServer{})
|
|
|
|
|
|
|
|
go s.Serve(l)
|
|
|
|
defer s.Stop()
|
|
|
|
|
|
|
|
// create mock registry
|
|
|
|
r := memory.NewRegistry()
|
|
|
|
|
|
|
|
// register service
|
|
|
|
r.Register(®istry.Service{
|
2019-06-19 14:34:45 +03:00
|
|
|
Name: "helloworld",
|
2019-06-03 20:44:43 +03:00
|
|
|
Version: "test",
|
|
|
|
Nodes: []*registry.Node{
|
2019-11-01 18:07:53 +03:00
|
|
|
{
|
2019-06-03 20:44:43 +03:00
|
|
|
Id: "test-1",
|
2019-07-17 10:38:50 +03:00
|
|
|
Address: l.Addr().String(),
|
2019-11-25 19:31:43 +03:00
|
|
|
Metadata: map[string]string{
|
|
|
|
"protocol": "grpc",
|
|
|
|
},
|
2019-06-03 20:44:43 +03:00
|
|
|
},
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
// create selector
|
|
|
|
se := selector.NewSelector(
|
|
|
|
selector.Registry(r),
|
|
|
|
)
|
|
|
|
|
|
|
|
// create client
|
|
|
|
c := NewClient(
|
|
|
|
client.Registry(r),
|
|
|
|
client.Selector(se),
|
|
|
|
)
|
|
|
|
|
|
|
|
testMethods := []string{
|
|
|
|
"/helloworld.Greeter/SayHello",
|
|
|
|
"Greeter.SayHello",
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, method := range testMethods {
|
2019-06-19 14:34:45 +03:00
|
|
|
req := c.NewRequest("helloworld", method, &pb.HelloRequest{
|
2019-06-03 20:44:43 +03:00
|
|
|
Name: "John",
|
|
|
|
})
|
|
|
|
|
|
|
|
rsp := pb.HelloReply{}
|
|
|
|
|
|
|
|
err = c.Call(context.TODO(), req, &rsp)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if rsp.Message != "Hello John" {
|
|
|
|
t.Fatalf("Got unexpected response %v", rsp.Message)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|