Skip to content

Instantly share code, notes, and snippets.

@VadimPushtaev VadimPushtaev/cases.py Secret
Last active Jun 27, 2019

Embed
What would you like to do?
class TestMetaClass(type):
def __new__(mcs, name, bases, dct):
for attr_name in dct.keys():
if hasattr(dct[attr_name], 'test_cases'):
cases = dct[attr_name].test_cases
del dct[attr_name].test_cases
hidden_name = '__' + attr_name
mcs._move_method(dct, attr_name, hidden_name)
for case in cases:
mcs._add_test_method(
dct, attr_name, hidden_name, case[0], case[1:]
)
return super(TestMetaClass, mcs).__new__(mcs, name, bases, dct)
@classmethod
def _move_method(mcs, dct, from_name, to_name):
dct[to_name] = dct[from_name]
dct[to_name].__name__ = str(to_name)
del dct[from_name]
@classmethod
def _add_test_method(mcs, dct, orig_name, hidden_name, postfix, params):
test_method_name = '{}__{}'.format(orig_name, postfix)
def test_method(self):
return getattr(self, hidden_name)(*params)
test_method.__name__ = str(test_method_name)
dct[test_method_name] = test_method
class BaseTestCase(TestCase):
__metaclass__ = TestMetaClass
@classmethod
def cases(cls, *cases):
"""
Create a bunch of test methods using the case table and test code.
Example. The following two pieces of code would behave identically:
@BaseTestCase.cases(['name1', 1], ['name2', 2])
def test_example(self, number):
self.assertGreater(number, 0)
def __test_example(self, number):
self.assertGreater(number, 0)
def test_example__name1(self):
return self.__test_example(1)
def test_example__name2(self):
return self.__test_example(2)
"""
def decorator(test_method):
test_method.test_cases = cases
return test_method
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.