3

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

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

4

2 回答 2

1

我在py.test文档中创建了解决方案:

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

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

于 2018-02-15T13:58:20.043 回答
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
于 2020-08-08T15:58:50.650 回答