Skip to content

Commit

Permalink
test(compress): Add additional tests to check the response in case no…
Browse files Browse the repository at this point in the history
… compression is performed
  • Loading branch information
Neurostep committed Jul 2, 2024
1 parent 07ad400 commit 19694e2
Showing 1 changed file with 39 additions and 2 deletions.
41 changes: 39 additions & 2 deletions middleware/compress_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package middleware

import (
"bytes"
"compress/flate"
"compress/gzip"
"fmt"
Expand Down Expand Up @@ -43,7 +44,7 @@ func TestCompressor(t *testing.T) {
})

r.Get("/getplain", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("textstring"))
})

Expand All @@ -55,18 +56,21 @@ func TestCompressor(t *testing.T) {
path string
expectedEncoding string
acceptedEncodings []string
checkRawResponse bool
}{
{
name: "no expected encodings due to no accepted encodings",
path: "/gethtml",
acceptedEncodings: nil,
acceptedEncodings: []string{""},
expectedEncoding: "",
checkRawResponse: true,
},
{
name: "no expected encodings due to content type",
path: "/getplain",
acceptedEncodings: nil,
expectedEncoding: "",
checkRawResponse: true,
},
{
name: "gzip is only encoding",
Expand All @@ -92,12 +96,16 @@ func TestCompressor(t *testing.T) {
path: "/getcss",
acceptedEncodings: []string{"nop, gzip, deflate"},
expectedEncoding: "nop",
checkRawResponse: true,
},
}

for _, tc := range tests {
tc := tc
t.Run(tc.name, func(t *testing.T) {
if tc.checkRawResponse {
testRequestRawResponse(t, ts, "GET", tc.path, []byte("textstring"), tc.acceptedEncodings...)
}
resp, respString := testRequestWithAcceptedEncodings(t, ts, "GET", tc.path, tc.acceptedEncodings...)
if respString != "textstring" {
t.Errorf("response text doesn't match; expected:%q, got:%q", "textstring", respString)
Expand Down Expand Up @@ -171,6 +179,35 @@ func TestCompressorWildcards(t *testing.T) {
}
}

func testRequestRawResponse(t *testing.T, ts *httptest.Server, method, path string, exp []byte, encodings ...string) {
req, err := http.NewRequest(method, ts.URL+path, nil)
if err != nil {
t.Fatal(err)
return
}
if len(encodings) > 0 {
encodingsString := strings.Join(encodings, ",")
req.Header.Set("Accept-Encoding", encodingsString)
}

resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
return
}

respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
return
}
defer resp.Body.Close()

if !bytes.Equal(respBody, exp) {
t.Errorf("expected %q but got %q", exp, respBody)
}
}

func testRequestWithAcceptedEncodings(t *testing.T, ts *httptest.Server, method, path string, encodings ...string) (*http.Response, string) {
req, err := http.NewRequest(method, ts.URL+path, nil)
if err != nil {
Expand Down

0 comments on commit 19694e2

Please sign in to comment.