File size: 2,351 Bytes
cb0011e | 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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | import pytest
from ttlcache import FakeClock, TTLCache
def make(clock, maxsize=3, ttl=10.0):
return TTLCache(maxsize=maxsize, ttl=ttl, clock=clock)
def test_set_and_get():
clock = FakeClock()
cache = make(clock)
cache["a"] = 1
assert cache["a"] == 1
assert cache.get("a") == 1
def test_missing_key_returns_default():
cache = make(FakeClock())
assert cache.get("nope") is None
assert cache.get("nope", 7) == 7
def test_getitem_raises_for_missing_key():
cache = make(FakeClock())
with pytest.raises(KeyError):
cache["nope"]
def test_entry_expires():
clock = FakeClock()
cache = make(clock)
cache["a"] = 1
clock.advance(10)
assert "a" not in cache
assert cache.get("a") is None
with pytest.raises(KeyError):
cache["a"]
def test_entry_survives_before_deadline():
clock = FakeClock()
cache = make(clock)
cache["a"] = 1
clock.advance(9.5)
assert cache["a"] == 1
def test_eviction_order_on_insert():
clock = FakeClock()
cache = make(clock, maxsize=2)
cache["a"] = 1
cache["b"] = 2
cache["c"] = 3
assert "a" not in cache
assert "b" in cache and "c" in cache
def test_overwrite_updates_value():
clock = FakeClock()
cache = make(clock)
cache["a"] = 1
cache["a"] = 2
assert cache["a"] == 2
assert len(cache) == 1
def test_setdefault_uses_factory_once():
clock = FakeClock()
cache = make(clock)
calls = []
def factory():
calls.append(1)
return "v"
assert cache.setdefault("k", factory) == "v"
assert cache.setdefault("k", factory) == "v"
assert len(calls) == 1
def test_pop_removes_entry():
clock = FakeClock()
cache = make(clock)
cache["a"] = 1
assert cache.pop("a") == 1
assert cache.pop("a", "gone") == "gone"
def test_items_skips_expired():
clock = FakeClock()
cache = make(clock)
cache["a"] = 1
clock.advance(4)
cache["b"] = 2
clock.advance(7)
assert list(cache.items()) == [("b", 2)]
def test_invalid_arguments():
with pytest.raises(ValueError):
TTLCache(maxsize=0)
with pytest.raises(ValueError):
TTLCache(ttl=0)
def test_repr_reports_live_count():
clock = FakeClock()
cache = make(clock)
cache["a"] = 1
assert "live=1" in repr(cache)
|