Monday 2 February 2009

Generic constructor assertion

It is quite common to write such initializers:

class Foo(object):
def __init__(self, a, b):
self.a = a
self.b = b
Why not test it in a generic way?
import inspect

def assert_simple_constructor(klass):
allargs = inspect.getargspec(klass.__init__)[0]
args = allargs[1:] # skipping self
instance = klass(*args)
for argname in args:
assert hasattr(instance, argname) # skipped the message
assert getattr(instance, argname) == argname # to keep short