Tuesday, September 22, 2009

I'm tired of typing "self." before every assert method in a python unit test

If you've spent anytime using the python unittest framework, and you have any appreciation for things being succinct, perhaps you will find something useful in this approach to co-opting the basic assert methods and making them available in a global context (as opposed to them only being available on the TestCase instance (through a 'self.' reference). It seems safe enough since these methods are generally not using a lot of instance state anyway -- just raising a particular exception. Enough talk. Here's the stuff:

class FakeTest(unittest.TestCase):
only purpose is to provide a surrogate for providing global assert methods below
def testNothing(self):

assertMethodStealerTestCaseInstance = FakeTest(methodName='testNothing')

assertEquals = assertEqual = assertMethodStealerTestCaseInstance.assertEqual
assertNotEquals = assertNotEqual =assertMethodStealerTestCaseInstance.assertNotEqual

After typing 'self.assert...' hundreds of times, I can attest that that 10 lines is well worth it - besides the typing, it makes your tests easier to read too!

1 comment:

Matt said...

revised to not use functools at all ... even simpler...