diff --git a/aiocache/factory.py b/aiocache/factory.py index 4037b815..81975790 100644 --- a/aiocache/factory.py +++ b/aiocache/factory.py @@ -137,9 +137,13 @@ def set_config(self, config): All keys in the config are optional, if they are not passed the defaults for the specified class will be used. + + If a config key already exists, it will be updated with the new values. """ if "default" not in config: raise ValueError("default config must be provided") + for config_name in config.keys(): + self._caches.pop(config_name, None) self._config = config diff --git a/tests/ut/test_factory.py b/tests/ut/test_factory.py index b6e53f45..26f98542 100644 --- a/tests/ut/test_factory.py +++ b/tests/ut/test_factory.py @@ -2,7 +2,7 @@ from aiocache import SimpleMemoryCache, RedisCache, caches from aiocache.factory import _class_from_string, _create_cache -from aiocache.serializers import PickleSerializer +from aiocache.serializers import JsonSerializer, PickleSerializer from aiocache.plugins import TimingPlugin, HitMissRatioPlugin @@ -212,6 +212,41 @@ def test_set_empty_config(self): with pytest.raises(ValueError): caches.set_config({}) + def test_set_config_updates_existing_values(self): + assert not isinstance(caches.get('default').serializer, JsonSerializer) + caches.set_config({ + 'default': { + 'cache': "aiocache.SimpleMemoryCache", + 'serializer': { + 'class': "aiocache.serializers.JsonSerializer" + } + } + }) + assert isinstance(caches.get('default').serializer, JsonSerializer) + + def test_set_config_removes_existing_caches(self): + caches.set_config({ + 'default': { + 'cache': "aiocache.SimpleMemoryCache", + }, + 'alt': { + 'cache': "aiocache.SimpleMemoryCache", + }, + }) + caches.get('default') + caches.get('alt') + assert len(caches._caches) == 2 + + caches.set_config({ + 'default': { + 'cache': "aiocache.SimpleMemoryCache", + }, + 'alt': { + 'cache': "aiocache.SimpleMemoryCache", + }, + }) + assert caches._caches == {} + def test_set_config_no_default(self): with pytest.raises(ValueError): caches.set_config({