Search code examples
testingcachingdjango-rest-frameworkredis

Redis Cache With Django Rest Framework Testing


In my current project I have some code that requires caching (I use Redis for now).And for that reason I can't use fake cache or mock. And through the tests I need a clean cache, so at setup of test case class I use the following:

from django_redis import get_redis_connection
get_redis_connection("default").flushall()

Which breaks the parallel testing(and can make race condition). What's the best practice of testing with active caching?


Solution

  • For anyone who passes by, I've changed the cache backend to LocMemCache when testing. After that, caches aren't affected by parallel testing anymore.

    Something like this:

    TESTING = 'test' in sys.argv
    if TESTING:
        CACHES = {
            'default': {
                'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            }
        }
    else:
        CACHES = {
            'default': {
                'BACKEND': 'django_redis.cache.RedisCache',
                'LOCATION': REDIS_HOST,
            }
        }
    

    Caution: some operations which are supported by RedisCache, aren't supported by LocMemCache. cache.ttl() is an example.