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)
一个简单的解决方案是
patch
throttle类的get_rate
方法。感谢tprestegard for this comment!在我有一个自定义类:
在你的测试中:
^{pr2}$还可以修补DRF包中的方法来更改标准throttle类的行为:
@patch('rest_framework.throttling.SimpleRateThrottle.get_rate')
正如前面提到的,这并不完全属于单元测试的范围,但是,简单地做这样的事情怎么样:
另外,关于您的副作用,只要您在
setUp
或setUpTestData
中创建用户,测试将被隔离(正如它们应该做的那样),因此无需担心“脏”的数据或范围。在关于cache clearing between tests,我只想在},或者尝试清除{a2}。在
tearDown
中添加{相关问题 更多 >
编程相关推荐