"""TTL-aware cache tests (isolated file via MDNS_CACHE_PATH).""" import importlib import time def _fresh_cache(tmp_path, monkeypatch): monkeypatch.setenv("MDNS_CACHE_PATH", str(tmp_path / "hosts.json")) from mdns_tools import cache importlib.reload(cache) return cache def test_put_get_roundtrip(tmp_path, monkeypatch): cache = _fresh_cache(tmp_path, monkeypatch) cache.put("dell.local", "192.168.1.17", ttl=120) assert cache.get("dell.local") == "192.168.1.17" def test_expired_returns_none_but_stale_available(tmp_path, monkeypatch): cache = _fresh_cache(tmp_path, monkeypatch) cache.put("x.local", "10.0.0.1", ttl=30) # Force expiry by rewriting with a past timestamp. data = cache._load() data["x.local|v4"]["expires"] = time.time() - 1 cache._save(data) assert cache.get("x.local") is None assert cache.get_stale("x.local") == "10.0.0.1" def test_families_are_separate(tmp_path, monkeypatch): cache = _fresh_cache(tmp_path, monkeypatch) cache.put("h.local", "192.168.1.9", family="v4") cache.put("h.local", "fe80::9", family="v6") assert cache.get("h.local", "v4") == "192.168.1.9" assert cache.get("h.local", "v6") == "fe80::9" def test_clear_specific_host(tmp_path, monkeypatch): cache = _fresh_cache(tmp_path, monkeypatch) cache.put("a.local", "1.1.1.1") cache.put("b.local", "2.2.2.2") assert cache.clear("a.local") == 1 assert cache.get("a.local") is None assert cache.get("b.local") == "2.2.2.2" def test_ttl_clamped_to_minimum(tmp_path, monkeypatch): cache = _fresh_cache(tmp_path, monkeypatch) cache.put("c.local", "3.3.3.3", ttl=1) # below floor assert cache.all_entries()["c.local|v4"]["ttl"] >= 30