decorators to add test* TestCase methods
Duncan Booth
duncan.booth at invalid.invalid
Fri Jan 27 08:07:58 EST 2006
Bruce Cropley wrote:
> Hi all
>
> I'm trying to generate test methods in a unittest TestCase
> subclass, using decorators. I'd like to be able to say:
>
> class MyTestCase(unittest.TestCase):
> @genTests(["Buy", "Sell"], [1,2,3], [True, False])
> def something(self, side, price, someFlag):
> # etc...
>
I would make the decorator simply save its arguments as attributes on the
function and then add an explicit call after the class has been created to
go and generate the tests.
so (untested code):
def generateTests(klass):
for name in dir(klass):
fn = getattr(klass, name)
if hasattr(fn, 'genTests'):
# generate tests here...
def genTests(*args):
def decorator(f):
f.genTests = args
return f
return decorator
and then:
class MyTestCase(unittest.TestCase):
@genTests(["Buy", "Sell"], [1,2,3], [True, False])
def something(self, side, price, someFlag):
# etc...
generateTests(MyTestCase)
You could automate the call to generateTests using a metaclass if you
wanted to avoid the explicit call.
More information about the Python-list
mailing list