Skip to content

Commit

Permalink
Merge pull request #50 from ikawaha/feat/add-debug-mode
Browse files Browse the repository at this point in the history
improve: Add debug option
  • Loading branch information
ikawaha authored Feb 3, 2024
2 parents 14becd8 + 57c2a69 commit 1dc6f8a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
9 changes: 9 additions & 0 deletions checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion checker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand Down
20 changes: 20 additions & 0 deletions tester.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package httpcheck
import (
"bytes"
"io"
"log"
"net/http"
"net/http/cookiejar"

Expand Down Expand Up @@ -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) {
Expand All @@ -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
}

Expand Down

0 comments on commit 1dc6f8a

Please sign in to comment.