unittest and automatically firing off tests

Steven Taschuk staschuk at telusplanet.net
Sat Jun 21 16:54:33 CEST 2003


Quoth Tom Plunket:
  [...]
> 1) Why in the name of all that is holy does unittest.main() throw
>    regardless of tests passing?

unittest.main is not intended for use other than
    if __name__ == '__main__':
        unittest.main()
and in this use, raising SystemExit is fine.

> 2) Why can't I readily pass a list of tests to unittest.main()? 
>    (I mean, besides the fact that it's not implemented; was this
>    a concious ommision?)

unittest.main is just a convenience function for the most common
case; if you want fancier things, you'll have to write them
yourself.  The module does have facilities to make this easy:

    def suite(dirname):
        """Create a TestSuite for the test files in the given directory."""
        suite = unittest.TestSuite()
        for filename in glob.glob(os.path.join(dirname, 'test_*.py')):
            modname = os.path.splitext(os.path.basename(filename))[0]
            modfile = file(filename)
            try:
                mod = imp.load_module(modname, modfile, filename,
                                      ('.py', 'r', imp.PY_SOURCE))
            finally:
                modfile.close()
            modsuite = unittest.defaultTestLoader.loadTestsFromModule(mod)
            suite.addTest(modsuite)
        return suite

    if __name__ == '__main__':
        runner = unittest.TextTestRunner()
        result = runner.run(suite('.'))
        if result.wasSuccessful():
            sys.exit(0)
        else:
            sys.exit(1)

(Untested.)

> 3) I feel like I should automatically batch up tests and fire
>    them off to unittest.run() or something similar.  Is this as
>    straight-forward and easy, and could I batch them all into one
>    mega-suite?  Are there any reasons why I wouldn't want to do
>    that?

Putting all your tests in a suite and running that suite is
entirely proper.  See above.

-- 
Steven Taschuk             "[W]e must be very careful when we give advice
staschuk at telusplanet.net    to younger people: sometimes they follow it!"
                             -- "The Humble Programmer", Edsger Dijkstra





More information about the Python-list mailing list