-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache_test.go
68 lines (60 loc) · 1.93 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
68
package main
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
)
// Tests requests resulting in HIT/MISS
func TestCacheMiddleware(t *testing.T) {
// Setup test
c := NewCacheMiddleware()
// Process request for '/' on empty Cache -> Cache MISS
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c.ProcessRequest(rec, req)
res := rec.Result()
expected := "MISS"
if cacheStatus := res.Header.Get("X-Cache-Status"); cacheStatus != expected {
t.Errorf("Expected '%v', got '%v'", expected, cacheStatus)
}
// Process response for '/', set to expire in 1h
freshRes := makeDummyResponse()
freshRes.Header.Set("Expires", time.Now().In(time.FixedZone("GMT", 0)).Add(time.Hour).Format(http.TimeFormat))
c.ProcessResponse(freshRes, req)
// Process new request for '/' -> Cache HIT
req = httptest.NewRequest(http.MethodGet, "/", nil)
rec = httptest.NewRecorder()
c.ProcessRequest(rec, req)
res = rec.Result()
expected = "HIT"
if cacheStatus := res.Header.Get("X-Cache-Status"); cacheStatus != expected {
t.Errorf("Expected '%v', got '%v'", expected, cacheStatus)
}
// Process response for '/', set expired
staleRes := makeDummyResponse()
staleRes.Header.Set("Expires", time.Now().In(time.FixedZone("GMT", 0)).Add(-time.Hour).Format(http.TimeFormat))
c.ProcessResponse(staleRes, req)
// Process new request for '/' -> Cache MISS
req = httptest.NewRequest(http.MethodGet, "/", nil)
rec = httptest.NewRecorder()
c.ProcessRequest(rec, req)
res = rec.Result()
expected = "MISS"
if cacheStatus := res.Header.Get("X-Cache-Status"); cacheStatus != expected {
t.Errorf("Expected '%v', got '%v'", expected, cacheStatus)
}
}
func makeDummyResponse() *http.Response {
return &http.Response{
Status: "200 OK",
StatusCode: 200,
Proto: "HTTP/1.0",
ProtoMajor: 1,
ProtoMinor: 0,
Header: make(http.Header),
Body: io.NopCloser(bytes.NewBufferString("Hello World")),
}
}