【发布时间】:2020-08-15 11:07:14
【问题描述】:
我有一个自定义限制类,例如:(打印语句用于调试 :))在 api.throttle.py
print("befor CustomThrottle class")
class CustomThrottle(BaseThrottle):
def __init__(self):
super().__init__()
print("initializing CustomThrottle", self)
self._wait = 0
def allow_request(self, request, view):
print("CustomThrottle.allow_request")
if request.method in SAFE_METHODS:
return True
# some checking here
if wait > 0:
self._wait = wait
return False
return True
def wait(self):
return self._wait
我的api.views.py 是这样的:
from api.throttle import CustomThrottle
print("views module")
class SomeView(APIView):
print("in view")
throttle_classes = [CustomThrottle]
def post(self, request, should_exist):
# some processing
return Response({"message": "Done."})
我的测试是api/tests/test_views.py:
@patch.object(api.views.CustomThrottle, "allow_request")
def test_can_get_confirmation_code_for_registered_user(self, throttle):
throttle.return_value = True
response = self.client.post(path, data=data)
self.assertEqual(
response.status_code,
status.HTTP_200_OK,
"Should be successful",
)
@patch("api.views.CustomThrottle")
def test_learn(self, throttle):
throttle.return_value.allow_request.return_value = True
response = self.client.post(path, data=data)
self.assertEqual(
response.status_code,
status.HTTP_200_OK,
"Should be successful",
)
第一个测试正确通过,但 CustomThrottle 类仍被实例化,但 allow_request 方法被模拟;第二个测试表明,CustomThrottle 类和 allow_request 方法都没有被模拟,并且它以 status 429 失败(CustomThrottle 的节流率为 2 分钟)。
【问题讨论】:
-
你想在第二次测试中模拟
CustomThrottle,对吗? -
@myuz,是的,在第一个测试中
allow_request方法被模拟,但在第二个测试中,我希望整个CustomThrottle类被模拟。
标签: python django unit-testing testing django-rest-framework