Python Unit Testing

By | 2013-08-11

I discussed C++ unit testing last time; I thought this time I’d make a quick mention of unit testing in Python with the unittest module (which uses a very similar structure to CppUnit – mostly because they are both based on JUnit).

The introspective abilities of dynamic languages like Python make unit test frameworks really easy to use.

# Class:    TemplateUnitTest
# Description:
class TemplateUnitTest(unittest.TestCase):
    def setUp(self):
        # Called once per test
        logging.basicConfig(format='[%(levelname)-5.5s]  %(message)s', level=logging.INFO)"*** UNITTEST Start")

    # tests have to be prefixed with "test_"
    def test_example(self):
        # self.assertTrue(element in self.seq)
        # self.assertEqual(self.seq, range(10))
        # self.assertRaises(TypeError, random.shuffle, (1,2,3))

# -------------- Module check
# __name__ is set to "__main__" when this is the top module
# if this module is loaded because of an "import" then this
# won't get run -- perfect
if __name__ == "__main__":
    suite = unittest.TestLoader().loadTestsFromTestCase(TemplateUnitTest)

While this is perfectly acceptable, for a real project you’ll likely want to run unit tests using the command line interface. That leaves you able to run your own code from the “if name” block. You can do that with python’s “-m” switch for running a particular module directly.

$ python -m unittest YOUR_MODULE

Alternatively, you can run test discovery automatically

$ python -m unittest discover -p "*.py"

Leave a Reply