micro/server/grpc/grpc_test.go

90 lines
2.1 KiB
Go
Raw Normal View History

2019-06-03 18:44:43 +01:00
package grpc
import (
"context"
"testing"
"github.com/micro/go-micro/v2/errors"
"github.com/micro/go-micro/v2/registry/memory"
"github.com/micro/go-micro/v2/server"
2019-06-03 18:44:43 +01:00
"google.golang.org/grpc"
"google.golang.org/grpc/status"
2019-06-03 18:44:43 +01:00
pb "github.com/micro/go-micro/v2/server/grpc/proto"
2019-06-03 18:44:43 +01:00
)
// server is used to implement helloworld.GreeterServer.
2019-06-05 10:22:28 +01:00
type testServer struct{}
2019-06-03 18:44:43 +01:00
2019-06-05 10:22:28 +01:00
// TestHello implements helloworld.GreeterServer
func (s *testServer) Call(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
if req.Name == "Error" {
return &errors.Error{Id: "1", Code: 99, Detail: "detail"}
}
2019-06-03 18:44:43 +01:00
rsp.Msg = "Hello " + req.Name
return nil
}
func TestGRPCServer(t *testing.T) {
r := memory.NewRegistry()
s := NewServer(
server.Name("foo"),
server.Registry(r),
)
2019-06-05 10:22:28 +01:00
pb.RegisterTestHandler(s, &testServer{})
2019-06-03 18:44:43 +01:00
if err := s.Start(); err != nil {
t.Fatalf("failed to start: %v", err)
}
// check registration
services, err := r.GetService("foo")
if err != nil || len(services) == 0 {
t.Fatalf("failed to get service: %v # %d", err, len(services))
}
defer func() {
if err := s.Stop(); err != nil {
t.Fatalf("failed to stop: %v", err)
}
}()
cc, err := grpc.Dial(s.Options().Address, grpc.WithInsecure())
if err != nil {
t.Fatalf("failed to dial server: %v", err)
}
2019-06-05 10:22:28 +01:00
testMethods := []string{"/test.Test/Call", "/go.micro.test.Test/Call"}
2019-06-03 18:44:43 +01:00
for _, method := range testMethods {
rsp := pb.Response{}
if err := cc.Invoke(context.Background(), method, &pb.Request{Name: "John"}, &rsp); err != nil {
t.Fatalf("error calling server: %v", err)
}
if rsp.Msg != "Hello John" {
t.Fatalf("Got unexpected response %v", rsp.Msg)
}
}
// Test grpc error
rsp := pb.Response{}
if err := cc.Invoke(context.Background(), "/test.Test/Call", &pb.Request{Name: "Error"}, &rsp); err != nil {
st, ok := status.FromError(err)
if !ok {
t.Fatalf("invalid error received %#+v\n", err)
}
verr, ok := st.Details()[0].(*errors.Error)
if !ok {
t.Fatalf("invalid error received %#+v\n", st.Details()[0])
}
if verr.Code != 99 && verr.Id != "1" && verr.Detail != "detail" {
t.Fatalf("invalid error received %#+v\n", verr)
}
}
2019-06-03 18:44:43 +01:00
}