From af9821f90fd1c45490ffb7c5dbc75dea7de92917 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carl-Magnus=20Bj=C3=B6rkell?= Date: Thu, 1 Feb 2024 11:24:27 +0100 Subject: [PATCH] Update RequestLogger interface To improve ergonomics of the request logger, make the interface use a Logf method that is also already fulfilled by the testing.T struct, so that this can be passed into the Option without needing adaptation. --- client_test.go | 4 ++-- options.go | 4 +++- verifier.go | 4 ++-- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/client_test.go b/client_test.go index 586b54b..53a1ba5 100644 --- a/client_test.go +++ b/client_test.go @@ -160,10 +160,10 @@ type logStore struct { logs []string } -func (l *logStore) Print(s string) { +func (l *logStore) Logf(format string, args ...any) { l.mu.Lock() defer l.mu.Unlock() - l.logs = append(l.logs, s) + l.logs = append(l.logs, fmt.Sprintf(format, args...)) } func TestRequestLogging(t *testing.T) { diff --git a/options.go b/options.go index 69c4d3b..bace798 100644 --- a/options.go +++ b/options.go @@ -47,8 +47,10 @@ func WithRequestValidation() Option { } } +// RequestLogger is a minimal interface that can fit for example a testing.T, allowing tests to easily print logs where +// needed. type RequestLogger interface { - Print(string) + Logf(format string, args ...any) } // WithRequestLogging is a functional Option that provides a logger that copper will use to log out requests and diff --git a/verifier.go b/verifier.go index 77525ea..6ba5bc5 100644 --- a/verifier.go +++ b/verifier.go @@ -108,12 +108,12 @@ func (v *Verifier) Record(res *http.Response) { count := v.reqCounter.Add(1) reqDump, err := httputil.DumpRequestOut(req, true) if err == nil { - v.conf.requestLogger.Print(fmt.Sprintf("REQUEST %04d ====\n%s", count, string(reqDump))) + v.conf.requestLogger.Logf("REQUEST %04d ====\n%s", count, string(reqDump)) } resDump, err := httputil.DumpResponse(res, true) if err == nil { - v.conf.requestLogger.Print(fmt.Sprintf("RESPONSE %04d ====\n%s", count, string(resDump))) + v.conf.requestLogger.Logf("RESPONSE %04d ====\n%s", count, string(resDump)) } }