From d8e5b33f36bf2eb00043ad687660dd587fabc666 Mon Sep 17 00:00:00 2001 From: hidu Date: Sun, 29 Oct 2023 21:42:43 +0800 Subject: [PATCH] assert: fix missing *http.Request.RequestURI RequestURI is the unmodified request-target of the Request-Line (RFC 7230, Section 3.1.1) as sent by the client to a server. --- assert/http_assertions.go | 2 ++ assert/http_assertions_test.go | 42 ++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/assert/http_assertions.go b/assert/http_assertions.go index 861ed4b7c..a0c2904e9 100644 --- a/assert/http_assertions.go +++ b/assert/http_assertions.go @@ -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 @@ -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() } diff --git a/assert/http_assertions_test.go b/assert/http_assertions_test.go index dd84f02f1..3a37ec94c 100644 --- a/assert/http_assertions_test.go +++ b/assert/http_assertions_test.go @@ -4,6 +4,7 @@ import ( "fmt" "io" "net/http" + "net/http/httptest" "net/url" "testing" ) @@ -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") + }) +}