Added tests for cache middleware.

This commit is contained in:
mikestefanello 2021-12-21 20:49:05 -05:00
parent d395993338
commit ac93e0f366
2 changed files with 79 additions and 5 deletions

View File

@ -13,13 +13,24 @@ import (
"github.com/labstack/echo/v4"
)
// CachedPage is what is used to store a rendered Page in the cache
type CachedPage struct {
URL string
HTML []byte
// URL stores the URL of the requested page
URL string
// HTML stores the complete HTML of the rendered Page
HTML []byte
// StatusCode stores the HTTP status code
StatusCode int
Headers map[string]string
// Headers stores the HTTP headers
Headers map[string]string
}
// ServeCachedPage attempts to load a page from the cache by matching on the complete request URL
// If a page is cached for the requested URL, it will be served here and the request terminated.
// Any request made by an authenticated user or that is not a GET will be skipped.
func ServeCachedPage(ch *cache.Cache) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
@ -33,10 +44,15 @@ func ServeCachedPage(ch *cache.Cache) echo.MiddlewareFunc {
return next(c)
}
res, err := marshaler.New(ch).Get(c.Request().Context(), c.Request().URL.String(), new(CachedPage))
// Attempt to load from cache
res, err := marshaler.New(ch).Get(
c.Request().Context(),
c.Request().URL.String(),
new(CachedPage),
)
if err != nil {
if err == redis.Nil {
c.Logger().Infof("no cached page found")
c.Logger().Info("no cached page found")
} else {
c.Logger().Errorf("failed getting cached page: %v", err)
}
@ -49,11 +65,13 @@ func ServeCachedPage(ch *cache.Cache) echo.MiddlewareFunc {
return next(c)
}
// Set any headers
if page.Headers != nil {
for k, v := range page.Headers {
c.Response().Header().Set(k, v)
}
}
c.Logger().Info("serving cached page")
return c.HTMLBlob(page.StatusCode, page.HTML)
@ -61,6 +79,7 @@ func ServeCachedPage(ch *cache.Cache) echo.MiddlewareFunc {
}
}
// CacheControl sets a Cache-Control header with a given max age
func CacheControl(maxAge time.Duration) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {

55
middleware/cache_test.go Normal file
View File

@ -0,0 +1,55 @@
package middleware
import (
"context"
"net/http"
"testing"
"time"
"goweb/tests"
"github.com/stretchr/testify/require"
"github.com/eko/gocache/v2/marshaler"
"github.com/stretchr/testify/assert"
)
func TestServeCachedPage(t *testing.T) {
// Cache a page
cp := CachedPage{
URL: "/cache",
HTML: []byte("html"),
Headers: make(map[string]string),
StatusCode: http.StatusCreated,
}
cp.Headers["a"] = "b"
cp.Headers["c"] = "d"
err := marshaler.New(c.Cache).Set(context.Background(), cp.URL, cp, nil)
require.NoError(t, err)
// Request the URL of the cached page
ctx, rec := tests.NewContext(c.Web, cp.URL)
err = tests.ExecuteMiddleware(ctx, ServeCachedPage(c.Cache))
assert.NoError(t, err)
assert.Equal(t, cp.StatusCode, ctx.Response().Status)
assert.Equal(t, cp.Headers["a"], ctx.Response().Header().Get("a"))
assert.Equal(t, cp.Headers["c"], ctx.Response().Header().Get("c"))
assert.Equal(t, cp.HTML, rec.Body.Bytes())
// Login and try again
tests.InitSession(ctx)
err = c.Auth.Login(ctx, usr.ID)
require.NoError(t, err)
_ = tests.ExecuteMiddleware(ctx, LoadAuthenticatedUser(c.Auth))
err = tests.ExecuteMiddleware(ctx, ServeCachedPage(c.Cache))
tests.AssertHTTPErrorCode(t, err, http.StatusNotFound)
}
func TestCacheControl(t *testing.T) {
ctx, _ := tests.NewContext(c.Web, "/")
_ = tests.ExecuteMiddleware(ctx, CacheControl(time.Second*5))
assert.Equal(t, "public, max-age=5", ctx.Response().Header().Get("Cache-Control"))
_ = tests.ExecuteMiddleware(ctx, CacheControl(0))
assert.Equal(t, "no-cache, no-store", ctx.Response().Header().Get("Cache-Control"))
}