Opened 6 years ago

Closed 6 years ago

#17995 closed Bug (duplicate)

Forcing a Specific Caching Backend in Tests

Reported by: dcooper Owned by: nobody
Component: Testing framework Version: 1.4
Severity: Normal Keywords: cache test
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


I declared a specific caching backend in my settings file (DatabaseCache in development).


    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'example_db_cache',

I'd like to unit test my code forcing the LocMemCache backend.

# myapp/

from django.conf import settings
from django.core.cache.backends.locmem import LocMemCache
from django.test import TestCase
from django.test.utils import override_settings

        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
class CacheTests(TestCase):
    def test_check_cache_backend(self):
        from django.core.cache import cache

        self.assertEqual(settings.CACHES, {
            'default': {
                'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',

        # This fails, since cache is DatabaseCache from!
        self.assertIsInstance(cache, LocMemCache)

which gives exception,

david@devbox:~/project$ ./ test myapp/
Creating test database for alias 'default'...
FAIL: test_check_cache_backend (myapp.tests.CacheTests)
Traceback (most recent call last):
  File "/home/david/project/myapp/", line 24, in test_check_cache_backend
    self.assertIsInstance(cache, LocMemCache)
AssertionError: <django.core.cache.backends.db.DatabaseCache object at 0x1ca4c10> is not an instance of <class 'django.core.cache.backends.locmem.LocMemCache'>

Ran 1 test in 0.002s

FAILED (failures=1)
Destroying test database for alias 'default'...

So the cache object is an instance of DatabaseCache, which is the setting from my master, even though the @override_settings properly overrode CACHES.

Is it possible to test using LocMemCache? Is this expected behaviour?

Thanks and keep up the great work!

David Cooper <dcooper@…>

Change History (1)

comment:1 Changed 6 years ago by Claude Paroz

Resolution: duplicate
Status: newclosed

AFAIK, the problem is that django.core.cache.cache is a global cache variable that should be reset (with get_cache) to dynamically change the cache. I think this is a duplicate of #17787.

Note: See TracTickets for help on using tickets.
Back to Top