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")) +}