github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/internal/gateway/gateway_test.go (about)

     1  package gateway
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/require"
     9  	"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
    10  	"go.opentelemetry.io/otel"
    11  	"go.opentelemetry.io/otel/propagation"
    12  	"go.opentelemetry.io/otel/trace"
    13  	"go.uber.org/goleak"
    14  )
    15  
    16  func TestOtelForwarding(t *testing.T) {
    17  	// Set the global propagator
    18  	otel.SetTextMapPropagator(propagation.TraceContext{})
    19  
    20  	// Create some test IDs
    21  	traceID, err := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736")
    22  	require.Nil(t, err)
    23  	spanID, err := trace.SpanIDFromHex("00f067aa0ba902b7")
    24  	require.Nil(t, err)
    25  
    26  	// Create a context with the test data
    27  	inCtx := trace.ContextWithSpanContext(context.Background(), trace.NewSpanContext(trace.SpanContextConfig{
    28  		TraceID: traceID,
    29  		SpanID:  spanID,
    30  	}))
    31  
    32  	// Create a new http request and inject the context into the headers
    33  	r, err := http.NewRequest(http.MethodPost, "/v1/schema/read", nil)
    34  	require.Nil(t, err)
    35  	otel.GetTextMapPropagator().Inject(inCtx, propagation.HeaderCarrier(r.Header))
    36  
    37  	// Run the annotator with a new context to ensure no existing tracing data
    38  	outCtx := context.Background()
    39  	md := OtelAnnotator(outCtx, r)
    40  
    41  	// Assert the context was injected into the gRPC context.
    42  	_, spanCtx := otelgrpc.Extract(outCtx, &md, defaultOtelOpts...)
    43  	require.True(t, spanCtx.HasTraceID())
    44  	require.Equal(t, traceID, spanCtx.TraceID())
    45  }
    46  
    47  func TestCloseConnections(t *testing.T) {
    48  	defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
    49  
    50  	gatewayHandler, err := NewHandler(context.Background(), "192.0.2.0:4321", "")
    51  	require.NoError(t, err)
    52  	// 4 conns for permission+schema+watch+experimental services, 1 for health check
    53  	require.Len(t, gatewayHandler.closers, 5)
    54  
    55  	// if connections are not closed, goleak would detect it
    56  	require.NoError(t, gatewayHandler.Close())
    57  }