jeff_new
jeff_new

Reputation: 551

pytest.raises Failed: DID NOT RAISE with try/except

When using pytest.raises to test an error that is caught by a try/except block, it fails due to it not being raised.

If I do a simple test with a dict lookup and don't put a try/except around it, the pytest.raises test passes. But if try/except is used, the test fails.

This is what works:

def lookup_value(key):

    lookup = {'A': 1, 'B': 2}

    return lookup[key]


def test_lookup():

    with pytest.raises(KeyError):
        lookup_value('C')

Now add the try/except:

def lookup_value(key):

    lookup = {'A': 1, 'B': 2}

    try:
        return lookup[key]
    except KeyError as err:
        print(err)


def test_lookup():

    with pytest.raises(KeyError):
        lookup_value('C')

First snippet, test passes. Second snippet, I get "Failed: DID NOT RAISE <class 'KeyError'>"

Upvotes: 10

Views: 23423

Answers (1)

Mark A
Mark A

Reputation: 948

This code here is swallowing the exception (catching it without propagating the fact that an exception occured).

    try:
        return lookup[key]
    except KeyError as err:
        print(err)

You just need to reraise the exception so that pytest.raises will see it

    try:
        return lookup[key]
    except KeyError as err:
        print(err)
        raise

Also, it's generally bad practice to omit a return statement at the end of a function that returns something in another code path. In Python there is an implied return None but why not help the reader out a little by writing it explicitly.

Upvotes: 8

Related Questions