I do not know any built-in functions for this in any general testing framework. The only problem with your solution is that the iteration is inside the test. Rather, it should be outside and generate tests, maybe something like this
import unittest def _apply(func, args): """Return a function with args applied after first argument""" def wrapped(self): return func(self, *args) return wrapped class TheoryMeta(type): """Metaclass that replaces test methods with multiple methods for each test case""" def __new__(meta, name, bases, attrs): newattrs = {} cases = attrs.pop('cases', []) for name, value in attrs.items(): if not name.startswith('test') or not callable(value): newattrs[name] = value continue for n, args in enumerate(cases): test_name = '%s_%d' % (name, n) newattrs[test_name] = _apply(value, args) return super().__new__(meta, name, bases, newattrs) class TestCase(unittest.TestCase, metaclass=TheoryMeta): pass
Then, to use it, create a subclass of TestCase that has the cases attribute, which is a list of arguments that apply to each test method in the test case.
class TestAdd(TestCase): cases = [
Depending on your needs and test setup, you can better use only those test methods developed with monkey patches in TestCase, instead of using a metaclass. Or you can generate them by overriding loadTestsFrom ... in TestLoader . In any case, use sample data to generate test methods.
source share