Skip to content

Commit 51fbc27

Browse files
committed
test: cover stale-heap-entry branch in _async_evict_oldest
Adds ``test_cache_eviction_skips_stale_heap_entries`` which fills the cache to ``_MAX_CACHE_RECORDS``, re-adds the closest-to-expiration record with a longer TTL (which leaves a stale ``(when, record)`` tuple at the head of ``_expire_heap`` and updates ``_expirations`` with the new ``when``), then forces a single eviction and asserts the refreshed record survives while the next-oldest legitimate record is the one that gets evicted. Without this test the ``continue`` branch inside ``_async_evict_oldest`` would be untouched by the suite.
1 parent c24fa39 commit 51fbc27

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

‎tests/test_cache.py‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -514,6 +514,59 @@ def test_cache_size_is_bounded() -> None:
514514
assert f"flood-{i}.local." in cache.cache
515515

516516

517+
def test_cache_eviction_skips_stale_heap_entries() -> None:
518+
"""Eviction must skip stale ``_expire_heap`` entries left by TTL re-adds."""
519+
cache = r.DNSCache()
520+
now = r.current_time_millis()
521+
# Fill to one shy of the cap so a single add triggers exactly one eviction
522+
cache.async_add_records(
523+
r.DNSAddress(
524+
f"stale-{i}.local.",
525+
const._TYPE_A,
526+
const._CLASS_IN,
527+
120,
528+
bytes((i & 0xFF, (i >> 8) & 0xFF, 0, 1)),
529+
created=now + i,
530+
)
531+
for i in range(const._MAX_CACHE_RECORDS)
532+
)
533+
assert cache._total_records == const._MAX_CACHE_RECORDS
534+
535+
# Re-add the closest-to-expiration record with a longer TTL. The original
536+
# (when, record) tuple stays at the head of _expire_heap as a stale entry;
537+
# _expirations[record] now points to the new (later) expiration. Eviction
538+
# must pop and skip that stale tuple before settling on a real victim.
539+
victim_name = "stale-0.local."
540+
refreshed = r.DNSAddress(
541+
victim_name,
542+
const._TYPE_A,
543+
const._CLASS_IN,
544+
7200,
545+
bytes((0, 0, 0, 1)),
546+
created=now + 0,
547+
)
548+
cache.async_add_records([refreshed])
549+
assert cache._total_records == const._MAX_CACHE_RECORDS
550+
551+
# Force one eviction. The next-oldest legitimate record must go; the
552+
# refreshed record stays alive.
553+
cache.async_add_records(
554+
[
555+
r.DNSAddress(
556+
"trigger.local.",
557+
const._TYPE_A,
558+
const._CLASS_IN,
559+
120,
560+
b"\xff\xff\xff\xff",
561+
created=now + const._MAX_CACHE_RECORDS,
562+
)
563+
]
564+
)
565+
assert cache._total_records == const._MAX_CACHE_RECORDS
566+
assert victim_name in cache.cache
567+
assert "stale-1.local." not in cache.cache
568+
569+
517570
def test_cache_eviction_decrements_total_records() -> None:
518571
"""Natural removal (goodbyes, expirations) must keep ``_total_records`` in sync."""
519572
cache = r.DNSCache()

0 commit comments

Comments
 (0)