1# -*- coding: utf-8 -*- 2 3from __future__ import print_function, division 4 5 6class MetaTest(type): 7 """Helper metaclass to simplify dynamic test creation 8 9 Creates test_methods in the TestCase class dynamically named after the 10 arguments used. 11 """ 12 @staticmethod 13 def make_function(classname, *args, **kwargs): 14 def test(self): 15 # ### Body of the usual test_testcase ### # 16 # Override and redefine this method # 17 pass 18 19 # Title of test in report 20 test.__doc__ = "{0}".format(args[0]) 21 22 return test 23 24 def __new__(meta, classname, bases, dct): 25 tests = dct.get("TESTS") 26 kwargs = dct.get("EXTRA", {}) 27 28 for i, args in enumerate(tests): 29 func = meta.make_function(classname, *args, **kwargs) 30 31 # Rename the function after a unique identifier 32 # Name of function must start with test_ to be ran by unittest 33 func.__name__ = "test_{0}".format(i) 34 35 # Attach the new test to the testclass 36 dct[func.__name__] = func 37 38 return super(MetaTest, meta).__new__(meta, classname, bases, dct) 39 40# vim: ai sts=4 et sw=4 41