Last active
April 11, 2024 20:37
-
-
Save pellared/1be421c4a7bee3406fbadb04c12bda26 to your computer and use it in GitHub Desktop.
grpctest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"net" | |
"testing" | |
"github.com/stretchr/testify/assert" | |
"github.com/stretchr/testify/require" | |
"google.golang.org/grpc" | |
) | |
// NewGRPCTestServer starts a gRPC server for testing purposes. | |
// The gRPC server is stopped at the end of the test during Cleanup. | |
// Use the register callback to setup custom gRPC method handlers. | |
func NewGRPCTestServer(t *testing.T, register func(*grpc.Server), opts ...grpc.ServerOption) net.Listener { | |
t.Helper() | |
l, err := net.Listen("tcp", "127.0.0.1:0") | |
require.NoError(t, err, "failed to open port") | |
srv := grpc.NewServer(opts...) | |
register(srv) | |
errCh := make(chan error, 1) | |
go func() { | |
errCh <- srv.Serve(l) | |
}() | |
t.Cleanup(func() { | |
srv.Stop() | |
assert.NoError(t, <-errCh, "grpcServer.Serve errored") | |
}) | |
return l | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment