unittest.py 31.1 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
            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

28
  http://docs.python.org/lib/module-unittest.html
29

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
##############################################################################
# Test framework core
##############################################################################

71 72 73
def _strclass(cls):
    return "%s.%s" % (cls.__module__, cls.__name__)

74 75
__unittest = 1

76
class TestResult(object):
77 78 79 80 81 82 83
    """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
84
    contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
85
    formatted traceback of the error that occurred.
86 87 88 89 90
    """
    def __init__(self):
        self.failures = []
        self.errors = []
        self.testsRun = 0
91
        self.shouldStop = False
92 93 94 95 96 97 98 99 100 101

    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):
102 103 104
        """Called when an error has occurred. 'err' is a tuple of values as
        returned by sys.exc_info().
        """
105
        self.errors.append((test, self._exc_info_to_string(err, test)))
106 107

    def addFailure(self, test, err):
108 109
        """Called when an error has occurred. 'err' is a tuple of values as
        returned by sys.exc_info()."""
110
        self.failures.append((test, self._exc_info_to_string(err, test)))
111

112 113 114 115
    def addSuccess(self, test):
        "Called when a test has completed successfully"
        pass

116 117 118 119 120 121
    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"
122
        self.shouldStop = True
Tim Peters's avatar
Tim Peters committed
123

124
    def _exc_info_to_string(self, err, test):
125
        """Converts a sys.exc_info()-style tuple of values into a string."""
126 127 128 129 130 131 132
        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)
133 134
            return ''.join(traceback.format_exception(exctype, value,
                                                      tb, length))
135 136 137
        return ''.join(traceback.format_exception(exctype, value, tb))

    def _is_relevant_tb_level(self, tb):
138
        return '__unittest' in tb.tb_frame.f_globals
139 140 141 142 143 144 145

    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
146

147 148
    def __repr__(self):
        return "<%s run=%i errors=%i failures=%i>" % \
149
               (_strclass(self.__class__), self.testsRun, len(self.errors),
150 151
                len(self.failures))

152
class AssertRaisesContext(object):
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    def __init__(self, expected, test_case, callable_obj=None):
        self.expected = expected
        self.failureException = test_case.failureException
        if callable_obj is not None:
            try:
                self.obj_name = callable_obj.__name__
            except AttributeError:
                self.obj_name = str(callable_obj)
        else:
            self.obj_name = None
    def __enter__(self):
        pass
    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is None:
            try:
                exc_name = self.expected.__name__
            except AttributeError:
                exc_name = str(self.expected)
            if self.obj_name:
                raise self.failureException("{0} not raised by {1}"
                    .format(exc_name, self.obj_name))
            else:
                raise self.failureException("{0} not raised"
                    .format(exc_name))
        if issubclass(exc_type, self.expected):
            return True
        # Let unexpected exceptions skip through
        return False

182
class TestCase(object):
183 184 185 186
    """A class whose instances are single test cases.

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

Tim Peters's avatar
Tim Peters committed
188
    If the fixture may be used for many test cases, create as
189 190 191
    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.
192

Tim Peters's avatar
Tim Peters committed
193
    Test authors should subclass TestCase for their own tests. Construction
194 195 196 197 198 199 200 201
    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.
202
    """
203 204 205 206 207 208 209

    # 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

210 211 212 213 214 215
    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:
216
            self._testMethodName = methodName
217
            testMethod = getattr(self, methodName)
218
            self._testMethodDoc = testMethod.__doc__
219
        except AttributeError:
220 221
            raise ValueError("no such test method in %s: %s" % \
                  (self.__class__, methodName))
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243

    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.
        """
244
        doc = self._testMethodDoc
245
        return doc and doc.split("\n")[0].strip() or None
246 247

    def id(self):
248
        return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
249

250 251 252 253 254 255 256 257 258 259 260 261
    def __eq__(self, other):
        if type(self) is not type(other):
            return False

        return self._testMethodName == other._testMethodName

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash((type(self), self._testMethodName))

262
    def __str__(self):
263
        return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
264 265 266

    def __repr__(self):
        return "<%s testMethod=%s>" % \
267
               (_strclass(self.__class__), self._testMethodName)
268 269 270 271

    def run(self, result=None):
        if result is None: result = self.defaultTestResult()
        result.startTest(self)
272
        testMethod = getattr(self, self._testMethodName)
273 274 275
        try:
            try:
                self.setUp()
276
            except Exception:
277
                result.addError(self, self._exc_info())
278 279
                return

280
            ok = False
281
            try:
282
                testMethod()
283
                ok = True
284
            except self.failureException:
285
                result.addFailure(self, self._exc_info())
286
            except Exception:
287
                result.addError(self, self._exc_info())
288 289 290

            try:
                self.tearDown()
291
            except Exception:
292
                result.addError(self, self._exc_info())
293
                ok = False
294
            if ok: result.addSuccess(self)
295 296 297
        finally:
            result.stopTest(self)

298 299
    def __call__(self, *args, **kwds):
        return self.run(*args, **kwds)
300

301
    def debug(self):
302
        """Run the test without collecting errors in a TestResult"""
303
        self.setUp()
304
        getattr(self, self._testMethodName)()
305 306
        self.tearDown()

307
    def _exc_info(self):
308 309 310
        """Return a version of sys.exc_info() with the traceback frame
           minimised; usually the top level of the traceback frame is not
           needed.
311
        """
312
        return sys.exc_info()
313

314 315
    def fail(self, msg=None):
        """Fail immediately, with the given message."""
316
        raise self.failureException(msg)
317 318 319

    def failIf(self, expr, msg=None):
        "Fail the test if the expression is true."
320
        if expr: raise self.failureException(msg)
321 322 323

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

326
    def failUnlessRaises(self, excClass, callableObj=None, *args, **kwargs):
327
        """Fail unless an exception of class excClass is thrown
328 329 330 331 332
           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.
333 334 335 336 337 338

           If called with callableObj omitted or None, will return a
           context object used like this::

                with self.failUnlessRaises(some_error_class):
                    do_something()
339
        """
340 341 342 343
        context = AssertRaisesContext(excClass, self, callableObj)
        if callableObj is None:
            return context
        with context:
344
            callableObj(*args, **kwargs)
345

346
    def failUnlessEqual(self, first, second, msg=None):
347
        """Fail if the two objects are unequal as determined by the '=='
348 349
           operator.
        """
350
        if not first == second:
351
            raise self.failureException(msg or '%r != %r' % (first, second))
352

353 354
    def failIfEqual(self, first, second, msg=None):
        """Fail if the two objects are equal as determined by the '=='
355 356
           operator.
        """
357
        if first == second:
358
            raise self.failureException(msg or '%r == %r' % (first, second))
359

360
    def failUnlessAlmostEqual(self, first, second, *, places=7, msg=None):
361 362 363 364
        """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.

365
           Note that decimal places (from zero) are usually not the same
366 367
           as significant digits (measured from the most signficant digit).
        """
368
        if round(abs(second-first), places) != 0:
369 370
            raise self.failureException(
                  msg or '%r != %r within %r places' % (first, second, places))
371

372
    def failIfAlmostEqual(self, first, second, *, places=7, msg=None):
373 374 375 376
        """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.

377
           Note that decimal places (from zero) are usually not the same
378 379
           as significant digits (measured from the most signficant digit).
        """
380
        if round(abs(second-first), places) == 0:
381 382
            raise self.failureException(
                  msg or '%r == %r within %r places' % (first, second, places))
383

384 385
    # Synonyms for assertion methods

386
    assertEqual = assertEquals = failUnlessEqual
387

388 389
    assertNotEqual = assertNotEquals = failIfEqual

390 391 392 393
    assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual

    assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual

394 395
    assertRaises = failUnlessRaises

396 397 398
    assert_ = assertTrue = failUnless

    assertFalse = failIf
399 400


401

402
class TestSuite(object):
403 404 405 406 407 408 409 410 411 412 413 414 415
    """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):
416
        return "<%s tests=%s>" % (_strclass(self.__class__), self._tests)
417 418 419

    __str__ = __repr__

420 421 422 423 424 425 426 427
    def __eq__(self, other):
        if type(self) is not type(other):
            return False
        return self._tests == other._tests

    def __ne__(self, other):
        return not self == other

428 429 430
    def __iter__(self):
        return iter(self._tests)

431 432 433
    def countTestCases(self):
        cases = 0
        for test in self._tests:
434
            cases += test.countTestCases()
435 436 437
        return cases

    def addTest(self, test):
438
        # sanity checks
439
        if not hasattr(test, '__call__'):
440
            raise TypeError("the test to add must be callable")
441
        if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)):
442 443
            raise TypeError("TestCases and TestSuites must be instantiated "
                            "before passing them to addTest()")
444 445 446
        self._tests.append(test)

    def addTests(self, tests):
447
        if isinstance(tests, str):
448
            raise TypeError("tests must be an iterable of tests, not a string")
449 450 451 452 453 454 455 456 457 458
        for test in tests:
            self.addTest(test)

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

459 460 461
    def __call__(self, *args, **kwds):
        return self.run(*args, **kwds)

462
    def debug(self):
463
        """Run the tests without collecting errors in a TestResult"""
464 465 466 467 468 469 470
        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
471
    unittest framework. Optionally, set-up and tidy-up functions can be
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
    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__

498 499 500 501 502 503 504 505 506 507 508 509 510 511
    def __eq__(self, other):
        if type(self) is not type(other):
            return False

        return self.__setUpFunc == other.__setUpFunc and \
               self.__tearDownFunc == other.__tearDownFunc and \
               self.__testFunc == other.__testFunc and \
               self.__description == other.__description

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash((type(self), self.__setUpFunc, self.__tearDownFunc,
512
                    self.__testFunc, self.__description))
513

514
    def __str__(self):
515 516
        return "%s (%s)" % (_strclass(self.__class__),
                            self.__testFunc.__name__)
517 518

    def __repr__(self):
519 520
        return "<%s testFunc=%s>" % (_strclass(self.__class__),
                                     self.__testFunc)
521 522 523 524

    def shortDescription(self):
        if self.__description is not None: return self.__description
        doc = self.__testFunc.__doc__
525
        return doc and doc.split("\n")[0].strip() or None
526 527 528 529



##############################################################################
530
# Locating and loading tests
531 532
##############################################################################

533 534 535 536 537 538 539 540 541
def CmpToKey(mycmp):
    'Convert a cmp= function into a key= function'
    class K(object):
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) == -1
    return K

542 543 544 545
def three_way_cmp(x, y):
    """Return -1 if x < y, 0 if x == y and 1 if x > y"""
    return (x > y) - (x < y)

546
class TestLoader(object):
547
    """This class is responsible for loading tests according to various
548
    criteria and returning them wrapped in a TestSuite
549
    """
550
    testMethodPrefix = 'test'
551
    sortTestMethodsUsing = staticmethod(three_way_cmp)
552
    suiteClass = TestSuite
553

554
    def loadTestsFromTestCase(self, testCaseClass):
555
        """Return a suite of all tests cases contained in testCaseClass"""
556
        if issubclass(testCaseClass, TestSuite):
557 558
            raise TypeError("Test cases should not be derived from TestSuite."
                            "Maybe you meant to derive from TestCase?")
559 560 561 562
        testCaseNames = self.getTestCaseNames(testCaseClass)
        if not testCaseNames and hasattr(testCaseClass, 'runTest'):
            testCaseNames = ['runTest']
        return self.suiteClass(map(testCaseClass, testCaseNames))
563

564
    def loadTestsFromModule(self, module):
565
        """Return a suite of all tests cases contained in the given module"""
566 567 568
        tests = []
        for name in dir(module):
            obj = getattr(module, name)
569
            if isinstance(obj, type) and issubclass(obj, TestCase):
570 571 572 573
                tests.append(self.loadTestsFromTestCase(obj))
        return self.suiteClass(tests)

    def loadTestsFromName(self, name, module=None):
574 575 576 577 578
        """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
579

580 581
        The method optionally resolves the names relative to a given module.
        """
582
        parts = name.split('.')
583
        if module is None:
584 585 586 587 588 589 590 591
            parts_copy = parts[:]
            while parts_copy:
                try:
                    module = __import__('.'.join(parts_copy))
                    break
                except ImportError:
                    del parts_copy[-1]
                    if not parts_copy: raise
592
            parts = parts[1:]
593 594
        obj = module
        for part in parts:
595
            parent, obj = obj, getattr(obj, part)
596

597
        if isinstance(obj, types.ModuleType):
598
            return self.loadTestsFromModule(obj)
599
        elif isinstance(obj, type) and issubclass(obj, TestCase):
600
            return self.loadTestsFromTestCase(obj)
601
        elif (isinstance(obj, types.FunctionType) and
602
              isinstance(parent, type) and
603
              issubclass(parent, TestCase)):
604 605 606
            name = obj.__name__
            inst = parent(name)
            # static methods follow a different path
Christian Heimes's avatar
Christian Heimes committed
607
            if not isinstance(getattr(inst, name), types.FunctionType):
608
                return TestSuite([inst])
609
        elif isinstance(obj, TestSuite):
610
            return obj
611 612

        if hasattr(obj, '__call__'):
613
            test = obj()
614 615 616 617 618 619 620
            if isinstance(test, TestSuite):
                return test
            elif isinstance(test, TestCase):
                return TestSuite([test])
            else:
                raise TypeError("calling %s returned %s, not a test" %
                                (obj, test))
621
        else:
622
            raise TypeError("don't know how to make test from: %s" % obj)
623

624
    def loadTestsFromNames(self, names, module=None):
625 626 627
        """Return a suite of all tests cases found using the given sequence
        of string specifiers. See 'loadTestsFromName()'.
        """
628
        suites = [self.loadTestsFromName(name, module) for name in names]
629
        return self.suiteClass(suites)
630

631
    def getTestCaseNames(self, testCaseClass):
632 633
        """Return a sorted sequence of method names found within testCaseClass
        """
634 635 636 637
        def isTestMethod(attrname, testCaseClass=testCaseClass,
                         prefix=self.testMethodPrefix):
            return attrname.startswith(prefix) \
                   and hasattr(getattr(testCaseClass, attrname), '__call__')
638
        testFnNames = list(filter(isTestMethod, dir(testCaseClass)))
639
        if self.sortTestMethodsUsing:
640
            testFnNames.sort(key=CmpToKey(self.sortTestMethodsUsing))
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
        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

659
def getTestCaseNames(testCaseClass, prefix, sortUsing=three_way_cmp):
660 661
    return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)

662 663 664 665
def makeSuite(testCaseClass, prefix='test', sortUsing=three_way_cmp,
              suiteClass=TestSuite):
    return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(
        testCaseClass)
666

667 668 669 670
def findTestCases(module, prefix='test', sortUsing=three_way_cmp,
                  suiteClass=TestSuite):
    return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(
        module)
671 672 673 674 675 676


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

677
class _WritelnDecorator(object):
678 679 680 681 682 683 684
    """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)

685 686
    def writeln(self, arg=None):
        if arg: self.write(arg)
687
        self.write('\n') # text-mode streams translate to \r\n if needed
Tim Peters's avatar
Tim Peters committed
688

689

690
class _TextTestResult(TestResult):
691 692
    """A test result class that can print formatted text results to a stream.

693
    Used by TextTestRunner.
694
    """
695 696 697 698
    separator1 = '=' * 70
    separator2 = '-' * 70

    def __init__(self, stream, descriptions, verbosity):
699 700
        TestResult.__init__(self)
        self.stream = stream
701 702
        self.showAll = verbosity > 1
        self.dots = verbosity == 1
703
        self.descriptions = descriptions
704 705

    def getDescription(self, test):
706
        if self.descriptions:
707
            return test.shortDescription() or str(test)
708
        else:
709
            return str(test)
710

711 712 713 714 715
    def startTest(self, test):
        TestResult.startTest(self, test)
        if self.showAll:
            self.stream.write(self.getDescription(test))
            self.stream.write(" ... ")
716
            self.stream.flush()
717 718 719 720

    def addSuccess(self, test):
        TestResult.addSuccess(self, test)
        if self.showAll:
721
            self.stream.writeln("ok")
722 723
        elif self.dots:
            self.stream.write('.')
724
            self.stream.flush()
725 726 727

    def addError(self, test, err):
        TestResult.addError(self, test, err)
728 729 730 731
        if self.showAll:
            self.stream.writeln("ERROR")
        elif self.dots:
            self.stream.write('E')
732
            self.stream.flush()
733 734 735

    def addFailure(self, test, err):
        TestResult.addFailure(self, test, err)
736 737 738 739
        if self.showAll:
            self.stream.writeln("FAIL")
        elif self.dots:
            self.stream.write('F')
740
            self.stream.flush()
741 742 743

    def printErrors(self):
        if self.dots or self.showAll:
744
            self.stream.writeln()
745 746 747 748 749 750 751 752
        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)
753
            self.stream.writeln("%s" % err)
754 755


756
class TextTestRunner(object):
757
    """A test runner class that displays results in textual form.
Tim Peters's avatar
Tim Peters committed
758

759 760 761
    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.
    """
762
    def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
763 764
        self.stream = _WritelnDecorator(stream)
        self.descriptions = descriptions
765 766 767 768
        self.verbosity = verbosity

    def _makeResult(self):
        return _TextTestResult(self.stream, self.descriptions, self.verbosity)
769 770 771

    def run(self, test):
        "Run the given test case or test suite."
772
        result = self._makeResult()
773 774 775
        startTime = time.time()
        test(result)
        stopTime = time.time()
776
        timeTaken = stopTime - startTime
777 778
        result.printErrors()
        self.stream.writeln(result.separator2)
779 780
        run = result.testsRun
        self.stream.writeln("Ran %d test%s in %.3fs" %
781
                            (run, run != 1 and "s" or "", timeTaken))
782 783 784
        self.stream.writeln()
        if not result.wasSuccessful():
            self.stream.write("FAILED (")
785
            failed, errored = len(result.failures), len(result.errors)
786 787 788 789 790 791 792 793 794
            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
795

796 797 798 799 800 801


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

802
class TestProgram(object):
803 804 805 806
    """A command-line program that runs a set of tests; this is primarily
       for making test modules conveniently executable.
    """
    USAGE = """\
807
Usage: %(progName)s [options] [test] [...]
808 809 810 811 812

Options:
  -h, --help       Show this message
  -v, --verbose    Verbose output
  -q, --quiet      Minimal output
813 814 815 816

Examples:
  %(progName)s                               - run default set of tests
  %(progName)s MyTestSuite                   - run suite 'MyTestSuite'
817 818
  %(progName)s MyTestCase.testSomething      - run MyTestCase.testSomething
  %(progName)s MyTestCase                    - run all 'test*' test methods
819 820 821
                                               in MyTestCase
"""
    def __init__(self, module='__main__', defaultTest=None,
822 823
                 argv=None, testRunner=TextTestRunner,
                 testLoader=defaultTestLoader):
824
        if isinstance(module, str):
825
            self.module = __import__(module)
826
            for part in module.split('.')[1:]:
827 828 829 830 831
                self.module = getattr(self.module, part)
        else:
            self.module = module
        if argv is None:
            argv = sys.argv
832
        self.verbosity = 1
833 834
        self.defaultTest = defaultTest
        self.testRunner = testRunner
835
        self.testLoader = testLoader
836 837 838 839 840
        self.progName = os.path.basename(argv[0])
        self.parseArgs(argv)
        self.runTests()

    def usageExit(self, msg=None):
841 842
        if msg: print(msg)
        print(self.USAGE % self.__dict__)
843 844 845 846 847
        sys.exit(2)

    def parseArgs(self, argv):
        import getopt
        try:
848 849
            options, args = getopt.getopt(argv[1:], 'hHvq',
                                          ['help','verbose','quiet'])
850 851 852
            for opt, value in options:
                if opt in ('-h','-H','--help'):
                    self.usageExit()
853 854 855 856
                if opt in ('-q','--quiet'):
                    self.verbosity = 0
                if opt in ('-v','--verbose'):
                    self.verbosity = 2
857
            if len(args) == 0 and self.defaultTest is None:
858 859
                self.test = self.testLoader.loadTestsFromModule(self.module)
                return
860 861 862 863
            if len(args) > 0:
                self.testNames = args
            else:
                self.testNames = (self.defaultTest,)
864
            self.createTests()
865
        except getopt.error as msg:
866 867 868
            self.usageExit(msg)

    def createTests(self):
869 870
        self.test = self.testLoader.loadTestsFromNames(self.testNames,
                                                       self.module)
871 872

    def runTests(self):
873
        if isinstance(self.testRunner, type):
874 875 876 877 878 879 880 881 882
            try:
                testRunner = self.testRunner(verbosity=self.verbosity)
            except TypeError:
                # didn't accept the verbosity argument
                testRunner = self.testRunner()
        else:
            # it is assumed to be a TestRunner instance
            testRunner = self.testRunner
        result = testRunner.run(self.test)
Tim Peters's avatar
Tim Peters committed
883
        sys.exit(not result.wasSuccessful())
884 885 886 887 888 889 890 891 892 893

main = TestProgram


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

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