如何使用 pytest 引发检查异常原因?

Eva*_*van 4 python exception pytest python-3.x

我想测试是否从另一种异常类型引发异常。

import pytest


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

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

有没有一种干净的方法可以使用 ptyest 加注来做到这一点?

Eva*_*van 7

在出现更具可读性的内容之前,我正在执行以下操作。

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
Run Code Online (Sandbox Code Playgroud)

  • 我建议使用“isinstance(exc_info.value.__cause__, ValueError)”而不是类型。 (3认同)