首页 > 解决方案 > 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',}”。请帮帮我,我快疯了。

标签: djangotestcase

解决方案


drf 的节流是由缓存工作的。我每次请求都会清除缓存以使其正常工作。


推荐阅读