Skipping some tests with Python’s unittest module

I was recently writing some tests for a Python extension module that uses Boost.Python. To keep things agile (i.e. keep compile times down) I have a few #ifdefs in my code that allows me to disable various parts of the module when I’m only interested in other parts. This greatly reduces the time of edit-compile-test cycle when your module starts getting really large. I wanted to skip certain tests in my test suite depending on whether a part of the module was available. Here’s what I came up with:

import unittest

class _test_foo:
    def setUp(self): pass
    def test_baz(self):
        self.assert_(True)
    def tearDown(self): pass

try:
    from extmodule import foo
    class test_foo(_test_foo, unittest.TestCase):
        pass
except ImportError:
    print 'skipping foo tests'

if __name__ == '__main__':
    unittest.main()

Leave a Reply