在pytest中引发异常(失败:未引发<class'ValueError'>)

时间:2019-12-13 15:28:02

标签: python pytest python-unittest valueerror

在我的统一代码中捕获异常时,我遇到了问题。 以下是我的代码

def get_param(param)        
    if param is None:
        raise ValueError('param is not set')

def test_param():
    with pytest.raises(ValueError) as e:
        get_param()

问题在于,当函数不引发异常时,test_param()会因以下错误而失败。

Failed: DID NOT RAISE <class 'ValueError'>

当get_param(param)函数引发异常时,它会按预期工作。

2 个答案:

答案 0 :(得分:0)

这不是问题,python.raises可以正常工作。通过使用它,您可以断言某个异常。 如果您确实不想获取该异常,则可以使用try-except来捕获和抑制它,如下所示:

from _pytest.outcomes import Failed

def test_param():
    try:
        with pytest.raises(ValueError):
            get_param()
    except Failed as exc:
        # suppress
        pass
        # or
        # do something else with the exception
        print(exc)
        # or
        raise SomeOtherException

答案 1 :(得分:0)

我遇到了同样的问题。此解决方案适用于我。

        try:
            with pytest.raises(ValidationError) as excinfo:
                validate_bank_account_number(value=value)
            assert excinfo.value.args[0] == 'your_error_message_returned_from_validation_error'
        except:
            assert True
相关问题