core_test.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. "errors"
  23. "io/ioutil"
  24. "os"
  25. "testing"
  26. "time"
  27. "go.uber.org/zap/internal/ztest"
  28. . "go.uber.org/zap/zapcore"
  29. "github.com/stretchr/testify/assert"
  30. "github.com/stretchr/testify/require"
  31. )
  32. func makeInt64Field(key string, val int) Field {
  33. return Field{Type: Int64Type, Integer: int64(val), Key: key}
  34. }
  35. func TestNopCore(t *testing.T) {
  36. entry := Entry{
  37. Message: "test",
  38. Level: InfoLevel,
  39. Time: time.Now(),
  40. LoggerName: "main",
  41. Stack: "fake-stack",
  42. }
  43. ce := &CheckedEntry{}
  44. allLevels := []Level{
  45. DebugLevel,
  46. InfoLevel,
  47. WarnLevel,
  48. ErrorLevel,
  49. DPanicLevel,
  50. PanicLevel,
  51. FatalLevel,
  52. }
  53. core := NewNopCore()
  54. assert.Equal(t, core, core.With([]Field{makeInt64Field("k", 42)}), "Expected no-op With.")
  55. for _, level := range allLevels {
  56. assert.False(t, core.Enabled(level), "Expected all levels to be disabled in no-op core.")
  57. assert.Equal(t, ce, core.Check(entry, ce), "Expected no-op Check to return checked entry unchanged.")
  58. assert.NoError(t, core.Write(entry, nil), "Expected no-op Writes to always succeed.")
  59. assert.NoError(t, core.Sync(), "Expected no-op Syncs to always succeed.")
  60. }
  61. }
  62. func TestIOCore(t *testing.T) {
  63. temp, err := ioutil.TempFile("", "zapcore-test-iocore")
  64. require.NoError(t, err, "Failed to create temp file.")
  65. defer os.Remove(temp.Name())
  66. // Drop timestamps for simpler assertions (timestamp encoding is tested
  67. // elsewhere).
  68. cfg := testEncoderConfig()
  69. cfg.TimeKey = ""
  70. core := NewCore(
  71. NewJSONEncoder(cfg),
  72. temp,
  73. InfoLevel,
  74. ).With([]Field{makeInt64Field("k", 1)})
  75. defer assert.NoError(t, core.Sync(), "Expected Syncing a temp file to succeed.")
  76. if ce := core.Check(Entry{Level: DebugLevel, Message: "debug"}, nil); ce != nil {
  77. ce.Write(makeInt64Field("k", 2))
  78. }
  79. if ce := core.Check(Entry{Level: InfoLevel, Message: "info"}, nil); ce != nil {
  80. ce.Write(makeInt64Field("k", 3))
  81. }
  82. if ce := core.Check(Entry{Level: WarnLevel, Message: "warn"}, nil); ce != nil {
  83. ce.Write(makeInt64Field("k", 4))
  84. }
  85. logged, err := ioutil.ReadFile(temp.Name())
  86. require.NoError(t, err, "Failed to read from temp file.")
  87. require.Equal(
  88. t,
  89. `{"level":"info","msg":"info","k":1,"k":3}`+"\n"+
  90. `{"level":"warn","msg":"warn","k":1,"k":4}`+"\n",
  91. string(logged),
  92. "Unexpected log output.",
  93. )
  94. }
  95. func TestIOCoreSyncFail(t *testing.T) {
  96. sink := &ztest.Discarder{}
  97. err := errors.New("failed")
  98. sink.SetError(err)
  99. core := NewCore(
  100. NewJSONEncoder(testEncoderConfig()),
  101. sink,
  102. DebugLevel,
  103. )
  104. assert.Equal(
  105. t,
  106. err,
  107. core.Sync(),
  108. "Expected core.Sync to return errors from underlying WriteSyncer.",
  109. )
  110. }
  111. func TestIOCoreSyncsOutput(t *testing.T) {
  112. tests := []struct {
  113. entry Entry
  114. shouldSync bool
  115. }{
  116. {Entry{Level: DebugLevel}, false},
  117. {Entry{Level: InfoLevel}, false},
  118. {Entry{Level: WarnLevel}, false},
  119. {Entry{Level: ErrorLevel}, false},
  120. {Entry{Level: DPanicLevel}, true},
  121. {Entry{Level: PanicLevel}, true},
  122. {Entry{Level: FatalLevel}, true},
  123. }
  124. for _, tt := range tests {
  125. sink := &ztest.Discarder{}
  126. core := NewCore(
  127. NewJSONEncoder(testEncoderConfig()),
  128. sink,
  129. DebugLevel,
  130. )
  131. core.Write(tt.entry, nil)
  132. assert.Equal(t, tt.shouldSync, sink.Called(), "Incorrect Sync behavior.")
  133. }
  134. }
  135. func TestIOCoreWriteFailure(t *testing.T) {
  136. core := NewCore(
  137. NewJSONEncoder(testEncoderConfig()),
  138. Lock(&ztest.FailWriter{}),
  139. DebugLevel,
  140. )
  141. err := core.Write(Entry{}, nil)
  142. // Should log the error.
  143. assert.Error(t, err, "Expected writing Entry to fail.")
  144. }