Skip to content

Instantly share code, notes, and snippets.

@Mause
Created June 8, 2015 19:05
Show Gist options
  • Save Mause/d875f1f3c98b875a492a to your computer and use it in GitHub Desktop.
Save Mause/d875f1f3c98b875a492a to your computer and use it in GitHub Desktop.
Simple parametrized test case implementation
import unittest
from functools import wraps
def parametrized_class(klass):
for name, thing in list(vars(klass).items()):
if not hasattr(thing, 'cases'):
continue
cases = thing.cases
cases = (
# handle labelled cases
cases.items() if isinstance(cases, dict)
else enumerate(cases)
)
for label, case in cases:
@wraps(thing) # default parameters & fun with python :P
def wrapper(self, thing=thing, case=case, *args, **kw):
return thing(self, case, *args, **kw)
func_name = '{}_{}'.format(name, label)
wrapper.__name__ = func_name
setattr(klass, func_name, wrapper)
delattr(klass, name) # remove original
return klass
def parametrized_def(cases):
def decorator(func):
func.cases = cases
return func
return decorator
def parametrized(thing):
if isinstance(thing, type):
return parametrized_class(thing)
else:
return parametrized_def(thing)
@parametrized
class Random(unittest.TestCase):
@parametrized([0, 0, 1])
def test_thing(self, case):
self.assertEqual(
case,
1
)
@parametrized({
"failed_first": 0,
"failed_second": 0,
"succeed": 1
})
def test_thingo(self, case):
self.assertEqual(
case,
1
)
if __name__ == '__main__':
unittest.main()
C:\Users\Dominic\Dropbox\temp\knwl>python test_param.py -v
test_thing_0 (__main__.Random) ... FAIL
test_thing_1 (__main__.Random) ... FAIL
test_thing_2 (__main__.Random) ... ok
test_thingo_failed_first (__main__.Random) ... FAIL
test_thingo_failed_second (__main__.Random) ... FAIL
test_thingo_succeed (__main__.Random) ... ok
----------------------------------------------------------------------
Ran 6 tests in 0.018s
FAILED (failures=4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment