get.porter.sh/porter@v1.3.0/tests/grpc/test_utils.go (about)

     1  package grpc
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net"
     7  	"testing"
     8  
     9  	pGRPC "get.porter.sh/porter/gen/proto/go/porterapis/porter/v1alpha1"
    10  	"get.porter.sh/porter/pkg/config"
    11  	pServer "get.porter.sh/porter/pkg/grpc/portergrpc"
    12  	"get.porter.sh/porter/pkg/porter"
    13  	grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
    14  
    15  	//"go.opentelemetry.io/otel/attribute"
    16  	"google.golang.org/grpc"
    17  	"google.golang.org/grpc/health"
    18  	"google.golang.org/grpc/health/grpc_health_v1"
    19  	"google.golang.org/grpc/reflection"
    20  	"google.golang.org/grpc/test/bufconn"
    21  )
    22  
    23  type TestPorterGRPCServer struct {
    24  	TestPorter       *porter.TestPorter
    25  	TestPorterConfig *config.TestConfig
    26  }
    27  
    28  var lis *bufconn.Listener
    29  
    30  func NewTestGRPCServer(t *testing.T) (*TestPorterGRPCServer, error) {
    31  	srv := &TestPorterGRPCServer{
    32  		TestPorter:       porter.NewTestPorter(t),
    33  		TestPorterConfig: config.NewTestConfig(t),
    34  	}
    35  	return srv, nil
    36  }
    37  
    38  func (s *TestPorterGRPCServer) newTestInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
    39  	ctx = pServer.AddPorterConnectionToContext(s.TestPorter.Porter, ctx)
    40  	h, err := handler(ctx, req)
    41  	return h, err
    42  }
    43  
    44  func (s *TestPorterGRPCServer) ListenAndServe() *grpc.Server {
    45  	bufSize := 1024 * 1024
    46  	lis = bufconn.Listen(bufSize)
    47  
    48  	srv := grpc.NewServer(
    49  		grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
    50  			s.newTestInterceptor,
    51  		)))
    52  
    53  	healthServer := health.NewServer()
    54  	reflection.Register(srv)
    55  	grpc_health_v1.RegisterHealthServer(srv, healthServer)
    56  	pSvc, err := pServer.NewPorterServer(s.TestPorter.Config)
    57  	if err != nil {
    58  		panic(err)
    59  	}
    60  	pGRPC.RegisterPorterServer(srv, pSvc)
    61  	healthServer.SetServingStatus("test-health", grpc_health_v1.HealthCheckResponse_SERVING)
    62  
    63  	go func() {
    64  		if err := srv.Serve(lis); err != nil {
    65  			panic(fmt.Errorf("failed to serve: %w", err))
    66  		}
    67  	}()
    68  	return srv
    69  }
    70  
    71  func bufDialer(context.Context, string) (net.Conn, error) {
    72  	return lis.Dial()
    73  }