2016-11-02 63 views
0

我寫一些測試,其中使用Python單元測試包(Python 2.7版) 和我在很大程度上依賴於xmlrunner.XMLTestRunner轉儲XML測試輸出傳遞參數給unittest.TestSuite和使用xmlrunner.XMLTestRunner

不幸,我找不到一些基本的例子,它描述瞭如何將一些命令行選項傳遞給測試類來參數化一些測試。 有人對我如何實現這一點(使用xmlrunner)有一些暗示嗎?

另外,這裏是我儘量做到: 我定義我的測試在一組類在以下myunittest.py文件:

import unittest 
class TestOne(unittest.TestCase): 
    def __init__(self, options=None): 
     unittest.TestCase.__init__(self) 
     self.__options = options 
    def A(self): 
     print self.__options.configXML # try to print the parameter 
     self.assertEqual(1, 1) 

,並從主要調用它。 py看起來像:

from optparse import OptionParser 
import unittest 
import xmlrunner 
from uitest import * 

def runit(opt): 
    suite = unittest.TestSuite() 
    suite.addTest(TestOne(options=opt)) 
    testrunner = xmlrunner.XMLTestRunner(output='tests', descriptions=True) 
    unittest.main(testRunner=testrunner).run(suite) 

if __name__ == "__main__": 
    parser = argparse.ArgumentParser(add_help=False) 
    parser.add_argument("-c", "--configXML", dest="configXML", help="xml file") 
    options = parser.parse_args() 
    runit(opt=options) 

非常感謝您的寶貴幫助。

回答

0

經過幾個小時試圖弄清楚,我來到這個解決方案,這使我的一天。我在這裏發佈它,以防有人遇到同樣的問題。 主要缺點是它似乎我需要在同一個python文件中包含所有內容。與test.py

python test.py --xmlConfig=configFile.xml --xmlRunner 

:我運行它像

import unittest 
import sys 
from optparse import OptionParser 
import xmlrunner 

class MyTests(unittest.TestCase): 
    def testFirstThing(self): 
     xmlConfig=options.xmlConfig 
     self.assertEqual(xmlConfig,"configFile.xml") 

if __name__ == '__main__': 
    parser = OptionParser() 
    parser.add_option("--xmlRunner", "--xmlRunner", help="perform a unittest and generate XML", dest="xmlRunner", default=False, action='store_true') 
    parser.add_option("--xmlConfig", "--xmlConfig", type="string", help="configuration file", dest="xmlConfig", default="config.xml") 

    options, arguments = parser.parse_args() 
    if options.xmlRunner: 
     del sys.argv[1:] 
     unittest.main(testRunner=xmlrunner.XMLTestRunner(output='./xml'))