diff --git a/src/akkudoktoreos/core/cache.py b/src/akkudoktoreos/core/cache.py index 108bc9d6..dcaa0a6a 100644 --- a/src/akkudoktoreos/core/cache.py +++ b/src/akkudoktoreos/core/cache.py @@ -1096,7 +1096,9 @@ def cache_in_file( # Fail gracefully - recreate the cache file in this call call_force_update = True if call_force_update or cache_file is None: - # Otherwise, call the function and save its result to the cache + # Otherwise, call the function and save its result to the cache. + # Call first: a call that raises leaves no empty cache file behind. + result = func(*args, **kwargs) logger.debug("Created cache file for function: " + func.__name__) cache_file = CacheFileStore().create( key, @@ -1107,7 +1109,6 @@ def cache_in_file( until_date=expiry["until_date"], with_ttl=expiry["with_ttl"], ) - result = func(*args, **kwargs) try: # Assure we have an empty file cache_file.truncate(0) diff --git a/tests/test_cache.py b/tests/test_cache.py index 0ef2c645..97864e0b 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -904,6 +904,27 @@ class TestCacheFileDecorators: assert f() == "result" assert len(calls) == 2 + def test_failed_call_leaves_no_cache_file(self, cache_file_store, caplog) -> None: + """A call that raises caches nothing, so the next call reads no empty file (#1571).""" + cache_file_store.clear(clear_all=True) + responses: list[Exception | str] = [RuntimeError("500 Server Error"), "result"] + + @cache_in_file(with_ttl="1 hour") + def fetch() -> str: + response = responses.pop(0) + if isinstance(response, Exception): + raise response + return response + + with pytest.raises(RuntimeError, match="500 Server Error"): + fetch() + assert len(cache_file_store._store) == 0 + + assert fetch() == "result" + assert "Read failed" not in caplog.text + assert fetch() == "result" + assert responses == [] + def test_var_positional_arguments_are_part_of_the_key(self, cache_file_store): cache_file_store.clear(clear_all=True)