How do I run multiple Classes in a single test suite in Python using unit testing?

后端 未结 5 957
无人共我
无人共我 2021-02-01 03:09

How do I run multiple Classes in a single test suite in Python using unit testing?

5条回答
  •  暖寄归人
    2021-02-01 03:41

    Normally you would do in the following way (which adds only one class per suite):

    # Add tests.
    alltests = unittest.TestSuite()
    alltests.addTest(unittest.makeSuite(Test1))
    alltests.addTest(unittest.makeSuite(Test2))
    

    If you'd like to have multiple classes per suite, you can use add these tests in the following way:

    for name in testnames:
        suite.addTest(tc_class(name, cargs=args))
    

    Here is same example to run all classes per separate suite you can define your own make_suite method:

    # Credits: http://codereview.stackexchange.com/a/88662/15346
    def make_suite(tc_class):
        testloader = unittest.TestLoader()
        testnames = testloader.getTestCaseNames(tc_class)
        suite = unittest.TestSuite()
        for name in testnames:
            suite.addTest(tc_class(name, cargs=args))
        return suite
    
    # Add all tests.
    alltests = unittest.TestSuite()
    for name, obj in inspect.getmembers(sys.modules[__name__]):
        if inspect.isclass(obj) and name.startswith("FooTest"):
            alltests.addTest(make_suite(obj))
    
    result = unittest.TextTestRunner(verbosity=2).run(alltests)
    

    If above doesn't suite, you can convert above example into method which could accept multiple classes.

提交回复
热议问题