2013-08-07 66 views
0

您好我正在嘗試根據自己的需要調整Python的標準單元測試庫。 到目前爲止,一切都處於實驗階段,我想知道如果我做錯事,所以這裏是我的代碼:在Python中包裝unittest TestCases

class Should(object): 
    def __init__(self, subject): 
     self.subject = subject 
     self.suite = unittest.TestSuite() 

    def run(self): 
     unittest.TextTestResult().run(self.suite) 

    def contain(self, elem): 
     subject = self.subject 
     class Contain(unittest.TestCase): 
      def test_contain(self): 
       self.assertIn(elem, subject) 
     self.suite.addTest(Contain('test_contain')) 

should = Should([1, 2, 3]) 
should.contain(1) 
should.run() 

如果我運行這段代碼,我得到以下錯誤:

unittest.TextTestResult().run(self.suite) 
TypeError: __init__() takes exactly 4 arguments (2 given) 

根據我從單元測試文檔中讀取的內容,行unittest.TextTestResult().run(self.suite)應該在套件上運行測試用例。

我做錯了什麼或只是我包裝測試用例的方式不可行。

在此先感謝。

回答

2

如果對Python有疑問,請檢查標準庫源代碼。

class TextTestResult(result.TestResult): 
    """A test result class that can print formatted text results to a stream. 

    Used by TextTestRunner. 
    """ 
    separator1 = '=' * 70 
    separator2 = '-' * 70 

    def __init__(self, stream, descriptions, verbosity): 
     super(TextTestResult, self).__init__() 
     self.stream = stream 
     self.showAll = verbosity > 1 
     self.dots = verbosity == 1 
     self.descriptions = descriptions 

因此丟失的參數是descriptionsverbosity。第一個是打開或關閉測試的長描述的布爾值,第二個調整詳細度。

2
class Should(object): 
    def __init__(self, *subject): 
     self.subject = subject 
     self.suite = unittest.TestSuite() 

    def run(self): 
     unittest.TextTestResult().run(self.suite) 

    def contain(self, elem): 
     subject = self.subject 
     class Contain(unittest.TestCase): 
      def test_contain(self): 
       self.assertIn(elem, subject) 
     self.suite.addTest(Contain('test_contain')) 

should = Should([1, 2, 3]) 
should.contain(1) 
should.run() 

使用*受,你不會現在得到的錯誤。