django - TestCase 中的“override_settings”不起作用
问题描述
我在测试用例中使用了“override_settings”,我想在测试用例中测试 REST_FRAMEWORK 的 DEFAULT_THROTTLE_RATES。当我测试我的api时,它没有用。
my settings.py:
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_RATES': {
'anon': '60/min',
'user': '500/hour',
'custom': '200/day',
}
}
test api:
@throttle_classes([AnonRateThrottle, UserRateThrottle])
def test_api(request):
pass
TestCase:
@override_settings(REST_FRAMEWORK = {
'DEFAULT_THROTTLE_RATES': {
'anon': '600000/min',
'user': '5000000/hour',
'custom': '200000/day',
}
})
def test_api(self):
from rest_framework.settings import api_settings
print(api_settings.DEFAULT_THROTTLE_RATES)
print(api_settings.user_settings)
from rest_framework.throttling import AnonRateThrottle, api_settings as throttling_setting
print(AnonRateThrottle().get_rate())
print(id(throttling_setting))
print(id(api_settings))
print(id(AnonRateThrottle().THROTTLE_RATES))
print(id(api_settings.DEFAULT_THROTTLE_RATES))
print(id(throttling_setting.DEFAULT_THROTTLE_RATES))
url = 'api'
for i in range(100000):
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
我希望测试用例能够工作,但它在 429 状态下断言。我打印了 "apisetting"、"DEFAULT_THROTTLE_RATES" 的 id,它们是相同的,但是 "AnonRateThrottle" 实例中的 "THROTTLE_RATES" id 不是一样,价值不一样。值为“{'anon': '60/min', 'user': '500/hour', 'custom': '200/day',}”。请帮帮我,我快疯了。
解决方案
drf 的节流是由缓存工作的。我每次请求都会清除缓存以使其正常工作。
推荐阅读
- python - 有没有办法在 for 循环上运行优化器?
- c++ - C ++从文件中读取字符,计算每个字符并排序
- python - 在 jupyternotebook 中使用 pyviz 作为表单,将输入放入嵌套列表并显示内容
- xml - 嵌套的 XML/JSON 结构标签,定义结构的正确方法是什么?
- python - 使用正则表达式删除字符串中的数字
- python-3.x - 使用 AND、OR、NOT 交换变量值的代码是什么
- firebase - 使用由第三方控制的 SSO 的 Firebase (Firestore) 自定义身份验证
- laravel - Laravel 工作中未定义的属性
- php - 检查已通过 10 分钟
- entity-framework - 实体框架中的蛮力收集