-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_cache_utils.py
More file actions
93 lines (75 loc) · 2.29 KB
/
test_cache_utils.py
File metadata and controls
93 lines (75 loc) · 2.29 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"""Tests for utils/cache_utils.py"""
import time
import pytest
from utils.cache_utils import TTLCache, memoize
class TestTTLCache:
def test_set_and_get(self):
cache = TTLCache(ttl=10)
cache.set("key", "value")
assert cache.get("key") == "value"
def test_missing_key_returns_default(self):
cache = TTLCache()
assert cache.get("missing") is None
assert cache.get("missing", "fallback") == "fallback"
def test_expired_entry_returns_default(self):
cache = TTLCache(ttl=0.05)
cache.set("k", "v")
time.sleep(0.1)
assert cache.get("k") is None
def test_delete(self):
cache = TTLCache()
cache.set("k", 1)
cache.delete("k")
assert cache.get("k") is None
def test_clear(self):
cache = TTLCache()
cache.set("a", 1)
cache.set("b", 2)
cache.clear()
assert cache.get("a") is None
assert cache.get("b") is None
def test_contains(self):
cache = TTLCache(ttl=10)
cache.set("x", 99)
assert "x" in cache
assert "y" not in cache
def test_maxsize_evicts_oldest(self):
cache = TTLCache(ttl=60, maxsize=2)
cache.set("a", 1)
time.sleep(0.01)
cache.set("b", 2)
time.sleep(0.01)
cache.set("c", 3) # should evict "a"
assert cache.get("c") == 3
assert cache.get("b") == 2
def test_per_key_ttl_override(self):
cache = TTLCache(ttl=60)
cache.set("short", "v", ttl=0.05)
time.sleep(0.1)
assert cache.get("short") is None
class TestMemoize:
def test_caches_result(self):
call_count = [0]
@memoize(ttl=10)
def fn(x):
call_count[0] += 1
return x * 2
assert fn(3) == 6
assert fn(3) == 6
assert call_count[0] == 1 # only called once
def test_different_args_cached_separately(self):
@memoize(ttl=10)
def fn(x):
return x + 1
assert fn(1) == 2
assert fn(2) == 3
def test_expired_result_recalculated(self):
call_count = [0]
@memoize(ttl=0.05)
def fn(x):
call_count[0] += 1
return x
fn("a")
time.sleep(0.1)
fn("a")
assert call_count[0] == 2