|
| 1 | +//go:build go1.21 |
| 2 | +// +build go1.21 |
| 3 | + |
| 4 | +/* |
| 5 | +Copyright 2021 The logr Authors. |
| 6 | +
|
| 7 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 8 | +you may not use this file except in compliance with the License. |
| 9 | +You may obtain a copy of the License at |
| 10 | +
|
| 11 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | +
|
| 13 | +Unless required by applicable law or agreed to in writing, software |
| 14 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 15 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 16 | +See the License for the specific language governing permissions and |
| 17 | +limitations under the License. |
| 18 | +*/ |
| 19 | + |
| 20 | +package logr |
| 21 | + |
| 22 | +import ( |
| 23 | + "context" |
| 24 | + "log/slog" |
| 25 | + "os" |
| 26 | + "testing" |
| 27 | +) |
| 28 | + |
| 29 | +func TestContextWithSlog(t *testing.T) { |
| 30 | + ctx := context.Background() |
| 31 | + |
| 32 | + if out := FromContextAsSlogLogger(ctx); out != nil { |
| 33 | + t.Errorf("expected no logger, got %#v", out) |
| 34 | + } |
| 35 | + |
| 36 | + // Write as slog... |
| 37 | + slogger := slog.New(slog.NewJSONHandler(os.Stderr, nil)) |
| 38 | + sctx := NewContextWithSlogLogger(ctx, slogger) |
| 39 | + |
| 40 | + // ...read as logr |
| 41 | + if out, err := FromContext(sctx); err != nil { |
| 42 | + t.Errorf("unexpected error: %v", err) |
| 43 | + } else if _, ok := out.sink.(*slogSink); !ok { |
| 44 | + t.Errorf("expected output to be type *logr.slogSink, got %T", out.sink) |
| 45 | + } |
| 46 | + |
| 47 | + // ...read as slog |
| 48 | + if out := FromContextAsSlogLogger(sctx); out == nil { |
| 49 | + t.Errorf("expected a *slog.JSONHandler, got nil") |
| 50 | + } else if _, ok := out.Handler().(*slog.JSONHandler); !ok { |
| 51 | + t.Errorf("expected output to be type *slog.JSONHandler, got %T", out.Handler()) |
| 52 | + } |
| 53 | + |
| 54 | + // Write as logr... |
| 55 | + logger := Discard() |
| 56 | + lctx := NewContext(ctx, logger) |
| 57 | + |
| 58 | + // ...read as slog |
| 59 | + if out := FromContextAsSlogLogger(lctx); out == nil { |
| 60 | + t.Errorf("expected a *log.slogHandler, got nil") |
| 61 | + } else if _, ok := out.Handler().(*slogHandler); !ok { |
| 62 | + t.Errorf("expected output to be type *logr.slogHandler, got %T", out.Handler()) |
| 63 | + } |
| 64 | + |
| 65 | + // ...read as logr is covered in the non-slog test |
| 66 | +} |
0 commit comments