Skip to content

Commit

Permalink
Add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
evgeniy-scherbina committed Oct 10, 2023
1 parent 4a7e7ef commit ecee8fb
Show file tree
Hide file tree
Showing 3 changed files with 412 additions and 0 deletions.
12 changes: 12 additions & 0 deletions service/cachemdw/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ type cacheContextKey string

const (
CachedContextKey cacheContextKey = "X-KAVA-PROXY-CACHED"

CacheHeaderKey = "X-Cache"
CacheHitHeaderValue = "HIT"
CacheMissHeaderValue = "MISS"
)

func (c *ServiceCache) Middleware(
Expand Down Expand Up @@ -51,6 +55,7 @@ func (c *ServiceCache) respond(
r *http.Request,
cachedQueryResponse []byte,
) {
w.Header().Add(CacheHeaderKey, CacheHitHeaderValue)
w.Header().Add("Content-Type", "application/json")
_, err := w.Write(cachedQueryResponse)
if err != nil {
Expand All @@ -68,6 +73,8 @@ func (c *ServiceCache) respondAndCache(
r *http.Request,
decodedReq *decode.EVMRPCRequestEnvelope,
) {
w.Header().Add(CacheHeaderKey, CacheMissHeaderValue)

recorder := httptest.NewRecorder()
next.ServeHTTP(recorder, r.WithContext(uncachedContext))
result := recorder.Result()
Expand Down Expand Up @@ -95,3 +102,8 @@ func (c *ServiceCache) respondAndCache(
c.Logger.Error().Msg(fmt.Sprintf("can't validate and cache response: %v", err))
}
}

func IsRequestCached(ctx context.Context) bool {
cached, ok := ctx.Value(CachedContextKey).(bool)
return ok && cached
}
94 changes: 94 additions & 0 deletions service/cachemdw/middleware_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package cachemdw

import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/stretchr/testify/require"

"github.com/kava-labs/kava-proxy-service/clients/cache"
"github.com/kava-labs/kava-proxy-service/decode"
"github.com/kava-labs/kava-proxy-service/logging"
"github.com/kava-labs/kava-proxy-service/service"
)

func TestServiceCacheMiddleware(t *testing.T) {
logger, err := logging.New("TRACE")
require.NoError(t, err)

inMemoryCache := cache.NewInMemoryCache()
evmClient := NewMockEVMClient()
cacheTTL := time.Duration(0) // TTL: no expiry

serviceCache := NewServiceCache(inMemoryCache, evmClient, cacheTTL, service.DecodedRequestContextKey, &logger)

handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !IsRequestCached(r.Context()) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(testEVMQueries[TestRequestEthBlockByNumberSpecific].ResponseBody))
}
})

t.Run("cache miss", func(t *testing.T) {
req := createTestHttpRequest(
t,
"https://api.kava.io:8545/thisshouldntshowup",
TestRequestEthBlockByNumberSpecific,
)
resp := httptest.NewRecorder()

serviceCache.Middleware(handler).ServeHTTP(resp, req)

require.Equal(t, http.StatusOK, resp.Code)
require.JSONEq(t, testEVMQueries[TestRequestEthBlockByNumberSpecific].ResponseBody, resp.Body.String())
require.Equal(t, CacheMissHeaderValue, resp.Header().Get(CacheHeaderKey))

cacheItems := inMemoryCache.GetAll(context.Background())
require.Len(t, cacheItems, 2)
require.Contains(t, cacheItems, "chain:api.kava.io:8545")
require.Contains(t, cacheItems, "query:1:0x5236d50a560cff0174f14be10bd00a21e8d73e89a200fbd219769b6aee297131")
})

t.Run("cache hit", func(t *testing.T) {
req := createTestHttpRequest(
t,
"https://api.kava.io:8545/thisshouldntshowup",
TestRequestEthBlockByNumberSpecific,
)
resp := httptest.NewRecorder()

serviceCache.Middleware(handler).ServeHTTP(resp, req)

require.Equal(t, http.StatusOK, resp.Code)
require.JSONEq(t, testEVMQueries[TestRequestEthBlockByNumberSpecific].ResponseBody, resp.Body.String())
require.Equal(t, CacheHitHeaderValue, resp.Header().Get(CacheHeaderKey))
})
}

func createTestHttpRequest(
t *testing.T,
url string,
reqName testReqName,
) *http.Request {
t.Helper()

req, err := http.NewRequest(http.MethodGet, url, nil)
require.NoError(t, err)

decodedReq, err := decode.DecodeEVMRPCRequest(
[]byte(testEVMQueries[reqName].RequestBody),
)
require.NoError(t, err)

decodedReqCtx := context.WithValue(
req.Context(),
service.DecodedRequestContextKey,
decodedReq,
)
req = req.WithContext(decodedReqCtx)

return req
}
Loading

0 comments on commit ecee8fb

Please sign in to comment.