Search code examples
python-unittesttest-suite

Python Unit-tests are running twice when run created test suite


[as I created test suite and generate a test report using HTMLTestRunner (Also modified little bit by me) single test run twice.] for that code (test suite) is:

import os
import time
import unittest
from xyz.base import log
from builtins import dir
from xyz.HTMLTestRunner import HTMLTestRunner

from xyz.tests.test.test_01 import TC01

class HTestSuite(unittest.TestCase):
    log.info('Running demo test suite')

    dir = os.getcwd()
    testLoad = unittest.TestLoader()
    log.info(dir)
    test_classes_to_run =[TC01]

    suites_list = []
    for test_class in test_classes_to_run:
        suite = testLoad.loadTestsFromTestCase(test_class)
        suites_list.append(suite)
    log.info(suites_list)
    newSuite = unittest.TestSuite(suites_list)
    log.info(newSuite.countTestCases())
    timestr = time.strftime("_%Y-%m-%d_%H.%M.%S")
    
    resultFile = open(os.path.join(dir, "TestReport"+ timestr + ".html"), "w")
    runner = HTMLTestRunner(stream=resultFile, title='test report', description='Tests Execution Report') 

    runner.run(newSuite)

if __name__ == "__main__":
    unittest.main()

Solution

  • You have the test runner code inside the test case - so your test will be executed by unittest.main, and then again by your own testrunner. You can replace unittest.main by your test runner code (and don't need HTestSuite):

    import os
    import time
    import unittest
    from xyz.base import log
    from builtins import dir
    from xyz.HTMLTestRunner import HTMLTestRunner
    
    from xyz.tests.test.test_01 import TC01
    
    if __name__ == "__main__":
        log.info('Running demo test suite')
    
        dir = os.getcwd()
        testLoad = unittest.TestLoader()
        log.info(dir)
        test_classes_to_run =[TC01]
    
        suites_list = []
        for test_class in test_classes_to_run:
            suite = testLoad.loadTestsFromTestCase(test_class)
            suites_list.append(suite)
        log.info(suites_list)
        newSuite = unittest.TestSuite(suites_list)
        log.info(newSuite.countTestCases())
        timestr = time.strftime("_%Y-%m-%d_%H.%M.%S")
        
        resultFile = open(os.path.join(dir, "TestReport"+ timestr + ".html"), "w")
        runner = HTMLTestRunner(stream=resultFile, title='test report', description='Tests Execution Report') 
    
        runner.run(newSuite)
    

    To run the tests, just use:

    python xyz\abc\def\demoTestSuite.py