ยปCore Development>Code coverage>Lib/test/test_py3kwarn.py

Python code coverage for Lib/test/test_py3kwarn.py

#countcontent
11import unittest
21import sys
31from test.test_support import check_py3k_warnings, CleanImport, run_unittest
41import warnings
5n/a
61if not sys.py3kwarning:
71 raise unittest.SkipTest('%s must be run with the -3 flag' % __name__)
8n/a
90try:
100 from test.test_support import __warningregistry__ as _registry
110except ImportError:
120 def check_deprecated_module(module_name):
130 return False
14n/aelse:
150 past_warnings = _registry.keys()
160 del _registry
170 def check_deprecated_module(module_name):
18n/a """Lookup the past warnings for module already loaded using
19n/a test_support.import_module(..., deprecated=True)
20n/a """
210 return any(module_name in msg and ' removed' in msg
22n/a and issubclass(cls, DeprecationWarning)
23n/a and (' module' in msg or ' package' in msg)
240 for (msg, cls, line) in past_warnings)
25n/a
260def reset_module_registry(module):
270 try:
280 registry = module.__warningregistry__
290 except AttributeError:
300 pass
31n/a else:
320 registry.clear()
33n/a
340class TestPy3KWarnings(unittest.TestCase):
35n/a
360 def assertWarning(self, _, warning, expected_message):
370 self.assertEqual(str(warning.message), expected_message)
38n/a
390 def assertNoWarning(self, _, recorder):
400 self.assertEqual(len(recorder.warnings), 0)
41n/a
420 def test_backquote(self):
430 expected = 'backquote not supported in 3.x; use repr()'
440 with check_py3k_warnings((expected, SyntaxWarning)):
450 exec "`2`" in {}
46n/a
470 def test_paren_arg_names(self):
480 expected = 'parenthesized argument names are invalid in 3.x'
490 def check(s):
500 with check_py3k_warnings((expected, SyntaxWarning)):
510 exec s in {}
520 check("def f((x)): pass")
530 check("def f((((x))), (y)): pass")
540 check("def f((x), (((y))), m=32): pass")
55n/a # Something like def f((a, (b))): pass will raise the tuple
56n/a # unpacking warning.
57n/a
580 def test_forbidden_names(self):
59n/a # So we don't screw up our globals
600 def safe_exec(expr):
610 def f(**kwargs): pass
620 exec expr in {'f' : f}
63n/a
640 tests = [("True", "assignment to True or False is forbidden in 3.x"),
650 ("False", "assignment to True or False is forbidden in 3.x"),
660 ("nonlocal", "nonlocal is a keyword in 3.x")]
670 with check_py3k_warnings(('', SyntaxWarning)) as w:
680 for keyword, expected in tests:
690 safe_exec("{0} = False".format(keyword))
700 self.assertWarning(None, w, expected)
710 w.reset()
720 try:
730 safe_exec("obj.{0} = True".format(keyword))
740 except NameError:
750 pass
760 self.assertWarning(None, w, expected)
770 w.reset()
780 safe_exec("def {0}(): pass".format(keyword))
790 self.assertWarning(None, w, expected)
800 w.reset()
810 safe_exec("class {0}: pass".format(keyword))
820 self.assertWarning(None, w, expected)
830 w.reset()
840 safe_exec("def f({0}=43): pass".format(keyword))
850 self.assertWarning(None, w, expected)
860 w.reset()
87n/a
88n/a
890 def test_type_inequality_comparisons(self):
900 expected = 'type inequality comparisons not supported in 3.x'
910 with check_py3k_warnings() as w:
920 self.assertWarning(int < str, w, expected)
930 w.reset()
940 self.assertWarning(type < object, w, expected)
95n/a
960 def test_object_inequality_comparisons(self):
970 expected = 'comparing unequal types not supported in 3.x'
980 with check_py3k_warnings() as w:
990 self.assertWarning(str < [], w, expected)
1000 w.reset()
1010 self.assertWarning(object() < (1, 2), w, expected)
102n/a
1030 def test_dict_inequality_comparisons(self):
1040 expected = 'dict inequality comparisons not supported in 3.x'
1050 with check_py3k_warnings() as w:
1060 self.assertWarning({} < {2:3}, w, expected)
1070 w.reset()
1080 self.assertWarning({} <= {}, w, expected)
1090 w.reset()
1100 self.assertWarning({} > {2:3}, w, expected)
1110 w.reset()
1120 self.assertWarning({2:3} >= {}, w, expected)
113n/a
1140 def test_cell_inequality_comparisons(self):
1150 expected = 'cell comparisons not supported in 3.x'
1160 def f(x):
1170 def g():
1180 return x
1190 return g
1200 cell0, = f(0).func_closure
1210 cell1, = f(1).func_closure
1220 with check_py3k_warnings() as w:
1230 self.assertWarning(cell0 == cell1, w, expected)
1240 w.reset()
1250 self.assertWarning(cell0 < cell1, w, expected)
126n/a
1270 def test_code_inequality_comparisons(self):
1280 expected = 'code inequality comparisons not supported in 3.x'
1290 def f(x):
1300 pass
1310 def g(x):
1320 pass
1330 with check_py3k_warnings() as w:
1340 self.assertWarning(f.func_code < g.func_code, w, expected)
1350 w.reset()
1360 self.assertWarning(f.func_code <= g.func_code, w, expected)
1370 w.reset()
1380 self.assertWarning(f.func_code >= g.func_code, w, expected)
1390 w.reset()
1400 self.assertWarning(f.func_code > g.func_code, w, expected)
141n/a
1420 def test_builtin_function_or_method_comparisons(self):
1430 expected = ('builtin_function_or_method '
144n/a 'order comparisons not supported in 3.x')
1450 func = eval
1460 meth = {}.get
1470 with check_py3k_warnings() as w:
1480 self.assertWarning(func < meth, w, expected)
1490 w.reset()
1500 self.assertWarning(func > meth, w, expected)
1510 w.reset()
1520 self.assertWarning(meth <= func, w, expected)
1530 w.reset()
1540 self.assertWarning(meth >= func, w, expected)
1550 w.reset()
1560 self.assertNoWarning(meth == func, w)
1570 self.assertNoWarning(meth != func, w)
1580 lam = lambda x: x
1590 self.assertNoWarning(lam == func, w)
1600 self.assertNoWarning(lam != func, w)
161n/a
1620 def test_frame_attributes(self):
1630 template = "%s has been removed in 3.x"
1640 f = sys._getframe(0)
1650 for attr in ("f_exc_traceback", "f_exc_value", "f_exc_type"):
1660 expected = template % attr
1670 with check_py3k_warnings() as w:
1680 self.assertWarning(getattr(f, attr), w, expected)
1690 w.reset()
1700 self.assertWarning(setattr(f, attr, None), w, expected)
171n/a
1720 def test_sort_cmp_arg(self):
1730 expected = "the cmp argument is not supported in 3.x"
1740 lst = range(5)
1750 cmp = lambda x,y: -1
176n/a
1770 with check_py3k_warnings() as w:
1780 self.assertWarning(lst.sort(cmp=cmp), w, expected)
1790 w.reset()
1800 self.assertWarning(sorted(lst, cmp=cmp), w, expected)
1810 w.reset()
1820 self.assertWarning(lst.sort(cmp), w, expected)
1830 w.reset()
1840 self.assertWarning(sorted(lst, cmp), w, expected)
185n/a
1860 def test_sys_exc_clear(self):
1870 expected = 'sys.exc_clear() not supported in 3.x; use except clauses'
1880 with check_py3k_warnings() as w:
1890 self.assertWarning(sys.exc_clear(), w, expected)
190n/a
1910 def test_methods_members(self):
1920 expected = '__members__ and __methods__ not supported in 3.x'
1930 class C:
1940 __methods__ = ['a']
1950 __members__ = ['b']
1960 c = C()
1970 with check_py3k_warnings() as w:
1980 self.assertWarning(dir(c), w, expected)
199n/a
2000 def test_softspace(self):
2010 expected = 'file.softspace not supported in 3.x'
2020 with file(__file__) as f:
2030 with check_py3k_warnings() as w:
2040 self.assertWarning(f.softspace, w, expected)
2050 def set():
2060 f.softspace = 0
2070 with check_py3k_warnings() as w:
2080 self.assertWarning(set(), w, expected)
209n/a
2100 def test_slice_methods(self):
2110 class Spam(object):
2120 def __getslice__(self, i, j): pass
2130 def __setslice__(self, i, j, what): pass
2140 def __delslice__(self, i, j): pass
2150 class Egg:
2160 def __getslice__(self, i, h): pass
2170 def __setslice__(self, i, j, what): pass
2180 def __delslice__(self, i, j): pass
219n/a
2200 expected = "in 3.x, __{0}slice__ has been removed; use __{0}item__"
221n/a
2220 for obj in (Spam(), Egg()):
2230 with check_py3k_warnings() as w:
2240 self.assertWarning(obj[1:2], w, expected.format('get'))
2250 w.reset()
2260 del obj[3:4]
2270 self.assertWarning(None, w, expected.format('del'))
2280 w.reset()
2290 obj[4:5] = "eggs"
2300 self.assertWarning(None, w, expected.format('set'))
231n/a
2320 def test_tuple_parameter_unpacking(self):
2330 expected = "tuple parameter unpacking has been removed in 3.x"
2340 with check_py3k_warnings((expected, SyntaxWarning)):
2350 exec "def f((a, b)): pass"
236n/a
2370 def test_buffer(self):
2380 expected = 'buffer() not supported in 3.x'
2390 with check_py3k_warnings() as w:
2400 self.assertWarning(buffer('a'), w, expected)
241n/a
2420 def test_file_xreadlines(self):
2430 expected = ("f.xreadlines() not supported in 3.x, "
244n/a "try 'for line in f' instead")
2450 with file(__file__) as f:
2460 with check_py3k_warnings() as w:
2470 self.assertWarning(f.xreadlines(), w, expected)
248n/a
2490 def test_hash_inheritance(self):
2500 with check_py3k_warnings() as w:
251n/a # With object as the base class
2520 class WarnOnlyCmp(object):
2530 def __cmp__(self, other): pass
2540 self.assertEqual(len(w.warnings), 0)
2550 w.reset()
2560 class WarnOnlyEq(object):
2570 def __eq__(self, other): pass
2580 self.assertEqual(len(w.warnings), 1)
2590 self.assertWarning(None, w,
2600 "Overriding __eq__ blocks inheritance of __hash__ in 3.x")
2610 w.reset()
2620 class WarnCmpAndEq(object):
2630 def __cmp__(self, other): pass
2640 def __eq__(self, other): pass
2650 self.assertEqual(len(w.warnings), 1)
2660 self.assertWarning(None, w,
2670 "Overriding __eq__ blocks inheritance of __hash__ in 3.x")
2680 w.reset()
2690 class NoWarningOnlyHash(object):
2700 def __hash__(self): pass
2710 self.assertEqual(len(w.warnings), 0)
272n/a # With an intermediate class in the heirarchy
2730 class DefinesAllThree(object):
2740 def __cmp__(self, other): pass
2750 def __eq__(self, other): pass
2760 def __hash__(self): pass
2770 class WarnOnlyCmp(DefinesAllThree):
2780 def __cmp__(self, other): pass
2790 self.assertEqual(len(w.warnings), 0)
2800 w.reset()
2810 class WarnOnlyEq(DefinesAllThree):
2820 def __eq__(self, other): pass
2830 self.assertEqual(len(w.warnings), 1)
2840 self.assertWarning(None, w,
2850 "Overriding __eq__ blocks inheritance of __hash__ in 3.x")
2860 w.reset()
2870 class WarnCmpAndEq(DefinesAllThree):
2880 def __cmp__(self, other): pass
2890 def __eq__(self, other): pass
2900 self.assertEqual(len(w.warnings), 1)
2910 self.assertWarning(None, w,
2920 "Overriding __eq__ blocks inheritance of __hash__ in 3.x")
2930 w.reset()
2940 class NoWarningOnlyHash(DefinesAllThree):
2950 def __hash__(self): pass
2960 self.assertEqual(len(w.warnings), 0)
297n/a
2980 def test_operator(self):
2990 from operator import isCallable, sequenceIncludes
300n/a
3010 callable_warn = ("operator.isCallable() is not supported in 3.x. "
302n/a "Use hasattr(obj, '__call__').")
3030 seq_warn = ("operator.sequenceIncludes() is not supported "
304n/a "in 3.x. Use operator.contains().")
3050 with check_py3k_warnings() as w:
3060 self.assertWarning(isCallable(self), w, callable_warn)
3070 w.reset()
3080 self.assertWarning(sequenceIncludes(range(3), 2), w, seq_warn)
309n/a
310n/a
3110class TestStdlibRemovals(unittest.TestCase):
312n/a
313n/a # test.testall not tested as it executes all unit tests as an
314n/a # import side-effect.
3150 all_platforms = ('audiodev', 'imputil', 'mutex', 'user', 'new', 'rexec',
3160 'Bastion', 'compiler', 'dircache', 'mimetools',
3170 'fpformat', 'ihooks', 'mhlib', 'statvfs', 'htmllib',
3180 'sgmllib', 'rfc822', 'sunaudio')
3190 inclusive_platforms = {'irix' : ('pure', 'AL', 'al', 'CD', 'cd', 'cddb',
3200 'cdplayer', 'CL', 'cl', 'DEVICE', 'GL',
3210 'gl', 'ERRNO', 'FILE', 'FL', 'flp', 'fl',
3220 'fm', 'GET', 'GLWS', 'imgfile', 'IN',
3230 'IOCTL', 'jpeg', 'panel', 'panelparser',
3240 'readcd', 'SV', 'torgb', 'WAIT'),
3250 'darwin' : ('autoGIL', 'Carbon', 'OSATerminology',
3260 'icglue', 'Nav',
327n/a # MacOS should (and does) give a Py3kWarning, but one of the
328n/a # earlier tests already imports the MacOS extension which causes
329n/a # this test to fail. Disabling the test for 'MacOS' avoids this
330n/a # spurious test failure.
331n/a #'MacOS',
3320 'aepack',
3330 'aetools', 'aetypes', 'applesingle',
3340 'appletrawmain', 'appletrunner',
3350 'argvemulator', 'bgenlocations',
3360 'EasyDialogs', 'macerrors', 'macostools',
3370 'findertools', 'FrameWork', 'ic',
3380 'gensuitemodule', 'icopen', 'macresource',
3390 'MiniAEFrame', 'pimp', 'PixMapWrapper',
3400 'terminalcommand', 'videoreader',
3410 '_builtinSuites', 'CodeWarrior',
3420 'Explorer', 'Finder', 'Netscape',
3430 'StdSuites', 'SystemEvents', 'Terminal',
3440 'cfmfile', 'bundlebuilder', 'buildtools',
3450 'ColorPicker', 'Audio_mac'),
3460 'sunos5' : ('sunaudiodev', 'SUNAUDIODEV'),
347n/a }
3480 optional_modules = ('bsddb185', 'Canvas', 'dl', 'linuxaudiodev', 'imageop',
3490 'sv', 'bsddb', 'dbhash')
350n/a
3510 def check_removal(self, module_name, optional=False):
352n/a """Make sure the specified module, when imported, raises a
353n/a DeprecationWarning and specifies itself in the message."""
3540 with CleanImport(module_name), warnings.catch_warnings():
3550 warnings.filterwarnings("error", ".+ (module|package) .+ removed",
3560 DeprecationWarning, __name__)
3570 warnings.filterwarnings("error", ".+ removed .+ (module|package)",
3580 DeprecationWarning, __name__)
3590 try:
3600 __import__(module_name, level=0)
3610 except DeprecationWarning as exc:
3620 self.assertIn(module_name, exc.args[0],
3630 "%s warning didn't contain module name"
3640 % module_name)
3650 except ImportError:
3660 if not optional:
3670 self.fail("Non-optional module {0} raised an "
3680 "ImportError.".format(module_name))
369n/a else:
370n/a # For extension modules, check the __warningregistry__.
371n/a # They won't rerun their init code even with CleanImport.
3720 if not check_deprecated_module(module_name):
3730 self.fail("DeprecationWarning not raised for {0}"
3740 .format(module_name))
375n/a
3760 def test_platform_independent_removals(self):
377n/a # Make sure that the modules that are available on all platforms raise
378n/a # the proper DeprecationWarning.
3790 for module_name in self.all_platforms:
3800 self.check_removal(module_name)
381n/a
3820 def test_platform_specific_removals(self):
383n/a # Test the removal of platform-specific modules.
3840 for module_name in self.inclusive_platforms.get(sys.platform, []):
3850 self.check_removal(module_name, optional=True)
386n/a
3870 def test_optional_module_removals(self):
388n/a # Test the removal of modules that may or may not be built.
3890 for module_name in self.optional_modules:
3900 self.check_removal(module_name, optional=True)
391n/a
3920 def test_os_path_walk(self):
3930 msg = "In 3.x, os.path.walk is removed in favor of os.walk."
3940 def dumbo(where, names, args): pass
3950 for path_mod in ("ntpath", "macpath", "os2emxpath", "posixpath"):
3960 mod = __import__(path_mod)
3970 reset_module_registry(mod)
3980 with check_py3k_warnings() as w:
3990 mod.walk("crashers", dumbo, None)
4000 self.assertEquals(str(w.message), msg)
401n/a
4020 def test_reduce_move(self):
4030 from operator import add
404n/a # reduce tests may have already triggered this warning
4050 reset_module_registry(unittest.case)
4060 with warnings.catch_warnings():
4070 warnings.filterwarnings("error", "reduce")
4080 self.assertRaises(DeprecationWarning, reduce, add, range(10))
409n/a
4100 def test_mutablestring_removal(self):
411n/a # UserString.MutableString has been removed in 3.0.
4120 import UserString
413n/a # UserString tests may have already triggered this warning
4140 reset_module_registry(UserString)
4150 with warnings.catch_warnings():
4160 warnings.filterwarnings("error", ".*MutableString",
4170 DeprecationWarning)
4180 self.assertRaises(DeprecationWarning, UserString.MutableString)
419n/a
420n/a
4210def test_main():
4220 run_unittest(TestPy3KWarnings,
4230 TestStdlibRemovals)
424n/a
4250if __name__ == '__main__':
4260 test_main()