Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override Django cache settings in tests

I'm using Django DummyCache in my tests, however, there are a few tests which relay on real caching so using fake caching is not good here.

Is there a clean way to override the general Django settings for a certain module or scope? Preferably using a Python decorator.

I'm using Django version 1.8.4.

like image 593
Forge Avatar asked Oct 01 '15 08:10

Forge


2 Answers

Take a look at https://docs.djangoproject.com/en/1.8/topics/testing/tools/#overriding-settings You can use decorator override_settings

from django.test import TestCase, override_settings

class MyTestCase(TestCase):

    @override_settings(CACHES=...)
    def test_something(self):
        ....
like image 88
sinitsynsv Avatar answered Nov 14 '22 23:11

sinitsynsv


Yes, it is possible to override a setting. From Django documentation: Testing:

For testing purposes it’s often useful to change a setting temporarily and revert to the original value after running the testing code. For this use case Django provides a standard Python context manager ... settings(), which can be used like this:

from django.test import TestCase

class LoginTestCase(TestCase):
    def test_login(self):
        # Override the LOGIN_URL setting
        with self.settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'}}):
            response = self.client.get(...)

I have tested the above approach with several other settings myself, but not with the particular cache setting, but this is the general idea.

EDIT (credits @Alasdair):

Regrading the particular setting override, the following warning can be found in the documentation:

Altering the CACHESsetting is possible, but a bit tricky if you are using internals that make using of caching, like django.contrib.sessions. For example, you will have to reinitialize the session backend in a test that uses cached sessions and overrides CACHES.

like image 31
Wtower Avatar answered Nov 14 '22 22:11

Wtower