在Python中包装unittest TestCases

时间:2013-08-07 09:27:16

标签: python unit-testing python-unittest

您好我正在尝试根据自己的需要调整Python的标准unittest库。 到目前为止,一切都是实验性的,我想知道我做错了什么,所以这是我的代码:

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文档中读到的内容,行unittest.TextTestResult().run(self.suite)应该在套件上运行测试用例。

我做错了什么,或者只是我包装测试用例的方式不可行。

提前致谢。

2 个答案:

答案 0 :(得分: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。第一个是用于打开或关闭测试的长描述的布尔值,第二个用于调整详细程度。

答案 1 :(得分: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()

使用 *主题,您现在不会收到错误。