|
| 1 | +package log |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "bufio" |
| 7 | + "io" |
| 8 | + |
| 9 | + "github.com/Sirupsen/logrus" |
| 10 | + "github.com/stretchr/testify/assert" |
| 11 | +) |
| 12 | + |
| 13 | +func TestDefaultLevelIsInfo(t *testing.T) { |
| 14 | + testLogger := NewMachineLogger() |
| 15 | + assert.Equal(t, testLogger.Logger().(*logrus.Logger).Level, logrus.InfoLevel) |
| 16 | +} |
| 17 | + |
| 18 | +func TestSetDebugToTrue(t *testing.T) { |
| 19 | + testLogger := NewMachineLogger() |
| 20 | + testLogger.SetDebug(true) |
| 21 | + assert.Equal(t, testLogger.Logger().(*logrus.Logger).Level, logrus.DebugLevel) |
| 22 | +} |
| 23 | + |
| 24 | +func TestSetDebugToFalse(t *testing.T) { |
| 25 | + testLogger := NewMachineLogger() |
| 26 | + testLogger.SetDebug(true) |
| 27 | + testLogger.SetDebug(false) |
| 28 | + assert.Equal(t, testLogger.Logger().(*logrus.Logger).Level, logrus.InfoLevel) |
| 29 | +} |
| 30 | + |
| 31 | +func TestSetSilenceOutput(t *testing.T) { |
| 32 | + testLogger := NewMachineLogger() |
| 33 | + testLogger.RedirectStdOutToStdErr() |
| 34 | + assert.Equal(t, testLogger.Logger().(*logrus.Logger).Level, logrus.ErrorLevel) |
| 35 | +} |
| 36 | + |
| 37 | +func TestDebug(t *testing.T) { |
| 38 | + testLogger := NewMachineLogger() |
| 39 | + testLogger.SetDebug(true) |
| 40 | + |
| 41 | + result := captureOutput(testLogger, func() { testLogger.Debug("debug") }) |
| 42 | + |
| 43 | + assert.Equal(t, result, "debug") |
| 44 | +} |
| 45 | + |
| 46 | +func TestInfo(t *testing.T) { |
| 47 | + testLogger := NewMachineLogger() |
| 48 | + |
| 49 | + result := captureOutput(testLogger, func() { testLogger.Info("info") }) |
| 50 | + |
| 51 | + assert.Equal(t, result, "info") |
| 52 | +} |
| 53 | + |
| 54 | +func TestWarn(t *testing.T) { |
| 55 | + testLogger := NewMachineLogger() |
| 56 | + |
| 57 | + result := captureOutput(testLogger, func() { testLogger.Warn("warn") }) |
| 58 | + |
| 59 | + assert.Equal(t, result, "warn") |
| 60 | +} |
| 61 | + |
| 62 | +func TestError(t *testing.T) { |
| 63 | + testLogger := NewMachineLogger() |
| 64 | + |
| 65 | + result := captureOutput(testLogger, func() { testLogger.Error("error") }) |
| 66 | + |
| 67 | + assert.Equal(t, result, "error") |
| 68 | +} |
| 69 | + |
| 70 | +func captureOutput(testLogger MachineLogger, lambda func()) string { |
| 71 | + pipeReader, pipeWriter := io.Pipe() |
| 72 | + scanner := bufio.NewScanner(pipeReader) |
| 73 | + testLogger.SetOutput(pipeWriter) |
| 74 | + go lambda() |
| 75 | + scanner.Scan() |
| 76 | + return scanner.Text() |
| 77 | +} |
0 commit comments