简体   繁体   中英

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

I am facing a problem while catching the exception in my unitest code. Following is my code

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()

The problem is that when function does not raise exception, test_param() gets fail with the following error.

Failed: DID NOT RAISE <class 'ValueError'>

It works as expected when get_param(param) function throws exception.

I have faced same problem. This solutions works for me.

        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

It's not a problem, python.raises works as expected. By using it you're asserting a certain exception. If you really don't want to get the exception, you can use try-except to catch and suppress it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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