简体   繁体   English

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

[英]How to check exception cause using pytest raises?

I'd like to test that an exception is raised from another exception type.我想测试一个异常是从另一个异常类型引发的。

import pytest


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

I'm surprised not to see a way to inspect the exception chain in the pytest raises docs.我很惊讶没有看到在 pytest raises docs 中检查异常链的方法。 https://docs.pytest.org/en/6.2.x/reference.html#pytest-raises https://docs.pytest.org/en/6.2.x/reference.html#pytest-raises

Is there a clean way to do this using ptyest raises?有没有一种干净的方法可以使用 ptyest raises 来做到这一点?

Until something more readable comes along, I'm doing the following.在出现更易读的东西之前,我正在执行以下操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM