Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

Commit

Permalink
Clean up tests
Browse files Browse the repository at this point in the history
  • Loading branch information
eitu5ami committed Dec 15, 2023
1 parent f949bd6 commit ad32cd2
Show file tree
Hide file tree
Showing 6 changed files with 67 additions and 97 deletions.
10 changes: 5 additions & 5 deletions internal/middleware/gunzip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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())

Expand All @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions internal/proxy/healthchecker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func TestBasicHealthchecker(t *testing.T) {
}

healthchecker, err := NewHealthchecker(healtcheckConfig)
assert.Nil(t, err)
assert.NoError(t, err)

healthchecker.Start(ctx)

Expand All @@ -52,13 +52,13 @@ 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
ctx, cancelFunc := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancelFunc()

_, err = performGasLeftCall(ctx, client, url)
assert.NotNil(t, err)
assert.Error(t, err)
}
29 changes: 14 additions & 15 deletions internal/proxy/healthchecker_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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",
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion internal/proxy/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
88 changes: 30 additions & 58 deletions internal/proxy/proxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"strconv"
"testing"

"github.com/go-http-utils/headers"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/assert"
)
Expand All @@ -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()

Expand Down Expand Up @@ -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)

Expand All @@ -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"))
Expand Down Expand Up @@ -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) {
Expand All @@ -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{
{
Expand All @@ -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) {
Expand Down Expand Up @@ -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)
}
Expand All @@ -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())
}
29 changes: 14 additions & 15 deletions internal/rpcgateway/rpcgateway_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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()
Expand All @@ -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())
Expand All @@ -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)
}

0 comments on commit ad32cd2

Please sign in to comment.