【问题标题】:Why isn't the exception caught by << try >>?为什么 << try >> 没有捕获到异常?
【发布时间】: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


【解决方案1】:

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

我的导入声明是:

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

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

from tastypie.exceptions import ImmediateHttpResponse

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

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

感谢收听!

【讨论】:

    【解决方案2】:

    您是否定义了自己的ImmediateHttpResponse? (我是这样的,不要那样做。)如果美味派正在提高,可能会出现您所描述的症状 tastypie.exceptions.ImmediateHttpResponse 当您的单元测试正在测试 一个本地定义的ImmediateHttpResponse

    如果是这样,要解决问题,请删除您对 ImmediateHttpResponse 的定义并输入类似

    from tastypie.exceptions import ImmediateHttpResponse
    

    改为在您的单元测试中。

    【讨论】:

    • 是的,就在你出现的时候发布了我的答案。查看我导入的异常的字符串值,并在第二个 except 块中捕获异常并获取其类型的字符串值。
    猜你喜欢
    • 1970-01-01
    • 2010-09-07
    • 2019-07-12
    • 2022-01-06
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多