ipython-unittest
ipython-unittest copied to clipboard
How do you test a function that throws an exception?
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:
Feel free to suggest a different syntax or to submit a pull request for testing exceptions