...
1
2
3
4
5 package idtoken
6
7 import (
8 "net/http"
9 "sync"
10 "testing"
11 "time"
12 )
13
14 type fakeClock struct {
15 mu sync.Mutex
16 t time.Time
17 }
18
19 func (c *fakeClock) Now() time.Time {
20 c.mu.Lock()
21 defer c.mu.Unlock()
22 return c.t
23 }
24
25 func (c *fakeClock) Sleep(d time.Duration) {
26 c.mu.Lock()
27 defer c.mu.Unlock()
28 c.t = c.t.Add(d)
29 }
30
31 func TestCacheHit(t *testing.T) {
32 clock := &fakeClock{t: time.Now()}
33 dummyResp := &certResponse{
34 Keys: []jwk{
35 {
36 Kid: "123",
37 },
38 },
39 }
40 cache := newCachingClient(nil)
41 cache.clock = clock.Now
42
43
44 cert, ok := cache.get(googleSACertsURL)
45 if ok || cert != nil {
46 t.Fatal("cache for SA certs should be empty")
47 }
48
49
50 cache.set(googleSACertsURL, dummyResp, make(http.Header))
51 clock.Sleep(time.Nanosecond)
52 cert, ok = cache.get(googleSACertsURL)
53 if ok || cert != nil {
54 t.Fatal("cache for SA certs should be expired")
55 }
56
57
58 h := make(http.Header)
59 h.Set("age", "0")
60 h.Set("cache-control", "public, max-age=1, must-revalidate, no-transform")
61 cache.set(googleSACertsURL, dummyResp, h)
62 cert, ok = cache.get(googleSACertsURL)
63 if !ok || cert == nil || cert.Keys[0].Kid != "123" {
64 t.Fatal("cache for SA certs have a resp")
65 }
66
67 clock.Sleep(2 * time.Second)
68 cert, ok = cache.get(googleSACertsURL)
69 if ok || cert != nil {
70 t.Fatal("cache for SA certs should be expired")
71 }
72 }
73
View as plain text