| 1 | package logr |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "strings" |
| 6 | "testing" |
| 7 | ) |
| 8 | |
| 9 | func TestNew(t *testing.T) { |
| 10 | logger := New("what", false, nil) |
| 11 | if logger.threshold != LevelInfo { |
| 12 | t.Error("expected invalid threshold to be silently set to INFO, got", logger.threshold) |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | func TestLogger(t *testing.T) { |
| 17 | var writer bytes.Buffer |
| 18 | logger := New(LevelWarn, false, &writer) |
| 19 | logger.Debug("this is debug") |
| 20 | logger.Info("this is info") |
| 21 | logger.Warn("this is warn") |
| 22 | logger.Error("this is error") |
| 23 | output := writer.String() |
| 24 | if numberOfNewLines := strings.Count(output, "\n"); numberOfNewLines != 2 { |
| 25 | t.Error("expected 2 newlines, got", numberOfNewLines) |
| 26 | } |
| 27 | if strings.Contains(output, "this is debug") { |
| 28 | t.Error("expected no debug message, got", output) |
| 29 | } |
| 30 | if strings.Contains(output, "this is info") { |
| 31 | t.Error("expected no info message, got", output) |
| 32 | } |
| 33 | if !strings.Contains(output, "this is warn") { |
| 34 | t.Error("expected warn message, got", output) |
| 35 | } |
| 36 | if !strings.Contains(output, "this is error") { |
| 37 | t.Error("expected error message, got", output) |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | func TestLogger_SetThreshold(t *testing.T) { |
| 42 | var writer bytes.Buffer |
| 43 | logger := New(LevelDebug, false, &writer) |
| 44 | logger.SetThreshold(LevelError) |
| 45 | logger.Debug("this is debug") |
| 46 | logger.Info("this is info") |
| 47 | logger.Warn("this is warn") |
| 48 | logger.Error("this is error") |
| 49 | output := writer.String() |
| 50 | if numberOfNewLines := strings.Count(output, "\n"); numberOfNewLines != 1 { |
| 51 | t.Error("expected 1 newline, got", numberOfNewLines) |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | func TestLoggerFormatting(t *testing.T) { |
| 56 | var writer bytes.Buffer |
| 57 | logger := New(LevelDebug, true, &writer) |
| 58 | logger.Debugf("hello, %s", "world") |
| 59 | logger.Infof("%d", 11111) |
| 60 | logger.Warnf("%s got %d%% in math", "John Doe", 87) |
| 61 | logger.Errorf("%s sent %s$%.02f to %s", "John", "CAD", 69.1, "Jane") |
| 62 | output := writer.String() |
| 63 | if !strings.Contains(output, "- DEBUG - hello, world") { |
| 64 | t.Error("expected '- DEBUG - hello, world.', got", output) |
| 65 | } |
| 66 | if !strings.Contains(output, "- INFO - 11111") { |
| 67 | t.Error("expected '- INFO - John Doe got 87% in math', got", output) |
| 68 | } |
| 69 | if !strings.Contains(output, "- WARN - John Doe got 87% in math") { |
| 70 | t.Error("expected '- WARN - John Doe got 87% in math', got", output) |
| 71 | } |
| 72 | if !strings.Contains(output, "- ERROR - John sent CAD$69.10 to Jane") { |
| 73 | t.Error("expected '- ERROR - John sent USD$123.40 to Jane', got", output) |
| 74 | } |
| 75 | } |