Python:运行unittest.TestCase而不调用unittest.main()?

时间:2013-06-23 10:14:14

标签: python python-2.7 unit-testing command-line-arguments python-unittest

我在Python的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 xmlrunner pacakge将输出格式化为Junit测试。

我添加了一个用于切换JUnit输出的命令行参数:

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的情况下运行脚本有效,但调用它--junitunittest的参数冲突:

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?

1 个答案:

答案 0 :(得分:7)

你真的应该使用一个合适的测试运行器(例如nosezope.testing)。在您的具体情况下,我会改为使用argparser.parse_known_args()

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