]> granicus.if.org Git - python/commitdiff
Fixing - Issue7026 - RuntimeError: dictionary changed size during iteration. Patch...
authorSenthil Kumaran <orsenthil@gmail.com>
Fri, 8 Jan 2010 18:41:40 +0000 (18:41 +0000)
committerSenthil Kumaran <orsenthil@gmail.com>
Fri, 8 Jan 2010 18:41:40 +0000 (18:41 +0000)
107 files changed:
Lib/test/infinite_reload.py
Lib/test/inspect_fodder.py
Lib/test/list_tests.py
Lib/test/mapping_tests.py
Lib/test/regrtest.py
Lib/test/seq_tests.py
Lib/test/test_StringIO.py
Lib/test/test_anydbm.py
Lib/test/test_array.py
Lib/test/test_ast.py
Lib/test/test_augassign.py
Lib/test/test_bigmem.py
Lib/test/test_binascii.py
Lib/test/test_binop.py
Lib/test/test_bool.py
Lib/test/test_buffer.py
Lib/test/test_builtin.py
Lib/test/test_call.py
Lib/test/test_capi.py
Lib/test/test_cgi.py
Lib/test/test_class.py
Lib/test/test_coercion.py
Lib/test/test_collections.py
Lib/test/test_commands.py
Lib/test/test_compile.py
Lib/test/test_compiler.py
Lib/test/test_complex_args.py
Lib/test/test_copy.py
Lib/test/test_ctypes.py
Lib/test/test_decimal.py
Lib/test/test_descr.py
Lib/test/test_descrtut.py
Lib/test/test_dict.py
Lib/test/test_exceptions.py
Lib/test/test_file.py
Lib/test/test_file2k.py
Lib/test/test_fractions.py
Lib/test/test_ftplib.py
Lib/test/test_functools.py
Lib/test/test_grammar.py
Lib/test/test_gzip.py
Lib/test/test_heapq.py
Lib/test/test_hotshot.py
Lib/test/test_import.py
Lib/test/test_importhooks.py
Lib/test/test_inspect.py
Lib/test/test_io.py
Lib/test/test_iter.py
Lib/test/test_itertools.py
Lib/test/test_json.py
Lib/test/test_linuxaudiodev.py
Lib/test/test_long.py
Lib/test/test_mailbox.py
Lib/test/test_marshal.py
Lib/test/test_multibytecodec_support.py
Lib/test/test_multifile.py
Lib/test/test_multiprocessing.py
Lib/test/test_mutants.py
Lib/test/test_opcodes.py
Lib/test/test_operator.py
Lib/test/test_optparse.py
Lib/test/test_ossaudiodev.py
Lib/test/test_peepholer.py
Lib/test/test_pep352.py
Lib/test/test_pkgimport.py
Lib/test/test_pyclbr.py
Lib/test/test_pyexpat.py
Lib/test/test_queue.py
Lib/test/test_random.py
Lib/test/test_repr.py
Lib/test/test_rfc822.py
Lib/test/test_richcmp.py
Lib/test/test_scope.py
Lib/test/test_set.py
Lib/test/test_sets.py
Lib/test/test_shelve.py
Lib/test/test_site.py
Lib/test/test_slice.py
Lib/test/test_socket.py
Lib/test/test_sort.py
Lib/test/test_sqlite.py
Lib/test/test_ssl.py
Lib/test/test_struct.py
Lib/test/test_syntax.py
Lib/test/test_sys.py
Lib/test/test_tarfile.py
Lib/test/test_threadsignals.py
Lib/test/test_trace.py
Lib/test/test_traceback.py
Lib/test/test_transformer.py
Lib/test/test_types.py
Lib/test/test_undocumented_details.py
Lib/test/test_unittest.py
Lib/test/test_univnewlines2k.py
Lib/test/test_urllib.py
Lib/test/test_urllib2_localnet.py
Lib/test/test_urllibnet.py
Lib/test/test_userdict.py
Lib/test/test_userlist.py
Lib/test/test_userstring.py
Lib/test/test_weakref.py
Lib/test/test_whichdb.py
Lib/test/test_with.py
Lib/test/test_wsgiref.py
Lib/test/test_xmllib.py
Lib/test/test_xpickle.py
Lib/test/test_zipimport_support.py

index bfbec91b0a1c2df3fd0085c39a4f4ce2e17f23b5..841ccad0b98b8b15ee8643d36d281da1078ec3eb 100644 (file)
@@ -3,5 +3,6 @@
 #  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)
index 823559bb3510e01e81477fc13843a0cbd72eefd9..afde2e2514b19fb55f11329cec2bf503c9391445 100644 (file)
@@ -15,7 +15,7 @@ def eggs(x, y):
     fr = inspect.currentframe()
     st = inspect.stack()
     p = x
-    q = y / 0
+    q = y // 0
 
 # line 20
 class StupidGit:
index c9aa3160a9b930a8c0a0b7762c337324bec51269..4fc99e049de2ede4730a7afb63791abc6380a091 100644 (file)
@@ -4,7 +4,7 @@ Tests common to list and UserList.UserList
 
 import sys
 import os
-
+import warnings
 from test import test_support, seq_tests
 
 class CommonTest(seq_tests.CommonTest):
@@ -36,7 +36,9 @@ 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]")
 
@@ -421,6 +423,13 @@ class CommonTest(seq_tests.CommonTest):
         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])
index 7ec4bb1e137272b96f45a4063737d6bd0ffac1b6..d17c94887fd694803af6dbf499e60a3ba8b7c255 100644 (file)
@@ -1,6 +1,7 @@
 # tests common to dict and UserDict
 import unittest
 import UserDict
+import test_support
 
 
 class BasicTestMappingProtocol(unittest.TestCase):
@@ -54,13 +55,18 @@ 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)
index fd6cafce7ecc4a72e98fc6c99b4e22b85a110cf1..56c53dad3fbbf3415ac9925569a8af68a078f9c1 100755 (executable)
@@ -150,7 +150,6 @@ option '-uall,-bsddb'.
 import cStringIO
 import getopt
 import itertools
-import json
 import os
 import random
 import re
@@ -160,15 +159,13 @@ import traceback
 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/)
index 14303aa4ad4e87e59544f3e158a27f0768b84035..f6b15bf645eb23d0a42877b4f089959f5d11c64e 100644 (file)
@@ -4,6 +4,7 @@ Tests common to tuple, list and UserList.UserList
 
 import unittest
 import sys
+import test_support
 
 # Various iterables
 # This is used for checking the constructor (here and in test_deque.py)
@@ -196,7 +197,9 @@ class CommonTest(unittest.TestCase):
         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])
index d10255de41f2ae151f07f48330804eecb5837fd0..e484f79c2cf1a2971635d624ae57e0df9a9c0abb 100644 (file)
@@ -137,12 +137,10 @@ class TestBuffercStringIO(TestcStringIO):
 
 
 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()
index 0cdc2c321d0c911cab464bf4e54e0ab9f0af9118..a01dd0bd9fc0b92f920660de2103763e7d2a60c5 100644 (file)
@@ -5,12 +5,14 @@
 
 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
index 63f7083d337341c5827771f94021b5b40a4e2565..004501acb529aa69a3ac9dca324591e91155d303 100755 (executable)
@@ -749,7 +749,9 @@ class BaseTest(unittest.TestCase):
 
     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):
index e5920329f12f6f8e992d8b4b77da880bb5969271..f16da156db64ae57644c4111ce3e9049bc66cc15 100644 (file)
@@ -1,6 +1,7 @@
 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)):
@@ -302,7 +303,11 @@ class ASTHelpers_Test(unittest.TestCase):
 
 
 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__':
index a5b7cc4aaa0362c82169c5534abf95b109f0bc83..51db28b80869ca730ab6dd54de8026a033e029fa 100644 (file)
@@ -2,6 +2,7 @@
 
 from test.test_support import run_unittest
 import unittest
+import warnings
 
 
 class AugAssignTest(unittest.TestCase):
@@ -324,7 +325,11 @@ __ilshift__ called
 '''.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()
index cb1b2f57680247a25d282ff8cceea81359f6817e..a3adaf3beba05d20911909cd08889079cb757a26 100644 (file)
@@ -97,21 +97,21 @@ class StrTest(unittest.TestCase):
     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)
@@ -122,7 +122,7 @@ class StrTest(unittest.TestCase):
     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
@@ -516,7 +516,7 @@ class StrTest(unittest.TestCase):
         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)
@@ -1053,7 +1053,9 @@ class BufferTest(unittest.TestCase):
     @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:
index c531c656db7b63d4e40d4ccbfc37e3353e00f2ae..6a1f972cbf87ae2d18787b66f69494841eb68346 100755 (executable)
@@ -26,10 +26,10 @@ class BinASCIITest(unittest.TestCase):
                 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):
index 8ae8f4295514a3ac4f67a7bf3c9f0b16e7b0664e..b1ef626a9ac4b2954582fca94a0b5dcd808591cd 100644 (file)
@@ -207,6 +207,9 @@ class Rat(object):
         """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."""
 
index 2a9ef5dd7ccfb8e16cfcb5204ae684d1a8d8d90c..805d7582da659cdf9753494517ebe2d3d95b8ed7 100644 (file)
@@ -91,10 +91,10 @@ class BoolTest(unittest.TestCase):
         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:
@@ -168,8 +168,8 @@ class BoolTest(unittest.TestCase):
         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)
@@ -184,8 +184,12 @@ class BoolTest(unittest.TestCase):
         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)
@@ -257,8 +261,10 @@ class BoolTest(unittest.TestCase):
         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)
index 3bede88bf96b0d97ab5e860e1ed2441d1020ea0f..ac89e05598e16f25724bc502e5965fbb144b7565 100644 (file)
@@ -6,6 +6,7 @@ For now, tests just new or changed functionality.
 
 import unittest
 from test import test_support
+import warnings
 
 class BufferTests(unittest.TestCase):
 
@@ -23,7 +24,11 @@ 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()
index f20d5430068fcc9aa2b06c0b2e168982620e1425..ac5b754bbe63df85a19bac258ceb29fda72e92c2 100644 (file)
@@ -7,10 +7,6 @@ from test.test_support import fcmp, have_unicode, TESTFN, unlink, \
 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
@@ -419,7 +415,11 @@ class BuiltinTest(unittest.TestCase):
     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
@@ -1542,17 +1542,30 @@ class TestSorted(unittest.TestCase):
         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
index f3c7c8c394f90573b3fea9fb4b3b43bb3d587600..3bbc0814f5246e77a8007e370d8ca9440f38dfef 100644 (file)
@@ -12,7 +12,9 @@ class CFunctionCalls(unittest.TestCase):
         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)
@@ -24,11 +26,15 @@ class CFunctionCalls(unittest.TestCase):
             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:
index 4dc3104aeea905677573b2ae73e110757491052d..c313dcf037be6efefdd1dd572237b787272ed3bf 100644 (file)
@@ -55,7 +55,7 @@ class TestPendingCalls(unittest.TestCase):
         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()
index aa26bb624253f61b707085a1fdea28f258e57359..44ebe10163ea3a88de5445b03d8e9e1b2db409d5 100644 (file)
@@ -104,7 +104,7 @@ parse_strict_test_cases = [
 
 def norm(list):
     if type(list) == type([]):
-        list.sort()
+        list.sort(key=str)
     return list
 
 def first_elts(list):
index fc61d21a22abede1392509a87d219cffb5c1a726..194b4730f62b3e4e64a566682145cb862d01b1b1 100644 (file)
@@ -1,7 +1,7 @@
 "Test the functionality of Python classes implementing operators."
 
 import unittest
-
+import warnings
 from test import test_support
 
 testmeths = [
@@ -407,7 +407,7 @@ class ClassTests(unittest.TestCase):
         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[:] = []
@@ -427,7 +427,7 @@ class ClassTests(unittest.TestCase):
         self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (1, testme))])
 
         callLst[:] = []
-        1 <> testme
+        eval('1 <> testme')
         self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (1, testme))])
 
         callLst[:] = []
@@ -616,7 +616,15 @@ class ClassTests(unittest.TestCase):
         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()
index 67d19a6120b35437f5d6b644034d531b70177bf7..c6a1c1763606aa3077da7f88ca19e0e12dccad44 100644 (file)
@@ -223,8 +223,11 @@ def process_infix_results():
             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' ]
@@ -337,11 +340,14 @@ class CoercionTest(unittest.TestCase):
             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()
index fb24d4391a0052b226bb3d62c5e0ac69e2125308..b44beab13492343691be7d71cda739a6f8286c6c 100644 (file)
@@ -510,8 +510,10 @@ class TestCounter(unittest.TestCase):
                          [('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)
index fcfa616cb74e87b1dbbb261ccdeaea2343b2b97d..27b6c3d56c2c0b8d00983b106c839e730069a09a 100644 (file)
@@ -9,7 +9,10 @@ import warnings
 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:
index 28b73325d8dd320d71a1d3b850e33167ab86779d..efc54e514aef1b174dc41fee93c9a08fbabb26ac 100644 (file)
@@ -2,6 +2,7 @@ import unittest
 import sys
 import _ast
 from test import test_support
+import textwrap
 
 class TestSpecifics(unittest.TestCase):
 
@@ -141,7 +142,9 @@ def f(x):
         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))
@@ -159,6 +162,7 @@ def f(x):
             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:
index 24930f8a6367a7d5254570705c36a2eb3d0b3572..a345ce629cd0e4ba5573f2cfab4ec63c8b2821ca 100644 (file)
@@ -75,7 +75,7 @@ class CompilerTest(unittest.TestCase):
 
     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
index c6d50a9d05e15474007531eccd8a45b590df9c6f..f6950a7261aad853dbec617b9541ea976b3984d2 100644 (file)
@@ -1,23 +1,31 @@
 
 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
@@ -26,16 +34,22 @@ class ComplexArgsTestCase(unittest.TestCase):
         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)
 
@@ -44,18 +58,22 @@ class ComplexArgsTestCase(unittest.TestCase):
 
         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
@@ -64,16 +82,22 @@ class ComplexArgsTestCase(unittest.TestCase):
         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)
 
@@ -82,10 +106,17 @@ class ComplexArgsTestCase(unittest.TestCase):
 
         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()
index 823e9b36a32a4f4683095e9e17cca2ab955f5cc0..bbe31d838de7923c70ff30fc8b168be3ab6febb0 100644 (file)
@@ -661,7 +661,7 @@ class TestCopy(unittest.TestCase):
         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)
index 85f137e45ee25e233c2bf11d10edfba72f883910..4e93c87f8d2c4a0b2c5ea12a4d8a777c1dfa283c 100644 (file)
@@ -4,12 +4,19 @@ from test.test_support import run_unittest, import_module
 #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()
index 69f31a0e54e0890a2f836f4e25d4c5c5642b2a34..9fef0d2232edf1c7172e7826a13e3130ab094fcf 100644 (file)
@@ -31,7 +31,8 @@ import pickle, copy
 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
@@ -202,7 +203,7 @@ class DecimalTest(unittest.TestCase):
         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:
@@ -361,8 +362,10 @@ class DecimalTest(unittest.TestCase):
         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)
@@ -617,12 +620,14 @@ class DecimalImplicitConstructionTest(unittest.TestCase):
             ('//', '__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))
@@ -1194,8 +1199,10 @@ class DecimalUsabilityTest(unittest.TestCase):
         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')
@@ -1704,11 +1711,14 @@ class ContextFlags(unittest.TestCase):
                 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: " +
index 418337b57a22fd85681c8da745f18b0e3a29ed08..a044faf77fc2615ddb760a4f5e9e12153f9b6ff1 100644 (file)
@@ -4598,9 +4598,19 @@ class PTypesLongInitTest(unittest.TestCase):
 
 
 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()
index c455e6b7106cfa4f5a0e9844302756028f6b6868..157b9f4fe9c25933875b9d72a46d3533698bd388 100644 (file)
@@ -66,7 +66,7 @@ dictionaries, such as the locals/globals dictionaries for the exec
 statement or the built-in function eval():
 
     >>> def sorted(seq):
-    ...     seq.sort()
+    ...     seq.sort(key=str)
     ...     return seq
     >>> print sorted(a.keys())
     [1, 2]
index 075f9dc32f0b846f495eecae53b276f1ffc9a902..de400aa580d6a28a8900bca077ac6c36b4ea4ed3 100644 (file)
@@ -33,8 +33,12 @@ class DictTest(unittest.TestCase):
         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)
 
@@ -57,14 +61,16 @@ class DictTest(unittest.TestCase):
 
     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))
@@ -395,8 +401,6 @@ class DictTest(unittest.TestCase):
         self.assertRaises(Exc, repr, d)
 
     def test_le(self):
-        self.assertTrue(not ({} < {}))
-        self.assertTrue(not ({1: 2} < {1L: 2L}))
 
         class Exc(Exception): pass
 
@@ -408,12 +412,18 @@ class DictTest(unittest.TestCase):
 
         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
@@ -501,7 +511,9 @@ class DictTest(unittest.TestCase):
                      '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:
@@ -549,7 +561,7 @@ class DictTest(unittest.TestCase):
         # 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
index a30f42bcd68bea2be447c505013d00610de10ea7..7b63718e564ea6ea309528c3f520002b1bc8dfde 100644 (file)
@@ -7,7 +7,7 @@ import pickle, cPickle
 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!
 
@@ -17,6 +17,7 @@ class ExceptionTests(unittest.TestCase):
         # 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:
@@ -108,11 +109,11 @@ class ExceptionTests(unittest.TestCase):
         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):
@@ -197,6 +198,7 @@ class ExceptionTests(unittest.TestCase):
             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
 
@@ -274,34 +276,32 @@ class ExceptionTests(unittest.TestCase):
         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))
-
-                    # 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))
+        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))
 
 
     def testDeprecatedMessageAttribute(self):
@@ -330,6 +330,7 @@ class ExceptionTests(unittest.TestCase):
         with self.assertRaises(AttributeError):
             exc.message
 
+    @ignore_deprecation_warnings
     def testPickleMessageAttribute(self):
         # Pickling with message attribute must work, as well.
         e = Exception("foo")
@@ -337,9 +338,7 @@ class ExceptionTests(unittest.TestCase):
         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")
 
@@ -348,7 +347,12 @@ class ExceptionTests(unittest.TestCase):
         # 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,
index 7d3e72d502fa83fcea508c0cd821ec7e138d1ec3..a91897e41730a3e74d94eb4d9d31772d5ecf2919 100644 (file)
@@ -127,7 +127,7 @@ class AutoFileTests(unittest.TestCase):
         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)
 
index bf47c6fa4592426d6b31e13d6f86c83e10ead924..bebc43ddd61abb8ac11db8e39fd67480e1585050 100644 (file)
@@ -34,13 +34,17 @@ class AutoFileTests(unittest.TestCase):
     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':
@@ -98,7 +102,8 @@ class AutoFileTests(unittest.TestCase):
     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')
 
@@ -110,13 +115,18 @@ class AutoFileTests(unittest.TestCase):
             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)
 
@@ -182,12 +192,12 @@ class OtherFileTests(unittest.TestCase):
         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)
index de8e539e44c7aad9875e5f2e0a6f516b615af378..9e3fc5e5a18cb18bb56c2bbb7b0c39dd192ca2b3 100644 (file)
@@ -43,6 +43,10 @@ class DummyFloat(object):
         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."""
@@ -76,6 +80,11 @@ class DummyRational(object):
     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):
index fb9d55b2eed1c00765a52d158db0b1d1e58e5b55..b3915615460e6966b7a9699431da93569786a315 100644 (file)
@@ -100,7 +100,7 @@ class DummyFTPHandler(asynchat.async_chat):
         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)
index ab5bac2c309ce90464f2c0c2c3cc8979f43102c9..aa672abe4f09d5308c0c768ac7a5f91df285c317 100644 (file)
@@ -116,7 +116,7 @@ class TestPartial(unittest.TestCase):
 
     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)
index f144ae782e5a5887f4ff92d3b40e63b0e6504f74..573a512131c54934c27cb0b68146ed86a084641a 100644 (file)
@@ -11,6 +11,7 @@
 from test.test_support import run_unittest, check_syntax_error
 import unittest
 import sys
+import warnings
 # testing import *
 from sys import *
 
@@ -152,8 +153,9 @@ class GrammarTests(unittest.TestCase):
         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'):
@@ -172,7 +174,8 @@ class GrammarTests(unittest.TestCase):
         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)
@@ -277,9 +280,10 @@ class GrammarTests(unittest.TestCase):
         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
@@ -474,7 +478,7 @@ hello world
                     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()
 
@@ -677,7 +681,6 @@ hello world
         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
@@ -686,7 +689,10 @@ hello world
         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
@@ -769,9 +775,10 @@ hello world
         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'
@@ -976,7 +983,19 @@ hello world
 
 
 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()
index 60094dceb1a1f0229c0d16cd8abbbd4e71c9f982..ed5aa964edec4893ba3bb5ecb1bec4b9e9686c3b 100644 (file)
@@ -246,11 +246,11 @@ class TestGzip(unittest.TestCase):
             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)
index e377384c87d4a8dad65fe4e542869d43b001857f..20eceedbcad809f0f60315cdee59031a3581cd7b 100644 (file)
@@ -356,7 +356,8 @@ class TestErrorHandling(unittest.TestCase):
         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))
index 38a8dddb6a6ce73565ce3d9a1baf8f5f6bb354da..c6dae363cdcb90ed29642e7dacb90ebc9b873bf5 100644 (file)
@@ -1,5 +1,3 @@
-import hotshot
-import hotshot.log
 import os
 import pprint
 import unittest
@@ -9,6 +7,8 @@ import gc
 
 from test import test_support
 
+# Silence Py3k warning
+hotshot = test_support.import_module('hotshot', deprecated=True)
 from hotshot.log import ENTER, EXIT, LINE
 
 
index 31375dc6eeeafbfaf36e7e58e8d9af4bbb509412..5f54b571af02a5e1cc1fefaf96a4504d2558c831 100644 (file)
@@ -7,6 +7,7 @@ import sys
 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)
 
@@ -56,11 +57,10 @@ class ImportTest(unittest.TestCase):
             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,
@@ -69,10 +69,9 @@ class ImportTest(unittest.TestCase):
                 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)
@@ -172,7 +171,7 @@ class ImportTest(unittest.TestCase):
     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
index 7fd8c62a22d9acbccbc20bbeb40897f0dc77d4e0..f3452fafaecb826fcf5c8150f979f5c6f4f424d3 100644 (file)
@@ -180,7 +180,7 @@ class ImportHooksTestCase(ImportHooksBaseTestCase):
         self.assertFalse(hasattr(reloadmodule,'reloaded'))
 
         TestImporter.modules['reloadmodule'] = (False, reload_co)
-        reload(reloadmodule)
+        imp.reload(reloadmodule)
         self.assertTrue(hasattr(reloadmodule,'reloaded'))
 
         import hooktestpackage.oldabs
@@ -247,9 +247,11 @@ class ImportHooksTestCase(ImportHooksBaseTestCase):
             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():
index f20b26ceb04229f9d4332affc5252254c72909e9..144fcf371300b283c24a43bc3f64dff52ff56067 100644 (file)
@@ -4,10 +4,11 @@ import unittest
 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
@@ -29,7 +30,7 @@ if modfile.endswith(('c', 'o')):
 import __builtin__
 
 try:
-    1/0
+    1 // 0
 except:
     tb = sys.exc_traceback
 
@@ -167,7 +168,7 @@ class TestInterpreterStack(IsTestBase):
         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)
@@ -418,11 +419,13 @@ class TestClassesAndFunctions(unittest.TestCase):
         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:
index a90dd504a388284e29a51245bdf7985c0ff77f00..48ffd455dea04e72dbcc4483addc0dcf40ea540b 100644 (file)
@@ -381,11 +381,11 @@ class IOTest(unittest.TestCase):
             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):
index f5d6e686de42ad23903a83e1ceb66afa68da2933..5e96c6ddae7eb21950f9b6196123bfb461d65762 100644 (file)
@@ -1,7 +1,8 @@
 # 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),
@@ -395,7 +396,12 @@ class TestCase(unittest.TestCase):
                 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))
 
@@ -506,7 +512,12 @@ class TestCase(unittest.TestCase):
                 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)
index 03f1d85111ef27a1bbdb00396774824b4b9416d5..d69aecf061c6e6683d87e82bb6a3bf5372980d40 100644 (file)
@@ -9,6 +9,7 @@ import operator
 import random
 import copy
 import pickle
+from functools import reduce
 maxsize = test_support.MAX_Py_ssize_t
 minsize = -maxsize-1
 
@@ -122,7 +123,7 @@ class TestBasicOps(unittest.TestCase):
             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:
@@ -178,7 +179,7 @@ class TestBasicOps(unittest.TestCase):
         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)]
@@ -257,7 +258,7 @@ class TestBasicOps(unittest.TestCase):
             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:
@@ -288,9 +289,9 @@ class TestBasicOps(unittest.TestCase):
 
                 # 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)))
@@ -543,7 +544,8 @@ class TestBasicOps(unittest.TestCase):
                 [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'
@@ -555,7 +557,8 @@ class TestBasicOps(unittest.TestCase):
         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)
 
@@ -1431,7 +1434,7 @@ Samuele
 # 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]
index 7b8f3de8a9814eac127d358812a397c3d9e93337..bb99dab1b9e828e475f9c75b46253075fdef8e3a 100644 (file)
@@ -7,10 +7,15 @@ be run.
 
 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__":
index 71d0633337937adaa7969e0d034dbc0011505c09..3772a58e94d1371b8312629b416484c71179f963 100644 (file)
@@ -4,12 +4,13 @@ test_support.requires('audio')
 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):
index 1943518e8a7861ea0cc8348d025043f7e4c61ec5..ad84589358e57ab6dd434fae42f255970bfc26a9 100644 (file)
@@ -575,11 +575,13 @@ class LongTest(unittest.TestCase):
             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
 
@@ -619,8 +621,10 @@ class LongTest(unittest.TestCase):
                 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
index 548850ad1ea32e3d4b4c83b590c1986bfd446029..01b1c36af4d9a62719d2a425378067ad1496ce7b 100644 (file)
@@ -5,7 +5,6 @@ import stat
 import socket
 import email
 import email.message
-import rfc822
 import re
 import StringIO
 from test import test_support
@@ -17,6 +16,8 @@ try:
 except ImportError:
     pass
 
+# Silence Py3k warning
+rfc822 = test_support.import_module('rfc822')
 
 class TestBase(unittest.TestCase):
 
index 76691824163f409d6719b6f4d46f5e13626c59d6..af89d185b064da25186c542733cd468e5426902b 100644 (file)
@@ -129,7 +129,9 @@ class StringTestCase(unittest.TestCase):
 
     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"))
index 3afe3a9ae15a425ce68e36b8c07b5f2114829e14..36245b746704c6b377bf683eb94cc4ac8d2521d3 100644 (file)
@@ -307,7 +307,7 @@ class TestBase_Mapping(unittest.TestCase):
                 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
 
index daf7ddefd8c260f9b4738329e7e1fd8adf55d94a..fd0960215c13de4a7c5c3a420046030348cb3227 100644 (file)
@@ -1,5 +1,5 @@
 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
 
index b6c6a844b0ab4a1a86062e74d89f18d1f9125595..94d4dd0336f260c6efceed20a8d0dc780ffdfbed 100644 (file)
@@ -19,6 +19,7 @@ import random
 import logging
 from test import test_support
 from StringIO import StringIO
+import warnings
 
 
 _multiprocessing = test_support.import_module('_multiprocessing')
@@ -1991,7 +1992,11 @@ def test_main(run=None):
 
     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()
index a219450b2556e96cbd47606bacb2d2b5e62d77af..69c381e060700d83e5876ec515c523350f61d4fd 100644 (file)
@@ -210,7 +210,7 @@ class Machiavelli:
         # Tim sez:  "luck of the draw; crashes with or without for me."
         print >> f
 
-        return `"machiavelli"`
+        return repr("machiavelli")
 
     def __hash__(self):
         return 0
index c03ca1df575847bd01c05809a39cb0d96091cf8e..6c9fd58310943e2a0b62c206e544324b5ac9bf99 100644 (file)
@@ -2,6 +2,7 @@
 
 from test.test_support import run_unittest
 import unittest
+import warnings
 
 class OpcodeTest(unittest.TestCase):
 
@@ -9,7 +10,7 @@ class OpcodeTest(unittest.TestCase):
         n = 0
         for i in range(10):
             n = n+i
-            try: 1/0
+            try: 1 // 0
             except NameError: pass
             except ZeroDivisionError: pass
             except TypeError: pass
@@ -110,7 +111,14 @@ class OpcodeTest(unittest.TestCase):
 
 
 def test_main():
-    run_unittest(OpcodeTest)
+    with warnings.catch_warnings():
+        # Silence Py3k warning
+        warnings.filterwarnings("ignore", "exceptions must derive from "
+                                "BaseException", DeprecationWarning)
+        warnings.filterwarnings("ignore", "catching classes that don't "
+                                "inherit from BaseException is not allowed",
+                                DeprecationWarning)
+        run_unittest(OpcodeTest)
 
 if __name__ == '__main__':
     test_main()
index 275885678d5479a0a6e1c994c32bb38ade65a956..70b9fd9c0cf11255161f6515b75c7bd6a585d9ed 100644 (file)
@@ -192,11 +192,12 @@ class OperatorTestCase(unittest.TestCase):
         class C:
             pass
         def check(self, o, v):
-            self.assertTrue(operator.isCallable(o) == callable(o) == v)
-        check(self, 4, 0)
-        check(self, operator.isCallable, 1)
-        check(self, C, 1)
-        check(self, C(), 0)
+            with test_support.check_warnings():
+                self.assertTrue(operator.isCallable(o) == callable(o) == v)
+        check(self, 4, False)
+        check(self, operator.isCallable, True)
+        check(self, C, True)
+        check(self, C(), False)
 
     def test_isMappingType(self):
         self.assertRaises(TypeError, operator.isMappingType)
@@ -306,8 +307,10 @@ class OperatorTestCase(unittest.TestCase):
         self.assertRaises(TypeError, operator.contains, None, None)
         self.assertTrue(operator.contains(range(4), 2))
         self.assertFalse(operator.contains(range(4), 5))
-        self.assertTrue(operator.sequenceIncludes(range(4), 2))
-        self.assertFalse(operator.sequenceIncludes(range(4), 5))
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            self.assertTrue(operator.sequenceIncludes(range(4), 2))
+            self.assertFalse(operator.sequenceIncludes(range(4), 5))
 
     def test_setitem(self):
         a = range(3)
index b11b8c95f8f79c97167bf51065bad888de42ca3f..f7eb47b65ab40b0605c19f6ec9851521fac16aa0 100644 (file)
@@ -26,12 +26,6 @@ from optparse import make_option, Option, IndentedHelpFormatter, \
 from optparse import _match_abbrev
 from optparse import _parse_num
 
-# Do the right thing with boolean values for all known Python versions.
-try:
-    True, False
-except NameError:
-    (True, False) = (1, 0)
-
 retype = type(re.compile(''))
 
 class InterceptedError(Exception):
index df047055f2273aa5db1fe80846752bc1b6c76e16..40903dc41c8731064b46d50f5ed08189ae7d3903 100644 (file)
@@ -71,7 +71,7 @@ class OSSAudioDevTests(unittest.TestCase):
                 self.fail("dsp.%s not read-only" % attr)
 
         # Compute expected running time of sound sample (in seconds).
-        expected_time = float(len(data)) / (ssize/8) / nchannels / rate
+        expected_time = float(len(data)) / (ssize//8) / nchannels / rate
 
         # set parameters based on .au file headers
         dsp.setparameters(AFMT_S16_NE, nchannels, rate)
index 1f6efb503f56bb427ad9a13e6654cd2d38f4bd13..de8d1eae12529ac1415973f1229e6dd2a8ec7580 100644 (file)
@@ -205,18 +205,24 @@ class TestTranforms(unittest.TestCase):
 def test_main(verbose=None):
     import sys
     from test import test_support
+    import warnings
     test_classes = (TestTranforms,)
-    test_support.run_unittest(*test_classes)
-
-    # verify reference counting
-    if verbose and hasattr(sys, "gettotalrefcount"):
-        import gc
-        counts = [None] * 5
-        for i in xrange(len(counts)):
-            test_support.run_unittest(*test_classes)
-            gc.collect()
-            counts[i] = sys.gettotalrefcount()
-        print counts
+
+    with warnings.catch_warnings():
+        # Silence Py3k warning
+        warnings.filterwarnings("ignore", "backquote not supported",
+                                SyntaxWarning)
+        test_support.run_unittest(*test_classes)
+
+        # verify reference counting
+        if verbose and hasattr(sys, "gettotalrefcount"):
+            import gc
+            counts = [None] * 5
+            for i in xrange(len(counts)):
+                test_support.run_unittest(*test_classes)
+                gc.collect()
+                counts[i] = sys.gettotalrefcount()
+            print counts
 
 if __name__ == "__main__":
     test_main(verbose=True)
index c6d3a8dcc16cb90c8b98603439255ee37d1ca59f..103d8356f85f15840cc04da530637bc0bbb914b5 100644 (file)
@@ -6,12 +6,23 @@ from test.test_support import run_unittest
 import os
 from platform import system as platform_system
 
-def ignore_message_warning():
-    """Ignore the DeprecationWarning for BaseException.message."""
-    warnings.resetwarnings()
-    warnings.filterwarnings("ignore", "BaseException.message",
-                            DeprecationWarning)
-
+DEPRECATION_WARNINGS = (
+    "BaseException.message has been deprecated",
+    "exceptions must derive from BaseException",
+    "catching classes that don't inherit from BaseException is not allowed",
+    "__getitem__ not supported for exception classes",
+)
+
+# Silence Py3k and other deprecation warnings
+def ignore_deprecation_warnings(func):
+    """Ignore the known DeprecationWarnings."""
+    def wrapper(*args, **kw):
+        with warnings.catch_warnings():
+            warnings.resetwarnings()
+            for text in DEPRECATION_WARNINGS:
+                warnings.filterwarnings("ignore", text, DeprecationWarning)
+            return func(*args, **kw)
+    return wrapper
 
 class ExceptionClassTests(unittest.TestCase):
 
@@ -21,14 +32,12 @@ class ExceptionClassTests(unittest.TestCase):
     def test_builtins_new_style(self):
         self.assertTrue(issubclass(Exception, object))
 
+    @ignore_deprecation_warnings
     def verify_instance_interface(self, ins):
-        with warnings.catch_warnings():
-            ignore_message_warning()
-            for attr in ("args", "message", "__str__", "__repr__",
-                            "__getitem__"):
-                self.assertTrue(hasattr(ins, attr),
-                        "%s missing %s attribute" %
-                            (ins.__class__.__name__, attr))
+        for attr in ("args", "message", "__str__", "__repr__", "__getitem__"):
+            self.assertTrue(hasattr(ins, attr),
+                    "%s missing %s attribute" %
+                        (ins.__class__.__name__, attr))
 
     def test_inheritance(self):
         # Make sure the inheritance hierarchy matches the documentation
@@ -91,43 +100,39 @@ class ExceptionClassTests(unittest.TestCase):
             self.assertEqual(given, expected, "%s: %s != %s" % (test_name,
                 given, expected))
 
+    @ignore_deprecation_warnings
     def test_interface_single_arg(self):
         # Make sure interface works properly when given a single argument
         arg = "spam"
         exc = Exception(arg)
-        with warnings.catch_warnings():
-            ignore_message_warning()
-            results = ([len(exc.args), 1], [exc.args[0], arg],
-                    [exc.message, arg],
-                    [str(exc), str(arg)], [unicode(exc), unicode(arg)],
-                [repr(exc), exc.__class__.__name__ + repr(exc.args)], [exc[0],
-                arg])
-            self.interface_test_driver(results)
+        results = ([len(exc.args), 1], [exc.args[0], arg], [exc.message, arg],
+                   [str(exc), str(arg)], [unicode(exc), unicode(arg)],
+                   [repr(exc), exc.__class__.__name__ + repr(exc.args)],
+                   [exc[0], arg])
+        self.interface_test_driver(results)
 
+    @ignore_deprecation_warnings
     def test_interface_multi_arg(self):
         # Make sure interface correct when multiple arguments given
         arg_count = 3
         args = tuple(range(arg_count))
         exc = Exception(*args)
-        with warnings.catch_warnings():
-            ignore_message_warning()
-            results = ([len(exc.args), arg_count], [exc.args, args],
-                    [exc.message, ''], [str(exc), str(args)],
-                    [unicode(exc), unicode(args)],
-                    [repr(exc), exc.__class__.__name__ + repr(exc.args)],
-                    [exc[-1], args[-1]])
-            self.interface_test_driver(results)
-
+        results = ([len(exc.args), arg_count], [exc.args, args],
+                   [exc.message, ''], [str(exc), str(args)],
+                   [unicode(exc), unicode(args)],
+                   [repr(exc), exc.__class__.__name__ + repr(exc.args)],
+                   [exc[-1], args[-1]])
+        self.interface_test_driver(results)
+
+    @ignore_deprecation_warnings
     def test_interface_no_arg(self):
         # Make sure that with no args that interface is correct
         exc = Exception()
-        with warnings.catch_warnings():
-            ignore_message_warning()
-            results = ([len(exc.args), 0], [exc.args, tuple()],
-                    [exc.message, ''],
-                    [str(exc), ''], [unicode(exc), u''],
-                    [repr(exc), exc.__class__.__name__ + '()'], [True, True])
-            self.interface_test_driver(results)
+        results = ([len(exc.args), 0], [exc.args, tuple()],
+                   [exc.message, ''],
+                   [str(exc), ''], [unicode(exc), u''],
+                   [repr(exc), exc.__class__.__name__ + '()'], [True, True])
+        self.interface_test_driver(results)
 
 
     def test_message_deprecation(self):
@@ -179,6 +184,7 @@ class UsageTests(unittest.TestCase):
             self.fail("TypeError expected when catching %s as specified in a "
                         "tuple" % type(object_))
 
+    @ignore_deprecation_warnings
     def test_raise_classic(self):
         # Raising a classic class is okay (for now).
         class ClassicClass:
index 8aa224a09398e211fa127ef0192893361530d215..20b13c1f717e1ec4b5cc1a8a3b569d4b9dc7443e 100644 (file)
@@ -6,14 +6,14 @@ class TestImport(unittest.TestCase):
 
     def __init__(self, *args, **kw):
         self.package_name = 'PACKAGE_'
-        while sys.modules.has_key(self.package_name):
+        while self.package_name in sys.modules:
             self.package_name += random.choose(string.letters)
         self.module_name = self.package_name + '.foo'
         unittest.TestCase.__init__(self, *args, **kw)
 
     def remove_modules(self):
         for module_name in (self.package_name, self.module_name):
-            if sys.modules.has_key(module_name):
+            if module_name in sys.modules:
                 del sys.modules[module_name]
 
     def setUp(self):
@@ -52,7 +52,7 @@ class TestImport(unittest.TestCase):
         try: __import__(self.module_name)
         except SyntaxError: pass
         else: raise RuntimeError, 'Failed to induce SyntaxError'
-        self.assertTrue(not sys.modules.has_key(self.module_name) and
+        self.assertTrue(self.module_name not in sys.modules and
                      not hasattr(sys.modules[self.package_name], 'foo'))
 
         # ...make up a variable name that isn't bound in __builtins__
index ec818d188d6e87b6934ed1c739b7ecd257c376f4..5bac62a3c060be8e4eacf89c76ef27bd6aae60a3 100644 (file)
@@ -2,7 +2,7 @@
    Test cases for pyclbr.py
    Nick Mathewson
 '''
-from test.test_support import run_unittest
+from test.test_support import run_unittest, import_module
 import sys
 from types import ClassType, FunctionType, MethodType, BuiltinFunctionType
 import pyclbr
@@ -13,6 +13,8 @@ ClassMethodType = type(classmethod(lambda c: None))
 
 # This next line triggers an error on old versions of pyclbr.
 
+# Silence Py3k warning
+import_module('commands', deprecated=True)
 from commands import getstatus
 
 # Here we test the python class browser code.
@@ -40,11 +42,11 @@ class PyclbrTest(TestCase):
 
 
     def assertHaskey(self, obj, key, ignore):
-        ''' succeed iff obj.has_key(key) or key in ignore. '''
+        ''' succeed iff key in obj or key in ignore. '''
         if key in ignore: return
-        if not obj.has_key(key):
-            print >>sys.stderr, "***",key
-        self.assertTrue(obj.has_key(key))
+        if key not in obj:
+            print >>sys.stderr, "***", key
+        self.assertTrue(key in obj)
 
     def assertEqualsOrIgnored(self, a, b, ignore):
         ''' succeed iff a == b or a in ignore or b in ignore '''
@@ -149,7 +151,9 @@ class PyclbrTest(TestCase):
     def test_easy(self):
         self.checkModule('pyclbr')
         self.checkModule('doctest', ignore=("DocTestCase",))
-        self.checkModule('rfc822')
+        # Silence Py3k warning
+        rfc822 = import_module('rfc822', deprecated=True)
+        self.checkModule('rfc822', rfc822)
         self.checkModule('difflib')
 
     def test_decorators(self):
index 649d5d23bfaade5a1bd975d6e145b452ea7dee61..ffd687580f20fddb7115a0f3b1c7949aebf044bc 100644 (file)
@@ -554,7 +554,7 @@ class ChardataBufferTest(unittest.TestCase):
 
         self.n=0
         parser.Parse(xml1, 0)
-        parser.buffer_size /= 2
+        parser.buffer_size //= 2
         self.assertEquals(parser.buffer_size, 1024)
         parser.Parse(xml2, 1)
         self.assertEquals(self.n, 4)
index 2fa36b759395f1102ffc4b7cab2fde05d4b69e17..e6d2e6961332460320dc0db8a9f56e9c9103a4df 100644 (file)
@@ -7,7 +7,8 @@ import time
 import unittest
 from test import test_support
 
-QUEUE_SIZE = 5
+QUEUE_SIZE = LAST = 5
+FULL = LAST+1
 
 # A thread to run a function that unclogs a blocked Queue.
 class _TriggerThread(threading.Thread):
@@ -102,21 +103,21 @@ class BaseQueueTest(unittest.TestCase, BlockingTestMixin):
             q.put(i)
             self.assertTrue(not q.empty(), "Queue should not be empty")
         self.assertTrue(not q.full(), "Queue should not be full")
-        q.put("last")
+        q.put(LAST)
         self.assertTrue(q.full(), "Queue should be full")
         try:
-            q.put("full", block=0)
+            q.put(FULL, block=0)
             self.fail("Didn't appear to block with a full queue")
         except Queue.Full:
             pass
         try:
-            q.put("full", timeout=0.01)
+            q.put(FULL, timeout=0.01)
             self.fail("Didn't appear to time-out with a full queue")
         except Queue.Full:
             pass
         # Test a blocking put
-        self.do_blocking_test(q.put, ("full",), q.get, ())
-        self.do_blocking_test(q.put, ("full", True, 10), q.get, ())
+        self.do_blocking_test(q.put, (FULL,), q.get, ())
+        self.do_blocking_test(q.put, (FULL, True, 10), q.get, ())
         # Empty it
         for i in range(QUEUE_SIZE):
             q.get()
index 14d0383b03df3b8ece79600629eb5f3a280d63fb..8d8c3c357c523c4dd139066f22c849bc498baf5a 100644 (file)
@@ -6,6 +6,7 @@ import time
 import pickle
 import warnings
 from math import log, exp, sqrt, pi, fsum, sin
+from functools import reduce
 from test import test_support
 
 class TestBasicOps(unittest.TestCase):
index 494a7c39454e85d9aeab6189c14e196b09493e4c..ef07075bfe42334b97c0f3869640a20a7a6e81ae 100644 (file)
@@ -8,7 +8,7 @@ import os
 import shutil
 import unittest
 
-from test.test_support import run_unittest
+from test.test_support import run_unittest, check_warnings
 from repr import repr as r # Don't shadow builtin repr
 from repr import Repr
 
@@ -174,7 +174,9 @@ class ReprTests(unittest.TestCase):
     def test_buffer(self):
         # XXX doesn't test buffers with no b_base or read-write buffers (see
         # bufferobject.c).  The test is fairly incomplete too.  Sigh.
-        x = buffer('foo')
+        # Silence the Py3k warning
+        with check_warnings():
+            x = buffer('foo')
         self.assertTrue(repr(x).startswith('<read-only buffer for 0x'))
 
     def test_cell(self):
index 8c2b2c6f3edc5ad3aadaffd7d77ba3bf0e2296bf..d8a0280f51e24f6eb07199a093ea5c5070335773 100644 (file)
@@ -46,9 +46,9 @@ class MessageTestCase(unittest.TestCase):
                 continue
             i = i + 1
             self.assertEqual(mn, n,
-                             "Un-expected name: %s != %s" % (`mn`, `n`))
+                             "Un-expected name: %r != %r" % (mn, n))
             self.assertEqual(ma, a,
-                             "Un-expected address: %s != %s" % (`ma`, `a`))
+                             "Un-expected address: %r != %r" % (ma, a))
             if mn == n and ma == a:
                 pass
             else:
index ed0b497a78297a7b734fad0f65b24397aad659e8..47dcc7002960dfcb361de567e88b8758cfe4af7d 100644 (file)
@@ -2,6 +2,7 @@
 
 import unittest
 from test import test_support
+import warnings
 
 import operator
 
@@ -330,7 +331,13 @@ class ListTest(unittest.TestCase):
             self.assertIs(op(x, y), True)
 
 def test_main():
-    test_support.run_unittest(VectorTest, NumberTest, MiscTest, DictTest, ListTest)
+    test_support.run_unittest(VectorTest, NumberTest, MiscTest, ListTest)
+    with warnings.catch_warnings():
+        # Silence Py3k warning
+        warnings.filterwarnings("ignore", "dict inequality comparisons "
+                                "not supported in 3.x", DeprecationWarning)
+        test_support.run_unittest(DictTest)
+
 
 if __name__ == "__main__":
     test_main()
index cf30ff9c2df7cfee8df72921eed73eda2432cc12..6ff53b3be2c6386f40971114ce474ce4b6bca5c2 100644 (file)
@@ -321,10 +321,16 @@ else:
 
         self.assertEqual(makeReturner2(a=11)()['a'], 11)
 
-        def makeAddPair((a, b)):
-            def addPair((c, d)):
-                return (a + c, b + d)
-            return addPair
+        with warnings.catch_warnings():
+            # Silence Py3k warning
+            warnings.filterwarnings("ignore", "tuple parameter unpacking "
+                                    "has been removed", SyntaxWarning)
+            exec """\
+def makeAddPair((a, b)):
+    def addPair((c, d)):
+        return (a + c, b + d)
+    return addPair
+""" in locals()
 
         self.assertEqual(makeAddPair((1, 2))((100, 200)), (101,202))
 
@@ -471,7 +477,7 @@ self.assertTrue(X.passed)
             return g
 
         d = f(2)(4)
-        self.assertTrue(d.has_key('h'))
+        self.assertTrue('h' in d)
         del d['h']
         self.assertEqual(d, {'x': 2, 'y': 7, 'w': 6})
 
index bc7465a5ba39092b3090b6bcfd6050acf4aa4109..8595368fc6c9004ed62673b33fea6ba9c5c0e2e5 100644 (file)
@@ -1218,15 +1218,16 @@ class TestOnlySetsInBinaryOps(unittest.TestCase):
         self.assertEqual(self.set != self.other, True)
 
     def test_ge_gt_le_lt(self):
-        self.assertRaises(TypeError, lambda: self.set < self.other)
-        self.assertRaises(TypeError, lambda: self.set <= self.other)
-        self.assertRaises(TypeError, lambda: self.set > self.other)
-        self.assertRaises(TypeError, lambda: self.set >= self.other)
+        with test_support.check_warnings():
+            self.assertRaises(TypeError, lambda: self.set < self.other)
+            self.assertRaises(TypeError, lambda: self.set <= self.other)
+            self.assertRaises(TypeError, lambda: self.set > self.other)
+            self.assertRaises(TypeError, lambda: self.set >= self.other)
 
-        self.assertRaises(TypeError, lambda: self.other < self.set)
-        self.assertRaises(TypeError, lambda: self.other <= self.set)
-        self.assertRaises(TypeError, lambda: self.other > self.set)
-        self.assertRaises(TypeError, lambda: self.other >= self.set)
+            self.assertRaises(TypeError, lambda: self.other < self.set)
+            self.assertRaises(TypeError, lambda: self.other <= self.set)
+            self.assertRaises(TypeError, lambda: self.other > self.set)
+            self.assertRaises(TypeError, lambda: self.other >= self.set)
 
     def test_update_operator(self):
         try:
@@ -1379,20 +1380,20 @@ class TestCopying(unittest.TestCase):
 
     def test_copy(self):
         dup = self.set.copy()
-        dup_list = list(dup); dup_list.sort()
-        set_list = list(self.set); set_list.sort()
+        dup_list = list(dup)
+        set_list = list(self.set)
         self.assertEqual(len(dup_list), len(set_list))
-        for i in range(len(dup_list)):
-            self.assertTrue(dup_list[i] is set_list[i])
+        for elt in dup_list:
+            self.assertTrue(elt in set_list)
 
     def test_deep_copy(self):
         dup = copy.deepcopy(self.set)
         ##print type(dup), repr(dup)
-        dup_list = list(dup); dup_list.sort()
-        set_list = list(self.set); set_list.sort()
+        dup_list = list(dup)
+        set_list = list(self.set)
         self.assertEqual(len(dup_list), len(set_list))
-        for i in range(len(dup_list)):
-            self.assertEqual(dup_list[i], set_list[i])
+        for elt in dup_list:
+            self.assertTrue(elt in set_list)
 
 #------------------------------------------------------------------------------
 
@@ -1552,7 +1553,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
         for cons in (set, frozenset):
             for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
                 for g in (G, I, Ig, S, L, R):
-                    self.assertEqual(sorted(cons(g(s))), sorted(g(s)))
+                    self.assertSameElements(cons(g(s)), g(s))
                 self.assertRaises(TypeError, cons , X(s))
                 self.assertRaises(TypeError, cons , N(s))
                 self.assertRaises(ZeroDivisionError, cons , E(s))
@@ -1567,7 +1568,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
                     if isinstance(expected, bool):
                         self.assertEqual(actual, expected)
                     else:
-                        self.assertEqual(sorted(actual), sorted(expected))
+                        self.assertSameElements(actual, expected)
                 self.assertRaises(TypeError, meth, X(s))
                 self.assertRaises(TypeError, meth, N(s))
                 self.assertRaises(ZeroDivisionError, meth, E(s))
@@ -1581,7 +1582,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
                     t = s.copy()
                     getattr(s, methname)(list(g(data)))
                     getattr(t, methname)(g(data))
-                    self.assertEqual(sorted(s), sorted(t))
+                    self.assertSameElements(s, t)
 
                 self.assertRaises(TypeError, getattr(set('january'), methname), X(data))
                 self.assertRaises(TypeError, getattr(set('january'), methname), N(data))
index 9c598361a68831fc7804a18234499c83a768af12..754ceb16c88da702566c74cbd7213400103fe1df 100644 (file)
@@ -510,15 +510,17 @@ class TestOnlySetsInBinaryOps(unittest.TestCase):
         self.assertEqual(self.set != self.other, True)
 
     def test_ge_gt_le_lt(self):
-        self.assertRaises(TypeError, lambda: self.set < self.other)
-        self.assertRaises(TypeError, lambda: self.set <= self.other)
-        self.assertRaises(TypeError, lambda: self.set > self.other)
-        self.assertRaises(TypeError, lambda: self.set >= self.other)
-
-        self.assertRaises(TypeError, lambda: self.other < self.set)
-        self.assertRaises(TypeError, lambda: self.other <= self.set)
-        self.assertRaises(TypeError, lambda: self.other > self.set)
-        self.assertRaises(TypeError, lambda: self.other >= self.set)
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            self.assertRaises(TypeError, lambda: self.set < self.other)
+            self.assertRaises(TypeError, lambda: self.set <= self.other)
+            self.assertRaises(TypeError, lambda: self.set > self.other)
+            self.assertRaises(TypeError, lambda: self.set >= self.other)
+
+            self.assertRaises(TypeError, lambda: self.other < self.set)
+            self.assertRaises(TypeError, lambda: self.other <= self.set)
+            self.assertRaises(TypeError, lambda: self.other > self.set)
+            self.assertRaises(TypeError, lambda: self.other >= self.set)
 
     def test_union_update_operator(self):
         try:
@@ -679,20 +681,20 @@ class TestCopying(unittest.TestCase):
 
     def test_copy(self):
         dup = self.set.copy()
-        dup_list = list(dup); dup_list.sort()
-        set_list = list(self.set); set_list.sort()
+        dup_list = list(dup)
+        set_list = list(self.set)
         self.assertEqual(len(dup_list), len(set_list))
-        for i in range(len(dup_list)):
-            self.assertTrue(dup_list[i] is set_list[i])
+        for elt in dup_list:
+            self.assertTrue(elt in set_list)
 
     def test_deep_copy(self):
         dup = copy.deepcopy(self.set)
         ##print type(dup), repr(dup)
-        dup_list = list(dup); dup_list.sort()
-        set_list = list(self.set); set_list.sort()
+        dup_list = list(dup)
+        set_list = list(self.set)
         self.assertEqual(len(dup_list), len(set_list))
-        for i in range(len(dup_list)):
-            self.assertEqual(dup_list[i], set_list[i])
+        for elt in dup_list:
+            self.assertTrue(elt in set_list)
 
 #------------------------------------------------------------------------------
 
index ffcc98da56e367c79f74d7d296be572b2427098c..3b20281a02b9b9e660889287607b35f64469d95d 100644 (file)
@@ -4,6 +4,8 @@ import shelve
 import glob
 from test import test_support
 
+test_support.import_module('anydbm', deprecated=True)
+
 class TestCase(unittest.TestCase):
 
     fn = "shelftemp" + os.extsep + "db"
index 56596c8751a06770f24758597f14aa997d156ee0..85d898abade0615c2d5097e3daca51fdb70bf792 100644 (file)
@@ -258,7 +258,7 @@ class ImportSideEffectTests(unittest.TestCase):
         site.abs__file__()
         for module in (sys, os, __builtin__):
             try:
-                self.assertTrue(os.path.isabs(module.__file__), `module`)
+                self.assertTrue(os.path.isabs(module.__file__), repr(module))
             except AttributeError:
                 continue
         # We could try everything in sys.modules; however, when regrtest.py
@@ -310,7 +310,7 @@ class ImportSideEffectTests(unittest.TestCase):
 
     def test_sitecustomize_executed(self):
         # If sitecustomize is available, it should have been imported.
-        if not sys.modules.has_key("sitecustomize"):
+        if "sitecustomize" not in sys.modules:
             try:
                 import sitecustomize
             except ImportError:
index 08de8e3ad708c83ccb6785e9ed7f74ea46ee9729..6aa3d4a5e7787d74a75c2ed2322db3a0d21924b6 100644 (file)
@@ -115,7 +115,9 @@ class SliceTest(unittest.TestCase):
                 tmp.append((i, j, k))
 
         x = X()
-        x[1:2] = 42
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            x[1:2] = 42
         self.assertEquals(tmp, [(1, 2, 42)])
 
     def test_pickle(self):
index faa06c5a8d1b8ff450404c50e7b23a5aa65fbac9..b4f37eb2a64ee4ca602178c846549fcea5c65da3 100644 (file)
@@ -123,7 +123,7 @@ class ThreadableTest:
         self.server_ready.wait()
         self.client_ready.set()
         self.clientSetUp()
-        if not callable(test_func):
+        if not hasattr(test_func, '__call__'):
             raise TypeError, "test_func must be a callable function"
         try:
             test_func()
@@ -282,7 +282,7 @@ class GeneralModuleTests(unittest.TestCase):
                 orig = sys.getrefcount(__name__)
                 socket.getnameinfo(__name__,0)
             except TypeError:
-                if sys.getrefcount(__name__) <> orig:
+                if sys.getrefcount(__name__) != orig:
                     self.fail("socket.getnameinfo loses a reference")
 
     def testInterpreterCrash(self):
@@ -1234,7 +1234,9 @@ class BufferIOTest(SocketConnectedTest):
         self.assertEqual(msg, MSG)
 
     def _testRecvInto(self):
-        buf = buffer(MSG)
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            buf = buffer(MSG)
         self.serv_conn.send(buf)
 
     def testRecvFromInto(self):
@@ -1245,7 +1247,9 @@ class BufferIOTest(SocketConnectedTest):
         self.assertEqual(msg, MSG)
 
     def _testRecvFromInto(self):
-        buf = buffer(MSG)
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            buf = buffer(MSG)
         self.serv_conn.send(buf)
 
 
index a61fb96b794f7ef249faf29d08748778e05f0dcb..a8e239a4eb962759c3bcdc470425d6bc7bf8ade4 100644 (file)
@@ -2,6 +2,7 @@ from test import test_support
 import random
 import sys
 import unittest
+import warnings
 
 verbose = test_support.verbose
 nerrors = 0
@@ -185,7 +186,7 @@ class TestDecorateSortUndecorate(unittest.TestCase):
     def test_stability(self):
         data = [(random.randrange(100), i) for i in xrange(200)]
         copy = data[:]
-        data.sort(key=lambda (x,y): x)  # sort on the random first field
+        data.sort(key=lambda x: x[0])   # sort on the random first field
         copy.sort()                     # sort using both fields
         self.assertEqual(data, copy)    # should get the same result
 
@@ -207,7 +208,7 @@ class TestDecorateSortUndecorate(unittest.TestCase):
         # Verify that the wrapper has been removed
         data = range(-2,2)
         dup = data[:]
-        self.assertRaises(ZeroDivisionError, data.sort, None, lambda x: 1/x)
+        self.assertRaises(ZeroDivisionError, data.sort, None, lambda x: 1 // x)
         self.assertEqual(data, dup)
 
     def test_key_with_mutation(self):
@@ -274,17 +275,21 @@ def test_main(verbose=None):
         TestBugs,
     )
 
-    test_support.run_unittest(*test_classes)
-
-    # verify reference counting
-    if verbose and hasattr(sys, "gettotalrefcount"):
-        import gc
-        counts = [None] * 5
-        for i in xrange(len(counts)):
-            test_support.run_unittest(*test_classes)
-            gc.collect()
-            counts[i] = sys.gettotalrefcount()
-        print counts
+    with warnings.catch_warnings():
+        # Silence Py3k warning
+        warnings.filterwarnings("ignore", "the cmp argument is not supported",
+                                DeprecationWarning)
+        test_support.run_unittest(*test_classes)
+
+        # verify reference counting
+        if verbose and hasattr(sys, "gettotalrefcount"):
+            import gc
+            counts = [None] * 5
+            for i in xrange(len(counts)):
+                test_support.run_unittest(*test_classes)
+                gc.collect()
+                counts[i] = sys.gettotalrefcount()
+            print counts
 
 if __name__ == "__main__":
     test_main(verbose=True)
index 167408cd3dbf68daa1771e8a85868bb1504d431e..f3bfd3e6812e5de113376a3e5fbd6878a22087a2 100644 (file)
@@ -4,14 +4,21 @@ from test.test_support import run_unittest, import_module
 # Skip test if _sqlite3 module was not built.
 import_module('_sqlite3')
 
+import warnings
 from sqlite3.test import (dbapi, types, userfunctions, py25tests,
                                 factory, transactions, hooks, regression,
                                 dump)
 
 def test_main():
-    run_unittest(dbapi.suite(), types.suite(), userfunctions.suite(),
-                 py25tests.suite(), factory.suite(), transactions.suite(),
-                 hooks.suite(), regression.suite(), dump.suite())
+    with warnings.catch_warnings():
+        # Silence Py3k warnings
+        warnings.filterwarnings("ignore", "buffer.. not supported",
+                                DeprecationWarning)
+        warnings.filterwarnings("ignore", "classic int division",
+                                DeprecationWarning)
+        run_unittest(dbapi.suite(), types.suite(), userfunctions.suite(),
+                     py25tests.suite(), factory.suite(), transactions.suite(),
+                     hooks.suite(), regression.suite(), dump.suite())
 
 if __name__ == "__main__":
     test_main()
index 5aca13528a35f62a1b96ac0dcd878e56fc615f1a..4ba2e2a4881ee84cfbde0730ebea522e8aafdfcc 100644 (file)
@@ -808,7 +808,7 @@ else:
                     if test_support.verbose:
                         sys.stdout.write(pprint.pformat(cert) + '\n')
                         sys.stdout.write("Connection cipher is " + str(cipher) + '.\n')
-                    if not cert.has_key('subject'):
+                    if 'subject' not in cert:
                         raise test_support.TestFailed(
                             "No subject field in certificate: %s." %
                             pprint.pformat(cert))
@@ -970,7 +970,9 @@ else:
                 # now fetch the same data from the HTTPS server
                 url = 'https://127.0.0.1:%d/%s' % (
                     server.port, os.path.split(CERTFILE)[1])
-                f = urllib.urlopen(url)
+                # Silence Py3k warning
+                with test_support.check_warnings():
+                    f = urllib.urlopen(url)
                 dlen = f.info().getheader("content-length")
                 if dlen and (int(dlen) > 0):
                     d2 = f.read(int(dlen))
index 556a5764eb82fa44ea866acf402a93676c5546ea..76a29cde5f4cc09c48bf9285152318334475affb 100644 (file)
@@ -471,7 +471,7 @@ class StructTest(unittest.TestCase):
     def test_bool(self):
         for prefix in tuple("<>!=")+('',):
             false = (), [], [], '', 0
-            true = [1], 'test', 5, -1, 0xffffffffL+1, 0xffffffff/2
+            true = [1], 'test', 5, -1, 0xffffffffL+1, 0xffffffff//2
 
             falseFormat = prefix + '?' * len(false)
             packedFalse = struct.pack(falseFormat, *false)
@@ -507,7 +507,11 @@ class StructTest(unittest.TestCase):
 
 
 def test_main():
-    run_unittest(StructTest)
+    with warnings.catch_warnings():
+        # Silence Py3k warnings
+        warnings.filterwarnings("ignore", "buffer.. not supported",
+                                DeprecationWarning)
+        run_unittest(StructTest)
 
 if __name__ == '__main__':
     test_main()
index 2118c62de875e335958a0681c6d74a7a305bf7ec..c6730cd83ed8bf51ec14704734401fd18845162e 100644 (file)
@@ -552,7 +552,11 @@ class SyntaxTestCase(unittest.TestCase):
 def test_main():
     test_support.run_unittest(SyntaxTestCase)
     from test import test_syntax
-    test_support.run_doctest(test_syntax, verbosity=True)
+    with warnings.catch_warnings():
+        # Silence Py3k warning
+        warnings.filterwarnings("ignore", "backquote not supported",
+                                SyntaxWarning)
+        test_support.run_doctest(test_syntax, verbosity=True)
 
 if __name__ == "__main__":
     test_main()
index 6768775c999007cca9fb36150212fa37062fad09..04e66071931851118bdeaa56ac7e08669154fded 100644 (file)
@@ -68,7 +68,9 @@ class SysModuleTest(unittest.TestCase):
     # Python/pythonrun.c::PyErr_PrintEx() is tricky.
 
     def test_exc_clear(self):
-        self.assertRaises(TypeError, sys.exc_clear, 42)
+        # Silence Py3k warning
+        with test.test_support.check_warnings():
+            self.assertRaises(TypeError, sys.exc_clear, 42)
 
         # Verify that exc_info is present and matches exc, then clear it, and
         # check that it worked.
@@ -78,7 +80,9 @@ class SysModuleTest(unittest.TestCase):
             self.assertTrue(value is exc)
             self.assertTrue(traceback is not None)
 
-            sys.exc_clear()
+            # Silence Py3k warning
+            with test.test_support.check_warnings():
+                sys.exc_clear()
 
             typ, value, traceback = sys.exc_info()
             self.assertTrue(typ is None)
@@ -484,7 +488,9 @@ class SizeofTest(unittest.TestCase):
         # bool
         check(True, size(h + 'l'))
         # buffer
-        check(buffer(''), size(h + '2P2Pil'))
+        # Silence Py3k warning
+        with test.test_support.check_warnings():
+            check(buffer(''), size(h + '2P2Pil'))
         # builtin_function_or_method
         check(len, size(h + '3P'))
         # bytearray
index bc0ae5899dbba9258fee8e0423584c0e28584b7e..8e48a53bb31b697906f3c89fabe4b6aeed76da4b 100644 (file)
@@ -712,7 +712,9 @@ class WriteTest(WriteTestBase):
                 return os.path.isfile(name)
 
             tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
-            tar.add(tempdir, arcname="empty_dir", exclude=exclude)
+            # Silence Py3k warning
+            with test_support.check_warnings():
+                tar.add(tempdir, arcname="empty_dir", exclude=exclude)
             tar.close()
 
             tar = tarfile.open(tmpname, "r")
index e1096bdbae2f553181a9b64d5a40414f699f9483..b28705f3a385ec466b21c7b1bd6f9f838321ac0a 100644 (file)
@@ -14,7 +14,7 @@ process_pid = os.getpid()
 signalled_all=thread.allocate_lock()
 
 
-def registerSignals((for_usr1, for_usr2, for_alrm)):
+def registerSignals(for_usr1, for_usr2, for_alrm):
     usr1 = signal.signal(signal.SIGUSR1, for_usr1)
     usr2 = signal.signal(signal.SIGUSR2, for_usr2)
     alrm = signal.signal(signal.SIGALRM, for_alrm)
@@ -74,11 +74,11 @@ def test_main():
                           signal.SIGUSR2 : {'tripped': 0, 'tripped_by': 0 },
                           signal.SIGALRM : {'tripped': 0, 'tripped_by': 0 } }
 
-    oldsigs = registerSignals((handle_signals, handle_signals, handle_signals))
+    oldsigs = registerSignals(handle_signals, handle_signals, handle_signals)
     try:
         run_unittest(ThreadSignals)
     finally:
-        registerSignals(oldsigs)
+        registerSignals(*oldsigs)
 
 if __name__ == '__main__':
     test_main()
index f69af8d40af3bd6fd7f1c30b278001470f65bbf5..df8c56f7582291ce278ed6a45a7e29f03aabb838 100644 (file)
@@ -401,7 +401,7 @@ class RaisingTraceFuncTestCase(unittest.TestCase):
         we're testing, so that the 'exception' trace event fires."""
         if self.raiseOnEvent == 'exception':
             x = 0
-            y = 1/x
+            y = 1 // x
         else:
             return 1
 
index b29869ac8f8a24f4c85f46f0007995055294241f..61195a5d035b658a685885b79848cdeba0f35b60 100644 (file)
@@ -4,6 +4,7 @@ from _testcapi import traceback_print
 from StringIO import StringIO
 import sys
 import unittest
+from imp import reload
 from test.test_support import run_unittest, is_jython, Error
 
 import traceback
@@ -148,7 +149,7 @@ def test():
     def test_format_exception_only_bad__str__(self):
         class X(Exception):
             def __str__(self):
-                1/0
+                1 // 0
         err = traceback.format_exception_only(X, X())
         self.assertEqual(len(err), 1)
         str_value = '<unprintable %s object>' % X.__name__
index 909cda51837cad3bbf574a62593bb8211bb6c47d..65909372e68cb1404d8fb2c1a16f774e899ba975 100644 (file)
@@ -1,5 +1,8 @@
 import unittest
 from test import test_support
+
+# Silence Py3k warning
+test_support.import_module('compiler', deprecated=True)
 from compiler import transformer, ast
 from compiler import compile
 
index 18ab9cc84b8deac47cd6bb3d941c4cbcbe0a38c4..d5d25b0b300471cbf2df95e19b67df78c76d2b11 100644 (file)
@@ -4,6 +4,7 @@ from test.test_support import run_unittest, have_unicode, run_with_locale
 import unittest
 import sys
 import locale
+import warnings
 
 class TypesTests(unittest.TestCase):
 
@@ -710,7 +711,13 @@ class TypesTests(unittest.TestCase):
             self.assertRaises(ValueError, format, 0, ',' + code)
 
 def test_main():
-    run_unittest(TypesTests)
+    with warnings.catch_warnings():
+        # Silence Py3k warnings
+        warnings.filterwarnings("ignore", "buffer.. not supported",
+                                DeprecationWarning)
+        warnings.filterwarnings("ignore", "classic long division",
+                                DeprecationWarning)
+        run_unittest(TypesTests)
 
 if __name__ == '__main__':
     test_main()
index ca66c19f65f3af82e8c768aca32d31b7935fc22f..f3508fcfac705ad6a127475916e51dc3004a5980 100644 (file)
@@ -1,4 +1,4 @@
-from test.test_support import run_unittest, have_unicode
+from test.test_support import run_unittest, check_warnings
 import unittest
 import sys
 
@@ -33,7 +33,9 @@ class TestImplementationComparisons(unittest.TestCase):
         self.assertTrue(g_cell != h_cell)
 
 def test_main():
-    run_unittest(TestImplementationComparisons)
+    # Silence Py3k warnings
+    with check_warnings():
+        run_unittest(TestImplementationComparisons)
 
 if __name__ == '__main__':
     test_main()
index db51f77d7bff8402558b5785cba4cb8822b2f47b..9b24c8c1532cb630de1a2dd533a95c5e7069af15 100644 (file)
@@ -3056,7 +3056,7 @@ class Test_Assertions(TestCase):
         try:
             self.assertRaises(KeyError, lambda: None)
         except self.failureException as e:
-            self.assert_("KeyError not raised" in e, str(e))
+            self.assert_("KeyError not raised" in e.args, str(e))
         else:
             self.fail("assertRaises() didn't fail")
         try:
@@ -3073,7 +3073,7 @@ class Test_Assertions(TestCase):
             with self.assertRaises(KeyError):
                 pass
         except self.failureException as e:
-            self.assert_("KeyError not raised" in e, str(e))
+            self.assert_("KeyError not raised" in e.args, str(e))
         else:
             self.fail("assertRaises() didn't fail")
         try:
@@ -3591,6 +3591,9 @@ class TestDiscovery(TestCase):
             def __eq__(self, other):
                 return self.path == other.path
 
+            # Silence Py3k warning
+            __hash__ = None
+
         loader._get_module_from_name = lambda name: Module(name)
         def loadTestsFromModule(module, use_load_tests):
             if use_load_tests:
index 63c6fe8240fe839425c234beada55789b9b478bd..c6d6e8bb8661567dbf1cf3ca8fbaec1ff71e82d4 100644 (file)
@@ -80,7 +80,9 @@ class TestGenericUnivNewlines(unittest.TestCase):
 
     def test_execfile(self):
         namespace = {}
-        execfile(test_support.TESTFN, namespace)
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            execfile(test_support.TESTFN, namespace)
         func = namespace['line3']
         self.assertEqual(func.func_code.co_firstlineno, 3)
         self.assertEqual(namespace['line4'], FATX)
index c74b101713c9d90990450f3b7a5b53759c141d3b..10c8d90478f8e12561d0d2e06c8581cab7023837 100644 (file)
@@ -6,6 +6,7 @@ import unittest
 from test import test_support
 import os
 import mimetools
+import random
 import tempfile
 import StringIO
 
@@ -101,7 +102,7 @@ class ProxyTests(unittest.TestCase):
         # Records changes to env vars
         self.env = test_support.EnvironmentVarGuard()
         # Delete all proxy related env vars
-        for k, v in os.environ.iteritems():
+        for k in os.environ.keys():
             if 'proxy' in k.lower():
                 self.env.unset(k)
 
@@ -409,6 +410,13 @@ class QuotingTests(unittest.TestCase):
         self.assertEqual(urllib.quote_plus('alpha+beta gamma', '+'),
                          'alpha+beta+gamma')
 
+    def test_quote_leak(self):
+        # bug 5596 - highlight the refleak in the internal _safemaps cache
+        safe = ''.join(chr(random.randrange(128)) for i in '123456')
+        text = 'abcdefghijklmnopqrstuvwxyz'
+        result = urllib.quote(text, safe=safe)
+        self.assertEqual(result, text)
+
 class UnquotingTests(unittest.TestCase):
     """Tests for unquote() and unquote_plus()
 
index 1375e112b8ed3982d7deb678c1c508eec4850df3..81f54aee12a888702ea47480c1c5844db30c03b2 100644 (file)
@@ -1,6 +1,5 @@
 #!/usr/bin/env python
 
-import mimetools
 import threading
 import urlparse
 import urllib2
@@ -8,6 +7,7 @@ import BaseHTTPServer
 import unittest
 import hashlib
 from test import test_support
+mimetools = test_support.import_module('mimetools', deprecated=True)
 
 # Loopback http server infrastructure
 
@@ -154,13 +154,13 @@ class DigestAuthHandler:
         if len(self._users) == 0:
             return True
 
-        if not request_handler.headers.has_key('Proxy-Authorization'):
+        if 'Proxy-Authorization' not in request_handler.headers:
             return self._return_auth_challenge(request_handler)
         else:
             auth_dict = self._create_auth_dict(
                 request_handler.headers['Proxy-Authorization']
                 )
-            if self._users.has_key(auth_dict["username"]):
+            if auth_dict["username"] in self._users:
                 password = self._users[ auth_dict["username"] ]
             else:
                 return self._return_auth_challenge(request_handler)
index 7ab2aa2477ccfe968c6dcb8e5a69c032e0e63251..9d312281ae0e63712a73bf1177bf72ddf379088b 100644 (file)
@@ -7,7 +7,7 @@ import socket
 import urllib
 import sys
 import os
-import mimetools
+mimetools = test_support.import_module("mimetools", deprecated=True)
 
 
 def _open_with_retry(func, host, *args, **kwargs):
index c86a773135b26a8a6c030f15ce45046ba070206b..cf631fffc659e472d49ad7718b53cc3308ac91eb 100644 (file)
@@ -45,7 +45,9 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol):
         # Test __repr__
         self.assertEqual(str(u0), str(d0))
         self.assertEqual(repr(u1), repr(d1))
-        self.assertEqual(`u2`, `d2`)
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            self.assertEqual(eval('`u2`'), eval('`d2`'))
 
         # Test __cmp__ and __len__
         all = [d0, d1, d2, u, u0, u1, u2, uu, uu0, uu1, uu2]
@@ -95,12 +97,14 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol):
 
         # Test has_key and "in".
         for i in u2.keys():
-            self.assertTrue(u2.has_key(i))
             self.assertTrue(i in u2)
-            self.assertEqual(u1.has_key(i), d1.has_key(i))
             self.assertEqual(i in u1, i in d1)
-            self.assertEqual(u0.has_key(i), d0.has_key(i))
             self.assertEqual(i in u0, i in d0)
+            # Silence Py3k warning
+            with test_support.check_warnings():
+                self.assertTrue(u2.has_key(i))
+                self.assertEqual(u1.has_key(i), d1.has_key(i))
+                self.assertEqual(u0.has_key(i), d0.has_key(i))
 
         # Test update
         t = UserDict.UserDict()
index ed3e5593733aafdbe0b511723a4b5a24b693b1b0..09fa188b19b611c3f28c8900ac830afd0ff6b462 100644 (file)
@@ -2,6 +2,7 @@
 
 from UserList import UserList
 from test import test_support, list_tests
+import warnings
 
 class UserListTest(list_tests.CommonTest):
     type2test = UserList
@@ -53,7 +54,11 @@ class UserListTest(list_tests.CommonTest):
         self.assertEqual(iter(T((1,2))).next(), "0!!!")
 
 def test_main():
-    test_support.run_unittest(UserListTest)
+    with warnings.catch_warnings():
+        # Silence Py3k warnings
+        warnings.filterwarnings("ignore", ".+slice__ has been removed",
+                                DeprecationWarning)
+        test_support.run_unittest(UserListTest)
 
 if __name__ == "__main__":
     test_main()
index b99581d6de5bbb792d90cf1a88d9a27c889f165d..8ec9ca3f3ed8155397b1392fec3542daee5fcf4c 100755 (executable)
@@ -136,8 +136,11 @@ class MutableStringTest(UserStringTest):
 
 def test_main():
     with warnings.catch_warnings():
+        # Silence Py3k warnings
         warnings.filterwarnings("ignore", ".*MutableString",
                                 DeprecationWarning)
+        warnings.filterwarnings("ignore", ".+slice__ has been removed",
+                                DeprecationWarning)
         test_support.run_unittest(UserStringTest, MutableStringTest)
 
 if __name__ == "__main__":
index 2106d8cd9bd50796234b7820fd8066712d60dd9f..f3eb43b2e298888053e3d60187ebfcbbd40ba228 100644 (file)
@@ -54,10 +54,10 @@ class ReferencesTestCase(TestBase):
         # Live reference:
         o = C()
         wr = weakref.ref(o)
-        `wr`
+        repr(wr)
         # Dead reference:
         del o
-        `wr`
+        repr(wr)
 
     def test_basic_callback(self):
         self.check_basic_callback(C)
@@ -169,7 +169,9 @@ class ReferencesTestCase(TestBase):
         p.append(12)
         self.assertEqual(len(L), 1)
         self.assertTrue(p, "proxy for non-empty UserList should be true")
-        p[:] = [2, 3]
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            p[:] = [2, 3]
         self.assertEqual(len(L), 2)
         self.assertEqual(len(p), 2)
         self.assertTrue(3 in p,
@@ -183,10 +185,12 @@ class ReferencesTestCase(TestBase):
         ## self.assertEqual(repr(L2), repr(p2))
         L3 = UserList.UserList(range(10))
         p3 = weakref.proxy(L3)
-        self.assertEqual(L3[:], p3[:])
-        self.assertEqual(L3[5:], p3[5:])
-        self.assertEqual(L3[:5], p3[:5])
-        self.assertEqual(L3[2:5], p3[2:5])
+        # Silence Py3k warning
+        with test_support.check_warnings():
+            self.assertEqual(L3[:], p3[:])
+            self.assertEqual(L3[5:], p3[5:])
+            self.assertEqual(L3[:5], p3[:5])
+            self.assertEqual(L3[2:5], p3[2:5])
 
     def test_proxy_unicode(self):
         # See bug 5037
@@ -832,7 +836,7 @@ class MappingTestCase(TestBase):
     def test_weak_keys(self):
         #
         #  This exercises d.copy(), d.items(), d[] = v, d[], del d[],
-        #  len(d), d.has_key().
+        #  len(d), in d.
         #
         dict, objects = self.make_weak_keyed_dict()
         for o in objects:
@@ -854,8 +858,8 @@ class MappingTestCase(TestBase):
                      "deleting the keys did not clear the dictionary")
         o = Object(42)
         dict[o] = "What is the meaning of the universe?"
-        self.assertTrue(dict.has_key(o))
-        self.assertTrue(not dict.has_key(34))
+        self.assertTrue(o in dict)
+        self.assertTrue(34 not in dict)
 
     def test_weak_keyed_iters(self):
         dict, objects = self.make_weak_keyed_dict()
@@ -867,7 +871,7 @@ class MappingTestCase(TestBase):
         objects2 = list(objects)
         for wr in refs:
             ob = wr()
-            self.assertTrue(dict.has_key(ob))
+            self.assertTrue(ob in dict)
             self.assertTrue(ob in dict)
             self.assertEqual(ob.arg, dict[ob])
             objects2.remove(ob)
@@ -878,7 +882,6 @@ class MappingTestCase(TestBase):
         self.assertEqual(len(list(dict.iterkeyrefs())), len(objects))
         for wr in dict.iterkeyrefs():
             ob = wr()
-            self.assertTrue(dict.has_key(ob))
             self.assertTrue(ob in dict)
             self.assertEqual(ob.arg, dict[ob])
             objects2.remove(ob)
@@ -993,13 +996,13 @@ class MappingTestCase(TestBase):
         weakdict = klass()
         o = weakdict.setdefault(key, value1)
         self.assertTrue(o is value1)
-        self.assertTrue(weakdict.has_key(key))
+        self.assertTrue(key in weakdict)
         self.assertTrue(weakdict.get(key) is value1)
         self.assertTrue(weakdict[key] is value1)
 
         o = weakdict.setdefault(key, value2)
         self.assertTrue(o is value1)
-        self.assertTrue(weakdict.has_key(key))
+        self.assertTrue(key in weakdict)
         self.assertTrue(weakdict.get(key) is value1)
         self.assertTrue(weakdict[key] is value1)
 
@@ -1013,20 +1016,20 @@ class MappingTestCase(TestBase):
 
     def check_update(self, klass, dict):
         #
-        #  This exercises d.update(), len(d), d.keys(), d.has_key(),
+        #  This exercises d.update(), len(d), d.keys(), in d,
         #  d.get(), d[].
         #
         weakdict = klass()
         weakdict.update(dict)
         self.assertTrue(len(weakdict) == len(dict))
         for k in weakdict.keys():
-            self.assertTrue(dict.has_key(k),
+            self.assertTrue(k in dict,
                          "mysterious new key appeared in weak dict")
             v = dict.get(k)
             self.assertTrue(v is weakdict[k])
             self.assertTrue(v is weakdict.get(k))
         for k in dict.keys():
-            self.assertTrue(weakdict.has_key(k),
+            self.assertTrue(k in weakdict,
                          "original key disappeared in weak dict")
             v = dict[k]
             self.assertTrue(v is weakdict[k])
index 1ce816f866fe2d9a21305c7fbc55e25bd15e0be0..427e323f4943e638d116f16399bb7980ea39c77d 100644 (file)
@@ -7,11 +7,13 @@ import os
 import test.test_support
 import unittest
 import whichdb
-import anydbm
 import glob
 
 _fname = test.test_support.TESTFN
 
+# Silence Py3k warning
+anydbm = test.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
@@ -37,8 +39,9 @@ for name in anydbm._names:
     # we define a new test method for each
     # candidate database module.
     try:
-        mod = __import__(name)
-    except ImportError:
+        # Silence Py3k warning
+        mod = test.test_support.import_module(name, deprecated=True)
+    except unittest.SkipTest:
         continue
 
     def test_whichdb_name(self, name=name, mod=mod):
index b572b912d0b963cb4f998e341990691a7119c39e..3e33e3156f94bf581b9f0422474b7acba94c8f2b 100644 (file)
@@ -520,7 +520,7 @@ class ExceptionalTestCase(unittest.TestCase, ContextmanagerAssertionMixin):
         self.assertRaises(AssertionError, falseAsBool)
 
         def failAsBool():
-            with cm(lambda: 1//0):
+            with cm(lambda: 1 // 0):
                 self.fail("Should NOT see this")
         self.assertRaises(ZeroDivisionError, failAsBool)
 
@@ -628,7 +628,7 @@ class ExitSwallowsExceptionTestCase(unittest.TestCase):
             def __exit__(self, t, v, tb): return True
         try:
             with AfricanSwallow():
-                1/0
+                1 // 0
         except ZeroDivisionError:
             self.fail("ZeroDivisionError should have been swallowed")
 
@@ -638,7 +638,7 @@ class ExitSwallowsExceptionTestCase(unittest.TestCase):
             def __exit__(self, t, v, tb): return False
         try:
             with EuropeanSwallow():
-                1/0
+                1 // 0
         except ZeroDivisionError:
             pass
         else:
index a3bc99fcf15d762c59da2f94df72da92262d3b74..c31ef189918e02583321c22805b741e714f3c4f4 100755 (executable)
@@ -432,10 +432,10 @@ class HandlerTests(TestCase):
         env = handler.environ
         from os import environ
         for k,v in environ.items():
-            if not empty.has_key(k):
+            if k not in empty:
                 self.assertEqual(env[k],v)
         for k,v in empty.items():
-            self.assertTrue(env.has_key(k))
+            self.assertTrue(k in env)
 
     def testEnviron(self):
         h = TestHandler(X="Y")
@@ -448,7 +448,7 @@ class HandlerTests(TestCase):
         h = BaseCGIHandler(None,None,None,{})
         h.setup_environ()
         for key in 'wsgi.url_scheme', 'wsgi.input', 'wsgi.errors':
-            self.assertTrue(h.environ.has_key(key))
+            self.assertTrue(key in h.environ)
 
     def testScheme(self):
         h=TestHandler(HTTPS="on"); h.setup_environ()
index 0780bc95f3d14281a7cb2f1dd8e804eb8788233d..68b883a0e50f31403353b35220bdf3493dd7b13b 100644 (file)
@@ -15,13 +15,10 @@ testdoc = """\
 
 nsdoc = "<foo xmlns='URI' attr='val'/>"
 
-import warnings
-warnings.filterwarnings("ignore", ".* xmllib .* obsolete.*",
-                        DeprecationWarning, r'xmllib$')
-
 from test import test_support
 import unittest
-import xmllib
+# Silence Py3k warning
+xmllib = test_support.import_module('xmllib', deprecated=True)
 
 class XMLParserTestCase(unittest.TestCase):
 
index 3ed7ef7c465cdca5fd5b2969d9abd5b6461945fe..f41c97adce32febf6e34ead819eb73276bbb3ea1 100644 (file)
@@ -25,7 +25,7 @@ from test import test_support
 mod_path = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                         "pickletester.py"))
 pickletester = types.ModuleType("test.pickletester")
-execfile(mod_path, pickletester.__dict__, pickletester.__dict__)
+exec compile(open(mod_path).read(), mod_path, 'exec') in pickletester.__dict__
 AbstractPickleTests = pickletester.AbstractPickleTests
 if pickletester.__name__ in sys.modules:
     raise RuntimeError("Did not expect to find test.pickletester loaded")
index 1b641388843b5768f9fc351d6d625c843d39a149..5bb66cb0eca1d31df8237d1fb2385b6a39825d1c 100644 (file)
@@ -168,8 +168,11 @@ class ZipSupportTests(ImportHooksBaseTestCase):
                 test_zipped_doctest.test_testfile,
                 test_zipped_doctest.test_unittest_reportflags,
             ]
-            for obj in known_good_tests:
-                _run_object_doctest(obj, test_zipped_doctest)
+            # Silence Py3k warning
+            # Needed for test_DocTestParser and test_debug
+            with test.test_support.check_warnings():
+                for obj in known_good_tests:
+                    _run_object_doctest(obj, test_zipped_doctest)
 
     def test_doctest_main_issue4197(self):
         test_src = textwrap.dedent("""\