112 lines
2.6 KiB
Go
112 lines
2.6 KiB
Go
|
|
package grpc
|
|
|
|
import (
|
|
"context"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"google.golang.org/grpc"
|
|
|
|
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
|
|
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/otel"
|
|
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc/opts"
|
|
)
|
|
|
|
// Mock gRPC service
|
|
type mockService struct{}
|
|
|
|
type MockServiceServer interface {
|
|
TestMethod(context.Context, *mockRequest) (*mockResponse, error)
|
|
}
|
|
|
|
type mockRequest struct{}
|
|
type mockResponse struct{}
|
|
|
|
func (s *mockService) TestMethod(ctx context.Context, req *mockRequest) (*mockResponse, error) {
|
|
return &mockResponse{}, nil
|
|
}
|
|
|
|
var _MockService_serviceDesc = grpc.ServiceDesc{
|
|
ServiceName: "test.MockService",
|
|
HandlerType: (*MockServiceServer)(nil),
|
|
Methods: []grpc.MethodDesc{
|
|
{
|
|
MethodName: "TestMethod",
|
|
Handler: func(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
|
in := new(mockRequest)
|
|
if err := dec(in); err != nil {
|
|
return nil, err
|
|
}
|
|
if interceptor == nil {
|
|
return srv.(MockServiceServer).TestMethod(ctx, in)
|
|
}
|
|
info := &grpc.UnaryServerInfo{
|
|
Server: srv,
|
|
FullMethod: "/test.MockService/TestMethod",
|
|
}
|
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
|
return srv.(MockServiceServer).TestMethod(ctx, req.(*mockRequest))
|
|
}
|
|
return interceptor(ctx, in, info, handler)
|
|
},
|
|
},
|
|
},
|
|
Streams: []grpc.StreamDesc{},
|
|
Metadata: "mock.proto",
|
|
}
|
|
|
|
func TestInitGRPCServer(t *testing.T) {
|
|
cfg := &config.AppConfig{
|
|
Name: "test-app",
|
|
GRPC: &config.GRPCConfig{
|
|
Enabled: true,
|
|
Listen: "127.0.0.1:0", // Use random available port
|
|
},
|
|
}
|
|
ctx := cfg.AddToCtx(context.Background())
|
|
ctx, _ = otel.Init(ctx)
|
|
|
|
grpcOpts := &opts.GRPCOpts{
|
|
GRPCConfig: cfg.GRPC,
|
|
AppGRPC: &opts.AppGRPC{
|
|
Services: []*opts.GRPCService{
|
|
{
|
|
Name: "mock",
|
|
Type: &_MockService_serviceDesc,
|
|
Service: &mockService{},
|
|
},
|
|
},
|
|
},
|
|
}
|
|
|
|
shutdown, done, err := InitGRPCServer(ctx, grpcOpts)
|
|
assert.NoError(t, err)
|
|
assert.NotNil(t, shutdown)
|
|
assert.NotNil(t, done)
|
|
|
|
// Shutdown the server
|
|
err = shutdown(context.Background())
|
|
assert.NoError(t, err)
|
|
}
|
|
|
|
func TestInitGRPCServer_NoServices(t *testing.T) {
|
|
cfg := &config.AppConfig{
|
|
Name: "test-app",
|
|
GRPC: &config.GRPCConfig{
|
|
Enabled: true,
|
|
Listen: "127.0.0.1:0",
|
|
},
|
|
}
|
|
ctx := cfg.AddToCtx(context.Background())
|
|
ctx, _ = otel.Init(ctx)
|
|
|
|
grpcOpts := &opts.GRPCOpts{
|
|
GRPCConfig: cfg.GRPC,
|
|
AppGRPC: &opts.AppGRPC{},
|
|
}
|
|
|
|
_, _, err := InitGRPCServer(ctx, grpcOpts)
|
|
assert.Error(t, err)
|
|
}
|