Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 断言异常消息?_Python_Pytest - Fatal编程技术网

Python 断言异常消息?

Python 断言异常消息?,python,pytest,Python,Pytest,我在一个项目中使用pytest,其中有很多自定义异常 pytest提供了一种方便的语法来检查是否引发了异常,但是,我不知道有哪种语法断言引发了正确的异常消息 假设我有一个打印“boo!”的CustomException,我怎么能断言“boo!”确实已打印,而不是说,“ #errors.py 类CustomException(异常): 定义str(self):返回“哎哟!” #test.py 导入pytest,myModule def测试_自定义_错误():#应失败 使用pytest.raise

我在一个项目中使用pytest,其中有很多自定义异常

pytest提供了一种方便的语法来检查是否引发了异常,但是,我不知道有哪种语法断言引发了正确的异常消息

假设我有一个打印“boo!”的
CustomException
,我怎么能断言“boo!”确实已打印,而不是说,“

#errors.py
类CustomException(异常):
定义str(self):返回“哎哟!”
#test.py
导入pytest,myModule
def测试_自定义_错误():#应失败
使用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!"

打印“boo!”的自定义异常
-您是指字符串表示为“boo”的自定义异常吗?e、 你想
断言str(exc)==“Boo!”
?如果你真的想捕获stdout或stderr,那么你可能想看看capsys装置:看看这个:,
excinfo.value
是实际提出的exeption,所以你可以
断言str(excinfo.value)==“Boo”
,这确实是我在寻找的,非常感谢你!注意:您必须在
块之外访问它,如本答案所示。在
failer()之后无法访问它