【问题标题】:Use LocMemCache for selective Django pytest使用 LocMemCache 进行选择性 Django pytest
【发布时间】:2016-03-22 03:36:43
【问题描述】:

我有一个基于 Django REST 框架 SimpleRateThrottle 的自定义 Throttling 类,我想用 pytest 测试我的自定义类。由于我的默认测试设置使用 DummyCache,我想为这个特定的测试模块切换到 LocMemCache(SimpleRateThrottle 使用缓存后端来跟踪计数)。有没有办法为选择性测试切换缓存后端?在夹具中设置 settings.CACHE 似乎不起作用。我还尝试在 SimpleRateThrottle 中模拟 default_cache,但我做错了。

naive_throttler.py

from rest_framework.throttling import SimpleRateThrottle

class NaiveThrottler(SimpleRateThrottle):
   ...

rest_framework/throttling.py

from django.core.cache import cache as default_cache  # Or how can I patch this?

class SimpleRateThrottle(BaseThrottle):
...

【问题讨论】:

    标签: python django django-rest-framework pytest pytest-django


    【解决方案1】:

    虽然 Django 提供的函数/装饰器可以工作,但pytest-django 提供了fixture for changing settings for a test。为了更好地遵循pytestusing fixtures for tests 范例,最好将特定于测试的设置更改如下:

    import pytest
    
    def test_cache(settings):
        settings.CACHES = {
            'default': {
                'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
            }
        }
        # test logic here
    

    【讨论】:

    • 你拯救了我的一天!
    • 啊,谢谢!请注意任何像我一样犯愚蠢错误的人 - 这不会引发错误,但它也不起作用! :settings.CACHES['default']['BACKEND'] = 'django.core.cache.backends.dummy.DummyCache'
    【解决方案2】:

    Django 为此提供了override_settings and modify_settings 装饰器。如果您只想为一项测试更改 CACHES 设置,您可以这样做:

    from django.test import TestCase, override_settings
    
    class MyTestCase(TestCase):
    
        @override_settings(CACHES = {
                               'default': {
                                  'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
                               }
                          })
        def test_chache(self):
            # your test code
    

    【讨论】:

    • 这是个好消息,但它似乎不支持 pytest 是吗?
    • 我只是将它与 pytest 一起用于普通函数,也应该与类函数一起使用
    猜你喜欢
    • 2012-02-13
    • 2015-07-15
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    相关资源
    最近更新 更多