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

时间:2018-01-26 09:54:42

标签: django caching redis pytest pytest-django

我正在使用带有django-pytest库的Django 1.11.9来测试我的应用。此外,我使用Redis作为缓存存储。我的问题是 - 如何在运行测试之前测试缓存存储并设置测试数据?像数据库那样做。

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

2 个答案:

答案 0 :(得分:1)

我在py.test docs

中创建了解决方案
  

类似地,围绕每个方法调用调用以下方法:

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

答案 1 :(得分:0)

假设您还使用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