繁体   English   中英

使用LocMemCache进行选择性Django pytest

[英]Use LocMemCache for selective Django pytest

我有一个基于Django REST框架的SimpleRateThrottle的自定义节流类,我想用pytest测试我的自定义类。 由于我的默认测试设置使用DummyCache,因此我想仅针对此特定测试模块切换到LocMemCache(SimpleRateThrottle使用缓存后端跟踪计数)。 有没有一种方法可以仅选择测试来切换缓存后端? 设置设置。夹具中的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提供的功能/装饰器可能起作用,但pytest-django提供了用于更改测试设置固定装置 为了更好地遵循pytest 使用夹具进行测试的范例,最好按以下方式更改特定于测试的设置:

import pytest

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

Django提供override_settingsmodify_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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM