"""Tests for the persistent detail-fetch cache (postcode_cache.py).""" from postcode_cache import load_cache, save_cache def test_save_then_load_round_trips_str_and_none_values(tmp_path): path = tmp_path / "rightmove.json" data = {"123": "SW9 0HD", "456": None, "789": "E20 1FH"} save_cache(path, data) assert load_cache(path) == data def test_save_then_load_round_trips_nested_dicts(tmp_path): # Zoopla caches a flat dict of primitives (or None) per listing id. path = tmp_path / "zoopla.json" data = { "59888978": { "lat": 51.4, "lng": -0.11, "postcode": "BR1 2AB", "uprn": "100023", "number_or_name": "12", "full_address": "12 High St", }, "broken": None, } save_cache(path, data) assert load_cache(path) == data def test_load_missing_file_returns_empty(tmp_path): assert load_cache(tmp_path / "does-not-exist.json") == {} def test_load_corrupt_file_returns_empty(tmp_path): path = tmp_path / "corrupt.json" path.write_text("{not valid json", encoding="utf-8") assert load_cache(path) == {} def test_load_non_object_file_returns_empty(tmp_path): path = tmp_path / "list.json" path.write_text("[1, 2, 3]", encoding="utf-8") assert load_cache(path) == {} def test_save_creates_parent_directory(tmp_path): path = tmp_path / "nested" / "dir" / "cache.json" save_cache(path, {"a": "B1 1AA"}) assert path.exists() assert load_cache(path) == {"a": "B1 1AA"} def test_save_overwrites_existing(tmp_path): path = tmp_path / "c.json" save_cache(path, {"a": "X1 1AA"}) save_cache(path, {"b": "Y2 2BB"}) assert load_cache(path) == {"b": "Y2 2BB"}