2020-04-29 21:32:39 +00:00
|
|
|
// Package testutil defines common unit test utils such as asserting logs.
|
2018-07-25 16:57:44 +00:00
|
|
|
package testutil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/sirupsen/logrus/hooks/test"
|
|
|
|
)
|
|
|
|
|
|
|
|
// AssertLogsContain checks that the desired string is a subset of the current log output.
|
|
|
|
// Set exitOnFail to true to immediately exit the test on failure
|
|
|
|
func AssertLogsContain(t *testing.T, hook *test.Hook, want string) {
|
|
|
|
assertLogs(t, hook, want, true)
|
|
|
|
}
|
|
|
|
|
|
|
|
// AssertLogsDoNotContain is the inverse check of AssertLogsContain
|
|
|
|
func AssertLogsDoNotContain(t *testing.T, hook *test.Hook, want string) {
|
|
|
|
assertLogs(t, hook, want, false)
|
|
|
|
}
|
|
|
|
|
|
|
|
func assertLogs(t *testing.T, hook *test.Hook, want string, flag bool) {
|
|
|
|
t.Logf("scanning for: %s", want)
|
|
|
|
entries := hook.AllEntries()
|
|
|
|
match := false
|
|
|
|
for _, e := range entries {
|
2019-04-18 17:23:38 +00:00
|
|
|
msg, err := e.String()
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("Failed to format log entry to string: %v", err)
|
|
|
|
}
|
|
|
|
if strings.Contains(msg, want) {
|
2018-07-25 16:57:44 +00:00
|
|
|
match = true
|
|
|
|
}
|
2020-07-21 02:05:23 +00:00
|
|
|
for _, field := range e.Data {
|
|
|
|
fieldStr, ok := field.(string)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if strings.Contains(fieldStr, want) {
|
|
|
|
match = true
|
|
|
|
}
|
|
|
|
}
|
2019-04-18 17:23:38 +00:00
|
|
|
t.Logf("log: %s", msg)
|
2018-07-25 16:57:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if flag && !match {
|
|
|
|
t.Fatalf("log not found: %s", want)
|
|
|
|
} else if !flag && match {
|
|
|
|
t.Fatalf("unwanted log found: %s", want)
|
|
|
|
}
|
|
|
|
}
|