TIL: Unit Testing Python Exceptions

So yesterday I talked about how you can create your own unique exceptions within your package. But how do you go about testing for them? Or testing for any exception for that matter? Let’s take a little look into it.

Let’s suppose that I have one of the exceptions defined in my application that I talked about yesterday:

1
2
3
4
5
6
class RandomUserError(Exception):
  def __init__(self, message):
      super(RandomUserError, self).__init__(message)

class resultsError(RandomUserError):
  """When there's an error with results value"""

And then I have some stupid method that does the following:

1
2
3
4
5
def helloBob():
   if false:
       return "Bob"
   else:
       raise RandomUserError("I can't find Bob!")

If I were to want to write a unit test for this stupid method, I would need to be testing that my expected exception was thrown (as it’s always going to be thrown).

To do so, I need to use the assertRaises assertion from the unittest package. This will allow me to check that my desired exception was thrown when executing the specified method:

1
2
3
4
class TestFailureCases(TestCase):
   def test_no_bob_here(self):
       with self.assertRaises(RandomUserError):
           helloBob()

This will do the check to ensure that the exception received is the one that you expected.

💚