【问题标题】:How to make testing cache storage (Redis) in Django with Pytest?如何使用 Pytest 在 Django 中测试缓存存储(Redis)?
【发布时间】:2018-07-05 15:44:57
【问题描述】:

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

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

【问题讨论】:

  • 您可以为测试定义自定义 django 设置并在运行测试时使用它们。在这些设置中,定义自己的 redis 缓存或从生产缓存中复制 CACHES。如果您想在测试之前填充缓存,请编写一个在测试之前调用的自定义夹具并请求应缓存的 django 视图。或者,如果你有一些自定义的东西要填充,直接使用 redis cli 命令。您可以使用flushall 命令清除缓存。如果不知道您到底想测试什么,很难详细说明。

标签: django caching redis pytest pytest-django


【解决方案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

【讨论】:

  • 我有同样的问题,但我不明白这些方法有什么帮助。你能再描述一下解决方案吗?最好有例子?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-19
    • 2020-06-29
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多