【问题标题】:Python: run a unittest.TestCase without calling unittest.main()?Python:在不调用 unittest.main() 的情况下运行 unittest.TestCase?
【发布时间】:2013-06-20 00:42:50
【问题描述】:

我在 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 的情况下运行脚本可以工作,但使用--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?

【问题讨论】:

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


    【解决方案1】:

    您确实应该使用合适的测试运行程序(例如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()

    【讨论】:

    • File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/main.py", line 93, in __init__ self.progName = os.path.basename(argv[0]) IndexError: list index out of range
    • 感谢您的修复。它适用于--junit,但没有它我会得到Ran 0 tests in 0.000s
    • @AdamMatan:删除TestRepoLists 参数?
    • 非常感谢。我想我真的应该看看nose 以备将来测试。
    • 这是此解决方案的另一种变体:stackoverflow.com/a/8660290/366698
    猜你喜欢
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 1970-01-01
    • 2013-08-22
    相关资源
    最近更新 更多