Debian Codegraph @

context_slog_test.go

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