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

问题描述 投票:3回答:2

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

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

python django testing django-rest-framework throttling
2个回答
2
投票

就像人们已经提到的那样,这并不完全属于单元测试的范围,但仍然如此简单地做这样的事情:

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,我只想在cache.clear()添加tearDown或尝试清除specific key defined for throttling


0
投票

一个简单的解决方案是patch你的油门类的get_rate方法。感谢tprestegard for this comment

在我的案例中我有一个自定义类:

from rest_framework.throttling import UserRateThrottle

class AuthRateThrottle(UserRateThrottle):
    scope = 'auth'

在你的测试中:

from unittest.mock import patch
from django.core.cache import cache
from rest_framework import status

class Tests(SimpleTestCase):
    def setUp(self):
        cache.clear()

    @patch('path.to.AuthRateThrottle.get_rate')
    def test_throttling(self, mock):
        mock.return_value = '1/day'
        response = self.client.post(self.url, {})
        self.assertEqual(
            response.status_code,
            status.HTTP_400_BAD_REQUEST,  # some fields are required
        )
        response = self.client.post(self.url, {})
        self.assertEqual(
            response.status_code,
            status.HTTP_429_TOO_MANY_REQUESTS,
        )

也可以在DRF包中修补该方法以更改标准油门类的行为:@patch('rest_framework.throttling.SimpleRateThrottle.get_rate')

© www.soinside.com 2019 - 2024. All rights reserved.