| 102 | } |
| 103 | |
| 104 | func TestConsoleWriter(t *testing.T) { |
| 105 | t.Run("Default field formatter", func(t *testing.T) { |
| 106 | buf := &bytes.Buffer{} |
| 107 | w := zerolog.ConsoleWriter{Out: buf, NoColor: true, PartsOrder: []string{"foo"}} |
| 108 | |
| 109 | _, err := w.Write([]byte(`{"foo": "DEFAULT"}`)) |
| 110 | if err != nil { |
| 111 | t.Errorf("Unexpected error when writing output: %s", err) |
| 112 | } |
| 113 | |
| 114 | expectedOutput := "DEFAULT foo=DEFAULT\n" |
| 115 | actualOutput := buf.String() |
| 116 | if actualOutput != expectedOutput { |
| 117 | t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput) |
| 118 | } |
| 119 | }) |
| 120 | |
| 121 | t.Run("Write colorized", func(t *testing.T) { |
| 122 | buf := &bytes.Buffer{} |
| 123 | w := zerolog.ConsoleWriter{Out: buf, NoColor: false} |
| 124 | |
| 125 | _, err := w.Write([]byte(`{"level": "warn", "message": "Foobar"}`)) |
| 126 | if err != nil { |
| 127 | t.Errorf("Unexpected error when writing output: %s", err) |
| 128 | } |
| 129 | |
| 130 | expectedOutput := "\x1b[90m<nil>\x1b[0m \x1b[33mWRN\x1b[0m \x1b[1mFoobar\x1b[0m\n" |
| 131 | actualOutput := buf.String() |
| 132 | if actualOutput != expectedOutput { |
| 133 | t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput) |
| 134 | } |
| 135 | }) |
| 136 | |
| 137 | t.Run("NO_COLOR = true", func(t *testing.T) { |
| 138 | os.Setenv("NO_COLOR", "anything") |
| 139 | |
| 140 | buf := &bytes.Buffer{} |
| 141 | w := zerolog.ConsoleWriter{Out: buf} |
| 142 | |
| 143 | _, err := w.Write([]byte(`{"level": "warn", "message": "Foobar"}`)) |
| 144 | if err != nil { |
| 145 | t.Errorf("Unexpected error when writing output: %s", err) |
| 146 | } |
| 147 | |
| 148 | expectedOutput := "<nil> WRN Foobar\n" |
| 149 | actualOutput := buf.String() |
| 150 | if actualOutput != expectedOutput { |
| 151 | t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput) |
| 152 | } |
| 153 | os.Unsetenv("NO_COLOR") |
| 154 | }) |
| 155 | |
| 156 | t.Run("Write fields", func(t *testing.T) { |
| 157 | buf := &bytes.Buffer{} |
| 158 | w := zerolog.ConsoleWriter{Out: buf, NoColor: true} |
| 159 | |
| 160 | ts := time.Unix(0, 0) |
| 161 | d := ts.UTC().Format(time.RFC3339) |