Test functions and test discovery (was: Re: Is there a better way of accessing functions in a module?)

Ben Finney bignose+hates-spam at benfinney.id.au
Tue Jun 13 17:54:28 EDT 2006


"Ant" <antroy at gmail.com> writes:

> def a_test():
>     print "Test A"
> 
> def b_test():
>     print "Test B"

Incidentally, the convention is to name test functions as 'test_foo'
not 'foo_test'; this will make your module more easily compatible with
existing testing tools.

> if __name__ == "__main__":
>     tests = ["%s()" % x for x in dir() if x.endswith("test")]
> 
>     for test in tests:
>         eval(test)

No need for eval. (You already found globals(), so I'll use that.)

    if __name__ == "__main__":
        test_funcs = [x for name, x in globals()
            if name.startswith("test") and hasattr(x, "__call__")
        ]

        for test in test_funcs:
            test()

I'll concur with other posters on this thread and encourage you to
consider using the standard 'unittest' module, and recommend 'nose'
for test discovery and execution:

    <URL:http://somethingaboutorange.com/mrl/projects/nose/>

-- 
 \     "Unix is an operating system, OS/2 is half an operating system, |
  `\       Windows is a shell, and DOS is a boot partition virus."  -- |
_o__)                                                  Peter H. Coffin |
Ben Finney




More information about the Python-list mailing list