create_test.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package logger
  2. import (
  3. "github.com/pkg/errors"
  4. "github.com/rs/zerolog"
  5. "github.com/stretchr/testify/assert"
  6. "io"
  7. "testing"
  8. )
  9. var writeCalls int
  10. type mockedWriter struct {
  11. wantErr bool
  12. }
  13. func (c mockedWriter) Write(p []byte) (int, error) {
  14. writeCalls++
  15. if c.wantErr {
  16. return -1, errors.New("Expected error")
  17. }
  18. return len(p), nil
  19. }
  20. // Tests that a new writer is only used if it actually works.
  21. func TestResilientMultiWriter(t *testing.T) {
  22. tests := []struct {
  23. name string
  24. writers []io.Writer
  25. }{
  26. {
  27. name: "All valid writers",
  28. writers: []io.Writer{
  29. mockedWriter {
  30. wantErr: false,
  31. },
  32. mockedWriter {
  33. wantErr: false,
  34. },
  35. },
  36. },
  37. {
  38. name: "All invalid writers",
  39. writers: []io.Writer{
  40. mockedWriter {
  41. wantErr: true,
  42. },
  43. mockedWriter {
  44. wantErr: true,
  45. },
  46. },
  47. },
  48. {
  49. name: "First invalid writer",
  50. writers: []io.Writer{
  51. mockedWriter {
  52. wantErr: true,
  53. },
  54. mockedWriter {
  55. wantErr: false,
  56. },
  57. },
  58. },
  59. {
  60. name: "First valid writer",
  61. writers: []io.Writer{
  62. mockedWriter {
  63. wantErr: false,
  64. },
  65. mockedWriter {
  66. wantErr: true,
  67. },
  68. },
  69. },
  70. }
  71. for _, tt := range tests {
  72. writers := tt.writers
  73. multiWriter := resilientMultiWriter{writers}
  74. logger := zerolog.New(multiWriter).With().Timestamp().Logger().Level(zerolog.InfoLevel)
  75. logger.Info().Msg("Test msg")
  76. assert.Equal(t, len(writers), writeCalls)
  77. writeCalls = 0
  78. }
  79. }