unittest.py 28.2 KB
Newer Older
1
#!/usr/bin/env python
2
'''
3 4 5 6 7 8
Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
Smalltalk testing framework.

This module contains the core framework classes that form the basis of
specific test cases and suites (TestCase, TestSuite etc.), and also a
text-based utility class for running the tests and reporting the results
Jeremy Hylton's avatar
Jeremy Hylton committed
9
 (TextTestRunner).
10

11 12 13 14 15 16 17 18
Simple usage:

    import unittest

    class IntegerArithmenticTestCase(unittest.TestCase):
        def testAdd(self):  ## test method names begin 'test*'
            self.assertEquals((1 + 2), 3)
            self.assertEquals(0 + 1, 1)
19
        def testMultiply(self):
20 21 22 23 24 25 26 27 28 29
            self.assertEquals((0 * 10), 0)
            self.assertEquals((5 * 8), 40)

    if __name__ == '__main__':
        unittest.main()

Further information is available in the bundled documentation, and from

  http://pyunit.sourceforge.net/

30
Copyright (c) 1999-2003 Steve Purcell
31 32 33 34 35 36 37 38 39 40 41 42 43 44
This module is free software, and you may redistribute it and/or modify
it under the same terms as Python itself, so long as this copyright message
and disclaimer are retained in their original form.

IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.

THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE.  THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
45
'''
46

47 48
__author__ = "Steve Purcell"
__email__ = "stephen_purcell at yahoo dot com"
49
__version__ = "#Revision: 1.63 $"[11:-2]
50 51 52 53 54

import time
import sys
import traceback
import os
55
import types
56

57 58 59 60 61 62
##############################################################################
# Exported classes and functions
##############################################################################
__all__ = ['TestResult', 'TestCase', 'TestSuite', 'TextTestRunner',
           'TestLoader', 'FunctionTestCase', 'main', 'defaultTestLoader']

63
# Expose obsolete functions for backwards compatibility
64 65 66
__all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])


67 68 69 70 71 72 73
##############################################################################
# Backward compatibility
##############################################################################
if sys.version_info[:2] < (2, 2):
    False, True = 0, 1
    def isinstance(obj, clsinfo):
        import __builtin__
74
        if type(clsinfo) in (tuple, list):
75 76 77 78 79 80 81 82
            for cls in clsinfo:
                if cls is type: cls = types.ClassType
                if __builtin__.isinstance(obj, cls):
                    return 1
            return 0
        else: return __builtin__.isinstance(obj, clsinfo)


83 84 85 86
##############################################################################
# Test framework core
##############################################################################

87 88 89
# All classes defined herein are 'new-style' classes, allowing use of 'super()'
__metaclass__ = type

90 91 92
def _strclass(cls):
    return "%s.%s" % (cls.__module__, cls.__name__)

93 94
__unittest = 1

95 96 97 98 99 100 101 102
class TestResult:
    """Holder for test result information.

    Test results are automatically managed by the TestCase and TestSuite
    classes, and do not need to be explicitly manipulated by writers of tests.

    Each instance holds the total number of tests run, and collections of
    failures and errors that occurred among those test runs. The collections
103
    contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
104
    formatted traceback of the error that occurred.
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    """
    def __init__(self):
        self.failures = []
        self.errors = []
        self.testsRun = 0
        self.shouldStop = 0

    def startTest(self, test):
        "Called when the given test is about to be run"
        self.testsRun = self.testsRun + 1

    def stopTest(self, test):
        "Called when the given test has been run"
        pass

    def addError(self, test, err):
121 122 123
        """Called when an error has occurred. 'err' is a tuple of values as
        returned by sys.exc_info().
        """
124
        self.errors.append((test, self._exc_info_to_string(err, test)))
125 126

    def addFailure(self, test, err):
127 128
        """Called when an error has occurred. 'err' is a tuple of values as
        returned by sys.exc_info()."""
129
        self.failures.append((test, self._exc_info_to_string(err, test)))
130

131 132 133 134
    def addSuccess(self, test):
        "Called when a test has completed successfully"
        pass

135 136 137 138 139 140
    def wasSuccessful(self):
        "Tells whether or not this result was a success"
        return len(self.failures) == len(self.errors) == 0

    def stop(self):
        "Indicates that the tests should be aborted"
141
        self.shouldStop = True
Tim Peters's avatar
Tim Peters committed
142

143
    def _exc_info_to_string(self, err, test):
144
        """Converts a sys.exc_info()-style tuple of values into a string."""
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
        exctype, value, tb = err
        # Skip test runner traceback levels
        while tb and self._is_relevant_tb_level(tb):
            tb = tb.tb_next
        if exctype is test.failureException:
            # Skip assert*() traceback levels
            length = self._count_relevant_tb_levels(tb)
            return ''.join(traceback.format_exception(exctype, value, tb, length))
        return ''.join(traceback.format_exception(exctype, value, tb))

    def _is_relevant_tb_level(self, tb):
        return tb.tb_frame.f_globals.has_key('__unittest')

    def _count_relevant_tb_levels(self, tb):
        length = 0
        while tb and not self._is_relevant_tb_level(tb):
            length += 1
            tb = tb.tb_next
        return length
164

165 166
    def __repr__(self):
        return "<%s run=%i errors=%i failures=%i>" % \
167
               (_strclass(self.__class__), self.testsRun, len(self.errors),
168 169 170 171 172 173 174
                len(self.failures))

class TestCase:
    """A class whose instances are single test cases.

    By default, the test code itself should be placed in a method named
    'runTest'.
175

Tim Peters's avatar
Tim Peters committed
176
    If the fixture may be used for many test cases, create as
177 178 179
    many test methods as are needed. When instantiating such a TestCase
    subclass, specify in the constructor arguments the name of the test method
    that the instance is to execute.
180

Tim Peters's avatar
Tim Peters committed
181
    Test authors should subclass TestCase for their own tests. Construction
182 183 184 185 186 187 188 189
    and deconstruction of the test's environment ('fixture') can be
    implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    If it is necessary to override the __init__ method, the base class
    __init__ method must always be called. It is important that subclasses
    should not change the signature of their __init__ method, since instances
    of the classes are instantiated automatically by parts of the framework
    in order to be run.
190
    """
191 192 193 194 195 196 197

    # This attribute determines which exception will be raised when
    # the instance's assertion methods fail; test methods raising this
    # exception will be deemed to have 'failed' rather than 'errored'

    failureException = AssertionError

198 199 200 201 202 203
    def __init__(self, methodName='runTest'):
        """Create an instance of the class that will use the named test
           method when executed. Raises a ValueError if the instance does
           not have a method with the specified name.
        """
        try:
204 205 206
            self.__testMethodName = methodName
            testMethod = getattr(self, methodName)
            self.__testMethodDoc = testMethod.__doc__
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
        except AttributeError:
            raise ValueError, "no such test method in %s: %s" % \
                  (self.__class__, methodName)

    def setUp(self):
        "Hook method for setting up the test fixture before exercising it."
        pass

    def tearDown(self):
        "Hook method for deconstructing the test fixture after testing it."
        pass

    def countTestCases(self):
        return 1

    def defaultTestResult(self):
        return TestResult()

    def shortDescription(self):
        """Returns a one-line description of the test, or None if no
        description has been provided.

        The default implementation of this method returns the first line of
        the specified test method's docstring.
        """
232
        doc = self.__testMethodDoc
233
        return doc and doc.split("\n")[0].strip() or None
234 235

    def id(self):
236
        return "%s.%s" % (_strclass(self.__class__), self.__testMethodName)
237 238

    def __str__(self):
239
        return "%s (%s)" % (self.__testMethodName, _strclass(self.__class__))
240 241 242

    def __repr__(self):
        return "<%s testMethod=%s>" % \
243
               (_strclass(self.__class__), self.__testMethodName)
244 245 246 247

    def run(self, result=None):
        if result is None: result = self.defaultTestResult()
        result.startTest(self)
248
        testMethod = getattr(self, self.__testMethodName)
249 250 251
        try:
            try:
                self.setUp()
252 253
            except KeyboardInterrupt:
                raise
254
            except:
Jeremy Hylton's avatar
Jeremy Hylton committed
255
                result.addError(self, self.__exc_info())
256 257
                return

258
            ok = False
259
            try:
260
                testMethod()
261
                ok = True
262
            except self.failureException:
Jeremy Hylton's avatar
Jeremy Hylton committed
263
                result.addFailure(self, self.__exc_info())
264 265
            except KeyboardInterrupt:
                raise
266
            except:
Jeremy Hylton's avatar
Jeremy Hylton committed
267
                result.addError(self, self.__exc_info())
268 269 270

            try:
                self.tearDown()
271 272
            except KeyboardInterrupt:
                raise
273
            except:
Jeremy Hylton's avatar
Jeremy Hylton committed
274
                result.addError(self, self.__exc_info())
275
                ok = False
276
            if ok: result.addSuccess(self)
277 278 279
        finally:
            result.stopTest(self)

280 281
    def __call__(self, *args, **kwds):
        return self.run(*args, **kwds)
282

283
    def debug(self):
284
        """Run the test without collecting errors in a TestResult"""
285
        self.setUp()
286
        getattr(self, self.__testMethodName)()
287 288
        self.tearDown()

289 290 291 292
    def __exc_info(self):
        """Return a version of sys.exc_info() with the traceback frame
           minimised; usually the top level of the traceback frame is not
           needed.
293
        """
294 295 296
        exctype, excvalue, tb = sys.exc_info()
        if sys.platform[:4] == 'java': ## tracebacks look different in Jython
            return (exctype, excvalue, tb)
297
        return (exctype, excvalue, tb)
298

299 300 301
    def fail(self, msg=None):
        """Fail immediately, with the given message."""
        raise self.failureException, msg
302 303 304

    def failIf(self, expr, msg=None):
        "Fail the test if the expression is true."
305 306 307 308 309
        if expr: raise self.failureException, msg

    def failUnless(self, expr, msg=None):
        """Fail the test unless the expression is true."""
        if not expr: raise self.failureException, msg
310

311 312
    def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
        """Fail unless an exception of class excClass is thrown
313 314 315 316 317 318 319
           by callableObj when invoked with arguments args and keyword
           arguments kwargs. If a different type of exception is
           thrown, it will not be caught, and the test case will be
           deemed to have suffered an error, exactly as for an
           unexpected exception.
        """
        try:
320
            callableObj(*args, **kwargs)
321 322 323 324 325
        except excClass:
            return
        else:
            if hasattr(excClass,'__name__'): excName = excClass.__name__
            else: excName = str(excClass)
326
            raise self.failureException, "%s not raised" % excName
327

328
    def failUnlessEqual(self, first, second, msg=None):
329
        """Fail if the two objects are unequal as determined by the '=='
330 331
           operator.
        """
332
        if not first == second:
Steve Purcell's avatar
Steve Purcell committed
333
            raise self.failureException, \
334
                  (msg or '%r != %r' % (first, second))
335

336 337
    def failIfEqual(self, first, second, msg=None):
        """Fail if the two objects are equal as determined by the '=='
338 339
           operator.
        """
340
        if first == second:
Steve Purcell's avatar
Steve Purcell committed
341
            raise self.failureException, \
342
                  (msg or '%r == %r' % (first, second))
343

344 345 346 347 348
    def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
        """Fail if the two objects are unequal as determined by their
           difference rounded to the given number of decimal places
           (default 7) and comparing to zero.

349
           Note that decimal places (from zero) are usually not the same
350 351 352 353
           as significant digits (measured from the most signficant digit).
        """
        if round(second-first, places) != 0:
            raise self.failureException, \
354
                  (msg or '%r != %r within %r places' % (first, second, places))
355 356 357 358 359 360

    def failIfAlmostEqual(self, first, second, places=7, msg=None):
        """Fail if the two objects are equal as determined by their
           difference rounded to the given number of decimal places
           (default 7) and comparing to zero.

361
           Note that decimal places (from zero) are usually not the same
362 363 364 365
           as significant digits (measured from the most signficant digit).
        """
        if round(second-first, places) == 0:
            raise self.failureException, \
366
                  (msg or '%r == %r within %r places' % (first, second, places))
367

368 369
    # Synonyms for assertion methods

370
    assertEqual = assertEquals = failUnlessEqual
371

372 373
    assertNotEqual = assertNotEquals = failIfEqual

374 375 376 377
    assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual

    assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual

378 379
    assertRaises = failUnlessRaises

380 381 382
    assert_ = assertTrue = failUnless

    assertFalse = failIf
383 384


385 386 387 388 389 390 391 392 393 394 395 396 397 398 399

class TestSuite:
    """A test suite is a composite test consisting of a number of TestCases.

    For use, create an instance of TestSuite, then add test case instances.
    When all tests have been added, the suite can be passed to a test
    runner, such as TextTestRunner. It will run the individual test cases
    in the order in which they were added, aggregating the results. When
    subclassing, do not forget to call the base class constructor.
    """
    def __init__(self, tests=()):
        self._tests = []
        self.addTests(tests)

    def __repr__(self):
400
        return "<%s tests=%s>" % (_strclass(self.__class__), self._tests)
401 402 403

    __str__ = __repr__

404 405 406
    def __iter__(self):
        return iter(self._tests)

407 408 409
    def countTestCases(self):
        cases = 0
        for test in self._tests:
410
            cases += test.countTestCases()
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
        return cases

    def addTest(self, test):
        self._tests.append(test)

    def addTests(self, tests):
        for test in tests:
            self.addTest(test)

    def run(self, result):
        for test in self._tests:
            if result.shouldStop:
                break
            test(result)
        return result

427 428 429
    def __call__(self, *args, **kwds):
        return self.run(*args, **kwds)

430
    def debug(self):
431
        """Run the tests without collecting errors in a TestResult"""
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
        for test in self._tests: test.debug()


class FunctionTestCase(TestCase):
    """A test case that wraps a test function.

    This is useful for slipping pre-existing test functions into the
    PyUnit framework. Optionally, set-up and tidy-up functions can be
    supplied. As with TestCase, the tidy-up ('tearDown') function will
    always be called if the set-up ('setUp') function ran successfully.
    """

    def __init__(self, testFunc, setUp=None, tearDown=None,
                 description=None):
        TestCase.__init__(self)
        self.__setUpFunc = setUp
        self.__tearDownFunc = tearDown
        self.__testFunc = testFunc
        self.__description = description

    def setUp(self):
        if self.__setUpFunc is not None:
            self.__setUpFunc()

    def tearDown(self):
        if self.__tearDownFunc is not None:
            self.__tearDownFunc()

    def runTest(self):
        self.__testFunc()

    def id(self):
        return self.__testFunc.__name__

    def __str__(self):
467
        return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__)
468 469

    def __repr__(self):
470
        return "<%s testFunc=%s>" % (_strclass(self.__class__), self.__testFunc)
471 472 473 474

    def shortDescription(self):
        if self.__description is not None: return self.__description
        doc = self.__testFunc.__doc__
475
        return doc and doc.split("\n")[0].strip() or None
476 477 478 479



##############################################################################
480
# Locating and loading tests
481 482
##############################################################################

483 484 485
class TestLoader:
    """This class is responsible for loading tests according to various
    criteria and returning them wrapped in a Test
486
    """
487 488 489
    testMethodPrefix = 'test'
    sortTestMethodsUsing = cmp
    suiteClass = TestSuite
490

491
    def loadTestsFromTestCase(self, testCaseClass):
492
        """Return a suite of all tests cases contained in testCaseClass"""
493 494
        if issubclass(testCaseClass, TestSuite):
            raise TypeError("Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?")
495 496 497 498
        testCaseNames = self.getTestCaseNames(testCaseClass)
        if not testCaseNames and hasattr(testCaseClass, 'runTest'):
            testCaseNames = ['runTest']
        return self.suiteClass(map(testCaseClass, testCaseNames))
499

500
    def loadTestsFromModule(self, module):
501
        """Return a suite of all tests cases contained in the given module"""
502 503 504
        tests = []
        for name in dir(module):
            obj = getattr(module, name)
505 506
            if (isinstance(obj, (type, types.ClassType)) and
                issubclass(obj, TestCase)):
507 508 509 510
                tests.append(self.loadTestsFromTestCase(obj))
        return self.suiteClass(tests)

    def loadTestsFromName(self, name, module=None):
511 512 513 514 515
        """Return a suite of all tests cases given a string specifier.

        The name may resolve either to a module, a test case class, a
        test method within a test case class, or a callable object which
        returns a TestCase or TestSuite instance.
Tim Peters's avatar
Tim Peters committed
516

517 518
        The method optionally resolves the names relative to a given module.
        """
519
        parts = name.split('.')
520
        if module is None:
521 522 523 524 525 526 527 528
            parts_copy = parts[:]
            while parts_copy:
                try:
                    module = __import__('.'.join(parts_copy))
                    break
                except ImportError:
                    del parts_copy[-1]
                    if not parts_copy: raise
529
            parts = parts[1:]
530 531
        obj = module
        for part in parts:
532
            parent, obj = obj, getattr(obj, part)
533 534 535

        if type(obj) == types.ModuleType:
            return self.loadTestsFromModule(obj)
536
        elif (isinstance(obj, (type, types.ClassType)) and
537
              issubclass(obj, TestCase)):
538 539
            return self.loadTestsFromTestCase(obj)
        elif type(obj) == types.UnboundMethodType:
540
            return parent(obj.__name__)
541
        elif isinstance(obj, TestSuite):
542
            return obj
543 544
        elif callable(obj):
            test = obj()
545
            if not isinstance(test, (TestCase, TestSuite)):
546
                raise ValueError, \
547
                      "calling %s returned %s, not a test" % (obj,test)
548 549 550
            return test
        else:
            raise ValueError, "don't know how to make test from: %s" % obj
551

552
    def loadTestsFromNames(self, names, module=None):
553 554 555
        """Return a suite of all tests cases found using the given sequence
        of string specifiers. See 'loadTestsFromName()'.
        """
556
        suites = [self.loadTestsFromName(name, module) for name in names]
557
        return self.suiteClass(suites)
558

559
    def getTestCaseNames(self, testCaseClass):
560 561
        """Return a sorted sequence of method names found within testCaseClass
        """
562
        def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
563
            return attrname.startswith(prefix) and callable(getattr(testCaseClass, attrname))
564
        testFnNames = filter(isTestMethod, dir(testCaseClass))
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
        for baseclass in testCaseClass.__bases__:
            for testFnName in self.getTestCaseNames(baseclass):
                if testFnName not in testFnNames:  # handle overridden methods
                    testFnNames.append(testFnName)
        if self.sortTestMethodsUsing:
            testFnNames.sort(self.sortTestMethodsUsing)
        return testFnNames



defaultTestLoader = TestLoader()


##############################################################################
# Patches for old functions: these functions should be considered obsolete
##############################################################################

def _makeLoader(prefix, sortUsing, suiteClass=None):
    loader = TestLoader()
    loader.sortTestMethodsUsing = sortUsing
    loader.testMethodPrefix = prefix
    if suiteClass: loader.suiteClass = suiteClass
    return loader

def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
    return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)

def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
    return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)

def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
    return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
597 598 599 600 601 602 603 604 605 606 607 608 609 610


##############################################################################
# Text UI
##############################################################################

class _WritelnDecorator:
    """Used to decorate file-like objects with a handy 'writeln' method"""
    def __init__(self,stream):
        self.stream = stream

    def __getattr__(self, attr):
        return getattr(self.stream,attr)

611 612
    def writeln(self, arg=None):
        if arg: self.write(arg)
613
        self.write('\n') # text-mode streams translate to \r\n if needed
Tim Peters's avatar
Tim Peters committed
614

615

616
class _TextTestResult(TestResult):
617 618
    """A test result class that can print formatted text results to a stream.

619
    Used by TextTestRunner.
620
    """
621 622 623 624
    separator1 = '=' * 70
    separator2 = '-' * 70

    def __init__(self, stream, descriptions, verbosity):
625 626
        TestResult.__init__(self)
        self.stream = stream
627 628
        self.showAll = verbosity > 1
        self.dots = verbosity == 1
629
        self.descriptions = descriptions
630 631

    def getDescription(self, test):
632
        if self.descriptions:
633
            return test.shortDescription() or str(test)
634
        else:
635
            return str(test)
636

637 638 639 640 641 642 643 644 645
    def startTest(self, test):
        TestResult.startTest(self, test)
        if self.showAll:
            self.stream.write(self.getDescription(test))
            self.stream.write(" ... ")

    def addSuccess(self, test):
        TestResult.addSuccess(self, test)
        if self.showAll:
646
            self.stream.writeln("ok")
647 648
        elif self.dots:
            self.stream.write('.')
649 650 651

    def addError(self, test, err):
        TestResult.addError(self, test, err)
652 653 654 655
        if self.showAll:
            self.stream.writeln("ERROR")
        elif self.dots:
            self.stream.write('E')
656 657 658

    def addFailure(self, test, err):
        TestResult.addFailure(self, test, err)
659 660 661 662 663 664 665
        if self.showAll:
            self.stream.writeln("FAIL")
        elif self.dots:
            self.stream.write('F')

    def printErrors(self):
        if self.dots or self.showAll:
666
            self.stream.writeln()
667 668 669 670 671 672 673 674
        self.printErrorList('ERROR', self.errors)
        self.printErrorList('FAIL', self.failures)

    def printErrorList(self, flavour, errors):
        for test, err in errors:
            self.stream.writeln(self.separator1)
            self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
            self.stream.writeln(self.separator2)
675
            self.stream.writeln("%s" % err)
676 677


678
class TextTestRunner:
679
    """A test runner class that displays results in textual form.
Tim Peters's avatar
Tim Peters committed
680

681 682 683
    It prints out the names of tests as they are run, errors as they
    occur, and a summary of the results at the end of the test run.
    """
684
    def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
685 686
        self.stream = _WritelnDecorator(stream)
        self.descriptions = descriptions
687 688 689 690
        self.verbosity = verbosity

    def _makeResult(self):
        return _TextTestResult(self.stream, self.descriptions, self.verbosity)
691 692 693

    def run(self, test):
        "Run the given test case or test suite."
694
        result = self._makeResult()
695 696 697
        startTime = time.time()
        test(result)
        stopTime = time.time()
698
        timeTaken = stopTime - startTime
699 700
        result.printErrors()
        self.stream.writeln(result.separator2)
701 702
        run = result.testsRun
        self.stream.writeln("Ran %d test%s in %.3fs" %
703
                            (run, run != 1 and "s" or "", timeTaken))
704 705 706 707 708 709 710 711 712 713 714 715 716
        self.stream.writeln()
        if not result.wasSuccessful():
            self.stream.write("FAILED (")
            failed, errored = map(len, (result.failures, result.errors))
            if failed:
                self.stream.write("failures=%d" % failed)
            if errored:
                if failed: self.stream.write(", ")
                self.stream.write("errors=%d" % errored)
            self.stream.writeln(")")
        else:
            self.stream.writeln("OK")
        return result
Tim Peters's avatar
Tim Peters committed
717

718 719 720 721 722 723 724 725 726 727 728


##############################################################################
# Facilities for running tests from the command line
##############################################################################

class TestProgram:
    """A command-line program that runs a set of tests; this is primarily
       for making test modules conveniently executable.
    """
    USAGE = """\
729
Usage: %(progName)s [options] [test] [...]
730 731 732 733 734

Options:
  -h, --help       Show this message
  -v, --verbose    Verbose output
  -q, --quiet      Minimal output
735 736 737 738

Examples:
  %(progName)s                               - run default set of tests
  %(progName)s MyTestSuite                   - run suite 'MyTestSuite'
739 740
  %(progName)s MyTestCase.testSomething      - run MyTestCase.testSomething
  %(progName)s MyTestCase                    - run all 'test*' test methods
741 742 743
                                               in MyTestCase
"""
    def __init__(self, module='__main__', defaultTest=None,
744
                 argv=None, testRunner=None, testLoader=defaultTestLoader):
745 746
        if type(module) == type(''):
            self.module = __import__(module)
747
            for part in module.split('.')[1:]:
748 749 750 751 752
                self.module = getattr(self.module, part)
        else:
            self.module = module
        if argv is None:
            argv = sys.argv
753
        self.verbosity = 1
754 755
        self.defaultTest = defaultTest
        self.testRunner = testRunner
756
        self.testLoader = testLoader
757 758 759 760 761 762 763 764 765 766 767 768
        self.progName = os.path.basename(argv[0])
        self.parseArgs(argv)
        self.runTests()

    def usageExit(self, msg=None):
        if msg: print msg
        print self.USAGE % self.__dict__
        sys.exit(2)

    def parseArgs(self, argv):
        import getopt
        try:
769 770
            options, args = getopt.getopt(argv[1:], 'hHvq',
                                          ['help','verbose','quiet'])
771 772 773
            for opt, value in options:
                if opt in ('-h','-H','--help'):
                    self.usageExit()
774 775 776 777
                if opt in ('-q','--quiet'):
                    self.verbosity = 0
                if opt in ('-v','--verbose'):
                    self.verbosity = 2
778
            if len(args) == 0 and self.defaultTest is None:
779 780
                self.test = self.testLoader.loadTestsFromModule(self.module)
                return
781 782 783 784
            if len(args) > 0:
                self.testNames = args
            else:
                self.testNames = (self.defaultTest,)
785
            self.createTests()
786 787 788 789
        except getopt.error, msg:
            self.usageExit(msg)

    def createTests(self):
790 791
        self.test = self.testLoader.loadTestsFromNames(self.testNames,
                                                       self.module)
792 793 794

    def runTests(self):
        if self.testRunner is None:
795
            self.testRunner = TextTestRunner(verbosity=self.verbosity)
796
        result = self.testRunner.run(self.test)
Tim Peters's avatar
Tim Peters committed
797
        sys.exit(not result.wasSuccessful())
798 799 800 801 802 803 804 805 806 807

main = TestProgram


##############################################################################
# Executing this module from the command line
##############################################################################

if __name__ == "__main__":
    main(module=None)