在DRF中测试节流的正确方法是什么?

2024-09-21 02:36:23 发布

您现在位置:Python中文网/ 问答频道 /正文

在DRF中测试节流的正确方法是什么?我在网上找不到这个问题的答案。我想对每个端点进行单独的测试,因为每个端点都有自定义的请求限制(ScopedRateThrottle)。在

重要的是它不能影响其他测试——它们必须以某种方式运行而不受限制和限制。在


Tags: 方法答案方式端点drf受限制节流scopedratethrottle
2条回答

一个简单的解决方案是patchthrottle类的get_rate方法。感谢tprestegard for this comment!在

我有一个自定义类:

from rest_framework.throttling import UserRateThrottle

class AuthRateThrottle(UserRateThrottle):
    scope = 'auth'

在你的测试中:

^{pr2}$

还可以修补DRF包中的方法来更改标准throttle类的行为:@patch('rest_framework.throttling.SimpleRateThrottle.get_rate')

正如前面提到的,这并不完全属于单元测试的范围,但是,简单地做这样的事情怎么样:

from django.core.urlresolvers import reverse
from django.test import override_settings
from rest_framework.test import APITestCase, APIClient


class ThrottleApiTests(APITestCase):
    # make sure to override your settings for testing
    TESTING_THRESHOLD = '5/min'
    # THROTTLE_THRESHOLD is the variable that you set for DRF DEFAULT_THROTTLE_RATES
    @override_settings(THROTTLE_THRESHOLD=TESTING_THRESHOLD)
    def test_check_health(self):
        client = APIClient()
        # some end point you want to test (in this case it's a public enpoint that doesn't require authentication
        _url = reverse('check-health')
        # this is probably set in settings in you case
        for i in range(0, self.TESTING_THRESHOLD):
            client.get(_url)

        # this call should err
        response = client.get(_url)
        # 429 - too many requests
        self.assertEqual(response.status_code, 429)

另外,关于您的副作用,只要您在setUpsetUpTestData中创建用户,测试将被隔离(正如它们应该做的那样),因此无需担心“脏”的数据或范围。在

关于cache clearing between tests,我只想在tearDown中添加{},或者尝试清除{a2}。在

相关问题 更多 >

    热门问题