Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve: Add debug option #50

Merged
merged 1 commit into from
Feb 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading