| 1 | import functools |
| 2 | import types |
| 3 | |
| 4 | from ._itertools import always_iterable |
| 5 | |
| 6 | |
| 7 | def parameterize(names, value_groups): |
| 8 | """ |
| 9 | Decorate a test method to run it as a set of subtests. |
| 10 | |
| 11 | Modeled after pytest.parametrize. |
| 12 | """ |
| 13 | |
| 14 | def decorator(func): |
| 15 | @functools.wraps(func) |
| 16 | def wrapped(self): |
| 17 | for values in value_groups: |
| 18 | resolved = map(Invoked.eval, always_iterable(values)) |
| 19 | params = dict(zip(always_iterable(names), resolved)) |
| 20 | with self.subTest(**params): |
| 21 | func(self, **params) |
| 22 | |
| 23 | return wrapped |
| 24 | |
| 25 | return decorator |
| 26 | |
| 27 | |
| 28 | class Invoked(types.SimpleNamespace): |
| 29 | """ |
| 30 | Wrap a function to be invoked for each usage. |
| 31 | """ |
| 32 | |
| 33 | @classmethod |
| 34 | def wrap(cls, func): |
| 35 | return cls(func=func) |
| 36 | |
| 37 | @classmethod |
| 38 | def eval(cls, cand): |
| 39 | return cand.func() if isinstance(cand, cls) else cand |