Skip to content

Commit

Permalink
assert: fix missing *http.Request.RequestURI
Browse files Browse the repository at this point in the history
RequestURI is the unmodified request-target of the
Request-Line (RFC 7230, Section 3.1.1) as sent by the client to a server.
  • Loading branch information
hidu committed Mar 6, 2024
1 parent edb8015 commit d8e5b33
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
2 changes: 2 additions & 0 deletions assert/http_assertions.go
Expand Up @@ -16,6 +16,7 @@ func httpCode(handler http.HandlerFunc, method, url string, values url.Values) (
if err != nil {
return -1, err
}
req.RequestURI = req.URL.RequestURI()
req.URL.RawQuery = values.Encode()
handler(w, req)
return w.Code, nil
Expand Down Expand Up @@ -120,6 +121,7 @@ func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) s
if err != nil {
return ""
}
req.RequestURI = req.URL.RequestURI()
handler(w, req)
return w.Body.String()
}
Expand Down
42 changes: 42 additions & 0 deletions assert/http_assertions_test.go
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
Expand Down Expand Up @@ -212,3 +213,44 @@ func TestHttpBodyWrappers(t *testing.T) {
assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World"))
assert.True(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world"))
}

func httpCheckRequest(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprintf(w, "URI: %s\n", r.RequestURI)
_, _ = fmt.Fprintf(w, "RawQuery: %s\n", r.URL.RawQuery)
}

func TestHTTPCheckRequest(t *testing.T) {
t.Run("by test-server", func(t *testing.T) {
assert := New(t)
ts := httptest.NewServer(http.HandlerFunc(httpCheckRequest))
defer ts.Close()
resp, err1 := ts.Client().Get(ts.URL + "/check?p1=World")
assert.NoError(err1)
bf, err2 := io.ReadAll(resp.Body)
_ = resp.Body.Close()
assert.NoError(err2)
assert.Contains(string(bf), "URI: /check")
assert.Contains(string(bf), "RawQuery: p1=World")
})

t.Run("by assert", func(t *testing.T) {
assert := New(t)

mockT1 := new(testing.T)
assert.Equal(HTTPSuccess(mockT1, httpCheckRequest, "GET", "/", nil), true)
assert.False(mockT1.Failed())

values2 := url.Values{
"p1": []string{"World"},
}
body2 := HTTPBody(httpCheckRequest, "GET", "/check", values2)
assert.Contains(body2, "URI: /check")

values3 := url.Values{
"p1": []string{"World"},
}
body3 := HTTPBody(httpCheckRequest, "GET", "/", values3)
assert.Contains(body3, "RawQuery: p1=World")
})
}

0 comments on commit d8e5b33

Please sign in to comment.