Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Lib/test/test_py3kwarn.py

    r2 r391  
    11import unittest
    22import sys
    3 from test.test_support import (check_warnings, CleanImport,
    4                                TestSkipped, run_unittest)
     3from test.test_support import check_py3k_warnings, CleanImport, run_unittest
    54import warnings
    65
    7 from contextlib import nested
    8 
    96if not sys.py3kwarning:
    10     raise TestSkipped('%s must be run with the -3 flag' % __name__)
     7    raise unittest.SkipTest('%s must be run with the -3 flag' % __name__)
     8
     9try:
     10    from test.test_support import __warningregistry__ as _registry
     11except ImportError:
     12    def check_deprecated_module(module_name):
     13        return False
     14else:
     15    past_warnings = _registry.keys()
     16    del _registry
     17    def check_deprecated_module(module_name):
     18        """Lookup the past warnings for module already loaded using
     19        test_support.import_module(..., deprecated=True)
     20        """
     21        return any(module_name in msg and ' removed' in msg
     22                   and issubclass(cls, DeprecationWarning)
     23                   and (' module' in msg or ' package' in msg)
     24                   for (msg, cls, line) in past_warnings)
    1125
    1226def reset_module_registry(module):
     
    2842    def test_backquote(self):
    2943        expected = 'backquote not supported in 3.x; use repr()'
    30         with check_warnings() as w:
     44        with check_py3k_warnings((expected, SyntaxWarning)):
    3145            exec "`2`" in {}
    32         self.assertWarning(None, w, expected)
    3346
    3447    def test_paren_arg_names(self):
    3548        expected = 'parenthesized argument names are invalid in 3.x'
    3649        def check(s):
    37             exec s in {}
    38             self.assertWarning(None, w, expected)
    39         with check_warnings() as w:
    40             check("def f((x)): pass")
    41             check("def f((((x))), (y)): pass")
    42             check("def f((x), (((y))), m=32): pass")
    43             # Something like def f((a, (b))): pass will raise the tuple
    44             # unpacking warning.
    45 
    46     def test_bool_assign(self):
     50            with check_py3k_warnings((expected, SyntaxWarning)):
     51                exec s in {}
     52        check("def f((x)): pass")
     53        check("def f((((x))), (y)): pass")
     54        check("def f((x), (((y))), m=32): pass")
     55        # Something like def f((a, (b))): pass will raise the tuple
     56        # unpacking warning.
     57
     58    def test_forbidden_names(self):
    4759        # So we don't screw up our globals
    4860        def safe_exec(expr):
     
    5062            exec expr in {'f' : f}
    5163
    52         expected = "assignment to True or False is forbidden in 3.x"
    53         with check_warnings() as w:
    54             safe_exec("True = False")
    55             self.assertWarning(None, w, expected)
    56             w.reset()
    57             safe_exec("False = True")
    58             self.assertWarning(None, w, expected)
    59             w.reset()
    60             try:
    61                 safe_exec("obj.False = True")
    62             except NameError: pass
    63             self.assertWarning(None, w, expected)
    64             w.reset()
    65             try:
    66                 safe_exec("obj.True = False")
    67             except NameError: pass
    68             self.assertWarning(None, w, expected)
    69             w.reset()
    70             safe_exec("def False(): pass")
    71             self.assertWarning(None, w, expected)
    72             w.reset()
    73             safe_exec("def True(): pass")
    74             self.assertWarning(None, w, expected)
    75             w.reset()
    76             safe_exec("class False: pass")
    77             self.assertWarning(None, w, expected)
    78             w.reset()
    79             safe_exec("class True: pass")
    80             self.assertWarning(None, w, expected)
    81             w.reset()
    82             safe_exec("def f(True=43): pass")
    83             self.assertWarning(None, w, expected)
    84             w.reset()
    85             safe_exec("def f(False=None): pass")
    86             self.assertWarning(None, w, expected)
    87             w.reset()
    88             safe_exec("f(False=True)")
    89             self.assertWarning(None, w, expected)
    90             w.reset()
    91             safe_exec("f(True=1)")
    92             self.assertWarning(None, w, expected)
     64        tests = [("True", "assignment to True or False is forbidden in 3.x"),
     65                 ("False", "assignment to True or False is forbidden in 3.x"),
     66                 ("nonlocal", "nonlocal is a keyword in 3.x")]
     67        with check_py3k_warnings(('', SyntaxWarning)) as w:
     68            for keyword, expected in tests:
     69                safe_exec("{0} = False".format(keyword))
     70                self.assertWarning(None, w, expected)
     71                w.reset()
     72                try:
     73                    safe_exec("obj.{0} = True".format(keyword))
     74                except NameError:
     75                    pass
     76                self.assertWarning(None, w, expected)
     77                w.reset()
     78                safe_exec("def {0}(): pass".format(keyword))
     79                self.assertWarning(None, w, expected)
     80                w.reset()
     81                safe_exec("class {0}: pass".format(keyword))
     82                self.assertWarning(None, w, expected)
     83                w.reset()
     84                safe_exec("def f({0}=43): pass".format(keyword))
     85                self.assertWarning(None, w, expected)
     86                w.reset()
    9387
    9488
    9589    def test_type_inequality_comparisons(self):
    9690        expected = 'type inequality comparisons not supported in 3.x'
    97         with check_warnings() as w:
     91        with check_py3k_warnings() as w:
    9892            self.assertWarning(int < str, w, expected)
    9993            w.reset()
     
    10296    def test_object_inequality_comparisons(self):
    10397        expected = 'comparing unequal types not supported in 3.x'
    104         with check_warnings() as w:
     98        with check_py3k_warnings() as w:
    10599            self.assertWarning(str < [], w, expected)
    106100            w.reset()
     
    109103    def test_dict_inequality_comparisons(self):
    110104        expected = 'dict inequality comparisons not supported in 3.x'
    111         with check_warnings() as w:
     105        with check_py3k_warnings() as w:
    112106            self.assertWarning({} < {2:3}, w, expected)
    113107            w.reset()
     
    126120        cell0, = f(0).func_closure
    127121        cell1, = f(1).func_closure
    128         with check_warnings() as w:
     122        with check_py3k_warnings() as w:
    129123            self.assertWarning(cell0 == cell1, w, expected)
    130124            w.reset()
     
    137131        def g(x):
    138132            pass
    139         with check_warnings() as w:
     133        with check_py3k_warnings() as w:
    140134            self.assertWarning(f.func_code < g.func_code, w, expected)
    141135            w.reset()
     
    151145        func = eval
    152146        meth = {}.get
    153         with check_warnings() as w:
     147        with check_py3k_warnings() as w:
    154148            self.assertWarning(func < meth, w, expected)
    155149            w.reset()
     
    166160            self.assertNoWarning(lam != func, w)
    167161
     162    def test_frame_attributes(self):
     163        template = "%s has been removed in 3.x"
     164        f = sys._getframe(0)
     165        for attr in ("f_exc_traceback", "f_exc_value", "f_exc_type"):
     166            expected = template % attr
     167            with check_py3k_warnings() as w:
     168                self.assertWarning(getattr(f, attr), w, expected)
     169                w.reset()
     170                self.assertWarning(setattr(f, attr, None), w, expected)
     171
    168172    def test_sort_cmp_arg(self):
    169173        expected = "the cmp argument is not supported in 3.x"
     
    171175        cmp = lambda x,y: -1
    172176
    173         with check_warnings() as w:
     177        with check_py3k_warnings() as w:
    174178            self.assertWarning(lst.sort(cmp=cmp), w, expected)
    175179            w.reset()
     
    182186    def test_sys_exc_clear(self):
    183187        expected = 'sys.exc_clear() not supported in 3.x; use except clauses'
    184         with check_warnings() as w:
     188        with check_py3k_warnings() as w:
    185189            self.assertWarning(sys.exc_clear(), w, expected)
    186190
     
    191195            __members__ = ['b']
    192196        c = C()
    193         with check_warnings() as w:
     197        with check_py3k_warnings() as w:
    194198            self.assertWarning(dir(c), w, expected)
    195199
     
    197201        expected = 'file.softspace not supported in 3.x'
    198202        with file(__file__) as f:
    199             with check_warnings() as w:
     203            with check_py3k_warnings() as w:
    200204                self.assertWarning(f.softspace, w, expected)
    201205            def set():
    202206                f.softspace = 0
    203             with check_warnings() as w:
     207            with check_py3k_warnings() as w:
    204208                self.assertWarning(set(), w, expected)
    205209
     
    217221
    218222        for obj in (Spam(), Egg()):
    219             with check_warnings() as w:
     223            with check_py3k_warnings() as w:
    220224                self.assertWarning(obj[1:2], w, expected.format('get'))
    221225                w.reset()
     
    228232    def test_tuple_parameter_unpacking(self):
    229233        expected = "tuple parameter unpacking has been removed in 3.x"
    230         with check_warnings() as w:
     234        with check_py3k_warnings((expected, SyntaxWarning)):
    231235            exec "def f((a, b)): pass"
    232             self.assertWarning(None, w, expected)
    233236
    234237    def test_buffer(self):
    235238        expected = 'buffer() not supported in 3.x'
    236         with check_warnings() as w:
     239        with check_py3k_warnings() as w:
    237240            self.assertWarning(buffer('a'), w, expected)
    238241
     
    241244                    "try 'for line in f' instead")
    242245        with file(__file__) as f:
    243             with check_warnings() as w:
     246            with check_py3k_warnings() as w:
    244247                self.assertWarning(f.xreadlines(), w, expected)
    245248
    246249    def test_hash_inheritance(self):
    247         with check_warnings() as w:
     250        with check_py3k_warnings() as w:
    248251            # With object as the base class
    249252            class WarnOnlyCmp(object):
    250253                def __cmp__(self, other): pass
    251             self.assertEqual(len(w.warnings), 1)
    252             self.assertWarning(None, w,
    253                  "Overriding __cmp__ blocks inheritance of __hash__ in 3.x")
     254            self.assertEqual(len(w.warnings), 0)
    254255            w.reset()
    255256            class WarnOnlyEq(object):
     
    262263                def __cmp__(self, other): pass
    263264                def __eq__(self, other): pass
    264             self.assertEqual(len(w.warnings), 2)
    265             self.assertWarning(None, w.warnings[0],
    266                  "Overriding __cmp__ blocks inheritance of __hash__ in 3.x")
     265            self.assertEqual(len(w.warnings), 1)
    267266            self.assertWarning(None, w,
    268267                 "Overriding __eq__ blocks inheritance of __hash__ in 3.x")
     
    278277            class WarnOnlyCmp(DefinesAllThree):
    279278                def __cmp__(self, other): pass
    280             self.assertEqual(len(w.warnings), 1)
    281             self.assertWarning(None, w,
    282                  "Overriding __cmp__ blocks inheritance of __hash__ in 3.x")
     279            self.assertEqual(len(w.warnings), 0)
    283280            w.reset()
    284281            class WarnOnlyEq(DefinesAllThree):
     
    291288                def __cmp__(self, other): pass
    292289                def __eq__(self, other): pass
    293             self.assertEqual(len(w.warnings), 2)
    294             self.assertWarning(None, w.warnings[0],
    295                  "Overriding __cmp__ blocks inheritance of __hash__ in 3.x")
     290            self.assertEqual(len(w.warnings), 1)
    296291            self.assertWarning(None, w,
    297292                 "Overriding __eq__ blocks inheritance of __hash__ in 3.x")
     
    300295                def __hash__(self): pass
    301296            self.assertEqual(len(w.warnings), 0)
     297
     298    def test_operator(self):
     299        from operator import isCallable, sequenceIncludes
     300
     301        callable_warn = ("operator.isCallable() is not supported in 3.x. "
     302                         "Use hasattr(obj, '__call__').")
     303        seq_warn = ("operator.sequenceIncludes() is not supported "
     304                    "in 3.x. Use operator.contains().")
     305        with check_py3k_warnings() as w:
     306            self.assertWarning(isCallable(self), w, callable_warn)
     307            w.reset()
     308            self.assertWarning(sequenceIncludes(range(3), 2), w, seq_warn)
    302309
    303310
     
    317324                                     'readcd', 'SV', 'torgb', 'WAIT'),
    318325                          'darwin' : ('autoGIL', 'Carbon', 'OSATerminology',
    319                                       'icglue', 'Nav', 'MacOS', 'aepack',
     326                                      'icglue', 'Nav',
     327                                      # MacOS should (and does) give a Py3kWarning, but one of the
     328                                      # earlier tests already imports the MacOS extension which causes
     329                                      # this test to fail. Disabling the test for 'MacOS' avoids this
     330                                      # spurious test failure.
     331                                      #'MacOS',
     332                                      'aepack',
    320333                                      'aetools', 'aetypes', 'applesingle',
    321334                                      'appletrawmain', 'appletrunner',
     
    339352        """Make sure the specified module, when imported, raises a
    340353        DeprecationWarning and specifies itself in the message."""
    341         with nested(CleanImport(module_name), warnings.catch_warnings()):
    342             # XXX: This is not quite enough for extension modules - those
    343             # won't rerun their init code even with CleanImport.
    344             # You can see this easily by running the whole test suite with -3
    345             warnings.filterwarnings("error", ".+ removed",
     354        with CleanImport(module_name), warnings.catch_warnings():
     355            warnings.filterwarnings("error", ".+ (module|package) .+ removed",
     356                                    DeprecationWarning, __name__)
     357            warnings.filterwarnings("error", ".+ removed .+ (module|package)",
    346358                                    DeprecationWarning, __name__)
    347359            try:
    348360                __import__(module_name, level=0)
    349361            except DeprecationWarning as exc:
    350                 self.assert_(module_name in exc.args[0],
    351                              "%s warning didn't contain module name"
    352                              % module_name)
     362                self.assertIn(module_name, exc.args[0],
     363                              "%s warning didn't contain module name"
     364                              % module_name)
    353365            except ImportError:
    354366                if not optional:
     
    356368                              "ImportError.".format(module_name))
    357369            else:
    358                 self.fail("DeprecationWarning not raised for {0}"
    359                             .format(module_name))
     370                # For extension modules, check the __warningregistry__.
     371                # They won't rerun their init code even with CleanImport.
     372                if not check_deprecated_module(module_name):
     373                    self.fail("DeprecationWarning not raised for {0}"
     374                              .format(module_name))
    360375
    361376    def test_platform_independent_removals(self):
     
    381396            mod = __import__(path_mod)
    382397            reset_module_registry(mod)
    383             with check_warnings() as w:
     398            with check_py3k_warnings() as w:
    384399                mod.walk("crashers", dumbo, None)
    385             self.assertEquals(str(w.message), msg)
    386 
    387     def test_commands_members(self):
    388         import commands
    389         # commands module tests may have already triggered this warning
    390         reset_module_registry(commands)
    391         members = {"mk2arg" : 2, "mkarg" : 1, "getstatus" : 1}
    392         for name, arg_count in members.items():
    393             with warnings.catch_warnings():
    394                 warnings.filterwarnings("error")
    395                 func = getattr(commands, name)
    396                 self.assertRaises(DeprecationWarning, func, *([None]*arg_count))
     400            self.assertEqual(str(w.message), msg)
    397401
    398402    def test_reduce_move(self):
    399403        from operator import add
    400404        # reduce tests may have already triggered this warning
    401         reset_module_registry(unittest)
     405        reset_module_registry(unittest.case)
    402406        with warnings.catch_warnings():
    403407            warnings.filterwarnings("error", "reduce")
     
    416420
    417421def test_main():
    418     with check_warnings():
    419         warnings.simplefilter("always")
    420         run_unittest(TestPy3KWarnings,
    421                      TestStdlibRemovals)
     422    run_unittest(TestPy3KWarnings,
     423                 TestStdlibRemovals)
    422424
    423425if __name__ == '__main__':
Note: See TracChangeset for help on using the changeset viewer.