Python – UnitTests in Jupyter Notebook

Unit testing is the “sweet” part of the programming – once you have tested “all the things”, you feel that the code you have submitted somewhere is actually valid and somehow it works. Furthermore, it allows you to nicely brag about it, by saying “Of course, we have a unit test for this case.” and adding a nice Mona Lisa smile. And that is the case, until the program works and the tests are running ok. Which is in the general case between 2 days and 2 weeks initially.

As I have written an article about C# Unit testing some years ago and I have made a live coding video for the xUnit Library in C# and TDD, I have decided to write an article for unit tests in Python with Jupyter Notebook. To continue the tradition in a way.

So, following the “best practices” of VitoshAcademy, we will present the Fibonacci function and we will test it. The class looks like this:

The Fibonacci(self, number) function is actually “Fibonacci on steroids”, using memoisation, while the FibonacciSlow(self, number) is the good old example of Fibonacci with recursion. To present the difference between the different Fibonacci calculations, I have written an article some years ago – C# – Three Algorithms For Fibonacci Numbers. The ResetNumber(self, number) function is actually put there, so I can illustrate what the def setUp(self):  and def tearDown(self):  in the unittest.TestCase are doing. And its main purpose is to reset the number variable in the class, together with the other counters. Take a look at the difference of the number of calculations, between the function with memoization and the function with recursion – 49 vs 75025 is quite impressive.

So, how do we UnitTests in Python?

  • import unittest
  • write unit tests
  • run the tests

I was quite “lucky” that I had prepared tests from the articles for C#, thus I did not have to come up with something extraordinary. Still, comparing the results of the “slow” and the “quick” Fibonacci and comparing their operations was quite a must:

The results of the UnitTests in Jupyter notebook is called by the following line:

And depending on the level of verbosity, you may get one of the following screens. The error comes from adding +1  to this line self.assertEqual(quick_steps+1, slow_steps), thus the explanation of th error is AssertionError: 4 != 3.

Leves of verbosity

Verbosity = 0 (quiet) – get the total numbers of tests executed and the global result

Verbosity = 1 (default) – quiet + a dot for every successful test or a F for every failure

Verbosity = 2 (verbose) – help string of every test and the result

As usual, the whole Jupyter Notebook is available in GitHub:

https://github.com/Vitosh/Python_personal/blob/master/JupyterNotebook/unit_tests_jupyter.ipynb

Enjoy it! 🙂

Tagged with: , , , , ,