Problem
The majority of test cases in our team are defined as follows:
ourtcfw.py is a “framework” class:
import unittest
class OurTcFw(unittest.TestCase):
def setUp:
# Something
# Other stuff that we want to use everywhere
There are also many test cases, such as 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()
I place “__” in front of all other tests when I’m writing new test code and want to run it frequently to save time. However, it’s inconvenient, diverts my attention away from the code I’m creating, and the resulting commit noise is grating.
So, while making changes to testItIsHot(), for example, I’d like to be able to d
$ python testMyCase.py testItIsHot
Then only run testItIsHot in unittest ()
What can I do to make it happen?
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.
Asked by Alois Mahdal
Solution #1
This works as you said; all you have to do now is supply the class name:
python testMyCase.py MyCase.testItIsHot
Answered by phihag
Solution #2
If you organize your test cases, that is, follow the same organization like the actual code and also use relative imports for modules in the same package, you can also use the following command format:
python -m unittest mypkg.tests.test_module.TestClass.test_method
# In your case, this would be:
python -m unittest testMyCase.MyCase.testItIsHot
This is documented in Python 3: CLI stands for Command-Line Interface.
Answered by Ajay M
Solution #3
It might work as well as you think.
python testMyCase.py MyCase.testItIsHot
There’s also another way to see if testItIsHot is working:
suite = unittest.TestSuite()
suite.addTest(MyCase("testItIsHot"))
runner = unittest.TextTestRunner()
runner.run(suite)
Answered by Yarkee
Solution #4
If you look at the unittest module’s help, you’ll see that there are numerous ways to run test case classes from a module and test methods from a test case class.
python3 -m unittest -h
[...]
Examples:
python3 -m unittest test_module - run tests from test_module
python3 -m unittest module.TestClass - run tests from module.TestClass
python3 -m unittest module.Class.test_method - run specified test method
```lang-none
It does not require you to define a `unittest.main()` as the default behaviour of your module.
Answered by skqr
Solution #5
If you only want to execute tests from a certain class, use the following command:
if __name__ == "__main__":
unittest.main(MyCase())
In Python 3.6, it works for me.
Answered by Bohdan
Post is based on https://stackoverflow.com/questions/15971735/running-a-single-test-from-unittest-testcase-via-the-command-line