-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware_test.go
More file actions
55 lines (45 loc) · 1.36 KB
/
Copy pathmiddleware_test.go
File metadata and controls
55 lines (45 loc) · 1.36 KB
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
package capsulecache
import (
"net/http"
"net/http/httptest"
"testing"
"time"
cache2 "github.com/spdeepak/capsulecache/cache"
)
func TestCacheMiddleware(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/", Handler)
cache := cache2.NewInMemoryQuotaLRU(2)
config := Config{
DefaultTTL: 1 * time.Second,
DefaultSWR: 1500 * time.Millisecond,
KeyGenerator: DefaultKeyGenerator,
ShouldCache: func(statusCode int) bool { return statusCode == http.StatusOK },
MaxBodyBytes: 1024,
StripHeaders: stripHopByHop,
}
client := NewCacheMiddleware(cache, &config)(mux)
req := httptest.NewRequest("GET", "/", nil)
r1 := httptest.NewRecorder()
client.ServeHTTP(r1, req)
if r1.Header().Get("X-Cache-Status") != "MISS" {
t.Fatalf("expected MISS, got %s", r1.Header().Get("X-Cache-Status"))
}
if r1.Body.String() != "fresh" {
t.Fatalf("unexpected body: %s", r1.Body.String())
}
//Sleep for some time so that the cache gets populated
time.Sleep(10 * time.Millisecond)
r2 := httptest.NewRecorder()
client.ServeHTTP(r2, req)
if r2.Header().Get("X-Cache-Status") != "HIT" {
t.Fatalf("expected HIT, got %s", r2.Header().Get("X-Cache-Status"))
}
if r2.Body.String() != "fresh" {
t.Fatalf("unexpected body: %s", r2.Body.String())
}
}
func Handler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("fresh"))
}