ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Lightweight Unittester
Submitter: Raymond Hettinger (other recipes)
Last Updated: 2008/05/08
Version no: 1.0
Category: Debugging

 

5 stars 1 vote(s)


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

    # 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)

    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


#################################
## Example of the tester in action

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



Add comment

Number of comments: 1

Similar goals, Justin Shaw, 2008/05/13
I had a similar idea, check out the related recipies:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/113408
and
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/125385
Add comment



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. Treat the Win32 Registry ...

4. Watching a directory ...

5. Union Find data structure

6. Function Decorators by ...

7. MS SQL Server log monitor

8. Table objects with ...

9. wx twisted support using ...

10. More accurate sum




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.