Commits

Senthil Kumaran committed 7caf54c

Fixing - Issue7026 - RuntimeError: dictionary changed size during iteration. Patch by flox

Comments (0)

Files changed (107)

Lib/test/infinite_reload.py

 #  reload()ing. This module is imported by test_import.py:test_infinite_reload
 #  to make sure this doesn't happen any more.
 
+import imp
 import infinite_reload
-reload(infinite_reload)
+imp.reload(infinite_reload)

Lib/test/inspect_fodder.py

     fr = inspect.currentframe()
     st = inspect.stack()
     p = x
-    q = y / 0
+    q = y // 0
 
 # line 20
 class StupidGit:

Lib/test/list_tests.py

 
 import sys
 import os
-
+import warnings
 from test import test_support, seq_tests
 
 class CommonTest(seq_tests.CommonTest):
 
         self.assertEqual(str(a0), str(l0))
         self.assertEqual(repr(a0), repr(l0))
-        self.assertEqual(`a2`, `l2`)
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            self.assertEqual(eval('`a2`'), eval('`l2`'))
         self.assertEqual(str(a2), "[0, 1, 2]")
         self.assertEqual(repr(a2), "[0, 1, 2]")
 
         self.assertRaises(TypeError, u.reverse, 42)
 
     def test_sort(self):
+        with warnings.catch_warnings():
+            # Silence Py3k warning
+            warnings.filterwarnings("ignore", "the cmp argument is not supported",
+                                    DeprecationWarning)
+            self._test_sort()
+
+    def _test_sort(self):
         u = self.type2test([1, 0])
         u.sort()
         self.assertEqual(u, [0, 1])

Lib/test/mapping_tests.py

 # tests common to dict and UserDict
 import unittest
 import UserDict
+import test_support
 
 
 class BasicTestMappingProtocol(unittest.TestCase):
         #len
         self.assertEqual(len(p), 0)
         self.assertEqual(len(d), len(self.reference))
-        #has_key
+        #in
         for k in self.reference:
-            self.assertTrue(d.has_key(k))
             self.assertTrue(k in d)
         for k in self.other:
-            self.assertFalse(d.has_key(k))
             self.assertFalse(k in d)
+        #has_key
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            for k in self.reference:
+                self.assertTrue(d.has_key(k))
+            for k in self.other:
+                self.assertFalse(d.has_key(k))
         #cmp
         self.assertEqual(cmp(p,p), 0)
         self.assertEqual(cmp(d,d), 0)

Lib/test/regrtest.py

 import cStringIO
 import getopt
 import itertools
-import json
 import os
 import random
 import re
 import warnings
 import unittest
 
-# I see no other way to suppress these warnings;
-# putting them in test_grammar.py has no effect:
-warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning,
-                        ".*test.test_grammar$")
-if sys.maxint > 0x7fffffff:
-    # Also suppress them in <string>, because for 64-bit platforms,
-    # that's where test_grammar.py hides them.
-    warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning,
-                            "<string>")
+with warnings.catch_warnings():
+    # Silence Py3k warnings
+    warnings.filterwarnings("ignore", "tuple parameter unpacking "
+                            "has been removed", SyntaxWarning)
+    warnings.filterwarnings("ignore", "assignment to True or False "
+                            "is forbidden", SyntaxWarning)
+    import json
 
 # Ignore ImportWarnings that only occur in the source tree,
 # (because of modules with the same name as source-directories in Modules/)

Lib/test/seq_tests.py

 
 import unittest
 import sys
+import test_support
 
 # Various iterables
 # This is used for checking the constructor (here and in test_deque.py)
         self.assertEqual(a[ -pow(2,128L): 3 ], self.type2test([0,1,2]))
         self.assertEqual(a[ 3: pow(2,145L) ], self.type2test([3,4]))
 
-        self.assertRaises(TypeError, u.__getslice__)
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            self.assertRaises(TypeError, u.__getslice__)
 
     def test_contains(self):
         u = self.type2test([0, 1, 2])

Lib/test/test_StringIO.py

 
 
 def test_main():
-    test_support.run_unittest(
-        TestStringIO,
-        TestcStringIO,
-        TestBufferStringIO,
-        TestBuffercStringIO
-    )
+    test_support.run_unittest(TestStringIO, TestcStringIO)
+    # Silence Py3k warning
+    with test_support.check_warnings():
+        test_support.run_unittest(TestBufferStringIO, TestBuffercStringIO)
 
 if __name__ == '__main__':
     test_main()

Lib/test/test_anydbm.py

 
 import os
 import unittest
-import anydbm
 import glob
 from test import test_support
 
 _fname = test_support.TESTFN
 
+# Silence Py3k warning
+anydbm = test_support.import_module('anydbm', deprecated=True)
+
 def _delete_files():
     # we don't know the precise name the underlying database uses
     # so we use glob to locate all names

Lib/test/test_array.py

 
     def test_buffer(self):
         a = array.array(self.typecode, self.example)
-        b = buffer(a)
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            b = buffer(a)
         self.assertEqual(b[0], a.tostring()[0])
 
     def test_weakref(self):

Lib/test/test_ast.py

 import sys, itertools, unittest
 from test import test_support
 import ast
+import warnings
 
 def to_tuple(t):
     if t is None or isinstance(t, (basestring, int, long, complex)):
 
 
 def test_main():
-    test_support.run_unittest(AST_Tests, ASTHelpers_Test)
+    with warnings.catch_warnings():
+        # Silence Py3k warning
+        warnings.filterwarnings("ignore", "backquote not supported",
+                                SyntaxWarning)
+        test_support.run_unittest(AST_Tests, ASTHelpers_Test)
 
 def main():
     if __name__ != '__main__':

Lib/test/test_augassign.py

 
 from test.test_support import run_unittest
 import unittest
+import warnings
 
 
 class AugAssignTest(unittest.TestCase):
 '''.splitlines())
 
 def test_main():
-    run_unittest(AugAssignTest)
+    with warnings.catch_warnings():
+        # Silence Py3k warning
+        warnings.filterwarnings("ignore", "classic int division",
+                                DeprecationWarning)
+        run_unittest(AugAssignTest)
 
 if __name__ == '__main__':
     test_main()

Lib/test/test_bigmem.py

     def test_encode(self, size):
         return self.basic_encode_test(size, 'utf-8')
 
-    @precisionbigmemtest(size=_4G / 6 + 2, memuse=2)
+    @precisionbigmemtest(size=_4G // 6 + 2, memuse=2)
     def test_encode_raw_unicode_escape(self, size):
         try:
             return self.basic_encode_test(size, 'raw_unicode_escape')
         except MemoryError:
             pass # acceptable on 32-bit
 
-    @precisionbigmemtest(size=_4G / 5 + 70, memuse=3)
+    @precisionbigmemtest(size=_4G // 5 + 70, memuse=3)
     def test_encode_utf7(self, size):
         try:
             return self.basic_encode_test(size, 'utf7')
         except MemoryError:
             pass # acceptable on 32-bit
 
-    @precisionbigmemtest(size=_4G / 4 + 5, memuse=6)
+    @precisionbigmemtest(size=_4G // 4 + 5, memuse=6)
     def test_encode_utf32(self, size):
         try:
             return self.basic_encode_test(size, 'utf32', expectedsize=4*size+4)
     def test_decodeascii(self, size):
         return self.basic_encode_test(size, 'ascii', c='A')
 
-    @precisionbigmemtest(size=_4G / 5, memuse=6+2)
+    @precisionbigmemtest(size=_4G // 5, memuse=6+2)
     def test_unicode_repr_oflw(self, size):
         try:
             s = u"\uAAAA"*size
         self.assertEquals(s.count('\\'), size)
         self.assertEquals(s.count('0'), size * 2)
 
-    @bigmemtest(minsize=2**32 / 5, memuse=6+2)
+    @bigmemtest(minsize=2**32 // 5, memuse=6+2)
     def test_unicode_repr(self, size):
         s = u"\uAAAA" * size
         self.assertTrue(len(repr(s)) > size)
     @precisionbigmemtest(size=_1G, memuse=4)
     def test_repeat(self, size):
         try:
-            b = buffer("AAAA")*size
+            # Silence Py3k warning
+            with test_support.check_warnings():
+                b = buffer("AAAA")*size
         except MemoryError:
             pass # acceptable on 32-bit
         else:

Lib/test/test_binascii.py

                 prefixes.extend(["crc_", "rlecode_", "rledecode_"])
             for prefix in prefixes:
                 name = prefix + suffix
-                self.assertTrue(callable(getattr(binascii, name)))
+                self.assertTrue(hasattr(getattr(binascii, name), '__call__'))
                 self.assertRaises(TypeError, getattr(binascii, name))
         for name in ("hexlify", "unhexlify"):
-            self.assertTrue(callable(getattr(binascii, name)))
+            self.assertTrue(hasattr(getattr(binascii, name), '__call__'))
             self.assertRaises(TypeError, getattr(binascii, name))
 
     def test_base64valid(self):

Lib/test/test_binop.py

         """Compare two Rats for inequality."""
         return not self == other
 
+    # Silence Py3k warning
+    __hash__ = None
+
 class RatTestCase(unittest.TestCase):
     """Unit tests for Rat class and its support utilities."""
 

Lib/test/test_bool.py

         self.assertEqual(False*1, 0)
         self.assertIsNot(False*1, False)
 
-        self.assertEqual(True/1, 1)
-        self.assertIsNot(True/1, True)
-        self.assertEqual(False/1, 0)
-        self.assertIsNot(False/1, False)
+        self.assertEqual(True//1, 1)
+        self.assertIsNot(True//1, True)
+        self.assertEqual(False//1, 0)
+        self.assertIsNot(False//1, False)
 
         for b in False, True:
             for i in 0, 1, 2:
         self.assertIs(hasattr([], "wobble"), False)
 
     def test_callable(self):
-        self.assertIs(callable(len), True)
-        self.assertIs(callable(1), False)
+        self.assertTrue(hasattr(len, '__call__'), True)
+        self.assertFalse(hasattr(1, '__call__'), False)
 
     def test_isinstance(self):
         self.assertIs(isinstance(True, bool), True)
         self.assertIs(issubclass(int, bool), False)
 
     def test_haskey(self):
-        self.assertIs({}.has_key(1), False)
-        self.assertIs({1:1}.has_key(1), True)
+        self.assertIs(1 in {}, False)
+        self.assertIs(1 in {1:1}, True)
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            self.assertIs({}.has_key(1), False)
+            self.assertIs({1:1}.has_key(1), True)
 
     def test_string(self):
         self.assertIs("xyz".endswith("z"), True)
         import operator
         self.assertIs(operator.truth(0), False)
         self.assertIs(operator.truth(1), True)
-        self.assertIs(operator.isCallable(0), False)
-        self.assertIs(operator.isCallable(len), True)
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            self.assertIs(operator.isCallable(0), False)
+            self.assertIs(operator.isCallable(len), True)
         self.assertIs(operator.isNumberType(None), False)
         self.assertIs(operator.isNumberType(0), True)
         self.assertIs(operator.not_(1), False)

Lib/test/test_buffer.py

 
 import unittest
 from test import test_support
+import warnings
 
 class BufferTests(unittest.TestCase):
 
 
 
 def test_main():
-    test_support.run_unittest(BufferTests)
+    with warnings.catch_warnings():
+        # Silence Py3k warning
+        warnings.filterwarnings("ignore", "buffer.. not supported",
+                                DeprecationWarning)
+        test_support.run_unittest(BufferTests)
 
 if __name__ == "__main__":
     test_main()

Lib/test/test_builtin.py

 from operator import neg
 
 import sys, warnings, cStringIO, random, fractions, UserDict
-warnings.filterwarnings("ignore", "hex../oct.. of negative int",
-                        FutureWarning, __name__)
-warnings.filterwarnings("ignore", "integer argument expected",
-                        DeprecationWarning, "unittest")
 
 # count the number of test runs.
 # used to skip running test_execfile() multiple times
     f.write('z = z+1\n')
     f.write('z = z*2\n')
     f.close()
-    execfile(TESTFN)
+    with warnings.catch_warnings():
+        # Silence Py3k warning
+        warnings.filterwarnings("ignore", ".+ not supported in 3.x",
+                                DeprecationWarning)
+        execfile(TESTFN)
 
     def test_execfile(self):
         global numruns
         data = 'The quick Brown fox Jumped over The lazy Dog'.split()
         self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0)
 
+def _run_unittest(*args):
+    with warnings.catch_warnings():
+        # Silence Py3k warnings
+        warnings.filterwarnings("ignore", ".+ not supported in 3.x",
+                                DeprecationWarning)
+        warnings.filterwarnings("ignore", ".+ is renamed to imp.reload",
+                                DeprecationWarning)
+        warnings.filterwarnings("ignore", "integer argument expected, got float",
+                                DeprecationWarning)
+        warnings.filterwarnings("ignore", "classic int division",
+                                DeprecationWarning)
+        run_unittest(*args)
+
 def test_main(verbose=None):
     test_classes = (BuiltinTest, TestSorted)
 
-    run_unittest(*test_classes)
+    _run_unittest(*test_classes)
 
     # verify reference counting
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
         for i in xrange(len(counts)):
-            run_unittest(*test_classes)
+            _run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()
         print counts

Lib/test/test_call.py

         self.assertRaises(TypeError, {}.has_key)
 
     def test_varargs1(self):
-        {}.has_key(0)
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            {}.has_key(0)
 
     def test_varargs2(self):
         self.assertRaises(TypeError, {}.has_key, 0, 1)
             pass
 
     def test_varargs1_ext(self):
-        {}.has_key(*(0,))
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            {}.has_key(*(0,))
 
     def test_varargs2_ext(self):
         try:
-            {}.has_key(*(1, 2))
+            # Silence Py3k warning
+            with test_support.check_warnings():
+                {}.has_key(*(1, 2))
         except TypeError:
             pass
         else:

Lib/test/test_capi.py

         context = foo()
         context.l = []
         context.n = 2 #submits per thread
-        context.nThreads = n / context.n
+        context.nThreads = n // context.n
         context.nFinished = 0
         context.lock = threading.Lock()
         context.event = threading.Event()

Lib/test/test_cgi.py

 
 def norm(list):
     if type(list) == type([]):
-        list.sort()
+        list.sort(key=str)
     return list
 
 def first_elts(list):

Lib/test/test_class.py

 "Test the functionality of Python classes implementing operators."
 
 import unittest
-
+import warnings
 from test import test_support
 
 testmeths = [
         self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (testme, 1))])
 
         callLst[:] = []
-        testme <> 1  # XXX kill this in py3k
+        eval('testme <> 1')  # XXX kill this in py3k
         self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (testme, 1))])
 
         callLst[:] = []
         self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (1, testme))])
 
         callLst[:] = []
-        1 <> testme
+        eval('1 <> testme')
         self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (1, testme))])
 
         callLst[:] = []
         hash(a.f)
 
 def test_main():
-    test_support.run_unittest(ClassTests)
+    with warnings.catch_warnings():
+        # Silence Py3k warnings
+        warnings.filterwarnings("ignore", ".+slice__ has been removed",
+                                DeprecationWarning)
+        warnings.filterwarnings("ignore", "classic int division",
+                                DeprecationWarning)
+        warnings.filterwarnings("ignore", "<> not supported",
+                                DeprecationWarning)
+        test_support.run_unittest(ClassTests)
 
 if __name__=='__main__':
     test_main()

Lib/test/test_coercion.py

             infix_results[key] = res
 
 
-
-process_infix_results()
+with warnings.catch_warnings():
+    # Silence Py3k warning
+    warnings.filterwarnings("ignore", "classic int division",
+                            DeprecationWarning)
+    process_infix_results()
 # now infix_results has two lists of results for every pairing.
 
 prefix_binops = [ 'divmod' ]
             raise exc
 
 def test_main():
-    warnings.filterwarnings("ignore",
-                            r'complex divmod\(\), // and % are deprecated',
-                            DeprecationWarning,
-                            r'test.test_coercion$')
-    run_unittest(CoercionTest)
+    with warnings.catch_warnings():
+        # Silence Py3k warnings
+        warnings.filterwarnings("ignore",
+                                "complex divmod.., // and % are deprecated",
+                                DeprecationWarning)
+        warnings.filterwarnings("ignore", "classic .+ division",
+                                DeprecationWarning)
+        run_unittest(CoercionTest)
 
 if __name__ == "__main__":
     test_main()

Lib/test/test_collections.py

                          [('a', 3), ('b', 2), ('c', 1)])
         self.assertEqual(c['b'], 2)
         self.assertEqual(c['z'], 0)
-        self.assertEqual(c.has_key('c'), True)
-        self.assertEqual(c.has_key('z'), False)
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            self.assertEqual(c.has_key('c'), True)
+            self.assertEqual(c.has_key('z'), False)
         self.assertEqual(c.__contains__('c'), True)
         self.assertEqual(c.__contains__('z'), False)
         self.assertEqual(c.get('b', 10), 2)

Lib/test/test_commands.py

 warnings.filterwarnings('ignore', r".*commands.getstatus.. is deprecated",
                         DeprecationWarning)
 
-from test.test_support import run_unittest, reap_children
+from test.test_support import run_unittest, reap_children, import_module
+
+# Silence Py3k warning
+import_module('commands', deprecated=True)
 from commands import *
 
 # The module says:

Lib/test/test_compile.py

 import sys
 import _ast
 from test import test_support
+import textwrap
 
 class TestSpecifics(unittest.TestCase):
 
         self.assertEqual(f(5), 0)
 
     def test_complex_args(self):
-
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            exec textwrap.dedent('''
         def comp_args((a, b)):
             return a,b
         self.assertEqual(comp_args((1, 2)), (1, 2))
             return a, b, c
         self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))
         self.assertEqual(comp_args(), (2, 3, 4))
+        ''')
 
     def test_argument_order(self):
         try:

Lib/test/test_compiler.py

 
     def testTryExceptFinally(self):
         # Test that except and finally clauses in one try stmt are recognized
-        c = compiler.compile("try:\n 1/0\nexcept:\n e = 1\nfinally:\n f = 1",
+        c = compiler.compile("try:\n 1//0\nexcept:\n e = 1\nfinally:\n f = 1",
                              "<string>", "exec")
         dct = {}
         exec c in dct

Lib/test/test_complex_args.py

 
 import unittest
 from test import test_support
+import textwrap
+import warnings
 
 class ComplexArgsTestCase(unittest.TestCase):
 
     def check(self, func, expected, *args):
         self.assertEqual(func(*args), expected)
 
-    # These functions are tested below as lambdas too.  If you add a function test,
-    # also add a similar lambda test.
+    # These functions are tested below as lambdas too.  If you add a
+    # function test, also add a similar lambda test.
+
+    # Functions are wrapped in "exec" statements in order to
+    # silence Py3k warnings
 
     def test_func_parens_no_unpacking(self):
+        exec textwrap.dedent("""
         def f(((((x))))): return x
         self.check(f, 1, 1)
         # Inner parens are elided, same as: f(x,)
         def f(((x)),): return x
         self.check(f, 2, 2)
+        """)
 
     def test_func_1(self):
+        exec textwrap.dedent("""
         def f(((((x),)))): return x
         self.check(f, 3, (3,))
         def f(((((x)),))): return x
         self.check(f, 5, (5,))
         def f(((x),)): return x
         self.check(f, 6, (6,))
+        """)
 
     def test_func_2(self):
+        exec textwrap.dedent("""
         def f(((((x)),),)): return x
         self.check(f, 2, ((2,),))
+        """)
 
     def test_func_3(self):
+        exec textwrap.dedent("""
         def f((((((x)),),),)): return x
         self.check(f, 3, (((3,),),))
+        """)
 
     def test_func_complex(self):
+        exec textwrap.dedent("""
         def f((((((x)),),),), a, b, c): return x, a, b, c
         self.check(f, (3, 9, 8, 7), (((3,),),), 9, 8, 7)
 
 
         def f(a, b, c, ((((((x)),)),),)): return a, b, c, x
         self.check(f, (9, 8, 7, 3), 9, 8, 7, (((3,),),))
+        """)
 
     # Duplicate the tests above, but for lambda.  If you add a lambda test,
     # also add a similar function test above.
 
     def test_lambda_parens_no_unpacking(self):
+        exec textwrap.dedent("""
         f = lambda (((((x))))): x
         self.check(f, 1, 1)
         # Inner parens are elided, same as: f(x,)
         f = lambda ((x)),: x
         self.check(f, 2, 2)
+        """)
 
     def test_lambda_1(self):
+        exec textwrap.dedent("""
         f = lambda (((((x),)))): x
         self.check(f, 3, (3,))
         f = lambda (((((x)),))): x
         self.check(f, 5, (5,))
         f = lambda (((x),)): x
         self.check(f, 6, (6,))
+        """)
 
     def test_lambda_2(self):
+        exec textwrap.dedent("""
         f = lambda (((((x)),),)): x
         self.check(f, 2, ((2,),))
+        """)
 
     def test_lambda_3(self):
+        exec textwrap.dedent("""
         f = lambda ((((((x)),),),)): x
         self.check(f, 3, (((3,),),))
+        """)
 
     def test_lambda_complex(self):
+        exec textwrap.dedent("""
         f = lambda (((((x)),),),), a, b, c: (x, a, b, c)
         self.check(f, (3, 9, 8, 7), (((3,),),), 9, 8, 7)
 
 
         f = lambda a, b, c, ((((((x)),)),),): (a, b, c, x)
         self.check(f, (9, 8, 7, 3), 9, 8, 7, (((3,),),))
+        """)
 
 
 def test_main():
-    test_support.run_unittest(ComplexArgsTestCase)
+    with warnings.catch_warnings():
+        # Silence Py3k warnings
+        warnings.filterwarnings("ignore", "tuple parameter unpacking "
+                                "has been removed", SyntaxWarning)
+        warnings.filterwarnings("ignore", "parenthesized argument names "
+                                "are invalid", SyntaxWarning)
+        test_support.run_unittest(ComplexArgsTestCase)
 
 if __name__ == "__main__":
     test_main()

Lib/test/test_copy.py

         v = copy.deepcopy(u)
         self.assertNotEqual(v, u)
         self.assertEqual(len(v), 2)
-        (x, y), (z, t) = sorted(v.items(), key=lambda (k, v): k.i)
+        (x, y), (z, t) = sorted(v.items(), key=lambda k: k[0].i)
         self.assertFalse(x is a)
         self.assertEqual(x.i, a.i)
         self.assertTrue(y is b)

Lib/test/test_ctypes.py

 #Skip tests if _ctypes module does not exist
 import_module('_ctypes')
 
+import warnings
 import ctypes.test
 
 def test_main():
     skipped, testcases = ctypes.test.get_tests(ctypes.test, "test_*.py", verbosity=0)
     suites = [unittest.makeSuite(t) for t in testcases]
-    run_unittest(unittest.TestSuite(suites))
+    with warnings.catch_warnings():
+        # Silence Py3k warnings
+        warnings.filterwarnings("ignore", "buffer.. not supported",
+                                DeprecationWarning)
+        warnings.filterwarnings("ignore", "classic long division",
+                                DeprecationWarning)
+        run_unittest(unittest.TestSuite(suites))
 
 if __name__ == "__main__":
     test_main()

Lib/test/test_decimal.py

 import unittest
 from decimal import *
 import numbers
-from test.test_support import (run_unittest, run_doctest, is_resource_enabled)
+from test.test_support import (run_unittest, run_doctest,
+                               is_resource_enabled, check_warnings)
 import random
 try:
     import threading
         if skip_expected:
             raise unittest.SkipTest
             return
-        for line in open(file).xreadlines():
+        for line in open(file):
             line = line.replace('\r\n', '').replace('\n', '')
             #print line
             try:
         myexceptions = self.getexceptions()
         self.context.clear_flags()
 
-        myexceptions.sort()
-        theirexceptions.sort()
+        # Silence Py3k warning
+        with check_warnings():
+            myexceptions.sort()
+            theirexceptions.sort()
 
         self.assertEqual(result, ans,
                          'Incorrect answer for ' + s + ' -- got ' + result)
             ('//', '__floordiv__', '__rfloordiv__'),
             ('**', '__pow__', '__rpow__')
         ]
-        if 1/2 == 0:
-            # testing with classic division, so add __div__
-            oplist.append(('/', '__div__', '__rdiv__'))
-        else:
-            # testing with -Qnew, so add __truediv__
-            oplist.append(('/', '__truediv__', '__rtruediv__'))
+        # Silence Py3k warning
+        with check_warnings():
+            if 1/2 == 0:
+                # testing with classic division, so add __div__
+                oplist.append(('/', '__div__', '__rdiv__'))
+            else:
+                # testing with -Qnew, so add __truediv__
+                oplist.append(('/', '__truediv__', '__rtruediv__'))
 
         for sym, lop, rop in oplist:
             setattr(E, lop, lambda self, other: 'str' + lop + str(other))
         self.assertEqual(a, b)
 
         # with None
-        self.assertFalse(Decimal(1) < None)
-        self.assertTrue(Decimal(1) > None)
+        # Silence Py3k warning
+        with check_warnings():
+            self.assertFalse(Decimal(1) < None)
+            self.assertTrue(Decimal(1) > None)
 
     def test_copy_and_deepcopy_methods(self):
         d = Decimal('43.24')
                 for flag in extra_flags:
                     if flag not in expected_flags:
                         expected_flags.append(flag)
-                expected_flags.sort()
 
                 # flags we actually got
                 new_flags = [k for k,v in context.flags.items() if v]
-                new_flags.sort()
+
+                # Silence Py3k warning
+                with check_warnings():
+                    expected_flags.sort()
+                    new_flags.sort()
 
                 self.assertEqual(ans, new_ans,
                                  "operation produces different answers depending on flags set: " +

Lib/test/test_descr.py

 
 
 def test_main():
-    # Run all local test cases, with PTypesLongInitTest first.
-    test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
-                              ClassPropertiesAndMethods, DictProxyTests)
+    with warnings.catch_warnings():
+        # Silence Py3k warnings
+        warnings.filterwarnings("ignore", "classic .+ division",
+                                DeprecationWarning)
+        warnings.filterwarnings("ignore", "coerce.. not supported",
+                                DeprecationWarning)
+        warnings.filterwarnings("ignore", "Overriding __cmp__ ",
+                                DeprecationWarning)
+        warnings.filterwarnings("ignore", ".+slice__ has been removed",
+                                DeprecationWarning)
+        # Run all local test cases, with PTypesLongInitTest first.
+        test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
+                                  ClassPropertiesAndMethods, DictProxyTests)
 
 if __name__ == "__main__":
     test_main()

Lib/test/test_descrtut.py

 statement or the built-in function eval():
 
     >>> def sorted(seq):
-    ...     seq.sort()
+    ...     seq.sort(key=str)
     ...     return seq
     >>> print sorted(a.keys())
     [1, 2]

Lib/test/test_dict.py

         self.assertEqual(d.keys(), [])
         d = {'a': 1, 'b': 2}
         k = d.keys()
-        self.assertTrue(d.has_key('a'))
-        self.assertTrue(d.has_key('b'))
+        self.assertTrue('a' in d)
+        self.assertTrue('b' in d)
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            self.assertTrue(d.has_key('a'))
+            self.assertTrue(d.has_key('b'))
 
         self.assertRaises(TypeError, d.keys, None)
 
 
     def test_has_key(self):
         d = {}
-        self.assertTrue(not d.has_key('a'))
+        self.assertTrue('a' not in d)
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            self.assertTrue(not d.has_key('a'))
+            self.assertRaises(TypeError, d.has_key)
         d = {'a': 1, 'b': 2}
         k = d.keys()
         k.sort()
         self.assertEqual(k, ['a', 'b'])
 
-        self.assertRaises(TypeError, d.has_key)
-
     def test_contains(self):
         d = {}
         self.assertTrue(not ('a' in d))
         self.assertRaises(Exc, repr, d)
 
     def test_le(self):
-        self.assertTrue(not ({} < {}))
-        self.assertTrue(not ({1: 2} < {1L: 2L}))
 
         class Exc(Exception): pass
 
 
         d1 = {BadCmp(): 1}
         d2 = {1: 1}
-        try:
-            d1 < d2
-        except Exc:
-            pass
-        else:
-            self.fail("< didn't raise Exc")
+
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            self.assertTrue(not ({} < {}))
+            self.assertTrue(not ({1: 2} < {1L: 2L}))
+
+            try:
+                d1 < d2
+            except Exc:
+                pass
+            else:
+                self.fail("< didn't raise Exc")
 
     def test_missing(self):
         # Make sure dict doesn't have a __missing__ method
                      'd.pop(x2)',
                      'd.update({x2: 2})']:
             try:
-                exec stmt in locals()
+                # Silence Py3k warning
+                with test_support.check_warnings():
+                    exec stmt in locals()
             except CustomException:
                 pass
             else:
         # Bug #3537: if an empty but presized dict with a size larger
         # than 7 was in the freelist, it triggered an assertion failure
         try:
-            d = {'a': 1/0,  'b': None, 'c': None, 'd': None, 'e': None,
+            d = {'a': 1 // 0, 'b': None, 'c': None, 'd': None, 'e': None,
                  'f': None, 'g': None, 'h': None}
         except ZeroDivisionError:
             pass

Lib/test/test_exceptions.py

 import warnings
 
 from test.test_support import TESTFN, unlink, run_unittest, captured_output
-from test.test_pep352 import ignore_message_warning
+from test.test_pep352 import ignore_deprecation_warnings
 
 # XXX This is not really enough, each *operation* should be tested!
 
         # Reloading the built-in exceptions module failed prior to Py2.2, while it
         # should act the same as reloading built-in sys.
         try:
+            from imp import reload
             import exceptions
             reload(exceptions)
         except ImportError, e:
         self.assertRaises(ValueError, chr, 10000)
 
         self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
-        try: x = 1/0
+        try: x = 1 // 0
         except ZeroDivisionError: pass
 
         self.raise_catch(Exception, "Exception")
-        try: x = 1/0
+        try: x = 1 // 0
         except Exception, e: pass
 
     def testSyntaxErrorMessage(self):
             self.assertEqual(WindowsError(1001, "message").errno, 22)
             self.assertEqual(WindowsError(1001, "message").winerror, 1001)
 
+    @ignore_deprecation_warnings
     def testAttributes(self):
         # test that exception attributes are happy
 
         except NameError:
             pass
 
-        with warnings.catch_warnings():
-            ignore_message_warning()
-            for exc, args, expected in exceptionList:
-                try:
-                    raise exc(*args)
-                except BaseException, e:
-                    if type(e) is not exc:
-                        raise
-                    # Verify module name
-                    self.assertEquals(type(e).__module__, 'exceptions')
-                    # Verify no ref leaks in Exc_str()
-                    s = str(e)
-                    for checkArgName in expected:
-                        self.assertEquals(repr(getattr(e, checkArgName)),
-                                          repr(expected[checkArgName]),
-                                          'exception "%s", attribute "%s"' %
-                                           (repr(e), checkArgName))
+        for exc, args, expected in exceptionList:
+            try:
+                raise exc(*args)
+            except BaseException, e:
+                if type(e) is not exc:
+                    raise
+                # Verify module name
+                self.assertEquals(type(e).__module__, 'exceptions')
+                # Verify no ref leaks in Exc_str()
+                s = str(e)
+                for checkArgName in expected:
+                    self.assertEquals(repr(getattr(e, checkArgName)),
+                                      repr(expected[checkArgName]),
+                                      'exception "%s", attribute "%s"' %
+                                       (repr(e), checkArgName))
 
-                    # test for pickling support
-                    for p in pickle, cPickle:
-                        for protocol in range(p.HIGHEST_PROTOCOL + 1):
-                            new = p.loads(p.dumps(e, protocol))
-                            for checkArgName in expected:
-                                got = repr(getattr(new, checkArgName))
-                                want = repr(expected[checkArgName])
-                                self.assertEquals(got, want,
-                                                  'pickled "%r", attribute "%s"' %
-                                                  (e, checkArgName))
+                # test for pickling support
+                for p in pickle, cPickle:
+                    for protocol in range(p.HIGHEST_PROTOCOL + 1):
+                        new = p.loads(p.dumps(e, protocol))
+                        for checkArgName in expected:
+                            got = repr(getattr(new, checkArgName))
+                            want = repr(expected[checkArgName])
+                            self.assertEquals(got, want,
+                                              'pickled "%r", attribute "%s"' %
+                                              (e, checkArgName))
 
 
     def testDeprecatedMessageAttribute(self):
         with self.assertRaises(AttributeError):
             exc.message
 
+    @ignore_deprecation_warnings
     def testPickleMessageAttribute(self):
         # Pickling with message attribute must work, as well.
         e = Exception("foo")
         f.message = "bar"
         for p in pickle, cPickle:
             ep = p.loads(p.dumps(e))
-            with warnings.catch_warnings():
-                ignore_message_warning()
-                self.assertEqual(ep.message, "foo")
+            self.assertEqual(ep.message, "foo")
             fp = p.loads(p.dumps(f))
             self.assertEqual(fp.message, "bar")
 
         # going through the 'args' attribute.
         args = (1, 2, 3)
         exc = BaseException(*args)
-        self.assertEqual(exc[:], args)
+        self.assertEqual(exc.args[:], args)
+        with warnings.catch_warnings():
+            # Silence Py3k warning
+            warnings.filterwarnings("ignore", "__getslice__ not supported for "
+                                    "exception classes", DeprecationWarning)
+            self.assertEqual(exc[:], args)
 
     def testKeywordArgs(self):
         # test that builtin exception don't take keyword args,

Lib/test/test_file.py

         self.assertEquals(self.f.__exit__(None, None, None), None)
         # it must also return None if an exception was given
         try:
-            1/0
+            1 // 0
         except:
             self.assertEquals(self.f.__exit__(*sys.exc_info()), None)
 

Lib/test/test_file2k.py

     def testAttributes(self):
         # verify expected attributes exist
         f = self.f
-        softspace = f.softspace
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            softspace = f.softspace
         f.name     # merely shouldn't blow up
         f.mode     # ditto
         f.closed   # ditto
 
-        # verify softspace is writable
-        f.softspace = softspace    # merely shouldn't blow up
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            # verify softspace is writable
+            f.softspace = softspace    # merely shouldn't blow up
 
         # verify the others aren't
         for attr in 'name', 'mode', 'closed':
     def testMethods(self):
         methods = ['fileno', 'flush', 'isatty', 'next', 'read', 'readinto',
                    'readline', 'readlines', 'seek', 'tell', 'truncate',
-                   'write', 'xreadlines', '__iter__']
+                   'write', '__iter__']
+        deprecated_methods = ['xreadlines']
         if sys.platform.startswith('atheos'):
             methods.remove('truncate')
 
             method = getattr(self.f, methodname)
             # should raise on closed file
             self.assertRaises(ValueError, method)
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            for methodname in deprecated_methods:
+                method = getattr(self.f, methodname)
+                self.assertRaises(ValueError, method)
         self.assertRaises(ValueError, self.f.writelines, [])
 
         # file is closed, __exit__ shouldn't do anything
         self.assertEquals(self.f.__exit__(None, None, None), None)
         # it must also return None if an exception was given
         try:
-            1/0
+            1 // 0
         except:
             self.assertEquals(self.f.__exit__(*sys.exc_info()), None)
 
         try:
             f = open(TESTFN, bad_mode)
         except ValueError, msg:
-            if msg[0] != 0:
+            if msg.args[0] != 0:
                 s = str(msg)
                 if s.find(TESTFN) != -1 or s.find(bad_mode) == -1:
                     self.fail("bad error message for invalid mode: %s" % s)
-            # if msg[0] == 0, we're probably on Windows where there may be
-            # no obvious way to discover why open() failed.
+            # if msg.args[0] == 0, we're probably on Windows where there may
+            # be no obvious way to discover why open() failed.
         else:
             f.close()
             self.fail("no error for invalid mode: %s" % bad_mode)

Lib/test/test_fractions.py

         assert False, "__sub__ should not be invoked for comparisons"
     __rsub__ = __sub__
 
+    # Silence Py3k warning
+    def __hash__(self):
+        assert False, "__hash__ should not be invoked for comparisons"
+
 
 class DummyRational(object):
     """Test comparison of Fraction with a naive rational implementation."""
     def __float__(self):
         assert False, "__float__ should not be invoked"
 
+    # Silence Py3k warning
+    def __hash__(self):
+        assert False, "__hash__ should not be invoked for comparisons"
+
+
 class GcdTest(unittest.TestCase):
 
     def testMisc(self):

Lib/test/test_ftplib.py

         sock.listen(5)
         sock.settimeout(2)
         ip, port = sock.getsockname()[:2]
-        ip = ip.replace('.', ','); p1 = port / 256; p2 = port % 256
+        ip = ip.replace('.', ','); p1, p2 = divmod(port, 256)
         self.push('227 entering passive mode (%s,%d,%d)' %(ip, p1, p2))
         conn, addr = sock.accept()
         self.dtp = self.dtp_handler(conn, baseclass=self)

Lib/test/test_functools.py

 
     def test_error_propagation(self):
         def f(x, y):
-            x / y
+            x // y
         self.assertRaises(ZeroDivisionError, self.thetype(f, 1, 0))
         self.assertRaises(ZeroDivisionError, self.thetype(f, 1), 0)
         self.assertRaises(ZeroDivisionError, self.thetype(f), 1, 0)

Lib/test/test_grammar.py

 from test.test_support import run_unittest, check_syntax_error
 import unittest
 import sys
+import warnings
 # testing import *
 from sys import *
 
         f1(*(), **{})
         def f2(one_argument): pass
         def f3(two, arguments): pass
-        def f4(two, (compound, (argument, list))): pass
-        def f5((compound, first), two): pass
+        # Silence Py3k warning
+        exec('def f4(two, (compound, (argument, list))): pass')
+        exec('def f5((compound, first), two): pass')
         self.assertEquals(f2.func_code.co_varnames, ('one_argument',))
         self.assertEquals(f3.func_code.co_varnames, ('two', 'arguments'))
         if sys.platform.startswith('java'):
         def v0(*rest): pass
         def v1(a, *rest): pass
         def v2(a, b, *rest): pass
-        def v3(a, (b, c), *rest): return a, b, c, rest
+        # Silence Py3k warning
+        exec('def v3(a, (b, c), *rest): return a, b, c, rest')
 
         f1()
         f2(1)
         d22v(*(1, 2, 3, 4))
         d22v(1, 2, *(3, 4, 5))
         d22v(1, *(2, 3), **{'d': 4})
-        def d31v((x)): pass
+        # Silence Py3k warning
+        exec('def d31v((x)): pass')
+        exec('def d32v((x,)): pass')
         d31v(1)
-        def d32v((x,)): pass
         d32v((1,))
 
         # keyword arguments after *arglist
                     continue
                 except:
                     raise
-            if count > 2 or big_hippo <> 1:
+            if count > 2 or big_hippo != 1:
                 self.fail("continue then break in try/except in loop broken!")
         test_inner()
 
         x = (1 == 1)
         if 1 == 1: pass
         if 1 != 1: pass
-        if 1 <> 1: pass
         if 1 < 1: pass
         if 1 > 1: pass
         if 1 <= 1: pass
         if 1 is not 1: pass
         if 1 in (): pass
         if 1 not in (): pass
-        if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass
+        if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass
+        # Silence Py3k warning
+        if eval('1 <> 1'): pass
+        if eval('1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1'): pass
 
     def testBinaryMaskOps(self):
         x = 1 & 1
         x = {'one': 1, 'two': 2,}
         x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
 
-        x = `x`
-        x = `1 or 2 or 3`
-        self.assertEqual(`1,2`, '(1, 2)')
+        # Silence Py3k warning
+        x = eval('`x`')
+        x = eval('`1 or 2 or 3`')
+        self.assertEqual(eval('`1,2`'), '(1, 2)')
 
         x = x
         x = 'x'
 
 
 def test_main():
-    run_unittest(TokenTests, GrammarTests)
+    with warnings.catch_warnings():
+        # Silence Py3k warnings
+        warnings.filterwarnings("ignore", "backquote not supported",
+                                SyntaxWarning)
+        warnings.filterwarnings("ignore", "tuple parameter unpacking has been removed",
+                                SyntaxWarning)
+        warnings.filterwarnings("ignore", "parenthesized argument names are invalid",
+                                SyntaxWarning)
+        warnings.filterwarnings("ignore", "classic int division",
+                                DeprecationWarning)
+        warnings.filterwarnings("ignore", ".+ not supported in 3.x",
+                                DeprecationWarning)
+        run_unittest(TokenTests, GrammarTests)
 
 if __name__ == '__main__':
     test_main()

Lib/test/test_gzip.py

             self.fail("__enter__ on a closed file didn't raise an exception")
         try:
             with gzip.GzipFile(self.filename, "wb") as f:
-                1/0
+                1 // 0
         except ZeroDivisionError:
             pass
         else:
-            self.fail("1/0 didn't raise an exception")
+            self.fail("1 // 0 didn't raise an exception")
 
 def test_main(verbose=None):
     test_support.run_unittest(TestGzip)

Lib/test/test_heapq.py

         for f in (self.module.nlargest, self.module.nsmallest):
             for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
                 for g in (G, I, Ig, L, R):
-                    self.assertEqual(f(2, g(s)), f(2,s))
+                    with test_support.check_warnings():
+                        self.assertEqual(f(2, g(s)), f(2,s))
                 self.assertEqual(f(2, S(s)), [])
                 self.assertRaises(TypeError, f, 2, X(s))
                 self.assertRaises(TypeError, f, 2, N(s))

Lib/test/test_hotshot.py

-import hotshot
-import hotshot.log
 import os
 import pprint
 import unittest
 
 from test import test_support
 
+# Silence Py3k warning
+hotshot = test_support.import_module('hotshot', deprecated=True)
 from hotshot.log import ENTER, EXIT, LINE
 
 

Lib/test/test_import.py

 import py_compile
 import warnings
 import marshal
+from imp import reload
 from test.test_support import (unlink, TESTFN, unload, run_unittest,
     check_warnings, TestFailed, EnvironmentVarGuard)
 
             f.close()
 
             try:
-                try:
-                    mod = __import__(TESTFN)
-                except ImportError, err:
-                    self.fail("import from %s failed: %s" % (ext, err))
-
+                mod = __import__(TESTFN)
+            except ImportError, err:
+                self.fail("import from %s failed: %s" % (ext, err))
+            else:
                 self.assertEquals(mod.a, a,
                     "module loaded (%s) but contents invalid" % mod)
                 self.assertEquals(mod.b, b,
                 os.unlink(source)
 
             try:
-                try:
-                    reload(mod)
-                except ImportError, err:
-                    self.fail("import from .pyc/.pyo failed: %s" % err)
+                reload(mod)
+            except ImportError, err:
+                self.fail("import from .pyc/.pyo failed: %s" % err)
             finally:
                 try:
                     os.unlink(pyc)
     def test_failing_import_sticks(self):
         source = TESTFN + os.extsep + "py"
         f = open(source, "w")
-        print >> f, "a = 1/0"
+        print >> f, "a = 1 // 0"
         f.close()
 
         # New in 2.4, we shouldn't be able to import that no matter how often

Lib/test/test_importhooks.py

         self.assertFalse(hasattr(reloadmodule,'reloaded'))
 
         TestImporter.modules['reloadmodule'] = (False, reload_co)
-        reload(reloadmodule)
+        imp.reload(reloadmodule)
         self.assertTrue(hasattr(reloadmodule,'reloaded'))
 
         import hooktestpackage.oldabs
             for n in sys.modules.keys():
                 if n.startswith(parent):
                     del sys.modules[n]
-        for mname in mnames:
-            m = __import__(mname, globals(), locals(), ["__dummy__"])
-            m.__loader__  # to make sure we actually handled the import
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            for mname in mnames:
+                m = __import__(mname, globals(), locals(), ["__dummy__"])
+                m.__loader__  # to make sure we actually handled the import
 
 
 def test_main():

Lib/test/test_inspect.py

 import inspect
 import datetime
 
-from test.test_support import TESTFN, run_unittest
+from test.test_support import TESTFN, run_unittest, check_warnings
 
-from test import inspect_fodder as mod
-from test import inspect_fodder2 as mod2
+with check_warnings():
+    from test import inspect_fodder as mod
+    from test import inspect_fodder2 as mod2
 
 # C module for test_findsource_binary
 import unicodedata
 import __builtin__
 
 try:
-    1/0
+    1 // 0
 except:
     tb = sys.exc_traceback
 
         self.assertEqual(git.tr[1][1:], (modfile, 9, 'spam',
                                          ['    eggs(b + d, c + f)\n'], 0))
         self.assertEqual(git.tr[2][1:], (modfile, 18, 'eggs',
-                                         ['    q = y / 0\n'], 0))
+                                         ['    q = y // 0\n'], 0))
 
     def test_frame(self):
         args, varargs, varkw, locals = inspect.getargvalues(mod.fr)
         self.assertArgSpecEquals(A.m, ['self'])
 
     def test_getargspec_sublistofone(self):
-        def sublistOfOne((foo,)): return 1
-        self.assertArgSpecEquals(sublistOfOne, [['foo']])
+        # Silence Py3k warning
+        with check_warnings():
+            exec 'def sublistOfOne((foo,)): return 1'
+            self.assertArgSpecEquals(sublistOfOne, [['foo']])
 
-        def fakeSublistOfOne((foo)): return 1
-        self.assertArgSpecEquals(fakeSublistOfOne, ['foo'])
+            exec 'def fakeSublistOfOne((foo)): return 1'
+            self.assertArgSpecEquals(fakeSublistOfOne, ['foo'])
 
     def test_classify_oldstyle(self):
         class A:

Lib/test/test_io.py

             f = None
             try:
                 with self.open(support.TESTFN, "wb", bufsize) as f:
-                    1/0
+                    1 // 0
             except ZeroDivisionError:
                 self.assertEqual(f.closed, True)
             else:
-                self.fail("1/0 didn't raise an exception")
+                self.fail("1 // 0 didn't raise an exception")
 
     # issue 5008
     def test_append_mode_tell(self):

Lib/test/test_iter.py

 # Test iterators.
 
 import unittest
-from test.test_support import run_unittest, TESTFN, unlink, have_unicode
+from test.test_support import run_unittest, TESTFN, unlink, have_unicode, \
+                              check_warnings
 
 # Test result of triple loop (too big to inline)
 TRIPLETS = [(0, 0, 0), (0, 0, 1), (0, 0, 2),
                 pass
 
     # Test map()'s use of iterators.
-    def test_builtin_map(self):
+    def test_deprecated_builtin_map(self):
+        # Silence Py3k warning
+        with check_warnings():
+            self._test_builtin_map()
+
+    def _test_builtin_map(self):
         self.assertEqual(map(None, SequenceClass(5)), range(5))
         self.assertEqual(map(lambda x: x+1, SequenceClass(5)), range(1, 6))
 
                 self.assertEqual(zip(x, y), expected)
 
     # Test reduces()'s use of iterators.
-    def test_builtin_reduce(self):
+    def test_deprecated_builtin_reduce(self):
+        # Silence Py3k warning
+        with check_warnings():
+            self._test_builtin_reduce()
+
+    def _test_builtin_reduce(self):
         from operator import add
         self.assertEqual(reduce(add, SequenceClass(5)), 10)
         self.assertEqual(reduce(add, SequenceClass(5), 42), 52)

Lib/test/test_itertools.py

 import random
 import copy
 import pickle
+from functools import reduce
 maxsize = test_support.MAX_Py_ssize_t
 minsize = -maxsize-1
 
             values = [5*x-12 for x in range(n)]
             for r in range(n+2):
                 result = list(combinations(values, r))
-                self.assertEqual(len(result), 0 if r>n else fact(n) / fact(r) / fact(n-r)) # right number of combs
+                self.assertEqual(len(result), 0 if r>n else fact(n) // fact(r) // fact(n-r)) # right number of combs
                 self.assertEqual(len(result), len(set(result)))         # no repeats
                 self.assertEqual(result, sorted(result))                # lexicographic order
                 for c in result:
         def numcombs(n, r):
             if not n:
                 return 0 if r else 1
-            return fact(n+r-1) / fact(r)/ fact(n-1)
+            return fact(n+r-1) // fact(r) // fact(n-1)
 
         for n in range(7):
             values = [5*x-12 for x in range(n)]
             values = [5*x-12 for x in range(n)]
             for r in range(n+2):
                 result = list(permutations(values, r))
-                self.assertEqual(len(result), 0 if r>n else fact(n) / fact(n-r))      # right number of perms
+                self.assertEqual(len(result), 0 if r>n else fact(n) // fact(n-r))      # right number of perms
                 self.assertEqual(len(result), len(set(result)))         # no repeats
                 self.assertEqual(result, sorted(result))                # lexicographic order
                 for p in result:
 
                 # Check size
                 self.assertEquals(len(prod), n**r)
-                self.assertEquals(len(cwr), (fact(n+r-1) / fact(r)/ fact(n-1)) if n else (not r))
-                self.assertEquals(len(perm), 0 if r>n else fact(n) / fact(n-r))
-                self.assertEquals(len(comb), 0 if r>n else fact(n) / fact(r) / fact(n-r))
+                self.assertEquals(len(cwr), (fact(n+r-1) // fact(r) // fact(n-1)) if n else (not r))
+                self.assertEquals(len(perm), 0 if r>n else fact(n) // fact(n-r))
+                self.assertEquals(len(comb), 0 if r>n else fact(n) // fact(r) // fact(n-r))
 
                 # Check lexicographic order without repeated tuples
                 self.assertEquals(prod, sorted(set(prod)))
                 [range(1000), range(0), range(3000,3050), range(1200), range(1500)],
                 [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)],
             ]:
-            target = map(None, *args)
+            target = [tuple([arg[i] if i < len(arg) else None for arg in args])
+                      for i in range(max(map(len, args)))]
             self.assertEqual(list(izip_longest(*args)), target)
             self.assertEqual(list(izip_longest(*args, **{})), target)
             target = [tuple((e is None and 'X' or e) for e in t) for t in target]   # Replace None fills with 'X'
         self.assertEqual(list(izip_longest([])), zip([]))
         self.assertEqual(list(izip_longest('abcdef')), zip('abcdef'))
 
-        self.assertEqual(list(izip_longest('abc', 'defg', **{})), map(None, 'abc', 'defg')) # empty keyword dict
+        self.assertEqual(list(izip_longest('abc', 'defg', **{})),
+                         zip(list('abc') + [None], 'defg'))  # empty keyword dict
         self.assertRaises(TypeError, izip_longest, 3)
         self.assertRaises(TypeError, izip_longest, range(3), 3)
 
 # is differencing with a range so that consecutive numbers all appear in
 # same group.
 >>> data = [ 1,  4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
->>> for k, g in groupby(enumerate(data), lambda (i,x):i-x):
+>>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
 ...     print map(operator.itemgetter(1), g)
 ...
 [1]

Lib/test/test_json.py

 
 import json.tests
 import test.test_support
+import warnings
 
 
 def test_main():
-    test.test_support.run_unittest(json.tests.test_suite())
+    with warnings.catch_warnings():
+        # Silence Py3k warning
+        warnings.filterwarnings("ignore", "comparing unequal types "
+                                "not supported", DeprecationWarning)
+        test.test_support.run_unittest(json.tests.test_suite())
 
 
 if __name__ == "__main__":

Lib/test/test_linuxaudiodev.py

 from test.test_support import findfile, run_unittest
 
 import errno
-linuxaudiodev = test_support.import_module('linuxaudiodev', deprecated=True)
 import sys
-import sunaudio
 import audioop
 import unittest
 
+linuxaudiodev = test_support.import_module('linuxaudiodev', deprecated=True)
+sunaudio = test_support.import_module('sunaudio', deprecated=True)
+
 SND_FORMAT_MULAW_8 = 1
 
 class LinuxAudioDevTests(unittest.TestCase):

Lib/test/test_long.py

             def __getslice__(self, i, j):
                 return i, j
 
-        self.assertEqual(X()[-5L:7L], (-5, 7))
-        # use the clamping effect to test the smallest and largest longs
-        # that fit a Py_ssize_t
-        slicemin, slicemax = X()[-2L**100:2L**100]
-        self.assertEqual(X()[slicemin:slicemax], (slicemin, slicemax))
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            self.assertEqual(X()[-5L:7L], (-5, 7))
+            # use the clamping effect to test the smallest and largest longs
+            # that fit a Py_ssize_t
+            slicemin, slicemax = X()[-2L**100:2L**100]
+            self.assertEqual(X()[slicemin:slicemax], (slicemin, slicemax))
 
 # ----------------------------------- tests of auto int->long conversion
 
                 checkit(x, '*', y)
 
                 if y:
-                    expected = longx / longy
-                    got = x / y
+                    # Silence Py3k warning
+                    with test_support.check_warnings():
+                        expected = longx / longy
+                        got = x / y
                     checkit(x, '/', y)
 
                     expected = longx // longy

Lib/test/test_mailbox.py

 import socket
 import email
 import email.message
-import rfc822
 import re
 import StringIO
 from test import test_support
 except ImportError:
     pass
 
+# Silence Py3k warning
+rfc822 = test_support.import_module('rfc822')
 
 class TestBase(unittest.TestCase):
 

Lib/test/test_marshal.py

 
     def test_buffer(self):
         for s in ["", "Andr� Previn", "abc", " "*10000]:
-            b = buffer(s)
+            # Silence Py3k warning
+            with test_support.check_warnings():
+                b = buffer(s)
             new = marshal.loads(marshal.dumps(b))
             self.assertEqual(s, new)
             marshal.dump(b, file(test_support.TESTFN, "wb"))

Lib/test/test_multibytecodec_support.py

                 continue
 
             unich = unichrs(data[1])
-            if ord(unich) == 0xfffd or urt_wa.has_key(unich):
+            if ord(unich) == 0xfffd or unich in urt_wa:
                 continue
             urt_wa[unich] = csetch
 

Lib/test/test_multifile.py

 from test import test_support
-import mimetools
+mimetools = test_support.import_module("mimetools", deprecated=True)
 multifile = test_support.import_module('multifile', deprecated=True)
 import cStringIO
 

Lib/test/test_multiprocessing.py

 import logging
 from test import test_support
 from StringIO import StringIO
+import warnings
 
 
 _multiprocessing = test_support.import_module('_multiprocessing')
 
     loadTestsFromTestCase = unittest.defaultTestLoader.loadTestsFromTestCase
     suite = unittest.TestSuite(loadTestsFromTestCase(tc) for tc in testcases)
-    run(suite)
+    with warnings.catch_warnings():
+        # Silence Py3k warnings
+        warnings.filterwarnings("ignore", ".+slice__ has been removed",
+                                DeprecationWarning)
+        run(suite)
 
     ThreadsMixin.pool.terminate()
     ProcessesMixin.pool.terminate()

Lib/test/test_mutants.py

         # Tim sez:  "luck of the draw; crashes with or without for me."
         print >> f
 
-        return `"machiavelli"`
+        return repr("machiavelli")
 
     def __hash__(self):
         return 0

Lib/test/test_opcodes.py

 
 from test.test_support import run_unittest
 import unittest
+import warnings
 
 class OpcodeTest(unittest.TestCase):
 
         n = 0
         for i in range(10):
             n = n+i