knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/logging/logger_test.go (about) 1 /* 2 Copyright 2018 The Knative Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package logging 18 19 import ( 20 "context" 21 "testing" 22 23 "go.uber.org/zap" 24 ) 25 26 func TestContext(t *testing.T) { 27 logger1 := zap.NewNop().Sugar() 28 logger2 := zap.NewExample().Sugar() 29 30 // Happy path tests 31 ctx := WithLogger(context.Background(), logger1) 32 checkFromContext(ctx, logger1, t) 33 34 ctx = WithLogger(ctx, logger2) 35 checkFromContext(ctx, logger2, t) 36 37 ctx = WithLogger(ctx, logger1) 38 checkFromContext(ctx, logger1, t) 39 40 // Empty logger 41 ctx = context.Background() 42 checkFromContext(ctx, fallbackLogger, t) 43 44 // Logger with a wrong type 45 ctx = context.WithValue(context.Background(), loggerKey{}, zap.NewNop()) 46 checkFromContext(ctx, fallbackLogger, t) 47 } 48 49 func checkFromContext(ctx context.Context, want *zap.SugaredLogger, t *testing.T) { 50 if got := FromContext(ctx); want != got { 51 t.Errorf("unexpected logger in context. want: %v, got: %v", want, got) 52 } 53 }