本文介绍了Python:运行unittest.TestCase而不调用unittest.main()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Python的单元测试中编写了一个小型测试套件:

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))

使用。

我添加了命令行AR切换JUnit输出的口香糖:

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)

问题是运行脚本时没有-junit 可以,但是用调用它–junit unittest 冲突s参数:

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
  ...

如何在不调用unittest.main()的情况下运行unittest.TestCase?

推荐答案

您确实应该使用适当的测试运行程序(例如 nose zope.testing )。在您的特定情况下,我将使用代替:

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)

请注意,我删除了-help 从您的参数解析器,因此-junit 选项被隐藏,但不再干扰 unittest.main 。我还将其余参数传递给 unittest.main()

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().

这篇关于Python:运行unittest.TestCase而不调用unittest.main()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 00:07