From 239cb2089f6324c49f2fa2e837adddc79d056af6 Mon Sep 17 00:00:00 2001 From: Pinank Solanki Date: Wed, 27 Apr 2022 01:17:32 +0530 Subject: [PATCH] :rotating_light: Improve Test_CustomExpiration --- middleware/cache/cache_test.go | 35 +++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/middleware/cache/cache_test.go b/middleware/cache/cache_test.go index 216d9cea27..7a46f20596 100644 --- a/middleware/cache/cache_test.go +++ b/middleware/cache/cache_test.go @@ -291,15 +291,40 @@ func Test_CustomExpiration(t *testing.T) { }})) app.Get("/", func(c *fiber.Ctx) error { - c.Response().Header.Add("Cache-Time", "6000") - return c.SendString("hi") + c.Response().Header.Add("Cache-Time", "2") + now := fmt.Sprintf("%d", time.Now().UnixNano()) + return c.SendString(now) }) - req := httptest.NewRequest("GET", "/", nil) - _, err := app.Test(req) + resp, err := app.Test(httptest.NewRequest("GET", "/", nil)) utils.AssertEqual(t, nil, err) utils.AssertEqual(t, true, called) - utils.AssertEqual(t, 6000, newCacheTime) + utils.AssertEqual(t, 2, newCacheTime) + + // Sleep until the cache is expired + time.Sleep(3 * time.Second) + + cachedResp, err := app.Test(httptest.NewRequest("GET", "/", nil)) + utils.AssertEqual(t, nil, err) + + body, err := ioutil.ReadAll(resp.Body) + utils.AssertEqual(t, nil, err) + cachedBody, err := ioutil.ReadAll(cachedResp.Body) + utils.AssertEqual(t, nil, err) + + if bytes.Equal(body, cachedBody) { + t.Errorf("Cache should have expired: %s, %s", body, cachedBody) + } + + // Next response should be cached + cachedRespNextRound, err := app.Test(httptest.NewRequest("GET", "/", nil)) + utils.AssertEqual(t, nil, err) + cachedBodyNextRound, err := ioutil.ReadAll(cachedRespNextRound.Body) + utils.AssertEqual(t, nil, err) + + if !bytes.Equal(cachedBodyNextRound, cachedBody) { + t.Errorf("Cache should not have expired: %s, %s", cachedBodyNextRound, cachedBody) + } } func Test_AdditionalE2EResponseHeaders(t *testing.T) {