unittest2
#
unittest2 is a backport of unittest, with improved API and better assertions than in previous Python versions.
Installation#
$ bin/python -m pip install unittest2
Example#
We want to test the following add
method:
[1]:
def add(a, b):
return a + b
Then we import the module under the name unittest
to make it easier to port code to newer versions of the module in the future:
[2]:
import unittest2 as unittest
class TestNotebook(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 2), 5)
unittest.main(argv=[''], verbosity=2, exit=False)
test_add (__main__.TestNotebook) ... FAIL
======================================================================
FAIL: test_add (__main__.TestNotebook)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/var/folders/f8/0034db6d78s5r6m34fxhpk7m0000gp/T/ipykernel_69328/3137592767.py", line 6, in test_add
AssertionError: 4 != 5
----------------------------------------------------------------------
Ran 1 test in 0.002s
FAILED (failures=1)
[2]:
<unittest2.main.TestProgram at 0x7f957c80a8e0>
This way, if you move to a newer Python version and no longer need the unittest2
module, you can simply change the import in your test module without having to change any further code.