0

我寫了一個小的測試套件Python的單元測試:Python:運行unittest.TestCase而不調用unittest.main()?

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?

回答

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

+0

'File「/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/main.py」,第93行,在__init__ self中。 progName = os.path.basename(argv [0]) IndexError:列表索引超出範圍' –

+0

@AdamMatan:updated; 'main()'期望我猜的是完整的argv。 –

+0

感謝您的修復。它可以使用'--junit',但沒有它,我會得到'0.000在0.000秒的測試。 –

相關問題