0

Please see the code below. I was trying to implement a test suite for my project

import unittest
class TestClass1(unittest.TestCase):
    def test_1_first(self):
        print("First test case")

    def test_2_second(self):
        print("Second test case")

class TestClass2(unittest.TestCase):
    def test_3_third(self):
        print("Third test case")

    def test_4_fourth(self):
        print("Fourth test case")

if __name__ == "__main__":
    # val = 1        <-- getting from user
    # if val == 1:
    #    Execute test cases in TestClass2
    # else
    #    Execute test cases in TestClass1\
    unittest.main()

I will get the class name as command line argument and I need to run each class of test according to the argument. Means I need to select and run some classes of test cases on runtime. So can any one help me to prevent a class from unit test execution at runtime? The problem is It's not allowed to use the method like passing class name while execution

shafeeq
  • 1,499
  • 1
  • 14
  • 30

2 Answers2

2

unittest.main() already parses sys.argv to allow the running of specific classes or individual tests.

For example, if your script is named test.py, you can run the following to run just TestClass1:

python test.py __main__.TestClass1

Or the following to run just TestClass1.test_1_first:

python test.py __main__.TestClass1.test_1_first

If you wish to do it in your script, you can pass the name of test you want to run as the defaultTest argument:

unittest.main(defaultTest='__main__.TestClass1')
blhsing
  • 91,368
  • 6
  • 71
  • 106
1

That is already built-in. You can run specific class via command:

python -m unittest test_module.TestClass1

If you really need to do it in your scpript, you can pass your classes to unittest.TestLoader().loadTestsFromName and then run test suite with unittest.TextTestRunner().run(suite). It will look something like this:

test_suite = unittest.TestLoader().loadTestsFromName('__main__.TestClass1')
unittest.TextTestRunner().run(test_suite)
Denis Fetinin
  • 1,746
  • 1
  • 9
  • 15