Why isn't the exception caught by << try >>?
I have a Python (Django) unit test FAIL from an exception, but the failing code is in a try / except block written for that exception. A similar block handles the exception when it is directly raised.
This passes:
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Code catches a directly raised ImmediateHttpResponse
try:
raise ImmediateHttpResponse(response=auth_result)
self.fail()
except ImmediateHttpResponse, e:
self.assertTrue(True)
This, immediately following it, fails:
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# FAIL
try:
resp = resource.dispatch_list(request) #<--- Line 172
self.fail()
except ImmediateHttpResponse, e:
self.assertTrue(True)
Here is the trace:
Traceback (most recent call last):
File ".../web_app/tests/api/tastypie_authentication.py", line 172, in test_dispatch_list_d开发者_C百科iagnostic
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
Per the trace, the dispatch_list() call fails because it raises an << ImmediateHttpResponse >> exception. But placing just such an exception in the try block does not create a similar failure.
Why is the try / except block handling the one exception but not the other?
Note that the test code is copied from a library's test code, which does run as expected. (I'm using the library test code to diagnose my own implementation failures.)
Did you define your own ImmediateHttpResponse
? (I so, do not do that.) It's possible to get the symptom you are describing if tastypie is raising a
tastypie.exceptions.ImmediateHttpResponse
while your unit test is testing for
a locally defined ImmediateHttpResponse
.
If so, to fix the problem, delete your definition of ImmediateHttpResponse
and put something like
from tastypie.exceptions import ImmediateHttpResponse
in your unit test instead.
Got it, the problem was that my import of ImmediateHttpException differed from that of the code raising the error.
My import statement was:
from convoluted.directory.structure.tastypie.exceptions import ImmediateHttpResponse
The resource.py code that threw the error used:
from tastypie.exceptions import ImmediateHttpResponse
So it raised an exception != to the one I imported, though their string outputs were the same.
Fixing my import statement resolved the problem.
Thanks for listening!
精彩评论