gpt4 book ai didi

python - 使用 pytest.raises 捕获预期的自定义错误

转载 作者:行者123 更新时间:2023-12-03 23:17:36 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to properly assert that an exception gets raised in pytest?

(12 个回答)


4年前关闭。




我是 pytest 的新手并且正在尝试将一些功能测试脚本转换为与 pytest 完美配合的脚本.我的模块有自定义错误类型,我正在尝试使用 with pytest.raises() as excinfo方法。这是一个科学/数值包,我需要测试某些方法在调用时是否一致,所以我不能只深入到较低级别的东西。

最佳答案

是什么阻止您导入特定异常并在 with 中使用它? pytest.raises陈述?为什么这不起作用?如果您可以提供有关您所面临问题的更多详细信息,那将会更有帮助。

# your code

class CustomError(Exception):
pass


def foo():
raise ValueError('everything is broken')

def bar():
raise CustomError('still broken')

#############
# your test

import pytest
# import your module, or functions from it, incl. exception class

def test_fooErrorHandling():
with pytest.raises(ValueError) as excinfo:
foo()
assert excinfo.value.message == 'everything is broken'

def test_barSimpleErrorHandling():
# don't care about the specific message
with pytest.raises(CustomError):
bar()

def test_barSpecificErrorHandling():
# check the specific error message
with pytest.raises(MyErr) as excinfo:
bar()
assert excinfo.value.message == 'oh no!'

def test_barWithoutImportingExceptionClass():
# if for some reason you can't import the specific exception class,
# catch it as generic and verify it's in the str(excinfo)
with pytest.raises(Exception) as excinfo:
bar()
assert 'MyErr:' in str(excinfo)

关于python - 使用 pytest.raises 捕获预期的自定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15012539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com