使用 LocMemCache 进行选择性 Django pytest

Use LocMemCache for selective Django pytest

我有一个基于 Django REST 框架 SimpleRateThrottle 的自定义限制 classes,我想用 pytest 测试我的自定义 class。由于我的默认测试设置使用 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):
...

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

虽然 Django 提供的 functions/decorators 可能有效,但 pytest-django 提供 fixture for changing settings for a test. To better follow pytest's paradigm of using fixtures for tests,最好更改特定于测试的设置,如下所示:

import pytest

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