Python unittest: how to run only part of a test file?
To run only a single specific test, you can use:
python -m unittest test_module.TestClass.test_method
More information is here.
The default unittest.main()
uses the default test loader to make a TestSuite out of the module in which main is running.
You don't have to use this default behavior.
You can, for example, make three unittest.TestSuite instances.
-
The "fast" subset.
fast = TestSuite() fast.addTests(TestFastThis) fast.addTests(TestFastThat)
-
The "slow" subset.
slow = TestSuite() slow.addTests(TestSlowAnother) slow.addTests(TestSlowSomeMore)
-
The "whole" set.
alltests = unittest.TestSuite([fast, slow])
Note that I've adjusted the TestCase names to indicate Fast vs. Slow. You can subclass unittest.TestLoader to parse the names of classes and create multiple loaders.
Then your main program can parse command-line arguments with optparse or argparse (available since 2.7 or 3.2) to pick which suite you want to run, fast, slow or all.
Or, you can trust that sys.argv[1]
is one of three values and use something as simple as this
if __name__ == "__main__":
suite = eval(sys.argv[1]) # Be careful with this line!
unittest.TextTestRunner().run(suite)
I'm doing this using a simple skipIf
:
import os
SLOW_TESTS = int(os.getenv('SLOW_TESTS', '0'))
@unittest.skipIf(not SLOW_TESTS, "slow")
class CheckMyFeature(unittest.TestCase):
def runTest(self):
…
This way I need only decorate an already existing test case with this single line (no need to create test suites or similar, just that one os.getenv()
call line in the beginning of my unit test file), and as a default this test gets skipped.
If I want to execute it despite being slow, I just call my script like this:
SLOW_TESTS=1 python -m unittest …