Ticket #15828: unittest-django-vs-python-2.7.2.diff

File unittest-django-vs-python-2.7.2.diff, 55.4 KB (added by aaugustin, 4 years ago)
  • unittest/__init__.py

    diff -u -Naur -x .svn -x .DS_Store -x test -x '*.pyc' -w django/utils/unittest/__init__.py /Users/myk/Downloads/cpython-eb3c9b74884c/Lib/unittest/__init__.py
    old new  
    11"""
    2 unittest2
     2Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
     3Smalltalk testing framework.
    34
    4 unittest2 is a backport of the new features added to the unittest testing
    5 framework in Python 2.7. It is tested to run on Python 2.4 - 2.6.
     5This module contains the core framework classes that form the basis of
     6specific test cases and suites (TestCase, TestSuite etc.), and also a
     7text-based utility class for running the tests and reporting the results
     8 (TextTestRunner).
    69
    7 To use unittest2 instead of unittest simply replace ``import unittest`` with
    8 ``import unittest2``.
     10Simple usage:
    911
     12    import unittest
     13
     14    class IntegerArithmenticTestCase(unittest.TestCase):
     15        def testAdd(self):  ## test method names begin 'test*'
     16            self.assertEqual((1 + 2), 3)
     17            self.assertEqual(0 + 1, 1)
     18        def testMultiply(self):
     19            self.assertEqual((0 * 10), 0)
     20            self.assertEqual((5 * 8), 40)
     21
     22    if __name__ == '__main__':
     23        unittest.main()
     24
     25Further information is available in the bundled documentation, and from
     26
     27  http://docs.python.org/library/unittest.html
    1028
    1129Copyright (c) 1999-2003 Steve Purcell
    1230Copyright (c) 2003-2010 Python Software Foundation
     
    2644SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
    2745"""
    2846
    29 import sys
    30 
    31 # Django hackery to load the appropriate version of unittest
    32 
    33 try:
    34     # check the system path first
    35     from unittest2 import *
    36 except ImportError:
    37     if sys.version_info >= (2,7):
    38         # unittest2 features are native in Python 2.7
    39         from unittest import *
    40     else:
    41         # otherwise use our bundled version
    4247        __all__ = ['TestResult', 'TestCase', 'TestSuite',
    4348                   'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main',
    4449                   'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless',
    45                    'expectedFailure', 'TextTestResult', '__version__', 'collector']
    46 
    47         __version__ = '0.5.1'
     50           'expectedFailure', 'TextTestResult', 'installHandler',
     51           'registerResult', 'removeResult', 'removeHandler']
    4852
    4953        # Expose obsolete functions for backwards compatibility
    5054        __all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
    5155
     56__unittest = True
    5257
    53         from django.utils.unittest.collector import collector
    54         from django.utils.unittest.result import TestResult
    55         from django.utils.unittest.case import \
    56             TestCase, FunctionTestCase, SkipTest, skip, skipIf,\
    57             skipUnless, expectedFailure
    58 
    59         from django.utils.unittest.suite import BaseTestSuite, TestSuite
    60         from django.utils.unittest.loader import \
    61             TestLoader, defaultTestLoader, makeSuite, getTestCaseNames,\
    62             findTestCases
    63 
    64         from django.utils.unittest.main import TestProgram, main, main_
    65         from django.utils.unittest.runner import TextTestRunner, TextTestResult
    66 
    67         try:
    68             from django.utils.unittest.signals import\
    69                 installHandler, registerResult, removeResult, removeHandler
    70         except ImportError:
    71             # Compatibility with platforms that don't have the signal module
    72             pass
    73         else:
    74             __all__.extend(['installHandler', 'registerResult', 'removeResult',
    75                             'removeHandler'])
     58from .result import TestResult
     59from .case import (TestCase, FunctionTestCase, SkipTest, skip, skipIf,
     60                   skipUnless, expectedFailure)
     61from .suite import BaseTestSuite, TestSuite
     62from .loader import (TestLoader, defaultTestLoader, makeSuite, getTestCaseNames,
     63                     findTestCases)
     64from .main import TestProgram, main
     65from .runner import TextTestRunner, TextTestResult
     66from .signals import installHandler, registerResult, removeResult, removeHandler
    7667
    7768        # deprecated
    7869        _TextTestResult = TextTestResult
    79 
    80         __unittest = True
  • unittest/__main__.py

    diff -u -Naur -x .svn -x .DS_Store -x test -x '*.pyc' -w django/utils/unittest/__main__.py /Users/myk/Downloads/cpython-eb3c9b74884c/Lib/unittest/__main__.py
    old new  
    22
    33import sys
    44if sys.argv[0].endswith("__main__.py"):
    5     sys.argv[0] = "unittest2"
     5    sys.argv[0] = "python -m unittest"
    66
    77__unittest = True
    88
    9 from django.utils.unittest.main import main_
    10 main_()
     9from .main import main, TestProgram, USAGE_AS_MAIN
     10TestProgram.USAGE = USAGE_AS_MAIN
     11
     12main(module=None)
  • unittest/case.py

    diff -u -Naur -x .svn -x .DS_Store -x test -x '*.pyc' -w django/utils/unittest/case.py /Users/myk/Downloads/cpython-eb3c9b74884c/Lib/unittest/case.py
    old new  
    11"""Test case implementation"""
    22
     3import collections
    34import sys
     5import functools
    46import difflib
    57import pprint
    68import re
    7 import unittest
    89import warnings
    910
    10 from django.utils.unittest import result
    11 from django.utils.unittest.util import\
    12     safe_repr, safe_str, strclass,\
    13     unorderable_list_difference
     11from . import result
     12from .util import (
     13    strclass, safe_repr, unorderable_list_difference,
     14    _count_diff_all_purpose, _count_diff_hashable
     15)
    1416
    15 from django.utils.unittest.compatibility import wraps
    1617
    1718__unittest = True
    1819
     
    2728    Usually you can use TestResult.skip() or one of the skipping decorators
    2829    instead of raising this directly.
    2930    """
     31    pass
    3032
    3133class _ExpectedFailure(Exception):
    3234    """
     
    3638    """
    3739
    3840    def __init__(self, exc_info):
    39         # can't use super because Python 2.4 exceptions are old style
    40         Exception.__init__(self)
     41        super(_ExpectedFailure, self).__init__()
    4142        self.exc_info = exc_info
    4243
    4344class _UnexpectedSuccess(Exception):
    4445    """
    4546    The test was supposed to fail, but it didn't!
    4647    """
     48    pass
    4749
    4850def _id(obj):
    4951    return obj
     
    5456    """
    5557    def decorator(test_item):
    5658        if not (isinstance(test_item, type) and issubclass(test_item, TestCase)):
    57             @wraps(test_item)
     59            @functools.wraps(test_item)
    5860            def skip_wrapper(*args, **kwargs):
    5961                raise SkipTest(reason)
    6062            test_item = skip_wrapper
     
    8284
    8385
    8486def expectedFailure(func):
    85     @wraps(func)
     87    @functools.wraps(func)
    8688    def wrapper(*args, **kwargs):
    8789        try:
    8890            func(*args, **kwargs)
     
    110112            except AttributeError:
    111113                exc_name = str(self.expected)
    112114            raise self.failureException(
    113                 "%s not raised" % (exc_name,))
     115                "{0} not raised".format(exc_name))
    114116        if not issubclass(exc_type, self.expected):
    115117            # let unexpected exceptions pass through
    116118            return False
     
    127129        return True
    128130
    129131
    130 class _TypeEqualityDict(object):
    131 
    132     def __init__(self, testcase):
    133         self.testcase = testcase
    134         self._store = {}
    135 
    136     def __setitem__(self, key, value):
    137         self._store[key] = value
    138 
    139     def __getitem__(self, key):
    140         value = self._store[key]
    141         if isinstance(value, basestring):
    142             return getattr(self.testcase, value)
    143         return value
    144 
    145     def get(self, key, default=None):
    146         if key in self._store:
    147             return self[key]
    148         return default
    149 
    150 
    151 class TestCase(unittest.TestCase):
     132class TestCase(object):
    152133    """A class whose instances are single test cases.
    153134
    154135    By default, the test code itself should be placed in a method named
     
    176157
    177158    failureException = AssertionError
    178159
     160    # This attribute determines whether long messages (including repr of
     161    # objects used in assert methods) will be printed on failure in *addition*
     162    # to any explicit message passed.
     163
     164    longMessage = False
     165
    179166    # This attribute sets the maximum length of a diff in failure messages
    180167    # by assert methods using difflib. It is looked up as an instance attribute
    181168    # so can be configured by individual tests if required.
    182169
    183170    maxDiff = 80*8
    184171
    185     # This attribute determines whether long messages (including repr of
    186     # objects used in assert methods) will be printed on failure in *addition*
    187     # to any explicit message passed.
    188 
    189     longMessage = True
     172    # If a string is longer than _diffThreshold, use normal comparison instead
     173    # of difflib.  See #11763.
     174    _diffThreshold = 2**16
    190175
    191176    # Attribute used by TestSuite for classSetUp
    192177
     
    202187        try:
    203188            testMethod = getattr(self, methodName)
    204189        except AttributeError:
    205             raise ValueError("no such test method in %s: %s" % \
     190            raise ValueError("no such test method in %s: %s" %
    206191                  (self.__class__, methodName))
    207192        self._testMethodDoc = testMethod.__doc__
    208193        self._cleanups = []
     
    210195        # Map types to custom assertEqual functions that will compare
    211196        # instances of said type in more detail to generate a more useful
    212197        # error message.
    213         self._type_equality_funcs = _TypeEqualityDict(self)
    214         self.addTypeEqualityFunc(dict, 'assertDictEqual')
    215         self.addTypeEqualityFunc(list, 'assertListEqual')
    216         self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
    217         self.addTypeEqualityFunc(set, 'assertSetEqual')
    218         self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
    219         self.addTypeEqualityFunc(unicode, 'assertMultiLineEqual')
     198        self._type_equality_funcs = {}
     199        self.addTypeEqualityFunc(dict, self.assertDictEqual)
     200        self.addTypeEqualityFunc(list, self.assertListEqual)
     201        self.addTypeEqualityFunc(tuple, self.assertTupleEqual)
     202        self.addTypeEqualityFunc(set, self.assertSetEqual)
     203        self.addTypeEqualityFunc(frozenset, self.assertSetEqual)
     204        self.addTypeEqualityFunc(unicode, self.assertMultiLineEqual)
    220205
    221206    def addTypeEqualityFunc(self, typeobj, function):
    222207        """Add a type specific assertEqual style function to compare a type.
     
    243228
    244229    def setUp(self):
    245230        "Hook method for setting up the test fixture before exercising it."
     231        pass
     232
     233    def tearDown(self):
     234        "Hook method for deconstructing the test fixture after testing it."
     235        pass
    246236
    247237    @classmethod
    248238    def setUpClass(cls):
     
    252242    def tearDownClass(cls):
    253243        "Hook method for deconstructing the class fixture after running all tests in the class."
    254244
    255     def tearDown(self):
    256         "Hook method for deconstructing the test fixture after testing it."
    257 
    258245    def countTestCases(self):
    259246        return 1
    260247
     
    299286        if addSkip is not None:
    300287            addSkip(self, reason)
    301288        else:
    302             warnings.warn("Use of a TestResult without an addSkip method is deprecated",
    303                           DeprecationWarning, 2)
     289            warnings.warn("TestResult has no addSkip method, skips not reported",
     290                          RuntimeWarning, 2)
    304291            result.addSuccess(self)
    305292
    306293    def run(self, result=None):
     
    315302        result.startTest(self)
    316303
    317304        testMethod = getattr(self, self._testMethodName)
    318 
    319305        if (getattr(self.__class__, "__unittest_skip__", False) or
    320306            getattr(testMethod, "__unittest_skip__", False)):
    321307            # If the class or method was skipped.
     
    330316            success = False
    331317            try:
    332318                self.setUp()
    333             except SkipTest, e:
     319            except SkipTest as e:
    334320                self._addSkip(result, str(e))
    335             except Exception:
     321            except KeyboardInterrupt:
     322                raise
     323            except:
    336324                result.addError(self, sys.exc_info())
    337325            else:
    338326                try:
    339327                    testMethod()
     328                except KeyboardInterrupt:
     329                    raise
    340330                except self.failureException:
    341331                    result.addFailure(self, sys.exc_info())
    342                 except _ExpectedFailure, e:
     332                except _ExpectedFailure as e:
    343333                    addExpectedFailure = getattr(result, 'addExpectedFailure', None)
    344334                    if addExpectedFailure is not None:
    345335                        addExpectedFailure(self, e.exc_info)
    346336                    else:
    347                         warnings.warn("Use of a TestResult without an addExpectedFailure method is deprecated",
    348                                       DeprecationWarning)
     337                        warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
     338                                      RuntimeWarning)
    349339                        result.addSuccess(self)
    350340                except _UnexpectedSuccess:
    351341                    addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess', None)
    352342                    if addUnexpectedSuccess is not None:
    353343                        addUnexpectedSuccess(self)
    354344                    else:
    355                         warnings.warn("Use of a TestResult without an addUnexpectedSuccess method is deprecated",
    356                                       DeprecationWarning)
     345                        warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failures",
     346                                      RuntimeWarning)
    357347                        result.addFailure(self, sys.exc_info())
    358                 except SkipTest, e:
     348                except SkipTest as e:
    359349                    self._addSkip(result, str(e))
    360                 except Exception:
     350                except:
    361351                    result.addError(self, sys.exc_info())
    362352                else:
    363353                    success = True
    364354
    365355                try:
    366356                    self.tearDown()
    367                 except Exception:
     357                except KeyboardInterrupt:
     358                    raise
     359                except:
    368360                    result.addError(self, sys.exc_info())
    369361                    success = False
    370362
     
    388380            function, args, kwargs = self._cleanups.pop(-1)
    389381            try:
    390382                function(*args, **kwargs)
    391             except Exception:
     383            except KeyboardInterrupt:
     384                raise
     385            except:
    392386                ok = False
    393387                result.addError(self, sys.exc_info())
    394388        return ok
     
    414408        raise self.failureException(msg)
    415409
    416410    def assertFalse(self, expr, msg=None):
    417         "Fail the test if the expression is true."
     411        """Check that the expression is false."""
    418412        if expr:
    419             msg = self._formatMessage(msg, "%s is not False" % safe_repr(expr))
     413            msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr))
    420414            raise self.failureException(msg)
    421415
    422416    def assertTrue(self, expr, msg=None):
    423         """Fail the test unless the expression is true."""
     417        """Check that the expression is true."""
    424418        if not expr:
    425             msg = self._formatMessage(msg, "%s is not True" % safe_repr(expr))
     419            msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
    426420            raise self.failureException(msg)
    427421
    428422    def _formatMessage(self, msg, standardMsg):
     
    440434        if msg is None:
    441435            return standardMsg
    442436        try:
     437            # don't switch to '{}' formatting in Python 2.X
     438            # it changes the way unicode input is handled
    443439            return '%s : %s' % (standardMsg, msg)
    444440        except UnicodeDecodeError:
    445             return '%s : %s' % (safe_str(standardMsg), safe_str(msg))
     441            return  '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
    446442
    447443
    448444    def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
     
    468464               the_exception = cm.exception
    469465               self.assertEqual(the_exception.error_code, 3)
    470466        """
     467        context = _AssertRaisesContext(excClass, self)
    471468        if callableObj is None:
    472             return _AssertRaisesContext(excClass, self)
    473         try:
     469            return context
     470        with context:
    474471            callableObj(*args, **kwargs)
    475         except excClass:
    476             return
    477 
    478         if hasattr(excClass,'__name__'):
    479             excName = excClass.__name__
    480         else:
    481             excName = str(excClass)
    482         raise self.failureException("%s not raised" % excName)
    483472
    484473    def _getAssertEqualityFunc(self, first, second):
    485474        """Get a detailed comparison function for the types of the two args.
     
    528517                                                           safe_repr(second)))
    529518            raise self.failureException(msg)
    530519
     520
    531521    def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None):
    532522        """Fail if the two objects are unequal as determined by their
    533523           difference rounded to the given number of decimal places
     
    613603    def _deprecate(original_func):
    614604        def deprecated_func(*args, **kwargs):
    615605            warnings.warn(
    616                 ('Please use %s instead.' % original_func.__name__),
     606                'Please use {0} instead.'.format(original_func.__name__),
    617607                PendingDeprecationWarning, 2)
    618608            return original_func(*args, **kwargs)
    619609        return deprecated_func
     
    626616    failUnlessRaises = _deprecate(assertRaises)
    627617    failIf = _deprecate(assertFalse)
    628618
    629     def assertSequenceEqual(self, seq1, seq2,
    630                             msg=None, seq_type=None, max_diff=80*8):
     619    def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
    631620        """An equality assertion for ordered sequences (like lists and tuples).
    632621
    633622        For the purposes of this function, a valid ordered sequence type is one
     
    640629                    datatype should be enforced.
    641630            msg: Optional message to use on failure instead of a list of
    642631                    differences.
    643             max_diff: Maximum size off the diff, larger diffs are not shown
    644632        """
    645633        if seq_type is not None:
    646634            seq_type_name = seq_type.__name__
     
    671659            if seq1 == seq2:
    672660                return
    673661
    674             seq1_repr = repr(seq1)
    675             seq2_repr = repr(seq2)
     662            seq1_repr = safe_repr(seq1)
     663            seq2_repr = safe_repr(seq2)
    676664            if len(seq1_repr) > 30:
    677665                seq1_repr = seq1_repr[:30] + '...'
    678666            if len(seq2_repr) > 30:
     
    727715        diffMsg = '\n' + '\n'.join(
    728716            difflib.ndiff(pprint.pformat(seq1).splitlines(),
    729717                          pprint.pformat(seq2).splitlines()))
    730 
    731718        standardMsg = self._truncateMessage(standardMsg, diffMsg)
    732719        msg = self._formatMessage(msg, standardMsg)
    733720        self.fail(msg)
     
    770757            msg: Optional message to use on failure instead of a list of
    771758                    differences.
    772759
    773         assertSetEqual uses ducktyping to support
    774         different types of sets, and is optimized for sets specifically
    775         (parameters must support a difference method).
     760        assertSetEqual uses ducktyping to support different types of sets, and
     761        is optimized for sets specifically (parameters must support a
     762        difference method).
    776763        """
    777764        try:
    778765            difference1 = set1.difference(set2)
     
    821808    def assertIs(self, expr1, expr2, msg=None):
    822809        """Just like self.assertTrue(a is b), but with a nicer default message."""
    823810        if expr1 is not expr2:
    824             standardMsg = '%s is not %s' % (safe_repr(expr1), safe_repr(expr2))
     811            standardMsg = '%s is not %s' % (safe_repr(expr1),
     812                                             safe_repr(expr2))
    825813            self.fail(self._formatMessage(msg, standardMsg))
    826814
    827815    def assertIsNot(self, expr1, expr2, msg=None):
     
    831819            self.fail(self._formatMessage(msg, standardMsg))
    832820
    833821    def assertDictEqual(self, d1, d2, msg=None):
    834         self.assertTrue(isinstance(d1, dict), 'First argument is not a dictionary')
    835         self.assertTrue(isinstance(d2, dict), 'Second argument is not a dictionary')
     822        self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
     823        self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
    836824
    837825        if d1 != d2:
    838826            standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
     
    870858
    871859    def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
    872860        """An unordered sequence specific comparison. It asserts that
    873         expected_seq and actual_seq contain the same elements. It is
    874         the equivalent of::
     861        actual_seq and expected_seq have the same element counts.
     862        Equivalent to::
    875863
    876             self.assertEqual(sorted(expected_seq), sorted(actual_seq))
    877 
    878         Raises with an error message listing which elements of expected_seq
    879         are missing from actual_seq and vice versa if any.
     864            self.assertEqual(Counter(iter(actual_seq)),
     865                             Counter(iter(expected_seq)))
    880866
    881867        Asserts that each element has the same count in both sequences.
    882868        Example:
    883869            - [0, 1, 1] and [1, 0, 1] compare equal.
    884870            - [0, 0, 1] and [0, 1] compare unequal.
    885871        """
     872        first_seq, second_seq = list(actual_seq), list(expected_seq)
     873        with warnings.catch_warnings():
     874            if sys.py3kwarning:
     875                # Silence Py3k warning raised during the sorting
     876                for _msg in ["(code|dict|type) inequality comparisons",
     877                             "builtin_function_or_method order comparisons",
     878                             "comparing unequal types"]:
     879                    warnings.filterwarnings("ignore", _msg, DeprecationWarning)
    886880        try:
    887             expected = sorted(expected_seq)
    888             actual = sorted(actual_seq)
     881                first = collections.Counter(first_seq)
     882                second = collections.Counter(second_seq)
    889883        except TypeError:
    890             # Unsortable items (example: set(), complex(), ...)
    891             expected = list(expected_seq)
    892             actual = list(actual_seq)
    893             missing, unexpected = unorderable_list_difference(
    894                 expected, actual, ignore_duplicate=False
    895             )
     884                # Handle case with unhashable elements
     885                differences = _count_diff_all_purpose(first_seq, second_seq)
    896886        else:
    897             return self.assertSequenceEqual(expected, actual, msg=msg)
     887                if first == second:
     888                    return
     889                differences = _count_diff_hashable(first_seq, second_seq)
    898890
    899         errors = []
    900         if missing:
    901             errors.append('Expected, but missing:\n    %s' %
    902                            safe_repr(missing))
    903         if unexpected:
    904             errors.append('Unexpected, but present:\n    %s' %
    905                            safe_repr(unexpected))
    906         if errors:
    907             standardMsg = '\n'.join(errors)
    908             self.fail(self._formatMessage(msg, standardMsg))
     891        if differences:
     892            standardMsg = 'Element counts were not equal:\n'
     893            lines = ['First has %d, Second has %d:  %r' % diff for diff in differences]
     894            diffMsg = '\n'.join(lines)
     895            standardMsg = self._truncateMessage(standardMsg, diffMsg)
     896            msg = self._formatMessage(msg, standardMsg)
     897            self.fail(msg)
    909898
    910899    def assertMultiLineEqual(self, first, second, msg=None):
    911900        """Assert that two multi-line strings are equal."""
    912         self.assertTrue(isinstance(first, basestring), (
    913                 'First argument is not a string'))
    914         self.assertTrue(isinstance(second, basestring), (
    915                 'Second argument is not a string'))
     901        self.assertIsInstance(first, basestring,
     902                'First argument is not a string')
     903        self.assertIsInstance(second, basestring,
     904                'Second argument is not a string')
    916905
    917906        if first != second:
    918             standardMsg = '%s != %s' % (safe_repr(first, True), safe_repr(second, True))
    919             diff = '\n' + ''.join(difflib.ndiff(first.splitlines(True),
    920                                                        second.splitlines(True)))
     907            # don't use difflib if the strings are too long
     908            if (len(first) > self._diffThreshold or
     909                len(second) > self._diffThreshold):
     910                self._baseAssertEqual(first, second, msg)
     911            firstlines = first.splitlines(True)
     912            secondlines = second.splitlines(True)
     913            if len(firstlines) == 1 and first.strip('\r\n') == first:
     914                firstlines = [first + '\n']
     915                secondlines = [second + '\n']
     916            standardMsg = '%s != %s' % (safe_repr(first, True),
     917                                        safe_repr(second, True))
     918            diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
    921919            standardMsg = self._truncateMessage(standardMsg, diff)
    922920            self.fail(self._formatMessage(msg, standardMsg))
    923921
     
    982980            args: Extra args.
    983981            kwargs: Extra kwargs.
    984982        """
     983        context = _AssertRaisesContext(expected_exception, self, expected_regexp)
    985984        if callable_obj is None:
    986             return _AssertRaisesContext(expected_exception, self, expected_regexp)
    987         try:
     985            return context
     986        with context:
    988987            callable_obj(*args, **kwargs)
    989         except expected_exception, exc_value:
    990             if isinstance(expected_regexp, basestring):
    991                 expected_regexp = re.compile(expected_regexp)
    992             if not expected_regexp.search(str(exc_value)):
    993                 raise self.failureException('"%s" does not match "%s"' %
    994                          (expected_regexp.pattern, str(exc_value)))
    995         else:
    996             if hasattr(expected_exception, '__name__'):
    997                 excName = expected_exception.__name__
    998             else:
    999                 excName = str(expected_exception)
    1000             raise self.failureException("%s not raised" % excName)
    1001988
    1002989    def assertRegexpMatches(self, text, expected_regexp, msg=None):
    1003990        """Fail the test unless the text matches the regular expression."""
     
    10211008                                               text)
    10221009            raise self.failureException(msg)
    10231010
     1011
    10241012class FunctionTestCase(TestCase):
    10251013    """A test case that wraps a test function.
    10261014
     
    10721060                            self._testFunc.__name__)
    10731061
    10741062    def __repr__(self):
    1075         return "<%s testFunc=%s>" % (strclass(self.__class__),
     1063        return "<%s tec=%s>" % (strclass(self.__class__),
    10761064                                     self._testFunc)
    10771065
    10781066    def shortDescription(self):
  • unittest/collector.py

    diff -u -Naur -x .svn -x .DS_Store -x test -x '*.pyc' -w django/utils/unittest/collector.py /Users/myk/Downloads/cpython-eb3c9b74884c/Lib/unittest/collector.py
    old new  
    1 import os
    2 import sys
    3 from django.utils.unittest.loader import defaultTestLoader
    4 
    5 def collector():
    6     # import __main__ triggers code re-execution
    7     __main__ = sys.modules['__main__']
    8     setupDir = os.path.abspath(os.path.dirname(__main__.__file__))
    9     return defaultTestLoader.discover(setupDir)
  • unittest/compatibility.py

    diff -u -Naur -x .svn -x .DS_Store -x test -x '*.pyc' -w django/utils/unittest/compatibility.py /Users/myk/Downloads/cpython-eb3c9b74884c/Lib/unittest/compatibility.py
    old new  
    1 import os
    2 import sys
    3 
    4 try:
    5     from functools import wraps
    6 except ImportError:
    7     # only needed for Python 2.4
    8     def wraps(_):
    9         def _wraps(func):
    10             return func
    11         return _wraps
    12 
    13 __unittest = True
    14 
    15 def _relpath_nt(path, start=os.path.curdir):
    16     """Return a relative version of a path"""
    17 
    18     if not path:
    19         raise ValueError("no path specified")
    20     start_list = os.path.abspath(start).split(os.path.sep)
    21     path_list = os.path.abspath(path).split(os.path.sep)
    22     if start_list[0].lower() != path_list[0].lower():
    23         unc_path, rest = os.path.splitunc(path)
    24         unc_start, rest = os.path.splitunc(start)
    25         if bool(unc_path) ^ bool(unc_start):
    26             raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
    27                                                                 % (path, start))
    28         else:
    29             raise ValueError("path is on drive %s, start on drive %s"
    30                                                 % (path_list[0], start_list[0]))
    31     # Work out how much of the filepath is shared by start and path.
    32     for i in range(min(len(start_list), len(path_list))):
    33         if start_list[i].lower() != path_list[i].lower():
    34             break
    35     else:
    36         i += 1
    37 
    38     rel_list = [os.path.pardir] * (len(start_list)-i) + path_list[i:]
    39     if not rel_list:
    40         return os.path.curdir
    41     return os.path.join(*rel_list)
    42 
    43 # default to posixpath definition
    44 def _relpath_posix(path, start=os.path.curdir):
    45     """Return a relative version of a path"""
    46 
    47     if not path:
    48         raise ValueError("no path specified")
    49 
    50     start_list = os.path.abspath(start).split(os.path.sep)
    51     path_list = os.path.abspath(path).split(os.path.sep)
    52 
    53     # Work out how much of the filepath is shared by start and path.
    54     i = len(os.path.commonprefix([start_list, path_list]))
    55 
    56     rel_list = [os.path.pardir] * (len(start_list)-i) + path_list[i:]
    57     if not rel_list:
    58         return os.path.curdir
    59     return os.path.join(*rel_list)
    60 
    61 if os.path is sys.modules.get('ntpath'):
    62     relpath = _relpath_nt
    63 else:
    64     relpath = _relpath_posix
  • unittest/loader.py

    diff -u -Naur -x .svn -x .DS_Store -x test -x '*.pyc' -w django/utils/unittest/loader.py /Users/myk/Downloads/cpython-eb3c9b74884c/Lib/unittest/loader.py
    old new  
    55import sys
    66import traceback
    77import types
    8 import unittest
    98
     9from functools import cmp_to_key as _CmpToKey
    1010from fnmatch import fnmatch
    1111
    12 from django.utils.unittest import case, suite
    13 
    14 try:
    15     from os.path import relpath
    16 except ImportError:
    17     from django.utils.unittest.compatibility import relpath
     12from . import case, suite
    1813
    1914__unittest = True
    2015
    21 
    22 def _CmpToKey(mycmp):
    23     'Convert a cmp= function into a key= function'
    24     class K(object):
    25         def __init__(self, obj):
    26             self.obj = obj
    27         def __lt__(self, other):
    28             return mycmp(self.obj, other.obj) == -1
    29     return K
    30 
    31 
    3216# what about .pyc or .pyo (etc)
    3317# we would need to avoid loading the same tests multiple times
    3418# from '.py', '.pyc' *and* '.pyo'
     
    3620
    3721
    3822def _make_failed_import_test(name, suiteClass):
    39     message = 'Failed to import test module: %s' % name
    40     if hasattr(traceback, 'format_exc'):
    41         # Python 2.3 compatibility
    42         # format_exc returns two frames of discover.py as well
    43         message += '\n%s' % traceback.format_exc()
     23    message = 'Failed to import test module: %s\n%s' % (name, traceback.format_exc())
    4424    return _make_failed_test('ModuleImportFailure', name, ImportError(message),
    4525                             suiteClass)
    4626
     
    5535    return suiteClass((TestClass(methodname),))
    5636
    5737
    58 class TestLoader(unittest.TestLoader):
     38class TestLoader(object):
    5939    """
    6040    This class is responsible for loading tests according to various criteria
    6141    and returning them wrapped in a TestSuite
     
    6848    def loadTestsFromTestCase(self, testCaseClass):
    6949        """Return a suite of all tests cases contained in testCaseClass"""
    7050        if issubclass(testCaseClass, suite.TestSuite):
    71             raise TypeError("Test cases should not be derived from TestSuite."
     51            raise TypeError("Test cases should not be derived from TestSuite." \
    7252                            " Maybe you meant to derive from TestCase?")
    7353        testCaseNames = self.getTestCaseNames(testCaseClass)
    7454        if not testCaseNames and hasattr(testCaseClass, 'runTest'):
     
    8161        tests = []
    8262        for name in dir(module):
    8363            obj = getattr(module, name)
    84             if isinstance(obj, type) and issubclass(obj, unittest.TestCase):
     64            if isinstance(obj, type) and issubclass(obj, case.TestCase):
    8565                tests.append(self.loadTestsFromTestCase(obj))
    8666
    8767        load_tests = getattr(module, 'load_tests', None)
     
    121101
    122102        if isinstance(obj, types.ModuleType):
    123103            return self.loadTestsFromModule(obj)
    124         elif isinstance(obj, type) and issubclass(obj, unittest.TestCase):
     104        elif isinstance(obj, type) and issubclass(obj, case.TestCase):
    125105            return self.loadTestsFromTestCase(obj)
    126106        elif (isinstance(obj, types.UnboundMethodType) and
    127107              isinstance(parent, type) and
    128108              issubclass(parent, case.TestCase)):
    129109            return self.suiteClass([parent(obj.__name__)])
    130         elif isinstance(obj, unittest.TestSuite):
     110        elif isinstance(obj, suite.TestSuite):
    131111            return obj
    132112        elif hasattr(obj, '__call__'):
    133113            test = obj()
    134             if isinstance(test, unittest.TestSuite):
     114            if isinstance(test, suite.TestSuite):
    135115                return test
    136             elif isinstance(test, unittest.TestCase):
     116            elif isinstance(test, case.TestCase):
    137117                return self.suiteClass([test])
    138118            else:
    139119                raise TypeError("calling %s returned %s, not a test" %
     
    215195                top_part = start_dir.split('.')[0]
    216196                start_dir = os.path.abspath(os.path.dirname((the_module.__file__)))
    217197                if set_implicit_top:
    218                     self._top_level_dir = os.path.abspath(os.path.dirname(os.path.dirname(sys.modules[top_part].__file__)))
     198                    self._top_level_dir = self._get_directory_containing_module(top_part)
    219199                    sys.path.remove(top_level_dir)
    220200
    221201        if is_not_importable:
     
    224204        tests = list(self._find_tests(start_dir, pattern))
    225205        return self.suiteClass(tests)
    226206
     207    def _get_directory_containing_module(self, module_name):
     208        module = sys.modules[module_name]
     209        full_path = os.path.abspath(module.__file__)
     210
     211        if os.path.basename(full_path).lower().startswith('__init__.py'):
     212            return os.path.dirname(os.path.dirname(full_path))
     213        else:
     214            # here we have been given a module rather than a package - so
     215            # all we can do is search the *same* directory the module is in
     216            # should an exception be raised instead
     217            return os.path.dirname(full_path)
     218
    227219    def _get_name_from_path(self, path):
    228220        path = os.path.splitext(os.path.normpath(path))[0]
    229221
    230         _relpath = relpath(path, self._top_level_dir)
     222        _relpath = os.path.relpath(path, self._top_level_dir)
    231223        assert not os.path.isabs(_relpath), "Path must be within the project"
    232224        assert not _relpath.startswith('..'), "Path must be within the project"
    233225
  • unittest/main.py

    diff -u -Naur -x .svn -x .DS_Store -x test -x '*.pyc' -w django/utils/unittest/main.py /Users/myk/Downloads/cpython-eb3c9b74884c/Lib/unittest/main.py
    old new  
    44import os
    55import types
    66
    7 from django.utils.unittest import loader, runner
    8 try:
    9     from django.utils.unittest.signals import installHandler
    10 except ImportError:
    11     installHandler = None
     7from . import loader, runner
     8from .signals import installHandler
    129
    1310__unittest = True
    1411
     
    2623%(failfast)s%(catchbreak)s%(buffer)s
    2724Examples:
    2825  %(progName)s test_module                       - run tests from test_module
    29   %(progName)s test_module.TestClass             - run tests from
    30                                                    test_module.TestClass
    31   %(progName)s test_module.TestClass.test_method - run specified test method
     26  %(progName)s module.TestClass          - run tests from module.TestClass
     27  %(progName)s module.Class.test_method  - run specified test method
    3228
    3329[tests] can be a list of any number of test modules, classes and test
    3430methods.
     
    6359"""
    6460
    6561
     62
    6663class TestProgram(object):
    6764    """A command-line program that runs a set of tests; this is primarily
    6865       for making test modules conveniently executable.
     
    7269    # defaults for testing
    7370    failfast = catchbreak = buffer = progName = None
    7471
    75     def __init__(self, module='__main__', defaultTest=None,
    76                  argv=None, testRunner=None,
    77                  testLoader=loader.defaultTestLoader, exit=True,
    78                  verbosity=1, failfast=None, catchbreak=None, buffer=None):
     72    def __init__(self, module='__main__', defaultTest=None, argv=None,
     73                    testRunner=None, testLoader=loader.defaultTestLoader,
     74                    exit=True, verbosity=1, failfast=None, catchbreak=None,
     75                   buffer=None):
    7976        if isinstance(module, basestring):
    8077            self.module = __import__(module)
    8178            for part in module.split('.')[1:]:
     
    8683            argv = sys.argv
    8784
    8885        self.exit = exit
    89         self.verbosity = verbosity
    9086        self.failfast = failfast
    9187        self.catchbreak = catchbreak
     88        self.verbosity = verbosity
    9289        self.buffer = buffer
    9390        self.defaultTest = defaultTest
    9491        self.testRunner = testRunner
     
    104101                 'buffer': ''}
    105102        if self.failfast != False:
    106103            usage['failfast'] = FAILFAST
    107         if self.catchbreak != False and installHandler is not None:
     104        if self.catchbreak != False:
    108105            usage['catchbreak'] = CATCHBREAK
    109106        if self.buffer != False:
    110107            usage['buffer'] = BUFFEROUTPUT
     
    132129                        self.failfast = True
    133130                    # Should this raise an exception if -f is not valid?
    134131                if opt in ('-c','--catch'):
    135                     if self.catchbreak is None and installHandler is not None:
     132                    if self.catchbreak is None:
    136133                        self.catchbreak = True
    137134                    # Should this raise an exception if -c is not valid?
    138135                if opt in ('-b','--buffer'):
     
    172169            parser.add_option('-f', '--failfast', dest='failfast', default=False,
    173170                              help='Stop on first fail or error',
    174171                              action='store_true')
    175         if self.catchbreak != False and installHandler is not None:
     172        if self.catchbreak != False:
    176173            parser.add_option('-c', '--catch', dest='catchbreak', default=False,
    177174                              help='Catch ctrl-C and display results so far',
    178175                              action='store_true')
     
    198195        # if they weren't set explicitly in the constructor
    199196        if self.failfast is None:
    200197            self.failfast = options.failfast
    201         if self.catchbreak is None and installHandler is not None:
     198        if self.catchbreak is None:
    202199            self.catchbreak = options.catchbreak
    203200        if self.buffer is None:
    204201            self.buffer = options.buffer
     
    234231            sys.exit(not self.result.wasSuccessful())
    235232
    236233main = TestProgram
    237 
    238 def main_():
    239     TestProgram.USAGE = USAGE_AS_MAIN
    240     main(module=None)
    241 
  • unittest/result.py

    diff -u -Naur -x .svn -x .DS_Store -x test -x '*.pyc' -w django/utils/unittest/result.py /Users/myk/Downloads/cpython-eb3c9b74884c/Lib/unittest/result.py
    old new  
    11"""Test result object"""
    22
     3import os
    34import sys
    45import traceback
    5 import unittest
    66
    77from StringIO import StringIO
    88
    9 from django.utils.unittest import util
    10 from django.utils.unittest.compatibility import wraps
     9from . import util
     10from functools import wraps
    1111
    1212__unittest = True
    1313
     
    1919        return method(self, *args, **kw)
    2020    return inner
    2121
    22 
    2322STDOUT_LINE = '\nStdout:\n%s'
    2423STDERR_LINE = '\nStderr:\n%s'
    2524
    26 class TestResult(unittest.TestResult):
     25
     26class TestResult(object):
    2727    """Holder for test result information.
    2828
    2929    Test results are automatically managed by the TestCase and TestSuite
     
    3535    formatted traceback of the error that occurred.
    3636    """
    3737    _previousTestClass = None
     38    _testRunEntered = False
    3839    _moduleSetUpFailed = False
    39 
    40     def __init__(self):
     40    def __init__(self, stream=None, descriptions=None, verbosity=None):
    4141        self.failfast = False
    4242        self.failures = []
    4343        self.errors = []
     
    5353        self._original_stderr = sys.stderr
    5454        self._mirrorOutput = False
    5555
     56    def printErrors(self):
     57        "Called by TestRunner after test run"
     58
    5659    def startTest(self, test):
    5760        "Called when the given test is about to be run"
    5861        self.testsRun += 1
    5962        self._mirrorOutput = False
     63        self._setupStdout()
     64
     65    def _setupStdout(self):
    6066        if self.buffer:
    6167            if self._stderr_buffer is None:
    6268                self._stderr_buffer = StringIO()
     
    7278
    7379    def stopTest(self, test):
    7480        """Called when the given test has been run"""
     81        self._restoreStdout()
     82        self._mirrorOutput = False
     83
     84    def _restoreStdout(self):
    7585        if self.buffer:
    7686            if self._mirrorOutput:
    7787                output = sys.stdout.getvalue()
     
    91101            self._stdout_buffer.truncate()
    92102            self._stderr_buffer.seek(0)
    93103            self._stderr_buffer.truncate()
    94         self._mirrorOutput = False
    95 
    96104
    97105    def stopTestRun(self):
    98106        """Called once after all tests are executed.
     
    135143
    136144    def wasSuccessful(self):
    137145        "Tells whether or not this result was a success"
    138         return (len(self.failures) + len(self.errors) == 0)
     146        return len(self.failures) == len(self.errors) == 0
    139147
    140148    def stop(self):
    141149        "Indicates that the tests should be aborted"
     
    147155        # Skip test runner traceback levels
    148156        while tb and self._is_relevant_tb_level(tb):
    149157            tb = tb.tb_next
     158
    150159        if exctype is test.failureException:
    151160            # Skip assert*() traceback levels
    152161            length = self._count_relevant_tb_levels(tb)
     
    167176                msgLines.append(STDERR_LINE % error)
    168177        return ''.join(msgLines)
    169178
     179
    170180    def _is_relevant_tb_level(self, tb):
    171181        return '__unittest' in tb.tb_frame.f_globals
    172182
     
    178188        return length
    179189
    180190    def __repr__(self):
    181         return "<%s run=%i errors=%i failures=%i>" % \
     191        return ("<%s run=%i errors=%i failures=%i>" %
    182192               (util.strclass(self.__class__), self.testsRun, len(self.errors),
    183                 len(self.failures))
     193                len(self.failures)))
  • unittest/runner.py

    diff -u -Naur -x .svn -x .DS_Store -x test -x '*.pyc' -w django/utils/unittest/runner.py /Users/myk/Downloads/cpython-eb3c9b74884c/Lib/unittest/runner.py
    old new  
    22
    33import sys
    44import time
    5 import unittest
    65
    7 from django.utils.unittest import result
    8 
    9 try:
    10     from django.utils.unittest.signals import registerResult
    11 except ImportError:
    12     def registerResult(_):
    13         pass
     6from . import result
     7from .signals import registerResult
    148
    159__unittest = True
    1610
     
    8781    def addSkip(self, test, reason):
    8882        super(TextTestResult, self).addSkip(test, reason)
    8983        if self.showAll:
    90             self.stream.writeln("skipped %r" % (reason,))
     84            self.stream.writeln("skipped {0!r}".format(reason))
    9185        elif self.dots:
    9286            self.stream.write("s")
    9387            self.stream.flush()
     
    121115            self.stream.writeln(self.separator2)
    122116            self.stream.writeln("%s" % err)
    123117
    124     def stopTestRun(self):
    125         super(TextTestResult, self).stopTestRun()
    126         self.printErrors()
    127 
    128118
    129 class TextTestRunner(unittest.TextTestRunner):
     119class TextTestRunner(object):
    130120    """A test runner class that displays results in textual form.
    131121
    132122    It prints out the names of tests as they are run, errors as they
     
    150140    def run(self, test):
    151141        "Run the given test case or test suite."
    152142        result = self._makeResult()
     143        registerResult(result)
    153144        result.failfast = self.failfast
    154145        result.buffer = self.buffer
    155         registerResult(result)
    156 
    157146        startTime = time.time()
    158147        startTestRun = getattr(result, 'startTestRun', None)
    159148        if startTestRun is not None:
     
    164153            stopTestRun = getattr(result, 'stopTestRun', None)
    165154            if stopTestRun is not None:
    166155                stopTestRun()
    167             else:
    168                 result.printErrors()
    169156        stopTime = time.time()
    170157        timeTaken = stopTime - startTime
     158        result.printErrors()
    171159        if hasattr(result, 'separator2'):
    172160            self.stream.writeln(result.separator2)
    173161        run = result.testsRun
     
    180168            results = map(len, (result.expectedFailures,
    181169                                result.unexpectedSuccesses,
    182170                                result.skipped))
    183             expectedFails, unexpectedSuccesses, skipped = results
    184171        except AttributeError:
    185172            pass
     173        else:
     174            expectedFails, unexpectedSuccesses, skipped = results
     175
    186176        infos = []
    187177        if not result.wasSuccessful():
    188178            self.stream.write("FAILED")
  • unittest/signals.py

    diff -u -Naur -x .svn -x .DS_Store -x test -x '*.pyc' -w django/utils/unittest/signals.py /Users/myk/Downloads/cpython-eb3c9b74884c/Lib/unittest/signals.py
    old new  
    11import signal
    22import weakref
    33
    4 from django.utils.unittest.compatibility import wraps
     4from functools import wraps
    55
    66__unittest = True
    77
  • unittest/suite.py

    diff -u -Naur -x .svn -x .DS_Store -x test -x '*.pyc' -w django/utils/unittest/suite.py /Users/myk/Downloads/cpython-eb3c9b74884c/Lib/unittest/suite.py
    old new  
    11"""TestSuite"""
    22
    33import sys
    4 import unittest
    5 from django.utils.unittest import case, util
     4
     5from . import case
     6from . import util
    67
    78__unittest = True
    89
    910
    10 class BaseTestSuite(unittest.TestSuite):
     11def _call_if_exists(parent, attr):
     12    func = getattr(parent, attr, lambda: None)
     13    func()
     14
     15
     16class BaseTestSuite(object):
    1117    """A simple test suite that doesn't provide class or module shared fixtures.
    1218    """
    1319    def __init__(self, tests=()):
     
    4046    def addTest(self, test):
    4147        # sanity checks
    4248        if not hasattr(test, '__call__'):
    43             raise TypeError("%r is not callable" % (repr(test),))
     49            raise TypeError("{} is not callable".format(repr(test)))
    4450        if isinstance(test, type) and issubclass(test,
    4551                                                 (case.TestCase, TestSuite)):
    4652            raise TypeError("TestCases and TestSuites must be instantiated "
     
    7985    subclassing, do not forget to call the base class constructor.
    8086    """
    8187
     88    def run(self, result, debug=False):
     89        topLevel = False
     90        if getattr(result, '_testRunEntered', False) is False:
     91            result._testRunEntered = topLevel = True
    8292
    83     def run(self, result):
    84         self._wrapped_run(result)
    85         self._tearDownPreviousClass(None, result)
    86         self._handleModuleTearDown(result)
    87         return result
    88 
    89     def debug(self):
    90         """Run the tests without collecting errors in a TestResult"""
    91         debug = _DebugResult()
    92         self._wrapped_run(debug, True)
    93         self._tearDownPreviousClass(None, debug)
    94         self._handleModuleTearDown(debug)
    95 
    96     ################################
    97     # private methods
    98     def _wrapped_run(self, result, debug=False):
    9993        for test in self:
    10094            if result.shouldStop:
    10195                break
     
    110104                    getattr(result, '_moduleSetUpFailed', False)):
    111105                    continue
    112106
    113             if hasattr(test, '_wrapped_run'):
    114                 test._wrapped_run(result, debug)
    115             elif not debug:
     107            if not debug:
    116108                test(result)
    117109            else:
    118110                test.debug()
    119111
     112        if topLevel:
     113            self._tearDownPreviousClass(None, result)
     114            self._handleModuleTearDown(result)
     115            result._testRunEntered = False
     116        return result
     117
     118    def debug(self):
     119        """Run the tests without collecting errors in a TestResult"""
     120        debug = _DebugResult()
     121        self.run(debug, True)
     122
     123    ################################
     124
    120125    def _handleClassSetUp(self, test, result):
    121126        previousClass = getattr(result, '_previousTestClass', None)
    122127        currentClass = test.__class__
     
    136141
    137142        setUpClass = getattr(currentClass, 'setUpClass', None)
    138143        if setUpClass is not None:
     144            _call_if_exists(result, '_setupStdout')
    139145            try:
    140146                setUpClass()
    141             except Exception, e:
     147            except Exception as e:
    142148                if isinstance(result, _DebugResult):
    143149                    raise
    144150                currentClass._classSetupFailed = True
    145151                className = util.strclass(currentClass)
    146152                errorName = 'setUpClass (%s)' % className
    147153                self._addClassOrModuleLevelException(result, e, errorName)
     154            finally:
     155                _call_if_exists(result, '_restoreStdout')
    148156
    149157    def _get_previous_module(self, result):
    150158        previousModule = None
     
    162170
    163171        self._handleModuleTearDown(result)
    164172
    165 
    166173        result._moduleSetUpFailed = False
    167174        try:
    168175            module = sys.modules[currentModule]
     
    170177            return
    171178        setUpModule = getattr(module, 'setUpModule', None)
    172179        if setUpModule is not None:
     180            _call_if_exists(result, '_setupStdout')
    173181            try:
    174182                setUpModule()
    175183            except Exception, e:
     
    178186                result._moduleSetUpFailed = True
    179187                errorName = 'setUpModule (%s)' % currentModule
    180188                self._addClassOrModuleLevelException(result, e, errorName)
     189            finally:
     190                _call_if_exists(result, '_restoreStdout')
    181191
    182192    def _addClassOrModuleLevelException(self, result, exception, errorName):
    183193        error = _ErrorHolder(errorName)
     
    201211
    202212        tearDownModule = getattr(module, 'tearDownModule', None)
    203213        if tearDownModule is not None:
     214            _call_if_exists(result, '_setupStdout')
    204215            try:
    205216                tearDownModule()
    206             except Exception, e:
     217            except Exception as e:
    207218                if isinstance(result, _DebugResult):
    208219                    raise
    209220                errorName = 'tearDownModule (%s)' % previousModule
    210221                self._addClassOrModuleLevelException(result, e, errorName)
     222            finally:
     223                _call_if_exists(result, '_restoreStdout')
    211224
    212225    def _tearDownPreviousClass(self, test, result):
    213226        previousClass = getattr(result, '_previousTestClass', None)
     
    223236
    224237        tearDownClass = getattr(previousClass, 'tearDownClass', None)
    225238        if tearDownClass is not None:
     239            _call_if_exists(result, '_setupStdout')
    226240            try:
    227241                tearDownClass()
    228242            except Exception, e:
     
    231245                className = util.strclass(previousClass)
    232246                errorName = 'tearDownClass (%s)' % className
    233247                self._addClassOrModuleLevelException(result, e, errorName)
     248            finally:
     249                _call_if_exists(result, '_restoreStdout')
    234250
    235251
    236252class _ErrorHolder(object):
  • unittest/util.py

    diff -u -Naur -x .svn -x .DS_Store -x test -x '*.pyc' -w django/utils/unittest/util.py /Users/myk/Downloads/cpython-eb3c9b74884c/Lib/unittest/util.py
    old new  
    11"""Various utility functions."""
     2from collections import namedtuple, OrderedDict
    23
    3 __unittest = True
    44
     5__unittest = True
    56
    67_MAX_LENGTH = 80
    78def safe_repr(obj, short=False):
     
    1314        return result
    1415    return result[:_MAX_LENGTH] + ' [truncated]...'
    1516
    16 def safe_str(obj):
    17     try:
    18         return str(obj)
    19     except Exception:
    20         return object.__str__(obj)
    2117
    2218def strclass(cls):
    2319    return "%s.%s" % (cls.__module__, cls.__name__)
     
    6258            break
    6359    return missing, unexpected
    6460
     61
    6562def unorderable_list_difference(expected, actual, ignore_duplicate=False):
    6663    """Same behavior as sorted_list_difference but
    6764    for lists of unorderable items (like dicts).
     
    9794
    9895    # anything left in actual is unexpected
    9996    return missing, actual
     97
     98_Mismatch = namedtuple('Mismatch', 'actual expected value')
     99
     100def _count_diff_all_purpose(actual, expected):
     101    'Returns list of (cnt_act, cnt_exp, elem) triples where the counts differ'
     102    # elements need not be hashable
     103    s, t = list(actual), list(expected)
     104    m, n = len(s), len(t)
     105    NULL = object()
     106    result = []
     107    for i, elem in enumerate(s):
     108        if elem is NULL:
     109            continue
     110        cnt_s = cnt_t = 0
     111        for j in range(i, m):
     112            if s[j] == elem:
     113                cnt_s += 1
     114                s[j] = NULL
     115        for j, other_elem in enumerate(t):
     116            if other_elem == elem:
     117                cnt_t += 1
     118                t[j] = NULL
     119        if cnt_s != cnt_t:
     120            diff = _Mismatch(cnt_s, cnt_t, elem)
     121            result.append(diff)
     122
     123    for i, elem in enumerate(t):
     124        if elem is NULL:
     125            continue
     126        cnt_t = 0
     127        for j in range(i, n):
     128            if t[j] == elem:
     129                cnt_t += 1
     130                t[j] = NULL
     131        diff = _Mismatch(0, cnt_t, elem)
     132        result.append(diff)
     133    return result
     134
     135def _ordered_count(iterable):
     136    'Return dict of element counts, in the order they were first seen'
     137    c = OrderedDict()
     138    for elem in iterable:
     139        c[elem] = c.get(elem, 0) + 1
     140    return c
     141
     142def _count_diff_hashable(actual, expected):
     143    'Returns list of (cnt_act, cnt_exp, elem) triples where the counts differ'
     144    # elements must be hashable
     145    s, t = _ordered_count(actual), _ordered_count(expected)
     146    result = []
     147    for elem, cnt_s in s.items():
     148        cnt_t = t.get(elem, 0)
     149        if cnt_s != cnt_t:
     150            diff = _Mismatch(cnt_s, cnt_t, elem)
     151            result.append(diff)
     152    for elem, cnt_t in t.items():
     153        if elem not in s:
     154            diff = _Mismatch(0, cnt_t, elem)
     155            result.append(diff)
     156    return result
Back to Top