MCPcopy
hub / github.com/gofiber/fiber / Test_Cache_CustomMethods

Function Test_Cache_CustomMethods

middleware/cache/cache_test.go:995–1111  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

993}
994
995func Test_Cache_CustomMethods(t *testing.T) {
996 t.Parallel()
997
998 t.Run("POST cached when in Methods", func(t *testing.T) {
999 t.Parallel()
1000 app := fiber.New()
1001 app.Use(New(Config{
1002 Methods: []string{fiber.MethodGet, fiber.MethodHead, fiber.MethodPost},
1003 }))
1004
1005 var count atomic.Int32
1006 app.Post("/", func(c fiber.Ctx) error {
1007 current := count.Add(1)
1008 return c.SendString(strconv.Itoa(int(current)))
1009 })
1010
1011 // First POST — cache miss
1012 resp, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/", http.NoBody))
1013 require.NoError(t, err)
1014 body, err := io.ReadAll(resp.Body)
1015 require.NoError(t, err)
1016 require.Equal(t, cacheMiss, resp.Header.Get("X-Cache"))
1017 require.Equal(t, "1", string(body))
1018
1019 // Second POST — cache hit
1020 resp, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/", http.NoBody))
1021 require.NoError(t, err)
1022 body, err = io.ReadAll(resp.Body)
1023 require.NoError(t, err)
1024 require.Equal(t, cacheHit, resp.Header.Get("X-Cache"))
1025 require.Equal(t, "1", string(body))
1026 })
1027
1028 t.Run("unconfigured method bypasses cache", func(t *testing.T) {
1029 t.Parallel()
1030 app := fiber.New()
1031 app.Use(New(Config{
1032 Methods: []string{fiber.MethodGet},
1033 }))
1034
1035 var count atomic.Int32
1036 app.Put("/", func(c fiber.Ctx) error {
1037 current := count.Add(1)
1038 return c.SendString(strconv.Itoa(int(current)))
1039 })
1040
1041 // PUT not in Methods — always bypasses cache
1042 resp, err := app.Test(httptest.NewRequest(fiber.MethodPut, "/", http.NoBody))
1043 require.NoError(t, err)
1044 require.Equal(t, cacheUnreachable, resp.Header.Get("X-Cache"))
1045 require.Equal(t, int32(1), count.Load())
1046
1047 resp, err = app.Test(httptest.NewRequest(fiber.MethodPut, "/", http.NoBody))
1048 require.NoError(t, err)
1049 require.Equal(t, cacheUnreachable, resp.Header.Get("X-Cache"))
1050 require.Equal(t, int32(2), count.Load(), "handler must be called on every bypass")
1051 })
1052

Callers

nothing calls this directly

Calls 10

TestMethod · 0.80
NewFunction · 0.70
NewMethod · 0.65
UseMethod · 0.65
PostMethod · 0.65
AddMethod · 0.65
SendStringMethod · 0.65
GetMethod · 0.65
PutMethod · 0.65
LoadMethod · 0.65

Tested by

no test coverage detected