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 <moyerm@vmware.com>
This commit is contained in:
Matt Moyer 2021-03-05 15:49:45 -06:00
parent 52f58477b8
commit c4f6fd5b3c
No known key found for this signature in database
GPG Key ID: EAE88AD172C5AE2D

View File

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