繁体   English   中英

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

[英]Raise exception in pytest (Failed: DID NOT RAISE <class 'ValueError'>)

在我的 unitest 代码中捕获异常时遇到问题。 以下是我的代码

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) 函数抛出异常时,它按预期工作。

我遇到了同样的问题。 这个解决方案对我有用。

        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

这不是问题,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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM