Search code examples
pythonpython-unittest

Run a specific unittest with loadTestsFromName


I want to run a single test and output the result to a txt file. I understood that I can use loadTestsFromName to specify the test. However, I'm getting an error.

test.py

import unittest
import sys
import os

def main(out=sys.stderr, verbosity=2):
    loader = unittest.TestLoader()
    suite = loader.loadTestsFromName(sys.modules[__name__]=='test1')
    unittest.TextTestRunner(out, verbosity=verbosity).run(suite)


class TestClass(unittest.TestCase):
    def test1(self):
        self.assertEqual(True, True)

if __name__ == '__main__':
    with open('test-results.txt', 'w') as f:
        main(f)

I run the test by executing python test.py

I'm not sure how to get test1. I tried sys.modules[__name__]=='test1' but it triggered this error.

parts = name.split('.')
AttributeError: 'bool' object has no attribute 'split'

Solution

  • According to the python doc-unittest.TestLoader.loadTestsFromName, below code is work for me.

    import unittest
    import sys
    import os
    
    
    def main(out=sys.stderr, verbosity=2):
        loader = unittest.TestLoader()
        suite = loader.loadTestsFromName('__main__.TestClass.test1')
        unittest.TextTestRunner(out, verbosity=verbosity).run(suite)
    
    
    class TestClass(unittest.TestCase):
        def test1(self):
            self.assertEqual(True, True)
    
    
    if __name__ == '__main__':
        with open('test-results.txt', 'w') as f:
            main(f)
    

    Besides, you'd better separate the TestCase to the single module, then change the __main__ to the module name.