[Distutils] unit test support for distutils

Fred L. Drake, Jr. fdrake@acm.org
Fri Apr 27 00:35:00 2001

Content-Type: text/plain; charset=us-ascii
Content-Description: message body and .signature
Content-Transfer-Encoding: 7bit

  I'm sure others have taken a stab at this, but I'd like to suggest
that we include some support for a standard test command for
setup.py.  I've attached the command I've been playing with, but would
love to hear other suggestions as well.
  Drop the attached file into the standard library as
distutils/command/test.py.  It adds the command "test" parallel to the
"build" and "install" commands.  It expects a directory named "test"
parallel to the setup.py script; that directory is searched for Python
module files named test_*.py.  Each such module is imported; if a
callable named test_suite() is found, it should return a
unittest.TestSuite instance that can be run.  I'm sure there's a
better way to report failures, but I haven't had time to dig that
deeply into the distutils yet.


Fred L. Drake, Jr.  <fdrake at acm.org>
PythonLabs at Digital Creations

Content-Type: text/x-python
Content-Description: test command for distutils
Content-Disposition: inline;
Content-Transfer-Encoding: 7bit


Implements the Distutils 'test' command.

import glob
import os
import sys
import unittest

from distutils.core import Command

class test(Command):

    # Brief (40-50 characters) description of the command
    description = "Run the test suite for the package."

    # List of option tuples: long name, short name (None if no short
    # name), and help string.
    user_options = [#('', '',
                    # ""),

    def initialize_options(self):
        self.test_dirs = None

    def finalize_options(self):
        if self.test_dirs is None:
            self.test_dirs = ["test"]

    def run(self):
        errors = failures = 0
        for dir in self.test_dirs:
            for filename in glob.glob(os.path.join(dir, "test_*.py")):
                self.announce("running test from " + filename)
                info = self._run_test(filename)
                errors = errors + info[0]
                failures = failures + info[1]
        if errors or failures:
            self.announce("%d errors and %d failures" % (errors, failures))

    def _run_test(self, filename):
        # make sure the file's directory is on sys.path so we can import.
        dirname, basename = os.path.split(filename)
        sys.path.insert(0, dirname)
            modname = os.path.splitext(basename)[0]
            mod = __import__(modname)
            if hasattr(mod, "test_suite"):
                suite = mod.test_suite()
                runner = unittest.TextTestRunner(stream=open("/dev/null", 'w'))
                results = runner.run(suite)
                return len(results.errors), len(results.failures)
                return (0, 0)
            if sys.path[0] == dirname:
                del sys.path[0]