My goal is to create a framework that is easier than command line testing with the benifit of automatic unittesting. That way there is simply no excuse for not testing.
-- Based on Bruce Eckels Java class UnitTest (see BruceEckel.com /Thinking in Patterns/). -- Best when combined with <a href="http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/113408">pretest.py</a>
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 | # mircotest.py
import sys
import traceback
class TestException(Exception): pass
def test(modulename, verbose=None, log=sys.stdout):
'''Execute all functions in named module with __test__ in the name
that take no arguments
modulename -- name of the module to be tested.
verbose -- If true print sequence of test names as they are executed
Returns None on success, raises exception on failure.'''
module = __import__(modulename)
total_tested = 0
total_failed = 0
for name in dir(module):
if name.find('__test__') >= 0:
if type(module.__dict__[name]) == type(unittest):
if (module.__dict__[name].func_code.co_argcount) == 0:
if verbose:
print >> log, 'Testing %s' % name
try:
total_tested += 1
module.__dict__[name]()
except Exception, e:
total_failed += 1
print >> sys.stderr, '%s.%s FAILED' % (modulename, name)
traceback.print_exc()
message = 'Module %s failed %s out of %s unittests.' %\
(modulename, total_failed, total_tested)
if total_failed > 0:
raise TestException(message)
if verbose:
print >> log, message
def __test__():
print 'in __test__'
import pretest
pretest.pretest('microtest', 1)
|
The extreme programming philosophy urges programmers to do the Simplest thing that could possibility work. For my purposes this works.
I usually use pretest.pretest to call microtest.test to insure tests are run only when the module is compiled.
Use __import__ rather than exec. The line
can be replaced by
Using exec will significantly affect the performance of the program.
Thanks, got it. Thanks for the suggetion; change applied.
there is no unittest type. Hi.
You are typechecking on
statement, but python has no builtin unittest type and the code stops.
Please let me know how you are running this test suits.
Hello
Everything in Python is an object and thus has a type. type(unittest) returns the module type. The code fails here because the import of unittest has been forgotten.
Cheers