package telemetry import ( "bytes" "context" "errors" "log/slog" "net/http" "net/http/httptest" "strings" "testing" "github.com/jackc/pgx/v5" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/propagation" sdktrace "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/sdk/trace/tracetest" "go.opentelemetry.io/otel/trace" ) // record installs a recording provider for one test. func record(t *testing.T) *tracetest.SpanRecorder { t.Helper() rec := tracetest.NewSpanRecorder() tp, err := newProvider(context.Background(), Info{Service: "tenant-registry"}, sdktrace.WithSpanProcessor(rec)) if err != nil { t.Fatal(err) } prev := otel.GetTracerProvider() otel.SetTracerProvider(tp) otel.SetTextMapPropagator(propagation.TraceContext{}) t.Cleanup(func() { otel.SetTracerProvider(prev) }) return rec } func attr(s sdktrace.ReadOnlySpan, key string) (attribute.Value, bool) { for _, kv := range s.Attributes() { if string(kv.Key) == key { return kv.Value, true } } return attribute.Value{}, false } // inSpan returns a context inside a recorded parent span. func inSpan(t *testing.T) (context.Context, trace.Span) { t.Helper() return otel.Tracer("test").Start(context.Background(), "parent") } func TestSetupWithoutEndpointIsNoop(t *testing.T) { t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "") shutdown, err := Setup(context.Background(), Info{Service: "tenant-registry"}) if err != nil { t.Fatal(err) } if err := shutdown(context.Background()); err != nil { t.Fatal(err) } if _, ok := otel.GetTextMapPropagator().(propagation.TraceContext); !ok { t.Fatalf("propagator = %T, want TraceContext", otel.GetTextMapPropagator()) } } func TestSetupWithEndpoint(t *testing.T) { t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://127.0.0.1:1") prev := otel.GetTracerProvider() t.Cleanup(func() { otel.SetTracerProvider(prev) }) shutdown, err := Setup(context.Background(), Info{Service: "tenant-registry", Version: "v0.1.9", Commit: "abc", Env: "stage"}) if err != nil { t.Fatal(err) } if _, ok := otel.GetTracerProvider().(*sdktrace.TracerProvider); !ok { t.Fatalf("provider = %T, want the SDK provider", otel.GetTracerProvider()) } ctx, cancel := context.WithTimeout(context.Background(), ShutdownTimeout) defer cancel() _ = shutdown(ctx) // nothing was recorded, so nothing to send } func TestSetupWithBadResourceEnv(t *testing.T) { t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://127.0.0.1:1") t.Setenv("OTEL_RESOURCE_ATTRIBUTES", "broken") if _, err := Setup(context.Background(), Info{Service: "tenant-registry"}); err == nil { t.Fatal("want an error for a malformed OTEL_RESOURCE_ATTRIBUTES") } } func TestResourceEnvOverridesDefaults(t *testing.T) { t.Setenv("OTEL_SERVICE_NAME", "tenant-registry-stage") t.Setenv("OTEL_RESOURCE_ATTRIBUTES", "deployment.environment=prod") tp, err := newProvider(context.Background(), Info{Service: "tenant-registry", Version: "v1", Commit: "c0ffee", Env: "stage"}) if err != nil { t.Fatal(err) } got := map[string]string{} for _, kv := range tpResource(tp) { got[string(kv.Key)] = kv.Value.String() } want := map[string]string{"service.name": "tenant-registry-stage", "deployment.environment": "prod", "service.version": "v1", "vcs.ref.head.revision": "c0ffee"} for k, v := range want { if got[k] != v { t.Errorf("%s = %q, want %q", k, got[k], v) } } } // tpResource reads the resource through a recorded span. func tpResource(tp *sdktrace.TracerProvider) []attribute.KeyValue { rec := tracetest.NewSpanRecorder() tp.RegisterSpanProcessor(rec) _, s := tp.Tracer("t").Start(context.Background(), "x") s.End() return rec.Ended()[0].Resource().Attributes() } func TestMiddlewareNamesSpanByRoute(t *testing.T) { rec := record(t) route := func(r *http.Request) string { switch r.URL.Path { case "/healthz": return "GET /healthz" case "/v1/tenants/by-slug/acme": return "GET /v1/tenants/by-slug/{slug}" case "/boom": return "GET /boom" } return "" } var inner trace.SpanContext h := Middleware(route, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/v1/tenants/by-slug/acme" { inner = trace.SpanContextFromContext(r.Context()) } if r.URL.Path == "/boom" { w.WriteHeader(http.StatusInternalServerError) } })) parent, ps := inSpan(t) req := httptest.NewRequest(http.MethodGet, "/v1/tenants/by-slug/acme?x=1", nil) otel.GetTextMapPropagator().Inject(parent, propagation.HeaderCarrier(req.Header)) ps.End() h.ServeHTTP(httptest.NewRecorder(), req) h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/healthz", nil)) h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/boom", nil)) h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/nope/acme", nil)) var server []sdktrace.ReadOnlySpan for _, s := range rec.Ended() { if s.SpanKind() == trace.SpanKindServer { server = append(server, s) } } if len(server) != 3 { t.Fatalf("server spans = %d, want 3 (healthz is skipped)", len(server)) } s := server[0] if s.Name() != "GET /v1/tenants/by-slug/{slug}" { t.Errorf("name = %q", s.Name()) } if s.Parent().TraceID() != ps.SpanContext().TraceID() { t.Error("incoming traceparent not continued") } if inner.SpanID() != s.SpanContext().SpanID() { t.Error("handler context does not carry the server span") } for _, kv := range s.Attributes() { if strings.Contains(kv.Value.String(), "acme") || strings.Contains(kv.Value.String(), "x=1") { t.Errorf("attribute %s leaks the raw path or query: %q", kv.Key, kv.Value.String()) } } if v, _ := attr(s, "http.response.status_code"); v.AsInt64() != 200 { t.Errorf("status = %d", v.AsInt64()) } if server[1].Status().Code != codes.Error { t.Error("a 500 must mark the span as an error") } if server[2].Name() != "GET unmatched" { t.Errorf("unmatched name = %q", server[2].Name()) } } func TestStatusWriterUnwrap(t *testing.T) { rr := httptest.NewRecorder() if (&statusWriter{ResponseWriter: rr}).Unwrap() != rr { t.Fatal("Unwrap must return the wrapped writer") } } func TestTransport(t *testing.T) { rec := record(t) var gotTraceparent string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotTraceparent = r.Header.Get("traceparent") if r.URL.Path == "/fail" { w.WriteHeader(http.StatusBadGateway) } })) defer srv.Close() client := &http.Client{Transport: Transport(nil)} get := func(ctx context.Context, path string) error { req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+path, nil) resp, err := client.Do(req) if err != nil { return err } return resp.Body.Close() } // Outside a trace: no span, no header. if err := get(context.Background(), "/ok"); err != nil { t.Fatal(err) } if gotTraceparent != "" || len(rec.Ended()) != 0 { t.Fatal("no span and no traceparent outside a trace") } ctx, parent := inSpan(t) if err := get(ctx, "/customer/acme?token=1"); err != nil { t.Fatal(err) } if err := get(ctx, "/fail"); err != nil { t.Fatal(err) } parent.End() if !strings.Contains(gotTraceparent, parent.SpanContext().TraceID().String()) { t.Errorf("traceparent %q does not carry the trace", gotTraceparent) } spans := rec.Ended() c := spans[0] if c.SpanKind() != trace.SpanKindClient || c.Name() != "GET 127.0.0.1" { t.Errorf("client span = %v %q", c.SpanKind(), c.Name()) } for _, kv := range c.Attributes() { if strings.Contains(kv.Value.String(), "acme") || strings.Contains(kv.Value.String(), "token") { t.Errorf("attribute %s leaks the path or query", kv.Key) } } if spans[1].Status().Code != codes.Error { t.Error("a 502 must mark the client span as an error") } // Transport failure. ctx, parent = inSpan(t) req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "http://127.0.0.1:1/", nil) if _, err := client.Do(req); err == nil { t.Fatal("want a connection error") } parent.End() failed := rec.Ended()[len(rec.Ended())-2] if failed.Status().Code != codes.Error { t.Error("a failed request must mark the client span as an error") } } func TestQueryTracer(t *testing.T) { rec := record(t) var qt QueryTracer // Outside a trace: untouched context, End is a no-op. ctx := qt.TraceQueryStart(context.Background(), nil, pgx.TraceQueryStartData{SQL: "SELECT 1"}) qt.TraceQueryEnd(ctx, nil, pgx.TraceQueryEndData{}) if len(rec.Ended()) != 0 { t.Fatal("no span outside a trace") } parentCtx, parent := inSpan(t) for _, q := range []struct { sql string err error }{ {"\n select id from tenants where slug = $1", nil}, {"INSERT INTO audit VALUES ($1)", errors.New("boom")}, {"SELECT * FROM t WHERE id = $1", pgx.ErrNoRows}, {"", nil}, } { c := qt.TraceQueryStart(parentCtx, nil, pgx.TraceQueryStartData{SQL: q.sql, Args: []any{"acme"}}) qt.TraceQueryEnd(c, nil, pgx.TraceQueryEndData{Err: q.err}) } if !parent.(sdktrace.ReadOnlySpan).EndTime().IsZero() { t.Fatal("TraceQueryEnd ended the parent span") } parent.End() spans := rec.Ended() if spans[0].Name() != "db SELECT" { t.Errorf("name = %q", spans[0].Name()) } if v, _ := attr(spans[0], "db.system"); v.AsString() != "postgresql" { t.Errorf("db.system = %q, the service map needs it", v.AsString()) } if v, _ := attr(spans[0], "db.query.text"); v.AsString() != "select id from tenants where slug = $1" { t.Errorf("db.query.text = %q", v.AsString()) } for _, kv := range spans[0].Attributes() { if strings.Contains(kv.Value.String(), "acme") { t.Error("query parameters must not be recorded") } } if spans[1].Status().Code != codes.Error { t.Error("a failed query must mark the span as an error") } if spans[2].Status().Code == codes.Error { t.Error("ErrNoRows is not an error") } if spans[3].Name() != "db QUERY" { t.Errorf("empty SQL name = %q", spans[3].Name()) } } func TestTruncate(t *testing.T) { if got := truncate(strings.Repeat("a", maxStatement+5), maxStatement); len(got) != maxStatement { t.Fatalf("len = %d", len(got)) } if truncate("abc", 5) != "abc" { t.Fatal("short strings stay") } } func TestLogHandlerAddsTraceIDs(t *testing.T) { record(t) var buf bytes.Buffer log := slog.New(NewLogHandler(slog.NewJSONHandler(&buf, nil))).With("svc", "tr").WithGroup("g") log.InfoContext(context.Background(), "outside") if strings.Contains(buf.String(), "trace_id") { t.Fatal("no trace_id outside a trace") } ctx, span := inSpan(t) defer span.End() buf.Reset() log.InfoContext(ctx, "inside") if !strings.Contains(buf.String(), span.SpanContext().TraceID().String()) || !strings.Contains(buf.String(), `"svc":"tr"`) { t.Fatalf("line = %s", buf.String()) } }