我正在使用带有django-pytest
库的 Django 1.11.9 来测试我的应用程序。另外,我使用 Redis 作为缓存存储。我的问题是——如何在运行测试之前制作一个测试缓存存储并使用测试数据进行设置?类似于 Django 数据库的做法。
我想添加一些key: value
数据来测试缓存存储(在 Redis 中),运行测试,然后删除所有这些测试数据(清除测试缓存)。
我正在使用带有django-pytest
库的 Django 1.11.9 来测试我的应用程序。另外,我使用 Redis 作为缓存存储。我的问题是——如何在运行测试之前制作一个测试缓存存储并使用测试数据进行设置?类似于 Django 数据库的做法。
我想添加一些key: value
数据来测试缓存存储(在 Redis 中),运行测试,然后删除所有这些测试数据(清除测试缓存)。
我在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.
"""
假设您也在使用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