Python: run a unittest.TestCase without calling unittest.main()?

我只是一个虾纸丫 提交于 2020-01-07 06:24:09

问题


I've written a small test suite in Python's unittest:

class TestRepos(unittest.TestCase):

@classmethod
def setUpClass(cls):
    """Get repo lists from the svn server."""
    ...

def test_repo_list_not_empty(self):
    """Assert the the repo list is not empty"""
    self.assertTrue(len(TestRepoLists.all_repos)>0)

def test_include_list_not_empty(self):
    """Assert the the include list is not empty"""
    self.assertTrue(len(TestRepoLists.svn_dirs)>0)

...

if __name__ == '__main__':
    unittest.main(testRunner=xmlrunner.XMLTestRunner(output='tests', 
                                                 descriptions=True))

The output is formatted as Junit test using the xmlrunner pacakge.

I've added a command line argument for toggling JUnit output:

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Validate repo lists.')
    parser.add_argument('--junit', action='store_true')
    args=parser.parse_args()
    print args
    if (args.junit):
        unittest.main(testRunner=xmlrunner.XMLTestRunner(output='tests', 
                                                     descriptions=True))
    else:
        unittest.main(TestRepoLists)

The problem is that running the script without --junit works, but calling it with --junit clashes with unittest's arguments:

option --junit not recognized
Usage: test_lists_of_repos_to_branch.py [options] [test] [...]

Options:
  -h, --help       Show this message
  -v, --verbose    Verbose output
  ...

How can I run a unittest.TestCase without calling unittest.main()?


回答1:


You really should use a proper test runner (such as nose or zope.testing). In your specific case, I'd use argparser.parse_known_args() instead:

if __name__ == '__main__':
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('--junit', action='store_true')
    options, args = parser.parse_known_args()

    testrunner = None
    if (options.junit):
        testrunner = xmlrunner.XMLTestRunner(output='tests', descriptions=True)
    unittest.main(testRunner=testrunner, argv=sys.argv[:1] + args)

Note that I removed --help from your argument parser, so the --junit option becomes hidden, but it will no longer interfere with unittest.main. I also pass the remaining arguments on to unittest.main().



来源:https://stackoverflow.com/questions/17259718/python-run-a-unittest-testcase-without-calling-unittest-main

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!