如何正确断言pytest中引发了异常?

如何正确断言pytest中引发了异常?,第1张

如何正确断言pytest中引发了异常?

pytest.raises(Exception)

是您所需要的。

import pytestdef test_passes():    with pytest.raises(Exception) as e_info:        x = 1 / 0def test_passes_without_info():    with pytest.raises(Exception):        x = 1 / 0def test_fails():    with pytest.raises(Exception) as e_info:        x = 1 / 1def test_fails_without_info():    with pytest.raises(Exception):        x = 1 / 1# Don't do this. Assertions are caught as exceptions.def test_passes_but_should_not():    try:        x = 1 / 1        assert False    except Exception:        assert True# Even if the appropriate exception is caught, it is bad style,# because the test result is less informative# than it would be with pytest.raises(e)# (it just says pass or fail.)def test_passes_but_bad_style():    try:        x = 1 / 0        assert False    except ZeroDivisionError:        assert Truedef test_fails_but_bad_style():    try:        x = 1 / 1        assert False    except ZeroDivisionError:        assert True

输出量

============================================================================================= test session starts ==============================================================================================platform linux2 -- Python 2.7.6 -- py-1.4.26 -- pytest-2.6.4collected 7 itemstest.py ..FF..F=================================================================================================== FAILURES ===================================================================================================__________________________________________________________________________________________________ test_fails __________________________________________________________________________________________________    def test_fails():        with pytest.raises(Exception) as e_info:>x = 1 / 1EFailed: DID NOT RAISEtest.py:13: Failed___________________________________________________________________________________________ test_fails_without_info ____________________________________________________________________________________________    def test_fails_without_info():        with pytest.raises(Exception):>x = 1 / 1EFailed: DID NOT RAISEtest.py:17: Failed___________________________________________________________________________________________ test_fails_but_bad_style ___________________________________________________________________________________________    def test_fails_but_bad_style():        try: x = 1 / 1>assert FalseEassert Falsetest.py:43: AssertionError====================================================================================== 3 failed, 4 passed in 0.02 seconds ======================================================================================

请注意,

e_info
将保存异常对象,以便您可以从中提取详细信息。例如,如果要检查异常调用堆栈或内部的另一个嵌套异常。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5618067.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存