loki
loki

Reputation: 2311

Wrapping unittest TestCases in Python

Hi I'm trying to tweak Python's standard unittest library to my own needs. So far everything is experimental and I want to know if I'm doing something wrong, so here is my code:

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()

If I run this piece of code I get the following error:

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

According to what I've read from the unittest documentation the line unittest.TextTestResult().run(self.suite) should run the test cases on the suite.

Am I doing something wrong or it's just that the way I'm wrapping the test cases is not viable.

Thanks in advance.

Upvotes: 0

Views: 1645

Answers (2)

Nilesh
Nilesh

Reputation: 2555

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()

Use *subject, You will not get error now.

Upvotes: 2

Duncan
Duncan

Reputation: 95742

When in doubt with Python, check the standard library source.

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

So the missing parameters are descriptions and verbosity. The first is a boolean to turn on or off long descriptions of the tests, the second adjusts verbosity.

Upvotes: 2

Related Questions