在测试中覆盖 Django 缓存设置

Override Django cache settings in tests

我在测试中使用 Django DummyCache,但是,有一些测试依赖于真实缓存,因此在这里使用假缓存并不好。

是否有一种干净的方法来覆盖常规 Django settings for a certain module or scope? Preferably using a Python decorator

我正在使用 Django 版本 1.8.4

是的,可以覆盖设置。来自 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(...)

我自己用其他几种设置测试了上述方法,但没有使用特定的缓存设置,但这是一般的想法。

编辑(感谢@Alasdair):

对特定设置覆盖进行重新分级,可以在文档中找到以下警告:

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.

看看https://docs.djangoproject.com/en/1.8/topics/testing/tools/#overriding-settings 您可以使用装饰器 override_settings

from django.test import TestCase, override_settings

class MyTestCase(TestCase):

    @override_settings(CACHES=...)
    def test_something(self):
        ....

如果您使用的是 pytest,则可以将此固定装置放入 conftest.py 文件

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()