context/tracing/otel_test.go

package tracing_test

import (
	stdcontext "context"
	"testing"

	"github.com/google/go-cmp/cmp"

	"mercemay.top/src/lambdalog/context/tracing"
)

func TestParseTraceParent_Valid(t *testing.T) {
	raw := "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"
	got, ok := tracing.ParseTraceParent(raw)
	if !ok {
		t.Fatal("should be valid")
	}
	want := tracing.TraceParent{
		Version: "00", TraceID: "0af7651916cd43dd8448eb211c80319c",
		ParentID: "b7ad6b7169203331", TraceFlags: "01",
	}
	if diff := cmp.Diff(want, got); diff != "" {
		t.Fatalf("(-want +got):\n%s", diff)
	}
}

func TestParseTraceParent_Invalid(t *testing.T) {
	cases := []string{
		"",
		"01-shortid-short-00",
		"00-0af7651916cd43dd8448eb211c80319c",
		"00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-0",
	}
	for _, raw := range cases {
		raw := raw
		t.Run(raw, func(t *testing.T) {
			t.Helper()
			if _, ok := tracing.ParseTraceParent(raw); ok {
				t.Fatalf("unexpectedly valid: %q", raw)
			}
		})
	}
}

func TestTraceParent_Sampled(t *testing.T) {
	p, _ := tracing.ParseTraceParent("00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01")
	if !p.Sampled() {
		t.Fatal("01 should be sampled")
	}
	p.TraceFlags = "00"
	if p.Sampled() {
		t.Fatal("00 should not be sampled")
	}
}

func TestContext_RoundTrip(t *testing.T) {
	p, _ := tracing.ParseTraceParent("00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01")
	ctx := tracing.WithTraceParent(stdcontext.Background(), p)
	got, ok := tracing.TraceParentFromContext(ctx)
	if !ok {
		t.Fatal("missing")
	}
	if diff := cmp.Diff(p, got); diff != "" {
		t.Fatalf("(-want +got):\n%s", diff)
	}
}

func TestLogFields_InvalidReturnsNil(t *testing.T) {
	p := tracing.TraceParent{}
	if got := p.LogFields(); got != nil {
		t.Fatalf("got %v, want nil", got)
	}
}

func TestFromXRay(t *testing.T) {
	x := tracing.XRayHeader{
		Root:    "1-5759e988-bd862e3fe1be46a994272793",
		Parent:  "53995c3f42cd8ad8",
		Sampled: "1",
	}
	p, ok := tracing.FromXRay(x)
	if !ok {
		t.Fatal("expected conversion")
	}
	if len(p.TraceID) != 32 || p.ParentID != "53995c3f42cd8ad8" {
		t.Fatalf("got %+v", p)
	}
	if !p.Sampled() {
		t.Fatal("sampled bit should be set")
	}
}