Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a specific unit tests in Python from main()

I am trying to run only a single test from the unit tests provided in a class. So assuming

class MytestSuite(unittest.TestCase):
    def test_false(self):
        a = False
        self.assertFalse(a, "Its false")

    def test_true(self):
        a = True
        self.assertTrue(a, "Its true")

I would like to run only test_false. Based on the Q&A provided on this site and online, I used the following lines of code in my main class

if __name__ == "__main__":  # Indentation was wrong
    singletest = unittest.TestSuite()
    singletest.addTest(MytestSuite().test_false)
    unittest.TextTestRunner().run(singletest)

I keep getting errors while trying to add the test. Mainly:

File "C:\Python27\Lib\unittest\case.py", line 189, in init
(self.class, methodName))
ValueError: no such test method in <class 'main.MytestSuite'>: runTest

Do I need a specific runTest method in my class? Is there a way to run particular tests that may belong to different suites? For example, method A belonging to suite class 1 and method B belonging to suite class 2. Surprisingly this has proven to be a difficult thing to find online. There are multiple examples of doing it through the command line, but not from the program itself.

like image 844
Fizi Avatar asked Apr 18 '16 19:04

Fizi


1 Answers

You're just passing the wrong thing to addTest. Rather than passing in a bound method, you need to pass a new instance of TestCase (in your case, an instance of MyTestSuite), constructed with the name of the single test you want it to run.

singletest.addTest(MyTestSuite('test_false'))

The documentation has a great deal of additional information and examples on this.

like image 132
Henry Keiter Avatar answered Sep 23 '22 14:09

Henry Keiter