-
Notifications
You must be signed in to change notification settings - Fork 2
/
cache_test.go
67 lines (54 loc) · 1.65 KB
/
cache_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package gincache
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func init() {
gin.SetMode(gin.TestMode)
}
func performRequest(method, target string, router *gin.Engine) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, target, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
return w
}
func TestWrite(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
writer := newCachedWriter(time.Second*3, c.Writer, "mykey")
c.Writer = writer
c.Writer.WriteHeader(204)
c.Writer.WriteHeaderNow()
c.Writer.Write([]byte("foo"))
assert.Equal(t, 204, c.Writer.Status())
assert.Equal(t, "foo", w.Body.String())
assert.True(t, c.Writer.Written())
}
func TestCachePage(t *testing.T) {
router := gin.New()
router.GET("/cache_ping", CacheMiddleware(time.Second*3, func(c *gin.Context) {
c.JSON(http.StatusOK, "pong "+fmt.Sprint(time.Now().UnixNano()))
}))
w1 := performRequest("GET", "/cache_ping", router)
w2 := performRequest("GET", "/cache_ping", router)
assert.Equal(t, 200, w1.Code)
assert.Equal(t, 200, w2.Code)
assert.Equal(t, w1.Body.String(), w2.Body.String())
}
func TestCachePageExpire(t *testing.T) {
router := gin.New()
router.GET("/cache_ping", CacheMiddleware(time.Second, func(c *gin.Context) {
c.JSON(http.StatusOK, "pong "+fmt.Sprint(time.Now().UnixNano()))
}))
w1 := performRequest("GET", "/cache_ping", router)
time.Sleep(time.Second * 3)
w2 := performRequest("GET", "/cache_ping", router)
assert.Equal(t, 200, w1.Code)
assert.Equal(t, 200, w2.Code)
assert.NotEqual(t, w1.Body.String(), w2.Body.String())
}