【问题标题】:How to check exception cause using pytest raises?如何使用 pytest raises 检查异常原因?
【发布时间】:2021-12-27 18:21:17
【问题描述】:

我想测试一个异常是从另一个异常类型引发的。

import pytest


def throw_with_cause():
  raise Exception("Failed") from ValueError("That was unexpected.")
 
with pytest.raises(Exception): # from ValueError???
  throw_with_cause()

我很惊讶没有看到在 pytest raises 文档中检查异常链的方法。 https://docs.pytest.org/en/6.2.x/reference.html#pytest-raises

有没有使用 ptyest raises 的干净方法来做到这一点?

【问题讨论】:

  • 我认为您在这里不走运 - 此信息不包含在异常信息中(也不包含在您要检查的异常本身中)。
  • 感谢收看!我可以做的事情是跳过 pytest 引发,捕获异常,然后检查 __ 原因 __。所以我认为这是可能的。如果可以的话,我宁愿更接近我们使用 pytest raises 的约定。
  • 没错,我忘了。如果你真的需要它,你可以编写自己的检查函数,但我同意通常坚持标准方法更好。
  • 哦,我可以通过 excinfo.value 获取异常。这不是很棒,但我可能会断言。
  • 是的,这通常会有所帮助 :) 是的,我从事医学成像,并为 pydicom 做出贡献,因为我也喜欢它。

标签: python python-3.x exception pytest


【解决方案1】:

在出现更易读的东西之前,我正在做以下事情。

import pytest

def throw_with_cause():
   raise Exception("Failed") from ValueError("That was unexpected.")


def test_throws_with_cause():
    with pytest.raises(Exception, match="Failed") as exc_info:
        throw_with_cause()
    assert type(exc_info.value.__cause__) is ValueError

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-06
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 2020-02-25
    • 2023-03-25
    • 2011-10-15
    相关资源
    最近更新 更多