Skip to content

Commit 2272744

Browse files
committed
Write unit tests for utils.go
Signed-off-by: Doğukan Teber <[email protected]>
1 parent 22c6ca4 commit 2272744

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

utils/utils_test.go

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
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

Comments
 (0)