Fizi
Fizi

Reputation: 1851

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.

Upvotes: 7

Views: 4919

Answers (1)

Henry Keiter
Henry Keiter

Reputation: 17168

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.

Upvotes: 8

Related Questions