Python 2.6 – Subclassing unittest.TestCase

“I need to write a lot of system and component integration tests. Many of them will involve hitting the database, getting a result set and transforming it into XML/JSON/something else. I´ll need to create some flat files which contain expected results for these kind of tests. It would help me immensly if I had some utility classes to help me out with the reading/parsing/transforming of said utility functions.”
The above is what I should have thought to myself a few weeks back. Naturally, I didn’t. So I began creating test cases with their own utility functions included. Shortly afterwards this way of doing things revealed itself to be silly, and bad. So I went through several rounds of refactoring, and ended up with some utility classes.
Now I want to subclass unittest.TestCase and include all my utility classes in every test case I write.

First attempt:

Code example will go here if I’m ever able to locate it (I started this post a year ago, got distracted and then forgot about it. The code examples I had prepared at the time are now long gone…)

Resulting error:

method __init__ takes 2 parameters only 1 provided

eh? …
Cue head scratching session.
Followed by a bit of googling. Didn’t quite find what I was looking for, though.

This last solution seemed great on paper, but multiple inheritance and calling functions in (one of) the super class(es) proved to be bafflingly complicated. I’m using jython/python 2.6, apparently multiple inheritance has been revamped in python 3.0 (but I’m stuck with 2.6 so I’ll never know).

Cue second head scratching session.

I decide to enlist the help of the resident genius on the project and he came up with the following snippet (took him a fair few tries though, which is why I’ve deemed it worthy of being posted here):

from my.testUtilities import DBMock
from my.testUtilities import JSONHelper
import unittest

class MyTest(unittest.TestCase):
    def __init__(self, methodName='runTest'):
        unittest.TestCase.__init__(self, methodName)
        self.DBMock = DBMOCK

Job done.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s