Created
June 12, 2020 21:02
-
-
Save Toshakins/57ee25cb4b294f31a4dcf2e5d9c7877f to your computer and use it in GitHub Desktop.
django redis test case
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from uuid import uuid4 | |
from django.conf import settings | |
from django.test import SimpleTestCase | |
from django.utils.decorators import classproperty | |
def _generate_record(host, port): | |
return { | |
'LOCATION': 'redis://{host}:{port}/24'.format( | |
host=host, port=port), | |
'BACKEND': 'django_redis.cache.RedisCache', | |
'KEY_PREFIX': 'testcase:{}:'.format(uuid4()), | |
} | |
def _is_django_redis_cache(cache_config): | |
return cache_config['BACKEND'] == 'django_redis.cache.RedisCache' | |
class DjangoRedisTestCase(SimpleTestCase): | |
HOST = '127.0.0.1' | |
PORT = '6379' | |
_django_redis_caches = set() | |
@classproperty | |
def _overridden_settings(cls): | |
caches = {} | |
for cache_name, config in settings.CACHES.items(): | |
if _is_django_redis_cache(config): | |
cache_config = _generate_record(cls.HOST, cls.PORT) | |
cls._django_redis_caches.add(cache_name) | |
else: | |
cache_config = config | |
caches[cache_name] = cache_config | |
return {'CACHES': caches} | |
def tearDown(self): | |
super(DjangoRedisTestCase, self).tearDown() | |
from django_redis import get_redis_connection | |
for connection in self._django_redis_caches: | |
get_redis_connection(connection).flushall() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment