Skip to content

Commit 9438029

Browse files
authored
test: improve cache handler testing (#310)
1 parent aabfebd commit 9438029

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

tests/trusted_packages/test_cache_handler.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,3 +154,39 @@ def test_clear_all_with_empty_cache_directory(self, tmp_path: Path) -> None:
154154

155155
# Should not raise any errors
156156
assert True
157+
158+
def test_get_cache_entry_json_decode_error(self, tmp_path, caplog):
159+
"""Test get_cache_entry handles JSONDecodeError and logs a warning."""
160+
cache_handler = CacheHandler(str(tmp_path))
161+
source = "bad-json"
162+
fpath = tmp_path / f"{cache_handler.get_cache_file_path(source)}"
163+
fpath.parent.mkdir(parents=True, exist_ok=True)
164+
fpath.write_text("not a json")
165+
with caplog.at_level("WARNING"):
166+
result = cache_handler.get_cache_entry(source)
167+
assert result is None
168+
assert any("Failed to decode JSON" in m for m in caplog.messages)
169+
170+
def test_get_cache_entry_validation_error(self, tmp_path, caplog):
171+
"""Test get_cache_entry handles ValidationError and logs a warning, clears entry."""
172+
cache_handler = CacheHandler(str(tmp_path))
173+
source = "bad-entry"
174+
fpath = tmp_path / f"{cache_handler.get_cache_file_path(source)}"
175+
# Write valid JSON but invalid CacheEntry (missing packages)
176+
fpath.parent.mkdir(parents=True, exist_ok=True)
177+
fpath.write_text('{"saved_date": "2025-01-01"}')
178+
with caplog.at_level("WARNING"):
179+
result = cache_handler.get_cache_entry(source)
180+
assert result is None
181+
assert any("Could not read cache for source" in m for m in caplog.messages)
182+
assert not fpath.exists() # Should be deleted
183+
184+
def test__clear_entry_deletes_file(self, tmp_path):
185+
cache_handler = CacheHandler(str(tmp_path))
186+
source = "to-delete"
187+
fpath = tmp_path / f"{cache_handler.get_cache_file_path(source)}"
188+
fpath.parent.mkdir(parents=True, exist_ok=True)
189+
fpath.write_text('{"saved_date": "2025-01-01", "packages": ["pkg"]}')
190+
assert fpath.exists()
191+
cache_handler._clear_entry(source)
192+
assert not fpath.exists()

0 commit comments

Comments
 (0)