hook_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. package zapcore_test
  21. import (
  22. "testing"
  23. . "go.uber.org/zap/zapcore"
  24. "go.uber.org/zap/zaptest/observer"
  25. "github.com/stretchr/testify/assert"
  26. )
  27. func TestHooks(t *testing.T) {
  28. tests := []struct {
  29. entryLevel Level
  30. coreLevel Level
  31. expectCall bool
  32. }{
  33. {DebugLevel, InfoLevel, false},
  34. {InfoLevel, InfoLevel, true},
  35. {WarnLevel, InfoLevel, true},
  36. }
  37. for _, tt := range tests {
  38. fac, logs := observer.New(tt.coreLevel)
  39. intField := makeInt64Field("foo", 42)
  40. ent := Entry{Message: "bar", Level: tt.entryLevel}
  41. var called int
  42. f := func(e Entry) error {
  43. called++
  44. assert.Equal(t, ent, e, "Hook called with unexpected Entry.")
  45. return nil
  46. }
  47. h := RegisterHooks(fac, f)
  48. if ce := h.With([]Field{intField}).Check(ent, nil); ce != nil {
  49. ce.Write()
  50. }
  51. if tt.expectCall {
  52. assert.Equal(t, 1, called, "Expected to call hook once.")
  53. assert.Equal(
  54. t,
  55. []observer.LoggedEntry{{Entry: ent, Context: []Field{intField}}},
  56. logs.AllUntimed(),
  57. "Unexpected logs written out.",
  58. )
  59. } else {
  60. assert.Equal(t, 0, called, "Didn't expect to call hook.")
  61. assert.Equal(t, 0, logs.Len(), "Unexpected logs written out.")
  62. }
  63. }
  64. }