package lambdalog
import (
"bytes"
"context"
"encoding/json"
"testing"
"time"
)
func TestWithFieldAccumulates(t *testing.T) {
t.Parallel()
base := WithField(context.Background(), "tenant", "acme")
left := WithField(base, "branch", "A")
right := WithField(base, "branch", "B")
var buf bytes.Buffer
l := New(&buf)
l.now = func() time.Time { return time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC) }
l.FromContext(left).Info("ping")
l.FromContext(right).Info("ping")
lines := bytes.Split(bytes.TrimSpace(buf.Bytes()), []byte{'\n'})
if len(lines) != 2 {
t.Fatalf("want 2 records, got %d", len(lines))
}
var first, second map[string]any
if err := json.Unmarshal(lines[0], &first); err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(lines[1], &second); err != nil {
t.Fatal(err)
}
if first["branch"] != "A" || second["branch"] != "B" {
t.Fatalf("branch isolation broken: %v / %v", first, second)
}
if first["tenant"] != "acme" || second["tenant"] != "acme" {
t.Fatalf("tenant should be shared: %v / %v", first, second)
}
}
func TestWithRequestIDOverridesRuntime(t *testing.T) {
t.Parallel()
ctx := WithRequestID(context.Background(), "explicit-rid")
if got := requestIDFromContext(ctx); got != "explicit-rid" {
t.Fatalf("expected explicit override, got %q", got)
}
}
func TestNilContextIsNoop(t *testing.T) {
t.Parallel()
if got := fieldsFromContext(context.Background()); got != nil {
t.Fatalf("expected nil fields, got %v", got)
}
}