2013-08-07 38 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() 

使用*受,你不会现在得到的错误。