This is recipe 572194 from Raymond HETTINGER with a little decorator to get timings on tested functions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | import sys
from types import GeneratorType
from time import clock as sysTime
def timedeco(fct):
def wrapper(*a, **k):
start=sysTime()
retval=fct(*a, **k)
elapsed=sysTime()-start
return (retval, elapsed)
return wrapper
@timedeco
def run_test_functions(source=None):
# source can be module, class, None, or a dictionary
if source is None:
ns = globals()
elif isinstance(source, dict):
ns = dict(source)
else:
ns = vars(source)
tests = [(name, func) for name, func in ns.items() if name.startswith('test_')]
tests = sorted(tests, reverse=True)
failures = 0
while tests:
name, func = tests.pop()
try:
rv, et = timedeco(func)()
except Exception, E:
failures += 1
print 'Err %s : %r ' % (name, E)
else:
if isinstance(rv, GeneratorType):
pairs = []
for func, arg in rv:
gname = '%s(%r)' % (func.__name__, arg)
gfunc = lambda func=func, arg=arg: func(arg)
pairs.append((gname, gfunc))
tests.extend(reversed(pairs))
else:
print 'Ok %s : %.2G s' % (name, et)
return failures
if __name__=='__main__':
def test_sum():
assert sum(range(5)) == 10
def test_badsum():
assert sum(range(5)) == 12, 'Bad Sum'
def test_excpt():
raise IndexError(3)
def test_generative():
x=1
while x<10000000:
x*=10
yield sum_range, x
def sum_range(arg):
s=sum(range(arg))
def td_setup():
global g
g = 1
def td_teardown():
global g
del g
def test_setup_and_teardown():
td_setup()
assert g == 1
td_teardown()
def test_att():
a=b
print '\n %i Err, %.2G s' % run_test_functions()
|
Here is the output of the test above :
Err test_att : NameError("global name 'b' is not defined",)
Err test_badsum : AssertionError('Bad Sum',)
Err test_excpt : IndexError(3,)
Ok sum_range(10) : 0 s
Ok sum_range(100) : 0 s
Ok sum_range(1000) : 0 s
Ok sum_range(10000) : 0 s
Ok sum_range(100000) : 0.02 s
Ok sum_range(1000000) : 0.2 s
Ok sum_range(10000000) : 2.2 s
Ok test_setup_and_teardown : 0 s
Ok test_sum : 0 s
3 Err, 2.5 s
see the original version : http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/572194