Skip to content

Commit

Permalink
add tests to cover different errors
Browse files Browse the repository at this point in the history
Signed-off-by: Ziqi Zhao <[email protected]>
  • Loading branch information
fatsheep9146 committed Jul 14, 2022
1 parent a7aa25b commit 3ab1d66
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions config/confighttp/compression_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ import (
"compress/gzip"
"compress/zlib"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"

Expand Down Expand Up @@ -257,6 +259,61 @@ func TestHTTPContentCompressionRequestWithNilBody(t *testing.T) {
require.NoError(t, res.Body.Close(), "failed to close request body: %v", err)
}

func TestHTTPContentCompressionCopyError(t *testing.T) {
copyErrorCompressRoundTripper := &compressRoundTripper{
RoundTripper: http.DefaultTransport,
compressionType: "copyFailed",
writer: func(buf *bytes.Buffer) (io.WriteCloser, error) {
return nil, fmt.Errorf("copy failed")
},
}

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
}))
defer server.Close()

req, err := http.NewRequest("GET", server.URL, nil)
require.NoError(t, err, "failed to create request to test handler")

client := http.Client{}
client.Transport = copyErrorCompressRoundTripper
_, err = client.Do(req)
require.Error(t, err)
}

type closeFailBody struct {
*bytes.Buffer
}

func (*closeFailBody) Close() error {
return fmt.Errorf("close failed")
}

func TestHTTPContentCompressionRequestBodyCloseError(t *testing.T) {
testBody := []byte("blank")
body := &closeFailBody{
Buffer: bytes.NewBuffer(testBody),
}

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
}))
defer server.Close()

url, _ := url.Parse(server.URL)
req := &http.Request{
Method: "GET",
URL: url,
Body: body,
}

client := http.Client{}
client.Transport = newCompressRoundTripper(http.DefaultTransport, configcompression.Gzip)
_, err := client.Do(req)
require.Error(t, err)
}

func compressGzip(body []byte) (*bytes.Buffer, error) {
var buf bytes.Buffer

Expand Down

0 comments on commit 3ab1d66

Please sign in to comment.