'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
.
Solution 1:[1]
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):
....
Solution 2:[2]
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
CACHES
setting is possible, but a bit tricky if you are using internals that make using of caching, likedjango.contrib.sessions
. For example, you will have to reinitialize the session backend in a test that uses cached sessions and overridesCACHES
.
Solution 3:[3]
If you are using pytest, you could put this fixture in your conftest.py file
from django.core.cache import cache
@pytest.fixture(autouse=True, scope="function")
def reset_cache():
"""
Fixture to reset the cache after each test
"""
yield
cache.clear()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | sinitsynsv |
Solution 2 | |
Solution 3 | Edwin Acevedo |