Python/Unittest : assertRaises raises Error
Today, a small hint about unit tests in Python I discovered while working on Tippy.
In order to get as reliable code as possible, I am currently experiencing Agile techniques, and especially TDD. I develop Tippy in Python, and test methods with the excellent unittest framework.One of (in my mind at least) the most important tips Agile provides is the “fail fast” rule. And to fit with this rule, all my methods check their inputs before performing anything else.
It implies a lot of assertRaises assertions in my tests. Here is an example of how it could be used :
Let’s say I want to create a (dum) function calculating the square value of a number. I will have to test that the input can really be multiplied.
- First, here is the corresponding (still dum :p) function in file dum_function.py :
- Here is the test to be performed (only this test is inserted):
- We are now ready to test our function! Here is what happens when trying to run the test :
The TypeError is actullay raised, and generates a test failure. The problem is that this is exactly the behavior we wanted :s.
To avoid this error, simply run the function using lambda in the test call :
The final output :
Note : For the purpose of this article, I did not work “backwards” (created test before the function). I think this would have been counter productive for the effect I wanted to highlight.