| 1 | package clog |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "log/slog" |
| 8 | "reflect" |
| 9 | "testing" |
| 10 | ) |
| 11 | |
| 12 | func TestContextHandler(t *testing.T) { |
| 13 | ctx := context.Background() |
| 14 | ctx = WithValues(ctx, "foo", "bar") |
| 15 | ctx2 := WithValues(ctx, |
| 16 | "a", "b", |
| 17 | "c", "d", |
| 18 | ) |
| 19 | ctx = WithValues(ctx, "b", 1) |
| 20 | |
| 21 | for _, tc := range []struct { |
| 22 | ctx context.Context |
| 23 | want map[string]any |
| 24 | }{ |
| 25 | {ctx, map[string]any{ |
| 26 | "b": float64(1), |
| 27 | "foo": "bar", |
| 28 | }}, |
| 29 | {ctx2, map[string]any{ |
| 30 | "foo": "bar", |
| 31 | "a": "b", |
| 32 | "c": "d", |
| 33 | }}, |
| 34 | } { |
| 35 | t.Run("", func(t *testing.T) { |
| 36 | b := new(bytes.Buffer) |
| 37 | log := slog.New(NewHandler(slog.NewJSONHandler(b, testopts))) |
| 38 | log.InfoContext(tc.ctx, "") |
| 39 | |
| 40 | tc.want["level"] = "INFO" |
| 41 | tc.want["msg"] = "" |
| 42 | |
| 43 | var got map[string]any |
| 44 | if err := json.Unmarshal(b.Bytes(), &got); err != nil { |
| 45 | t.Fatal(err) |
| 46 | } |
| 47 | |
| 48 | if !reflect.DeepEqual(tc.want, got) { |
| 49 | t.Errorf("want %v, got %v", tc.want, got) |
| 50 | } |
| 51 | }) |
| 52 | } |
| 53 | } |