我有一个 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() 调用失败,因为它引发了 << ImmediateHttpResponse >> 异常。但是在 try 块中放置这样的异常不会产生类似的失败。
为什么 try / except 块处理一个异常而不是另一个?
请注意,测试代码是从库的测试代码中复制而来的,它确实按预期运行。(我正在使用库测试代码来诊断我自己的实现失败。)