prysm-pulse/shared/testutil/log.go

68 lines
1.6 KiB
Go
Raw Normal View History

// Package testutil defines the testing utils such as asserting logs.
package testutil
import (
"strings"
"testing"
2018-09-21 19:33:53 +00:00
"time"
"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 {
if strings.Contains(e.Message, want) {
match = true
}
t.Logf("log: %s", e.Message)
}
if flag && !match {
t.Fatalf("log not found: %s", want)
} else if !flag && match {
t.Fatalf("unwanted log found: %s", want)
}
}
2018-09-21 19:33:53 +00:00
// WaitForLog scans for log entries in a way that prevents
// race conditions from causing failed tests.
func WaitForLog(t *testing.T, hook *test.Hook, want string) {
t.Logf("scanning for: %s", want)
match := false
ticker := time.NewTicker(1 * time.Second)
for {
entries := hook.AllEntries()
if match {
ticker.Stop()
break
}
if len(ticker.C) != 0 {
ticker.Stop()
t.Fatalf("log not found: %s", want)
break
}
for _, e := range entries {
if strings.Contains(e.Message, want) {
match = true
t.Logf("log: %s", e.Message)
}
}
}
}