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

时间:2016-09-03 16:29:37

标签: python django testing django-rest-framework throttling

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

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

2 个答案:

答案 0 :(得分: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中进行用户创建,测试就会被隔离(应该如此),因此无需担心& #39;脏'这种意义上的数据或范围。

关于cache clearing between tests,我只需在cache.clear()中添加tearDown或尝试清除specific key defined for throttling

答案 1 :(得分: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')