diff --git a/README.md b/README.md index 46ef4a7..efec186 100644 --- a/README.md +++ b/README.md @@ -77,3 +77,9 @@ Do this :) >>> from pokebase import cache >>> cache.API_CACHE ``` + +To delete the existing cache, don't delete files directly, as `shelve`'s file structure is platform-dependant. Indead, do +```python console +>>> from pokebase import cache +>>> cache.empty_cache() +``` diff --git a/pokebase/cache.py b/pokebase/cache.py index 5613d5b..5d3354e 100644 --- a/pokebase/cache.py +++ b/pokebase/cache.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- +import glob import os import shelve @@ -9,6 +10,7 @@ CACHE_DIR = None API_CACHE = None SPRITE_CACHE = None +API_CACHE_FILE_NAME = "api.cache" def save(data, endpoint, resource_id=None, subresource=None): @@ -137,10 +139,18 @@ def set_cache(new_path=None): new_path = get_default_cache() CACHE_DIR = safe_make_dirs(os.path.abspath(new_path)) - API_CACHE = os.path.join(CACHE_DIR, "api.cache") + API_CACHE = os.path.join(CACHE_DIR, API_CACHE_FILE_NAME) SPRITE_CACHE = safe_make_dirs(os.path.join(CACHE_DIR, "sprite")) return CACHE_DIR, API_CACHE, SPRITE_CACHE +def empty_cache(): + """Depending on the database backend that shelve is using, different database files will be created. + Shelve does not offer a way to detect which one it has created, so this function catches all of them""" + for f in glob.glob(f"{API_CACHE}*"): + if os.path.exists(f): + os.remove(f) + + CACHE_DIR, API_CACHE, SPRITE_CACHE = set_cache() diff --git a/tests/test_module_cache.py b/tests/test_module_cache.py index 53c1b2c..63c3ef8 100644 --- a/tests/test_module_cache.py +++ b/tests/test_module_cache.py @@ -3,6 +3,7 @@ import importlib import os import shelve +import glob import unittest from hypothesis import assume, given @@ -60,7 +61,7 @@ def testArg_subresource_Text(self, data, endpoint, resource_id, subresource): resource_id=integers(min_value=1)) def testEnv_CacheFileNotFound(self, data, endpoint, resource_id): assume(data != dict()) - os.remove(cache.API_CACHE) + cache.empty_cache() self.assertIsNone(cache.save(data, endpoint, resource_id)) @given(data=dictionaries(text(), text()), @@ -113,7 +114,7 @@ def testArg_subresource_Text(self, data, endpoint, resource_id, subresource): def testEnv_CacheFileNotFound(self, endpoint, resource_id): # ensure it exsists before we delete it, cache.set_cache('testing') - os.remove(cache.API_CACHE) + cache.empty_cache() with self.assertRaises(KeyError): cache.load(endpoint, resource_id) @@ -168,8 +169,7 @@ def testAttr_Caches_Default(self): def testEnv_CacheDirNotFound(self): cache.set_cache('testing') os.rmdir(cache.SPRITE_CACHE) - if os.path.exists(cache.API_CACHE): os.remove(cache.API_CACHE) - os.rmdir(cache.CACHE_DIR) + cache.empty_cache() self.assertEqual(cache.set_cache(), (cache.CACHE_DIR, cache.API_CACHE, cache.SPRITE_CACHE))