2011-09-30 46 views
0

我有一个Python(Django)单元测试FAIL从一个异常,但失败的代码是在为这个异常写入的try/except块。一个类似的块在直接提升时处理异常。为什么<< try >>不被例外?

这传递:

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
# 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块处理一个异常而不是另一个?

请注意,测试代码是从库的测试代码复制而来的,测试代码按预期运行。 (我正在使用库测试代码来诊断我自己的执行失败。)

+0

您确定您在实际代码中拼写ImmediateHttpResponse正确吗? –

+0

像新手一样可以。但在<<:%s/ImmediateHttpResponse/FOOBAR/g >>之后,搜索“Immediate”并没有任何结果。 – chernevik

回答

3

您是否定义了自己的ImmediateHttpResponse? (我这样做,不这样做。)如果你的单元测试正在测试 本地定义的ImmediateHttpResponse,那么如果tastypie提高了 tastypie.exceptions.ImmediateHttpResponse,就可能得到你所描述的症状。

如果是这样,来解决这个问题,请删除您的ImmediateHttpResponse定义,并把像

from tastypie.exceptions import ImmediateHttpResponse 

在单元测试来代替。

+0

是的,贴出我的答案就像你的出现。想通过查看我导入的异常的字符串值,并捕获除了块以外的第二个异常中获得的异常,并获取其类型的字符串值。 – chernevik

0

明白了,问题是我的导入ImmediateHttpException与引发错误的代码不同。

我的import语句是:

from convoluted.directory.structure.tastypie.exceptions import ImmediateHttpResponse 

抛出使用错误的resource.py代码:

from tastypie.exceptions import ImmediateHttpResponse 

所以引发异常=到一个我进口的,虽然它们的字符串产出是相同的。

修复我的导入语句解决了问题。

感谢收听!

相关问题