Ada*_*tan 0 python unit-testing command-line-arguments python-2.7 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))
Run Code Online (Sandbox Code Playgroud)
使用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)
Run Code Online (Sandbox Code Playgroud)
问题是运行脚本没有--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
...
Run Code Online (Sandbox Code Playgroud)
如何在不调用unittest.main()的情况下运行unittest.TestCase?
你真的应该使用一个合适的测试运行器(例如nose或zope.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)
Run Code Online (Sandbox Code Playgroud)
请注意,我--help从您的参数解析器中删除了,因此该--junit选项变为隐藏,但它将不再干扰unittest.main.我还将剩下的论点传递给了unittest.main().