Tuesday, August 30, 2016

Using with to handle exception inside of your python unit tests

I am sure you have seem something like that in one of the tests

def test_me(self):
  with self.assertRaises(ZeroDivisionError):
    1 / 0

What does it do? It is simply means that test_me would pass if the logic inside of it would throw ZeroDivisionError exception.

But what all that 'with' stuff?

If you ever tried to open up a file to read data, etc you certainly remember doing all error checking, catching errors, closing files, etc... nightmare, hence context manager was introduced that would allow you to open the file by using 'with' and majority of checks and file closing was done for you.

Same in this case, you are using 'with' in this case to use assertRaises as a context manager that ensures that the error in this case is properly caught and cleaned up while it is being recorded. (Same idea as dealing with files...)

So without context manager, your code would have looked like following the old format

def test_me_in_old_way(self):
  import operator
  self.assertRaises(ZeroDivisionError, operator.devide, 1, 0)

First argument is error type that you expect to raise, second is the operator, and last two are the args.
Much more verbose

No comments:

Post a Comment