File: cache_test.go

package info (click to toggle)
golang-google-api 0.61.0-6
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid, trixie
  • size: 209,156 kB
  • sloc: sh: 183; makefile: 22; python: 4
file content (72 lines) | stat: -rw-r--r-- 1,602 bytes parent folder | download | duplicates (3)
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
69
70
71
72
// Copyright 2020 Google LLC.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package idtoken

import (
	"net/http"
	"sync"
	"testing"
	"time"
)

type fakeClock struct {
	mu sync.Mutex
	t  time.Time
}

func (c *fakeClock) Now() time.Time {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.t
}

func (c *fakeClock) Sleep(d time.Duration) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.t = c.t.Add(d)
}

func TestCacheHit(t *testing.T) {
	clock := &fakeClock{t: time.Now()}
	dummyResp := &certResponse{
		Keys: []jwk{
			{
				Kid: "123",
			},
		},
	}
	cache := newCachingClient(nil)
	cache.clock = clock.Now

	// Cache should be empty
	cert, ok := cache.get(googleSACertsURL)
	if ok || cert != nil {
		t.Fatal("cache for SA certs should be empty")
	}

	// Add an item, but make it expire now
	cache.set(googleSACertsURL, dummyResp, make(http.Header))
	clock.Sleep(time.Nanosecond) // it expires when current time is > expiration, not >=
	cert, ok = cache.get(googleSACertsURL)
	if ok || cert != nil {
		t.Fatal("cache for SA certs should be expired")
	}

	// Add an item that expires in 1 seconds
	h := make(http.Header)
	h.Set("age", "0")
	h.Set("cache-control", "public, max-age=1, must-revalidate, no-transform")
	cache.set(googleSACertsURL, dummyResp, h)
	cert, ok = cache.get(googleSACertsURL)
	if !ok || cert == nil || cert.Keys[0].Kid != "123" {
		t.Fatal("cache for SA certs have a resp")
	}
	// Wait
	clock.Sleep(2 * time.Second)
	cert, ok = cache.get(googleSACertsURL)
	if ok || cert != nil {
		t.Fatal("cache for SA certs should be expired")
	}
}