diff --git a/internal/middleware/gunzip_test.go b/internal/middleware/gunzip_test.go index bb53705..3b651ee 100644 --- a/internal/middleware/gunzip_test.go +++ b/internal/middleware/gunzip_test.go @@ -25,8 +25,8 @@ func TestGunzip(t *testing.T) { body := &strings.Builder{} nbytes, err := io.Copy(body, r.Body) - assert.True(t, nbytes > 0) - assert.Nil(t, err) + assert.NotZero(t, nbytes) + assert.NoError(t, err) assert.Equal(t, ethChainID, body.String()) assert.Equal(t, int64(len(ethChainID)), r.ContentLength) @@ -38,7 +38,7 @@ func TestGunzip(t *testing.T) { nbytes, err := io.Copy(w, bytes.NewBufferString(ethChainID)) - assert.Nil(t, err) + assert.NoError(t, err) assert.True(t, nbytes > 0) assert.Nil(t, w.Close()) @@ -56,8 +56,8 @@ func TestGunzip(t *testing.T) { body := &strings.Builder{} nbytes, err := io.Copy(body, r.Body) - assert.True(t, nbytes > 0) - assert.Nil(t, err) + assert.NotZero(t, nbytes) + assert.NoError(t, err) assert.Equal(t, ethChainID, body.String()) assert.Equal(t, int64(len(ethChainID)), r.ContentLength) diff --git a/internal/proxy/healthchecker_test.go b/internal/proxy/healthchecker_test.go index 803d7c5..bf798c2 100644 --- a/internal/proxy/healthchecker_test.go +++ b/internal/proxy/healthchecker_test.go @@ -31,7 +31,7 @@ func TestBasicHealthchecker(t *testing.T) { } healthchecker, err := NewHealthchecker(healtcheckConfig) - assert.Nil(t, err) + assert.NoError(t, err) healthchecker.Start(ctx) @@ -52,7 +52,7 @@ func TestGasLeftCall(t *testing.T) { url := env.GetDefault("RPC_GATEWAY_NODE_URL_1", "https://cloudflare-eth.com") result, err := performGasLeftCall(context.TODO(), client, url) - assert.Nil(t, err) + assert.NoError(t, err) assert.NotZero(t, result) // testing the timeout @@ -60,5 +60,5 @@ func TestGasLeftCall(t *testing.T) { defer cancelFunc() _, err = performGasLeftCall(ctx, client, url) - assert.NotNil(t, err) + assert.Error(t, err) } diff --git a/internal/proxy/healthchecker_utils.go b/internal/proxy/healthchecker_utils.go index cc3103e..cb74ec4 100644 --- a/internal/proxy/healthchecker_utils.go +++ b/internal/proxy/healthchecker_utils.go @@ -4,11 +4,12 @@ import ( "bytes" "context" "encoding/json" - "fmt" - "io" "net/http" "strconv" "strings" + + "github.com/go-http-utils/headers" + "github.com/pkg/errors" ) type JSONRPCResponse struct { @@ -22,7 +23,7 @@ func hexToUint(hexString string) (uint64, error) { return strconv.ParseUint(hexString, 16, 64) } -func performGasLeftCall(ctx context.Context, client *http.Client, url string) (uint64, error) { +func performGasLeftCall(c context.Context, client *http.Client, url string) (uint64, error) { var gasLeftCallRaw = []byte(` { "method": "eth_call", @@ -46,30 +47,28 @@ func performGasLeftCall(ctx context.Context, client *http.Client, url string) (u } `) - requestBody := bytes.NewBuffer(gasLeftCallRaw) - request, err := http.NewRequestWithContext(ctx, "POST", url, requestBody) - - request.Header.Add("Content-Type", "application/json") - request.Header.Set("User-Agent", userAgent) - + r, err := http.NewRequestWithContext(c, http.MethodPost, url, bytes.NewBuffer(gasLeftCallRaw)) if err != nil { - return 0, err + return 0, errors.Wrap(err, "new request failed") } - resp, err := client.Do(request) + + r.Header.Add(headers.ContentEncoding, "application/json") + r.Header.Set(headers.UserAgent, userAgent) + + resp, err := client.Do(r) if err != nil { - return 0, err + return 0, errors.Wrap(err, "request failed") } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - bodyContent, _ := io.ReadAll(resp.Body) - return 0, fmt.Errorf("got non-200 response, status: %d, body: %s", resp.StatusCode, bodyContent) + return 0, errors.Wrap(err, "gas left check failed") } result := &JSONRPCResponse{} err = json.NewDecoder(resp.Body).Decode(result) if err != nil { - return 0, err + return 0, errors.Wrap(err, "json response decode failed") } return hexToUint(result.Result) diff --git a/internal/proxy/manager_test.go b/internal/proxy/manager_test.go index 13cf1a2..4e9932f 100644 --- a/internal/proxy/manager_test.go +++ b/internal/proxy/manager_test.go @@ -54,7 +54,7 @@ func TestHealthcheckManager(t *testing.T) { nextIdx = manager.GetNextHealthyTargetIndex() assert.Equal(t, 1, nextIdx) - manager.Stop(ctx) + assert.NoError(t, manager.Stop(ctx)) } func TestGetNextHealthyTargetIndexExcluding(t *testing.T) { diff --git a/internal/proxy/proxy_test.go b/internal/proxy/proxy_test.go index f2824c7..840a008 100644 --- a/internal/proxy/proxy_test.go +++ b/internal/proxy/proxy_test.go @@ -9,6 +9,7 @@ import ( "strconv" "testing" + "github.com/go-http-utils/headers" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/assert" ) @@ -32,7 +33,8 @@ func TestHttpFailoverProxyRerouteRequests(t *testing.T) { prometheus.DefaultRegisterer = prometheus.NewRegistry() fakeRPC1Server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.Error(w, "Bad Request", http.StatusInternalServerError) + http.Error(w, + http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) })) defer fakeRPC1Server.Close() @@ -72,7 +74,7 @@ func TestHttpFailoverProxyRerouteRequests(t *testing.T) { httpFailoverProxy := NewProxy(rpcGatewayConfig, healthcheckManager) requestBody := bytes.NewBufferString(`{"this_is": "body"}`) - req, err := http.NewRequest("POST", "/", requestBody) + req, err := http.NewRequest(http.MethodPost, "/", requestBody) assert.Nil(t, err) @@ -93,8 +95,8 @@ func TestHttpFailoverProxyDecompressRequest(t *testing.T) { var receivedBody, receivedHeaderContentEncoding, receivedHeaderContentLength string fakeRPC1Server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - receivedHeaderContentEncoding = r.Header.Get("Content-Encoding") - receivedHeaderContentLength = r.Header.Get("Content-Length") + receivedHeaderContentEncoding = r.Header.Get(headers.ContentEncoding) + receivedHeaderContentLength = r.Header.Get(headers.ContentLength) body, _ := io.ReadAll(r.Body) receivedBody = string(body) w.Write([]byte("OK")) @@ -122,37 +124,23 @@ func TestHttpFailoverProxyDecompressRequest(t *testing.T) { var buf bytes.Buffer g := gzip.NewWriter(&buf) + _, err := g.Write([]byte(`{"body": "content"}`)) - if err != nil { - t.Fatal(err) - } - err = g.Close() - if err != nil { - t.Fatal(err) - } + assert.NoError(t, err) + assert.NoError(t, g.Close()) - req, err := http.NewRequest("POST", "/", &buf) - req.Header.Add("Content-Encoding", "gzip") - if err != nil { - t.Fatal(err) - } + req, err := http.NewRequest(http.MethodPost, "/", &buf) + assert.NoError(t, err) + + req.Header.Add(headers.ContentEncoding, "gzip") rr := httptest.NewRecorder() handler := http.HandlerFunc(httpFailoverProxy.ServeHTTP) handler.ServeHTTP(rr, req) - want := `{"body": "content"}` - if receivedBody != want { - t.Errorf("the proxy didn't decompress the request before forwarding the body to the target: want: %s, got: %s", want, receivedBody) - } - want = "" - if receivedHeaderContentEncoding != want { - t.Errorf("the proxy didn't remove the `Content-Encoding: gzip` after decompressing the body, want empty, got: %s", receivedHeaderContentEncoding) - } - want = strconv.Itoa(len(`{"body": "content"}`)) - if receivedHeaderContentLength != want { - t.Errorf("the proxy didn't correctly re-calculate the `Content-Length` after decompressing the body, want: %s, got: %s", want, receivedHeaderContentLength) - } + assert.Equal(t, `{"body": "content"}`, receivedBody) + assert.Equal(t, "", receivedHeaderContentEncoding) + assert.Equal(t, strconv.Itoa(len(`{"body": "content"}`)), receivedHeaderContentLength) } func TestHttpFailoverProxyWithCompressionSupportedTarget(t *testing.T) { @@ -161,11 +149,12 @@ func TestHttpFailoverProxyWithCompressionSupportedTarget(t *testing.T) { var receivedHeaderContentEncoding string var receivedBody []byte fakeRPC1Server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - receivedHeaderContentEncoding = r.Header.Get("Content-Encoding") + receivedHeaderContentEncoding = r.Header.Get(headers.ContentEncoding) receivedBody, _ = io.ReadAll(r.Body) w.Write([]byte("OK")) })) defer fakeRPC1Server.Close() + rpcGatewayConfig := createConfig() rpcGatewayConfig.Targets = []TargetConfig{ { @@ -189,38 +178,27 @@ func TestHttpFailoverProxyWithCompressionSupportedTarget(t *testing.T) { var buf bytes.Buffer g := gzip.NewWriter(&buf) + _, err := g.Write([]byte(`{"body": "content"}`)) - if err != nil { - t.Fatal(err) - } - err = g.Close() - if err != nil { - t.Fatal(err) - } + assert.NoError(t, err) + assert.NoError(t, g.Close()) - req, err := http.NewRequest("POST", "/", &buf) - req.Header.Add("Content-Encoding", "gzip") - if err != nil { - t.Fatal(err) - } + req, err := http.NewRequest(http.MethodPost, "/", &buf) + req.Header.Add(headers.ContentEncoding, "gzip") + assert.NoError(t, err) rr := httptest.NewRecorder() handler := http.HandlerFunc(httpFailoverProxy.ServeHTTP) handler.ServeHTTP(rr, req) - want := "gzip" - if receivedHeaderContentEncoding != want { - t.Errorf("the proxy didn't keep the header of `Content-Encoding: gzip`, want: %s, got: %s", want, receivedHeaderContentEncoding) - } + assert.Equal(t, "gzip", receivedHeaderContentEncoding) var wantBody bytes.Buffer g = gzip.NewWriter(&wantBody) g.Write([]byte(`{"body": "content"}`)) - g.Close() - if !bytes.Equal(receivedBody, wantBody.Bytes()) { - t.Errorf("the proxy didn't keep the body as is when forwarding gzipped body to the target.") - } + assert.NoError(t, g.Close()) + assert.Equal(t, wantBody.Bytes(), receivedBody) } func TestHTTPFailoverProxyWhenCannotConnectToPrimaryProvider(t *testing.T) { @@ -267,7 +245,7 @@ func TestHTTPFailoverProxyWhenCannotConnectToPrimaryProvider(t *testing.T) { httpFailoverProxy := NewProxy(rpcGatewayConfig, healthcheckManager) requestBody := bytes.NewBufferString(`{"this_is": "body"}`) - req, err := http.NewRequest("POST", "/", requestBody) + req, err := http.NewRequest(http.MethodPost, "/", requestBody) if err != nil { t.Fatal(err) } @@ -277,12 +255,6 @@ func TestHTTPFailoverProxyWhenCannotConnectToPrimaryProvider(t *testing.T) { handler.ServeHTTP(rr, req) - if status := rr.Code; status != http.StatusOK { - t.Errorf("server returned wrong status code: got %v want %v", status, http.StatusOK) - } - - want := `{"this_is": "body"}` - if rr.Body.String() != want { - t.Errorf("server returned unexpected body: got '%v' want '%v'", rr.Body.String(), want) - } + assert.Equal(t, http.StatusOK, rr.Code) + assert.Equal(t, `{"this_is": "body"}`, rr.Body.String()) } diff --git a/internal/rpcgateway/rpcgateway_test.go b/internal/rpcgateway/rpcgateway_test.go index 79d5733..11c0584 100644 --- a/internal/rpcgateway/rpcgateway_test.go +++ b/internal/rpcgateway/rpcgateway_test.go @@ -12,6 +12,7 @@ import ( toxiproxy "github.com/Shopify/toxiproxy/client" "github.com/caitlinelfring/go-env-default" + "github.com/go-http-utils/headers" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/assert" "go.uber.org/zap" @@ -76,15 +77,15 @@ func TestRpcGatewayFailover(t *testing.T) { // Toxic Proxy setup toxiClient := toxiproxy.NewClient("localhost:8474") err := toxiClient.ResetState() - assert.Nil(t, err) + assert.NoError(t, err) proxy, err := toxiClient.CreateProxy("primary", "0.0.0.0:9991", ts.URL[7:]) - assert.Nil(t, err) + assert.NoError(t, err) _, err = proxy.AddToxic("latency_down", "latency", "downstream", 1.0, toxiproxy.Attributes{ "latency": 100000, }) - assert.Nil(t, err) + assert.NoError(t, err) defer func() { _ = toxiClient.ResetState() @@ -95,17 +96,14 @@ func TestRpcGatewayFailover(t *testing.T) { var tpl bytes.Buffer tu := TestURL{"http://0.0.0.0:9991", env.GetDefault("RPC_GATEWAY_NODE_URL_1", "https://cloudflare-eth.com")} tmpl, err := template.New("test").Parse(rpcGatewayConfig) - assert.Nil(t, err) + assert.NoError(t, err) err = tmpl.Execute(&tpl, tu) - assert.Nil(t, err) + assert.NoError(t, err) configString := tpl.String() - - t.Log(configString) - config, err := NewRPCGatewayFromConfigString(configString) - assert.Nil(t, err) + assert.NoError(t, err) gateway := NewRPCGateway(*config) go gateway.Start(context.TODO()) @@ -118,20 +116,21 @@ func TestRpcGatewayFailover(t *testing.T) { MaxConnsPerHost: 1, } - req, _ := http.NewRequest("POST", gs.URL, bytes.NewBufferString(rpcRequestBody)) - req.Header.Set("Content-Type", "application/json") + req, _ := http.NewRequest(http.MethodPost, gs.URL, bytes.NewBufferString(rpcRequestBody)) + req.Header.Set(headers.ContentEncoding, "application/json") req.ContentLength = int64(len(rpcRequestBody)) res, err := gsClient.Do(req) - assert.Nil(t, err) + assert.NoError(t, err) defer res.Body.Close() assert.Equal(t, http.StatusOK, res.StatusCode) - _, err = io.ReadAll(res.Body) - assert.Nil(t, err) + nbytes, err := io.ReadAll(res.Body) + assert.NoError(t, err) + assert.NotZero(t, nbytes) err = gateway.Stop(context.TODO()) - assert.Nil(t, err) + assert.NoError(t, err) }