context/tracing/xray_test.go

package tracing_test

import (
	stdcontext "context"
	"testing"

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

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

func TestParseXRay(t *testing.T) {
	raw := "Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1;Foo=bar"
	got := tracing.ParseXRay(raw)

	want := tracing.XRayHeader{
		Root:    "1-5759e988-bd862e3fe1be46a994272793",
		Parent:  "53995c3f42cd8ad8",
		Sampled: "1",
		Extras:  map[string]string{"Foo": "bar"},
	}
	if diff := cmp.Diff(want, got); diff != "" {
		t.Fatalf("header (-want +got):\n%s", diff)
	}
}

func TestParseXRay_EmptyAndMalformed(t *testing.T) {
	cases := []string{"", ";;;", "Root", "=value", "Root=;Parent="}
	for _, raw := range cases {
		raw := raw
		t.Run(raw, func(t *testing.T) {
			t.Helper()
			got := tracing.ParseXRay(raw)
			if got.Extras == nil {
				t.Fatalf("Extras should be initialised: %+v", got)
			}
		})
	}
}

func TestXRay_ContextRoundTrip(t *testing.T) {
	h := tracing.XRayHeader{Root: "r", Parent: "p", Sampled: "1", Extras: map[string]string{}}
	ctx := tracing.WithXRay(stdcontext.Background(), h)
	got, ok := tracing.XRayFromContext(ctx)
	if !ok {
		t.Fatal("not present")
	}
	if diff := cmp.Diff(h, got); diff != "" {
		t.Fatalf("(-want +got):\n%s", diff)
	}
}

func TestXRay_NilSafe(t *testing.T) {
	if _, ok := tracing.XRayFromContext(nil); ok {
		t.Fatal("expected ok=false")
	}
}

func TestXRay_IsSampled(t *testing.T) {
	if !(tracing.XRayHeader{Sampled: "1"}).IsSampled() {
		t.Fatal("should be sampled")
	}
	if (tracing.XRayHeader{Sampled: "0"}).IsSampled() {
		t.Fatal("should not be sampled")
	}
}

func TestXRay_SpanID(t *testing.T) {
	h := tracing.XRayHeader{Root: "r", Parent: "p"}
	if got := h.SpanID(); got != "p" {
		t.Fatalf("got %q, want p", got)
	}
	h.Parent = ""
	if got := h.SpanID(); got != "r" {
		t.Fatalf("got %q, want r", got)
	}
}

func TestXRay_LogFields(t *testing.T) {
	empty := tracing.XRayHeader{}
	if got := empty.LogFields(); got != nil {
		t.Fatalf("empty should yield nil: %v", got)
	}
	h := tracing.XRayHeader{Root: "r", Parent: "p", Sampled: "1"}
	if len(h.LogFields()) != 3 {
		t.Fatalf("fields: %v", h.LogFields())
	}
}