Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a single test from unittest.TestCase via the command line

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, I do 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, for example, 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.

like image 679
Alois Mahdal Avatar asked Apr 12 '13 12:04

Alois Mahdal


People also ask

How do I run unittest from command line?

The command to run the tests is python -m unittest filename.py . In our case, the command to run the tests is python -m unittest test_utils.py .

How do I run a unittest test?

If you're using the PyCharm IDE, you can run unittest or pytest by following these steps: In the Project tool window, select the tests directory. On the context menu, choose the run command for unittest . For example, choose Run 'Unittests in my Tests…'.

How do I run a python test in terminal?

Calling pytest through python -m pytest You can invoke testing through the Python interpreter from the command line: python -m pytest [...] This is almost equivalent to invoking the command line script pytest [...] directly, except that calling via python will also add the current directory to sys.


1 Answers

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

python testMyCase.py MyCase.testItIsHot 
like image 83
phihag Avatar answered Oct 03 '22 20:10

phihag