|
Description:
Inspired by py.test, the unittester is a single, simple function that is easily customized. The main virtue is that tests are much clearer than with the unittest.py.
Source: Text Source
def run_test_functions(source=None, stderr=None):
import sys, types, collections, functools
if source is None:
ns = globals()
elif isinstance(source, dict):
ns = dict(source)
else:
ns = vars(source)
if stderr is None:
stderr = sys.stderr
tests = [(name, func) for name, func in ns.items() if name.startswith('test_')]
tests = collections.deque(sorted(tests))
successes = failures = 0
while tests:
name, func = tests.popleft()
try:
rv = func()
except Exception, E:
failures += 1
print name, '...', repr(E)
else:
if isinstance(rv, types.GeneratorType):
pairs = []
for func, arg in rv:
gname = 'gen:%s(%r)' % (name, arg)
gfunc = functools.partial(func, arg)
pairs.append((gname, gfunc))
tests.extendleft(reversed(pairs))
else:
successes += 1
print name, '... Success'
result = (successes+failures, failures)
print 'Ran %d tests with %d failures' % result
return result
def test_sum():
assert sum(range(5)) == 10
def test_badsum():
assert sum(range(5)) == 12
def test_excpt():
raise IndexError(3)
def test_generative():
for x in (42,17,49):
yield check, x
def check(arg):
assert arg % 7 == 0
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()
print run_test_functions()
Discussion:
Supports the most popular features offered by py.test. See: http://codespeak.net/py/dist/test.html#starting-point-py-test-command-line-tool
Provides simply formatted output. For example, the example code above produces:
test_badsum ... AssertionError()
test_excpt ... IndexError(3,)
gen:test_generative(42) ... Success
gen:test_generative(17) ... AssertionError()
gen:test_generative(49) ... Success
test_setup_and_teardown ... Success
test_sum ... Success
Ran 7 tests with 3 failures
(7, 3)
Unlike py.test, the tool itself is very simple (a single 40 line function). Being so short, it is easily extended or altered to work with various test drivers and reporters.
The style of writing tests is *much* simpler than with the unittest.py module in the standard library. Compare the unittest.py style:
class TestStats(unittest.TestSuite):
def test_sum(self):
self.assertEqual(sum(range(5)), 10)
To the py.test style:
def test_sum():
assert sum(range(5)) == 10
|