我在一个有很多自定义异常的项目中使用 pytest。
pytest 提供了一种方便的语法来检查是否已引发异常,但是,我不知道是否有一种语法可以断言已引发了正确的异常消息。
假设我有一个 CustomException
打印“boo!”,我如何断言“boo!”确实已打印,而不是“
#errors.py
class CustomException(Exception):
def __str__(self): return "ouch!"
#test.py
import pytest, myModule
def test_custom_error(): # SHOULD FAIL
with pytest.raises(myModule.CustomException):
raise myModule.CustomException == "boo!"
最佳答案
我认为您正在寻找的是:
def failer():
raise myModule.CustomException()
def test_failer():
with pytest.raises(myModule.CustomException) as excinfo:
failer()
assert str(excinfo.value) == "boo!"
关于python - 断言异常消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57560531/