diff --git a/checker.go b/checker.go index 15003e6..ff805dc 100644 --- a/checker.go +++ b/checker.go @@ -32,6 +32,12 @@ func CheckRedirect(policy func(req *http.Request, via []*http.Request) error) Op } } +func Debug() Option { + return func(c *Checker) { + c.debug = true + } +} + // NoRedirect is the alias of the following: // // CheckRedirect(func(req *http.Request, via []*http.Request) error { @@ -59,6 +65,9 @@ type Checker struct { url string server *httptest.Server handler http.Handler + + // debug mode + debug bool } // New creates an HTTP Checker for testing with the given handler. diff --git a/checker_test.go b/checker_test.go index d351df7..f97419e 100644 --- a/checker_test.go +++ b/checker_test.go @@ -95,11 +95,12 @@ func TestNewExternal(t *testing.T) { }) ts := httptest.NewServer(mux) defer ts.Close() - checker := NewExternal(ts.URL) + checker := NewExternal(ts.URL, Debug()) require.NotNil(t, checker) assert.Equal(t, DefaultClientTimeout, checker.client.Timeout) assert.True(t, checker.external) checker.Test(t, http.MethodGet, "/some"). + WithJSON(map[string]string{"key": "value"}). Check(). HasStatus(http.StatusOK). HasBody([]byte("hello")) diff --git a/tester.go b/tester.go index d11da0b..3a3aa0f 100644 --- a/tester.go +++ b/tester.go @@ -3,6 +3,7 @@ package httpcheck import ( "bytes" "io" + "log" "net/http" "net/http/cookiejar" @@ -35,6 +36,19 @@ func (tt *Tester) Check() *Tester { tt.run() defer tt.stop() + if tt.debug { + log.Println("==", tt.request.Method, tt.request.URL) + log.Println(">> header", tt.request.Header) + body := "nil" + if tt.request.Body != nil { + b, err := io.ReadAll(tt.request.Body) + require.NoError(tt.t, err, "failed to read request body") + tt.request.Body = io.NopCloser(bytes.NewReader(b)) + body = string(b) + } + log.Println(">> body:", string(body)) + } + newJar, _ := cookiejar.New(nil) for name := range tt.pcookies { for _, oldCookie := range tt.client.Jar.Cookies(tt.request.URL) { @@ -60,6 +74,12 @@ func (tt *Tester) Check() *Tester { tt.response = response tt.response.Body = io.NopCloser(bytes.NewReader(b)) + + if tt.debug { + log.Println("<< status:", tt.response.Status) + log.Println("<< body:", string(b)) + } + return tt }