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.
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? 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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With