![](/img/trans.png)
[英]How to test that class __init__ method raises exception using fixture in pytest (Python)
[英]How to check exception cause using pytest raises?
我想測試一個異常是從另一個異常類型引發的。
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 docs 中檢查異常鏈的方法。 https://docs.pytest.org/en/6.2.x/reference.html#pytest-raises
有沒有一種干凈的方法可以使用 ptyest raises 來做到這一點?
在出現更易讀的東西之前,我正在執行以下操作。
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.