0

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

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)应该在套件上运行测试用例。

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

提前致谢。

4

2 回答 2

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。第一个是打开或关闭测试的长描述的布尔值,第二个调整详细程度。

于 2013-08-07T09:32:57.840 回答
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()

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

于 2013-10-15T11:03:53.187 回答