2

我有一个基于 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):
...
4

2 回答 2

3

虽然 Django 提供的函数/装饰器可以工作,但pytest-django它提供了一个用于更改测试设置的夹具。为了更好地遵循使用夹具进行测试pytest的范例,最好将特定于测试的设置更改如下:

import pytest

def test_cache(settings):
    settings.CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
        }
    }
    # test logic here
于 2016-10-29T15:42:13.353 回答
2

Django 为此提供了override_settings装饰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
于 2016-03-22T09:41:09.887 回答