Skip to content

Commit 3f37a0f

Browse files
REGTEST: Added unit tests for logs (#35)
1 parent 6a6fdaa commit 3f37a0f

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

haproxy/halog/log_test.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package halog
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/bmizerany/assert"
8+
"github.com/sirupsen/logrus"
9+
)
10+
11+
type fakeHook struct {
12+
lastMessage map[logrus.Level]string
13+
}
14+
15+
// newFakeHook build a fake hook to retrive last error messages
16+
func newFakeHook() *fakeHook {
17+
h := fakeHook{}
18+
h.lastMessage = make(map[logrus.Level]string, 4)
19+
return &h
20+
}
21+
22+
func (*fakeHook) Levels() []logrus.Level {
23+
return logrus.AllLevels
24+
}
25+
26+
func (h *fakeHook) Fire(e *logrus.Entry) error {
27+
h.lastMessage[e.Level] = e.Message
28+
return nil
29+
}
30+
31+
func ensureLogIsPresent(t *testing.T, hook *fakeHook, expectedLevel logrus.Level, prefix, msg string) {
32+
haproxyLog("haproxy", fmt.Sprintf("%s%s", prefix, msg))
33+
assert.Equal(t, fmt.Sprintf("haproxy: %s", msg), hook.lastMessage[expectedLevel])
34+
}
35+
36+
func Test_log(t *testing.T) {
37+
log := logrus.StandardLogger()
38+
hook := newFakeHook()
39+
log.AddHook(hook)
40+
// Test the parsing that should fail being parsed
41+
ensureLogIsPresent(t, hook, logrus.ErrorLevel, "", "lol")
42+
ensureLogIsPresent(t, hook, logrus.ErrorLevel, "", "[lol")
43+
ensureLogIsPresent(t, hook, logrus.ErrorLevel, "", "lol]")
44+
ensureLogIsPresent(t, hook, logrus.ErrorLevel, "", "[]")
45+
46+
// while crap is well formatted, no recognized as valid type
47+
ensureLogIsPresent(t, hook, logrus.ErrorLevel, "", "[CRAP] Unknown kind of error")
48+
49+
ensureLogIsPresent(t, hook, logrus.InfoLevel, "[NOTICE]", "yup")
50+
ensureLogIsPresent(t, hook, logrus.InfoLevel, "[NOTICE]", "")
51+
52+
ensureLogIsPresent(t, hook, logrus.WarnLevel, "[WARNING]", "yup")
53+
ensureLogIsPresent(t, hook, logrus.ErrorLevel, "[ALERT]", "yup")
54+
}

0 commit comments

Comments
 (0)