Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python unittest: how to run only part of a test file?

I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class.

Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the best way would be with a command-line argument, ie "./tests.py --offline" or something like that), so I could run most of the tests often and quickly and the whole set once in a while, when I have time.

For now, I just use unittest.main() to start the tests.

like image 347
Gohu Avatar asked Jul 01 '09 09:07

Gohu


People also ask

How do we define unit tests within a test file in Python?

Unit tests are usually written as a separate code in a different file, and there could be different naming conventions that you could follow. You could either write the name of the unit test file as the name of the code/unit + test separated by an underscore or test + name of the code/unit separated by an underscore.

Which is better pytest or unittest?

Which is better – pytest or unittest? Although both the frameworks are great for performing testing in python, pytest is easier to work with. The code in pytest is simple, compact, and efficient. For unittest, we will have to import modules, create a class and define the testing functions within that class.


2 Answers

To run only a single specific test, you can use:

python -m unittest test_module.TestClass.test_method 

More information is here.

like image 138
Amit Kotlovski Avatar answered Nov 02 '22 09:11

Amit Kotlovski


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.

  1. The "fast" subset.

    fast = TestSuite() fast.addTests(TestFastThis) fast.addTests(TestFastThat) 
  2. The "slow" subset.

    slow = TestSuite() slow.addTests(TestSlowAnother) slow.addTests(TestSlowSomeMore) 
  3. 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) 
like image 39
S.Lott Avatar answered Nov 02 '22 11:11

S.Lott