Search code examples
pythonpytestpython-unittestvalueerror

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.


Solution

  • 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