2025-10-04 17:29:20 +00:00
|
|
|
package pokecache
|
|
|
|
|
|
|
|
|
|
import (
|
2025-10-05 14:00:38 +00:00
|
|
|
"fmt"
|
2025-10-04 17:29:20 +00:00
|
|
|
"testing"
|
|
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func TestAddGet(t *testing.T) {
|
|
|
|
|
const interval = 5 * time.Second
|
|
|
|
|
cases := []struct {
|
|
|
|
|
key string
|
|
|
|
|
val []byte
|
|
|
|
|
}{
|
|
|
|
|
{
|
|
|
|
|
key: "https://example.com",
|
|
|
|
|
val: []byte("testdata"),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
key: "https://example.com/path",
|
|
|
|
|
val: []byte("moretestdata"),
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for i, c := range cases {
|
|
|
|
|
t.Run(fmt.Sprintf("Test case %v", i), func(t *testing.T) {
|
|
|
|
|
cache := NewCache(interval)
|
|
|
|
|
cache.Add(c.key, c.val)
|
|
|
|
|
val, ok := cache.Get(c.key)
|
|
|
|
|
if !ok {
|
|
|
|
|
t.Errorf("expected to find key")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if string(val) != string(c.val) {
|
|
|
|
|
t.Errorf("expected to find value")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestGetNonexistent(t *testing.T) {
|
|
|
|
|
const interval = 2 * time.Second
|
|
|
|
|
cache := NewCache(interval)
|
|
|
|
|
value, ok := cache.Get("http://does.not.exist/")
|
|
|
|
|
if ok || (value != nil) {
|
|
|
|
|
t.Errorf("expected cache miss")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestReapLoop(t *testing.T) {
|
|
|
|
|
const baseTime = 5 * time.Millisecond
|
|
|
|
|
const waitTime = baseTime + 5*time.Millisecond
|
|
|
|
|
cache := NewCache(baseTime)
|
|
|
|
|
cache.Add("https://example.com", []byte("testdata"))
|
2025-10-05 14:00:38 +00:00
|
|
|
|
2025-10-04 17:29:20 +00:00
|
|
|
_, ok := cache.Get("https://example.com")
|
|
|
|
|
if !ok {
|
|
|
|
|
t.Errorf("expected to find key")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
time.Sleep(waitTime)
|
|
|
|
|
|
|
|
|
|
_, ok = cache.Get("https://example.com")
|
|
|
|
|
if ok {
|
|
|
|
|
t.Errorf("expected to not find key")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|