unittest.main() python如何执行_Python:运行unittest.TestCase而不调用unittest.main()?...

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

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值