Writing unit tests in Python: How do I start? [closed] Writing unit tests in Python: How do I start? [closed] python python

Writing unit tests in Python: How do I start? [closed]


If you're brand new to using unittests, the simplest approach to learn is often the best. On that basis along I recommend using py.test rather than the default unittest module.

Consider these two examples, which do the same thing:

Example 1 (unittest):

import unittestclass LearningCase(unittest.TestCase):    def test_starting_out(self):        self.assertEqual(1, 1)def main():    unittest.main()if __name__ == "__main__":    main()

Example 2 (pytest):

def test_starting_out():    assert 1 == 1

Assuming that both files are named test_unittesting.py, how do we run the tests?

Example 1 (unittest):

cd /path/to/dir/python test_unittesting.py

Example 2 (pytest):

cd /path/to/dir/py.test


The free Python book Dive Into Python has a chapter on unit testing that you might find useful.

If you follow modern practices you should probably write the tests while you are writing your project, and not wait until your project is nearly finished.

Bit late now, but now you know for next time. :)


There are, in my opinion, three great Python testing frameworks that are good to check out:

  • unittest - module comes standard with all Python distributions
  • nose - can run unittest tests, and has less boilerplate.
  • pytest - also runs unittest tests, has less boilerplate, better reporting, and lots of cool extra features

To get a good comparison of all of these, read through the introductions to each at Start Here - Python Testing.There are also extended articles on fixtures, and more there.