Python Friday #46: Testing Exceptions in Pytest

I prefer code that throws an exception as soon as it detects an unrecoverable situation. This is annoying but a lot less troublesome as when those errors go unnoticed to production. How can we test if our code throws the expected exceptions?

This post is part of my journey to learn Python. You can find the other parts of this series here.

 

Unexpected exceptions

If we write code that throws an unexpected exception, pytest will show us the error like this (with an E at the start of the line):

pytest shows us where the exception was thrown

The output shows us only the code of our test method that was run up to the line which throw the exception. Thanks to the code of the called method and the values we called the method with; we are able to figure out where the problem is. In this case the parameter b was 0 what got us a ZeroDivisionError exception.

 

Expect an exception

Now that we know that the divide() method throws a ZeroDivisionError when we use 0 as the second parameter, we can create a test that checks for this exception. We need to import pytest to get the raises() method. We can wrap the call that should throw an exception in a with block, the same way we would work with files:

This test passes as long as the exception is thrown. If the exception is not thrown, we will get a failing test with the reason that our expected exception was not raised:

pytest shows us that an exception was not thrown

 

Next

After this little detour it is now time to look at test fixtures in pytest.

1 thought on “Python Friday #46: Testing Exceptions in Pytest”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.