From c434c377685cb280614e6e6a84b0cc793ad9ad72 Mon Sep 17 00:00:00 2001 From: Peter Boothe Date: Tue, 21 Apr 2020 14:41:19 -0400 Subject: [PATCH] Coverage improvement in one package (#284) * Make sure the Handler handles things correctly --- logging/logging.go | 5 +++-- logging/logging_test.go | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) create mode 100644 logging/logging_test.go diff --git a/logging/logging.go b/logging/logging.go index 693cd4df..bf4cc717 100644 --- a/logging/logging.go +++ b/logging/logging.go @@ -3,6 +3,7 @@ package logging import ( + golog "log" "net/http" "os" @@ -17,7 +18,7 @@ import ( // when dockerising an Apache or Nginx instance. var Logger = log.Logger{ Handler: json.New(os.Stderr), - Level: log.DebugLevel, + Level: log.DebugLevel, } // MakeAccessLogHandler wraps |handler| with another handler that logs @@ -26,5 +27,5 @@ var Logger = log.Logger{ // access logs, because access logs are a fairly standard format that // has been around for a long time now, so better to follow such standard. func MakeAccessLogHandler(handler http.Handler) http.Handler { - return handlers.LoggingHandler(os.Stdout, handler) + return handlers.LoggingHandler(golog.Writer(), handler) } diff --git a/logging/logging_test.go b/logging/logging_test.go new file mode 100644 index 00000000..c8bae43d --- /dev/null +++ b/logging/logging_test.go @@ -0,0 +1,40 @@ +package logging + +import ( + "bytes" + "log" + "net/http" + "testing" + + "github.com/m-lab/go/httpx" + "github.com/m-lab/go/rtx" +) + +type fakeHandler struct{} + +func (s *fakeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(200) +} + +func TestMakeAccessLogHandler(t *testing.T) { + buff := &bytes.Buffer{} + old := log.Writer() + defer func() { + log.SetOutput(old) + }() + log.SetOutput(buff) + f := MakeAccessLogHandler(&fakeHandler{}) + log.SetOutput(old) + srv := http.Server{ + Addr: ":0", + Handler: f, + } + rtx.Must(httpx.ListenAndServeAsync(&srv), "Could not start server") + defer srv.Close() + _, err := http.Get("http://" + srv.Addr + "/") + rtx.Must(err, "Could not get") + s, err := buff.ReadString('\n') + if s == "" { + t.Error("We should not have had an empty string") + } +}