Codebase list golang-github-go-logr-logr / 3dceec2
Merge pull request #35 from thockin/test-context Add tests for context funcs Tim Hockin authored 3 years ago GitHub committed 3 years ago
1 changed file(s) with 76 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 /*
1 Copyright 2021 The logr Authors.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 */
15
16 package logr
17
18 import (
19 "context"
20 "testing"
21 )
22
23 // testLogger is a Logger just for testing that does nothing.
24 type testLogger struct{}
25
26 func (l *testLogger) Enabled() bool {
27 return false
28 }
29
30 func (l *testLogger) Info(msg string, keysAndValues ...interface{}) {
31 }
32
33 func (l *testLogger) Error(err error, msg string, keysAndValues ...interface{}) {
34 }
35
36 func (l *testLogger) V(level int) Logger {
37 return l
38 }
39
40 func (l *testLogger) WithValues(keysAndValues ...interface{}) Logger {
41 return l
42 }
43
44 func (l *testLogger) WithName(name string) Logger {
45 return l
46 }
47
48 // Verify that it actually implements the interface
49 var _ Logger = &testLogger{}
50
51 func TestContext(t *testing.T) {
52 ctx := context.TODO()
53
54 if out := FromContext(ctx); out != nil {
55 t.Errorf("expected nil logger, got %#v", out)
56 }
57 if out := FromContextOrDiscard(ctx); out == nil {
58 t.Errorf("expected non-nil logger")
59 } else if _, ok := out.(discardLogger); !ok {
60 t.Errorf("expected a discardLogger, got %#v", out)
61 }
62
63 logger := &testLogger{}
64 lctx := NewContext(ctx, logger)
65 if out := FromContext(lctx); out == nil {
66 t.Errorf("expected non-nil logger")
67 } else if out.(*testLogger) != logger {
68 t.Errorf("expected output to be the same as input: got in=%p, out=%p", logger, out)
69 }
70 if out := FromContextOrDiscard(lctx); out == nil {
71 t.Errorf("expected non-nil logger")
72 } else if out.(*testLogger) != logger {
73 t.Errorf("expected output to be the same as input: got in=%p, out=%p", logger, out)
74 }
75 }