如何使用 Pytest 在 Django 中测试缓存存储(Redis)?

How to make testing cache storage (Redis) in Django with Pytest?

我正在使用带有 django-pytest 库的 Django 1.11.9 来测试我的应用程序。另外,我使用 Redis 作为缓存存储。我的问题是 — 如何在 运行ning 测试之前制作测试缓存存储并使用测试数据设置它?类似于Django数据库做的方式。

我想添加一些key: value数据来测试缓存存储(在Redis中),运行测试,然后删除所有这些测试数据(清除测试缓存)。

我在 py.test 文档中找到了解决方案:

Similarly, the following methods are called around each method invocation:

def setup_method(self, method):
    """ setup any state tied to the execution of the given method in a
    class.  setup_method is invoked for every test method of a class.
    """

def teardown_method(self, method):
    """ teardown any state that was previously setup with a setup_method
    call.
    """

参见:https://docs.pytest.org/en/latest/xunit_setup.html?highlight=setup_class#method-and-function-level-setup-teardown

假设您也在使用 django-redis 库,那么最好使用 fakeredis 库和以下设置:

app/tests/test_settings.py中:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://redis:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "REDIS_CLIENT_CLASS": "fakeredis.FakeStrictRedis",
        },
    },
}

app/pytest.ini中:

[pytest]
DJANGO_SETTINGS_MODULE = ur_l.tests.test_settings

然后在你的 app/tests/test_something.py:

from django.core.cache import cache

def test_cache():
    cache.client._clients # check if this points to `fakeredis.FakeStrictRedis` class
    # If yes then anything below should now use fake cache