package requestid_test
import (
stdcontext "context"
"testing"
"github.com/aws/aws-lambda-go/lambdacontext"
"mercemay.top/src/lambdalog/context/requestid"
)
func TestExtract_FromInject(t *testing.T) {
ctx := requestid.Inject(stdcontext.Background(), "req-1")
got, ok := requestid.Extract(ctx)
if !ok || got != "req-1" {
t.Fatalf("got %q ok=%v, want req-1 true", got, ok)
}
}
func TestExtract_FromLambdaContext(t *testing.T) {
ctx := lambdacontext.NewContext(stdcontext.Background(), &lambdacontext.LambdaContext{
AwsRequestID: "aws-7",
})
got, ok := requestid.Extract(ctx)
if !ok || got != "aws-7" {
t.Fatalf("got %q ok=%v, want aws-7 true", got, ok)
}
}
func TestExtract_InjectOverridesLambda(t *testing.T) {
ctx := lambdacontext.NewContext(stdcontext.Background(), &lambdacontext.LambdaContext{AwsRequestID: "aws"})
ctx = requestid.Inject(ctx, "override")
got, _ := requestid.Extract(ctx)
if got != "override" {
t.Fatalf("got %q, want override", got)
}
}
func TestExtract_NilSafe(t *testing.T) {
if _, ok := requestid.Extract(nil); ok {
t.Fatal("expected ok=false for nil context")
}
}
func TestMust_EmptyWhenMissing(t *testing.T) {
if got := requestid.Must(stdcontext.Background()); got != "" {
t.Fatalf("got %q, want empty", got)
}
}
func TestTrim(t *testing.T) {
cases := []struct {
in, want string
}{
{"", ""},
{"short", "short"},
{"1234567890abcdef", "12345678"},
}
for _, tc := range cases {
tc := tc
t.Run(tc.in, func(t *testing.T) {
t.Helper()
if got := requestid.Trim(tc.in); got != tc.want {
t.Fatalf("got %q, want %q", got, tc.want)
}
})
}
}
func TestLogFields(t *testing.T) {
ctx := requestid.Inject(stdcontext.Background(), "r")
fs := requestid.LogFields(ctx)
if len(fs) != 1 || fs[0].Key != "request_id" || fs[0].Value != "r" {
t.Fatalf("fields = %#v", fs)
}
if got := requestid.LogFields(stdcontext.Background()); got != nil {
t.Fatalf("empty ctx should yield nil: %#v", got)
}
}
func TestEqual(t *testing.T) {
ctx := requestid.Inject(stdcontext.Background(), "r")
if !requestid.Equal(ctx, "r") {
t.Fatal("expected equal")
}
if requestid.Equal(ctx, "other") {
t.Fatal("unexpected equal")
}
}