From 7ceba6b1f8ba831b8a73b1b38843f9e32aeeaa0d Mon Sep 17 00:00:00 2001 From: RemiRigal Date: Wed, 14 Dec 2022 09:46:40 +0100 Subject: [PATCH] Improve management of cache loading errors (#62) --- plex_auto_languages/plex_server_cache.py | 12 +++++++++--- tests/conftest.py | 3 +++ tests/test_plex_server_cache.py | 8 ++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/plex_auto_languages/plex_server_cache.py b/plex_auto_languages/plex_server_cache.py index 507e827..18d3b48 100644 --- a/plex_auto_languages/plex_server_cache.py +++ b/plex_auto_languages/plex_server_cache.py @@ -107,11 +107,17 @@ def _get_cache_file_path(self): return os.path.join(cache_dir, self._plex.unique_id) def _load(self): - if not os.path.exists(self._cache_file_path): + if not os.path.exists(self._cache_file_path) or not os.path.isfile(self._cache_file_path): return False logger.debug("[Cache] Loading server cache from file") - with open(self._cache_file_path, "r", encoding="utf-8") as stream: - cache = json.load(stream) + try: + with open(self._cache_file_path, "r", encoding="utf-8") as stream: + cache = json.load(stream) + except json.JSONDecodeError: + logger.warning("[Cache] The cache is corrupted, clearing the cache before trying again") + if os.path.exists(self._cache_file_path) and os.path.isfile(self._cache_file_path): + os.remove(self._cache_file_path) + return False self.newly_updated = cache.get("newly_updated", self.newly_updated) self.newly_updated = {key: isoparse(value) for key, value in self.newly_updated.items()} self.newly_added = cache.get("newly_added", self.newly_added) diff --git a/tests/conftest.py b/tests/conftest.py index c498e0b..32e6b01 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,10 +2,13 @@ import pytest import plexapi +from plex_auto_languages.utils.logger import init_logger from plex_auto_languages.plex_server import PlexServer from plex_auto_languages.utils.configuration import Configuration +init_logger() + SERVER_BASEURL = plexapi.CONFIG.get("auth.server_baseurl") SERVER_TOKEN = plexapi.CONFIG.get("auth.server_token") diff --git a/tests/test_plex_server_cache.py b/tests/test_plex_server_cache.py index 4c13cc3..78f246f 100644 --- a/tests/test_plex_server_cache.py +++ b/tests/test_plex_server_cache.py @@ -56,6 +56,14 @@ def test_load_save(): assert old_episode_parts == cache.episode_parts + with open(mocked_path, "w") as stream: + stream.write("Not a JSON object") + assert os.path.exists(mocked_path) + mocked_refresh.reset_mock() + cache = PlexServerCache(None) + mocked_refresh.assert_called_once() + assert not os.path.exists(mocked_path) + def test_instance_users(plex): assert plex.cache.get_instance_users() is None