Python – Running a single test from unittest.TestCase via the command line

pythonpython-unittestunit testing

In our team, we define most test cases like this:

One "framework" class ourtcfw.py:

import unittest

class OurTcFw(unittest.TestCase):
    def setUp:
        # Something

    # Other stuff that we want to use everywhere

And a lot of test cases like testMyCase.py:

import localweather

class MyCase(OurTcFw):

    def testItIsSunny(self):
        self.assertTrue(localweather.sunny)

    def testItIsHot(self):
        self.assertTrue(localweather.temperature > 20)

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

When I'm writing new test code and want to run it often, and save time, I do put "__" in front of all other tests. But it's cumbersome, distracts me from the code I'm writing, and the commit noise this creates is plain annoying.

So, for example, when making changes to testItIsHot(), I want to be able to do this:

$ python testMyCase.py testItIsHot

and have unittest run only testItIsHot()

How can I achieve that?

I tried to rewrite the if __name__ == "__main__": part, but since I'm new to Python, I'm feeling lost and keep bashing into everything else than the methods.

Best Answer

This works as you suggest - you just have to specify the class name as well:

python testMyCase.py MyCase.testItIsHot