context/context_test.go

package context_test

import (
	stdcontext "context"
	"testing"
	"time"

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

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

func TestWithAttributes_AddsAndMerges(t *testing.T) {
	ctx := stdcontext.Background()
	ctx = lctx.WithAttributes(ctx, lctx.Attributes{"a": 1})
	ctx = lctx.WithAttributes(ctx, lctx.Attributes{"b": 2, "a": 99})

	got := lctx.AttributesFromContext(ctx)
	want := lctx.Attributes{"a": 99, "b": 2}
	if diff := cmp.Diff(want, got); diff != "" {
		t.Fatalf("attrs (-want +got):\n%s", diff)
	}
}

func TestWithAttributes_EmptyInputDoesNotAllocate(t *testing.T) {
	ctx := stdcontext.Background()
	same := lctx.WithAttributes(ctx, nil)
	if same != ctx {
		t.Fatalf("expected original ctx returned for empty input")
	}
}

func TestAttributes_CloneIsIndependent(t *testing.T) {
	a := lctx.Attributes{"k": 1}
	cp := a.Clone()
	cp["k"] = 2
	if a["k"] != 1 {
		t.Fatalf("clone mutated source: %v", a)
	}
}

func TestAttributes_MergeEmpty(t *testing.T) {
	a := lctx.Attributes{"k": 1}
	if diff := cmp.Diff(a, a.Merge(nil)); diff != "" {
		t.Fatalf("merge with nil (-want +got):\n%s", diff)
	}
	if diff := cmp.Diff(a, lctx.Attributes(nil).Merge(a)); diff != "" {
		t.Fatalf("merge into nil (-want +got):\n%s", diff)
	}
}

func TestAttributesFromContext_NilSafe(t *testing.T) {
	t.Helper()
	if got := lctx.AttributesFromContext(nil); got != nil {
		t.Fatalf("got %v, want nil", got)
	}
}

func TestWithSoftDeadline_RoundTrip(t *testing.T) {
	ctx := stdcontext.Background()
	at := time.Unix(1_700_000_000, 0).UTC()
	ctx = lctx.WithSoftDeadline(ctx, at)
	got, ok := lctx.SoftDeadlineFromContext(ctx)
	if !ok || !got.Equal(at) {
		t.Fatalf("got %v ok=%v, want %v ok=true", got, ok, at)
	}
}

func TestSoftDeadline_DoesNotCancel(t *testing.T) {
	t.Helper()
	parent, cancel := stdcontext.WithCancel(stdcontext.Background())
	t.Cleanup(cancel)

	past := time.Now().Add(-time.Hour)
	ctx := lctx.WithSoftDeadline(parent, past)
	select {
	case <-ctx.Done():
		t.Fatal("soft deadline must not fire ctx.Done")
	default:
	}
}

func TestSoftDeadlineFromContext_NilSafe(t *testing.T) {
	if _, ok := lctx.SoftDeadlineFromContext(nil); ok {
		t.Fatal("expected ok=false for nil context")
	}
}