How do you perform unit testing for Python code?

We can use the unit testing modules unittest or unittest2 to create and run unit tests for Python code.

We can even do automation of tests with these modules. Some of the main components of unittest are as follows:

  • Test fixture: We use test fixture to create preparation methods required to run a test. It can even perform post-test cleanup.
  • Test case: This is main unit test that we run on a piece of code. We can use Testcase base class to create new test cases.
  • Test suite: We can aggregate our unit test cases in a Test suite.
  • Test runner: We use test runner to execute unit tests and produce reports of the test run.