Bufconn Test
In-memory gRPC test using bufconn. No network, no port conflicts.
package main
import (
"context"
"net"
"testing"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/grpc/test/bufconn"
"shortener/pb"
)
func setupTest(t *testing.T) pb.LinkServiceClient {
t.Helper()
lis := bufconn.Listen(1024 * 1024)
srv := grpc.NewServer()
pb.RegisterLinkServiceServer(srv, newLinkServer())
go srv.Serve(lis)
t.Cleanup(func() { srv.Stop(); lis.Close() })
conn, err := grpc.NewClient("passthrough:///bufconn",
grpc.WithContextDialer(func(ctx context.Context, s string) (net.Conn, error) {
return lis.DialContext(ctx)
}),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { conn.Close() })
return pb.NewLinkServiceClient(conn)
}
func TestCreateAndGet(t *testing.T) {
client := setupTest(t)
ctx := context.Background()
created, err := client.CreateLink(ctx, &pb.CreateLinkRequest{Url: "https://test.com"})
if err != nil {
t.Fatal(err)
}
fetched, err := client.GetLink(ctx, &pb.GetLinkRequest{ShortCode: created.GetLink().GetShortCode()})
if err != nil {
t.Fatal(err)
}
if fetched.GetLink().GetUrl() != "https://test.com" {
t.Errorf("got %q, want %q", fetched.GetLink().GetUrl(), "https://test.com")
}
}
func TestGetNotFound(t *testing.T) {
client := setupTest(t)
_, err := client.GetLink(context.Background(), &pb.GetLinkRequest{ShortCode: "nope"})
st, _ := status.FromError(err)
if st.Code() != codes.NotFound {
t.Errorf("got %v, want NotFound", st.Code())
}
}