ipython-unittest icon indicating copy to clipboard operation
ipython-unittest copied to clipboard

How do you test a function that throws an exception?

Open danielpcampagna opened this issue 6 years ago • 1 comments

danielpcampagna avatar Jun 03 '18 09:06 danielpcampagna

This is tricky. The function to test exceptions in unittest is self.assertRaises. To use it in ipython unittest, you must have a docstring delimiting the tests

For instance:

%%unittest
'''Test exception'''
self.assertRaises(ValueError, function, False)
'''Another test'''
assert function(1) == 1

Note that if you start doing this, all tests below a docstring must also have a docstring.

If you think that using an undefined self or docstrings to separate the tests looks weird, you can also use explicit function definitions:

%%unittest
assert function(1) == 1
def test_exception(self):
    self.assertRaises(ValueError, function, False)

Image with these examples: image

Feel free to suggest a different syntax or to submit a pull request for testing exceptions

JoaoFelipe avatar Jun 03 '18 17:06 JoaoFelipe