Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using pytest.raises to catch expected custom error [duplicate]

Tags:

I am new to pytest and am trying to convert some functional test scripts into ones that play nicely with pytest. My module has custom error types and I'm trying to use the with pytest.raises() as excinfo method. This is a scientific/numerical package and I need to test that certain methods are consistent when called, so I can't just drill down to the lower-level stuff.

like image 604
user2097190 Avatar asked Feb 21 '13 21:02

user2097190


People also ask

What is the purpose of Pytest raises?

The raises() method The pytest framework's raises() method asserts that a block of code or a function call raises the specified exception. If it does not, the method raises a failure exception, indicating that the intended exception was not raised.

What is Pytest Assertionerror?

Pytest, by way of magic (also known as introspection) can infere the actual value, the expected value, and the operation used in a plain old assert statement and can provide a rather nice error message.


1 Answers

What is stopping you importing the specific exception and using it in your with pytest.raises statement? Why is this not working? It would be more helpful if you could provide more detail about what problem you are facing.

# your code

class CustomError(Exception):
    pass


def foo():
    raise ValueError('everything is broken')

def bar():
    raise CustomError('still broken')    

#############    
# your test

import pytest
# import your module, or functions from it, incl. exception class    

def test_fooErrorHandling():
    with pytest.raises(ValueError) as excinfo:
        foo()
    assert excinfo.value.message == 'everything is broken'

def test_barSimpleErrorHandling():
    # don't care about the specific message
    with pytest.raises(CustomError):
        bar()

def test_barSpecificErrorHandling():
    # check the specific error message
    with pytest.raises(MyErr) as excinfo:
        bar()
    assert excinfo.value.message == 'oh no!'

def test_barWithoutImportingExceptionClass():
    # if for some reason you can't import the specific exception class,
    # catch it as generic and verify it's in the str(excinfo)
    with pytest.raises(Exception) as excinfo:
        bar()
    assert 'MyErr:' in str(excinfo)
like image 117
pfctdayelise Avatar answered Oct 11 '22 23:10

pfctdayelise