Running single test from unittest.TestCase via command line

Alois Mahdal picture Alois Mahdal · Apr 12, 2013 · Viewed 154.2k times · Source

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, what I do is that I 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 e.g. 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.

Answer

phihag picture phihag · Apr 12, 2013

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

python testMyCase.py MyCase.testItIsHot