github.com/Laisky/zap@v1.27.0/zapcore/hook_test.go (about) 1 // Copyright (c) 2016 Uber Technologies, Inc. 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to deal 5 // in the Software without restriction, including without limitation the rights 6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 // copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 // THE SOFTWARE. 20 21 package zapcore_test 22 23 import ( 24 "testing" 25 26 //revive:disable:dot-imports 27 . "github.com/Laisky/zap/zapcore" 28 "github.com/Laisky/zap/zaptest/observer" 29 30 "github.com/stretchr/testify/assert" 31 "github.com/stretchr/testify/require" 32 ) 33 34 func TestHooks(t *testing.T) { 35 tests := []struct { 36 entryLevel Level 37 coreLevel Level 38 expectCall bool 39 }{ 40 {DebugLevel, InfoLevel, false}, 41 {InfoLevel, InfoLevel, true}, 42 {WarnLevel, InfoLevel, true}, 43 } 44 45 for _, tt := range tests { 46 fac, logs := observer.New(tt.coreLevel) 47 48 // sanity check 49 require.Equal(t, tt.coreLevel, LevelOf(fac), "Original logger has the wrong level") 50 51 intField := makeInt64Field("foo", 42) 52 ent := Entry{Message: "bar", Level: tt.entryLevel} 53 54 var called int 55 f := func(e Entry) error { 56 called++ 57 assert.Equal(t, ent, e, "Hook called with unexpected Entry.") 58 return nil 59 } 60 61 h := RegisterHooks(fac, f) 62 if ce := h.With([]Field{intField}).Check(ent, nil); ce != nil { 63 ce.Write() 64 } 65 66 t.Run("LevelOf", func(t *testing.T) { 67 assert.Equal(t, tt.coreLevel, LevelOf(h), "Wrapped logger has the wrong log level") 68 }) 69 70 if tt.expectCall { 71 assert.Equal(t, 1, called, "Expected to call hook once.") 72 assert.Equal( 73 t, 74 []observer.LoggedEntry{{Entry: ent, Context: []Field{intField}}}, 75 logs.AllUntimed(), 76 "Unexpected logs written out.", 77 ) 78 } else { 79 assert.Equal(t, 0, called, "Didn't expect to call hook.") 80 assert.Equal(t, 0, logs.Len(), "Unexpected logs written out.") 81 } 82 } 83 }