0

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

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

4

2 回答 2

3

你定义了你自己的ImmediateHttpResponse吗?(我是这样,不要那样做。)如果 tastypie.exceptions.ImmediateHttpResponse在你的单元测试正在测试本地定义的ImmediateHttpResponse.

如果是这样,要解决问题,请删除您的定义ImmediateHttpResponse并放置类似的内容

from tastypie.exceptions import ImmediateHttpResponse

在你的单元测试中。

于 2011-09-30T15:18:18.687 回答
0

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

我的导入声明是:

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

使用的引发错误的 resource.py 代码:

from tastypie.exceptions import ImmediateHttpResponse

所以它引发了一个例外!= 我导入的那个,尽管它们的字符串输出是相同的。

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

感谢收听!

于 2011-09-30T15:19:02.127 回答