From c4f6fd5b3cbcdd69b5ae23c6759dfdbefa8e832a Mon Sep 17 00:00:00 2001 From: Matt Moyer Date: Fri, 5 Mar 2021 15:49:45 -0600 Subject: [PATCH] Add a bit nicer assertion helper in testutil/testlogger. This makes output that's easier to copy-paste into the test. We could also make it ignore the order of key/value pairs in the future. Signed-off-by: Matt Moyer --- internal/testutil/testlogger/testlogger.go | 23 ++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/internal/testutil/testlogger/testlogger.go b/internal/testutil/testlogger/testlogger.go index f20cbc7e..51b6ead6 100644 --- a/internal/testutil/testlogger/testlogger.go +++ b/internal/testutil/testlogger/testlogger.go @@ -6,6 +6,7 @@ package testlogger import ( "bytes" + "fmt" "log" "strings" "sync" @@ -13,6 +14,7 @@ import ( "github.com/go-logr/logr" "github.com/go-logr/stdr" + "github.com/stretchr/testify/require" ) // Logger implements logr.Logger in a way that captures logs for test assertions. @@ -46,6 +48,12 @@ func (l *Logger) Lines() []string { return result } +// Expect the emitted lines to match known-good output. +func (l *Logger) Expect(expected []string) { + actual := l.Lines() + require.Equalf(l.t, expected, actual, "did not see expected log output, actual output:\n%#v", backtickStrings(actual)) +} + // syncBuffer synchronizes access to a bytes.Buffer. type syncBuffer struct { mutex sync.Mutex @@ -57,3 +65,18 @@ func (s *syncBuffer) Write(p []byte) (n int, err error) { defer s.mutex.Unlock() return s.buffer.Write(p) } + +type backtickStrings []string + +func (b backtickStrings) GoString() string { + lines := make([]string, 0, len(b)) + for _, s := range b { + if strings.Contains(s, "`") { + s = fmt.Sprintf("%#v", s) + } else { + s = fmt.Sprintf("`%s`", s) + } + lines = append(lines, fmt.Sprintf("\t%s,", s)) + } + return fmt.Sprintf("[]string{\n%s\n}", strings.Join(lines, "\n")) +}