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

Python:运行unittest.TestCase而不调用unittest.main()?,python,python-2.7,unit-testing,command-line-arguments,python-unittest,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.

我已经用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))
使用将输出格式化为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运行脚本是可行的,但使用-junit调用脚本与unittest的参数冲突:

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。在您的具体情况下,我将使用:


请注意,我从参数解析器中删除了-help,因此-junit选项变为隐藏,但它将不再干扰unittest.main。我还将剩余的参数传递给unittest.main。

File/usr/local/ceral/python/2.7.5/Frameworks/python.framework/Versions/2.7/lib/python2.7/unittest/main.py,第93行,在_uinit__; self.progName=os.path.basenameargv[0]索引器中:列表索引超出范围感谢修复。它与-junit一起工作,但如果没有它,我将在0.000秒内运行0个测试。@AdamMatan:删除testrepolits参数?非常感谢。我想我真的应该研究一下鼻子,以便将来进行测试。下面是此解决方案的另一个变体:
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)