Fix Python – __init__ for unittest.TestCase

Question

Asked By – ffledgling

I’d like to add a couple of things to what the unittest.TestCase class does upon being initialized but I can’t figure out how to do it.

Right now I’m doing this:

#filename test.py

class TestingClass(unittest.TestCase):

    def __init__(self):
        self.gen_stubs()

    def gen_stubs(self):
        # Create a couple of tempfiles/dirs etc etc.
        self.tempdir = tempfile.mkdtemp()
        # more stuff here

I’d like all the stubs to be generated only once for this entire set of tests. I can’t use setUpClass() because I’m working on Python 2.4 (I haven’t been able to get that working on python 2.7 either).

What am I doing wrong here?

I get this error:

 `TypeError: __init__() takes 1 argument (2 given)` 

…and other errors when I move all of the stub code into __init__ when I run it with the command python -m unittest -v test.

Now we will see solution for issue: __init__ for unittest.TestCase


Answer

Try this:

class TestingClass(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        super(TestingClass, self).__init__(*args, **kwargs)
        self.gen_stubs()

You are overriding the TestCase‘s __init__, so you might want to let the base class handle the arguments for you.

This question is answered By – karthikr

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0