【发布时间】:2011-11-28 13:28:28
【问题描述】:
我有一个 Python (Django) 单元测试因异常而失败,但失败的代码位于为该异常编写的 try / except 块中。直接引发异常时,类似的块会处理异常。
通过了:
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Code catches a directly raised ImmediateHttpResponse
try:
raise ImmediateHttpResponse(response=auth_result)
self.fail()
except ImmediateHttpResponse, e:
self.assertTrue(True)
这紧随其后,失败了:
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# FAIL
try:
resp = resource.dispatch_list(request) #<--- Line 172
self.fail()
except ImmediateHttpResponse, e:
self.assertTrue(True)
这是踪迹:
Traceback (most recent call last):
File ".../web_app/tests/api/tastypie_authentication.py", line 172, in test_dispatch_list_diagnostic
resource.dispatch_list(request)
File ".../libraries/django_tastypie/tastypie/resources.py", line 410, in dispatch_list
return self.dispatch('list', request, **kwargs)
File ".../libraries/django_tastypie/tastypie/resources.py", line 434, in dispatch
self.is_authenticated(request)
File ".../libraries/django_tastypie/tastypie/resources.py", line 534, in is_authenticated
raise ImmediateHttpResponse(response=auth_result)
ImmediateHttpResponse
根据跟踪,dispatch_list() 调用失败,因为它引发了 > 异常。但是在 try 块中放置这样的异常不会造成类似的失败。
为什么 try / except 块只处理一个异常而不处理另一个?
请注意,测试代码是从库的测试代码中复制而来的,它确实按预期运行。 (我正在使用库测试代码来诊断我自己的实现失败。)
【问题讨论】:
-
您确定您在实际代码中拼写的 ImmediateHttpResponse 正确吗?
-
像新手一样肯定。但是在 > 之后,搜索“立即”一无所获。
标签: python django unit-testing exception-handling tastypie