|
| 1 | +package utils |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "errors" |
| 6 | + "os" |
| 7 | + "strings" |
| 8 | + "testing" |
| 9 | + |
| 10 | + "github.com/sirupsen/logrus" |
| 11 | + "github.com/stretchr/testify/assert" |
| 12 | +) |
| 13 | + |
| 14 | +type exitFuncMock struct { |
| 15 | + called bool |
| 16 | + code int |
| 17 | +} |
| 18 | + |
| 19 | +func (e *exitFuncMock) exitFunc(code int) { |
| 20 | + e.called = true |
| 21 | + e.code = code |
| 22 | +} |
| 23 | + |
| 24 | +func TestLogrusErrorWriter_Write(t *testing.T) { |
| 25 | + testErr := []byte("test error message") |
| 26 | + |
| 27 | + buf := &bytes.Buffer{} |
| 28 | + logrus.SetOutput(buf) |
| 29 | + defer logrus.SetOutput(os.Stderr) |
| 30 | + |
| 31 | + writer := LogrusErrorWriter{} |
| 32 | + n, err := writer.Write(testErr) |
| 33 | + |
| 34 | + assert.NoError(t, err) |
| 35 | + assert.Equal(t, len(testErr), n) |
| 36 | + |
| 37 | + assert.True(t, strings.Contains(buf.String(), "test error message")) |
| 38 | +} |
| 39 | + |
| 40 | +func TestCheckErr(t *testing.T) { |
| 41 | + err := errors.New("test error") |
| 42 | + exitMock := &exitFuncMock{} |
| 43 | + |
| 44 | + buf := &bytes.Buffer{} |
| 45 | + logrus.SetOutput(buf) |
| 46 | + defer logrus.SetOutput(os.Stderr) |
| 47 | + |
| 48 | + CheckErrWithExit("An error occurred", err, exitMock.exitFunc) |
| 49 | + |
| 50 | + assert.True(t, strings.Contains(buf.String(), "test error")) |
| 51 | + assert.True(t, exitMock.called) |
| 52 | + assert.Equal(t, 1, exitMock.code) |
| 53 | +} |
| 54 | + |
| 55 | +func TestCheckErr_NoError(t *testing.T) { |
| 56 | + err := error(nil) |
| 57 | + exitMock := &exitFuncMock{} |
| 58 | + |
| 59 | + buf := &bytes.Buffer{} |
| 60 | + logrus.SetOutput(buf) |
| 61 | + defer logrus.SetOutput(os.Stderr) |
| 62 | + |
| 63 | + CheckErrWithExit("No error should occur", err, exitMock.exitFunc) |
| 64 | + |
| 65 | + assert.False(t, strings.Contains(buf.String(), "No error should occur")) |
| 66 | + assert.False(t, exitMock.called) |
| 67 | +} |
0 commit comments