]> granicus.if.org Git - python/commitdiff
Merged revisions 79539 via svnmerge from
authorEzio Melotti <ezio.melotti@gmail.com>
Mon, 2 Aug 2010 23:34:49 +0000 (23:34 +0000)
committerEzio Melotti <ezio.melotti@gmail.com>
Mon, 2 Aug 2010 23:34:49 +0000 (23:34 +0000)
svn+ssh://pythondev@svn.python.org/python/trunk

........
  r79539 | florent.xicluna | 2010-04-01 01:01:03 +0300 (Thu, 01 Apr 2010) | 2 lines

  Replace catch_warnings with check_warnings when it makes sense.  Use assertRaises context manager to simplify some tests.
........

20 files changed:
Lib/test/test_coercion.py
Lib/test/test_commands.py
Lib/test/test_complex.py
Lib/test/test_contextlib.py
Lib/test/test_cookie.py
Lib/test/test_ctypes.py
Lib/test/test_descr.py
Lib/test/test_doctest.py
Lib/test/test_exceptions.py
Lib/test/test_global.py
Lib/test/test_int_literal.py
Lib/test/test_io.py
Lib/test/test_macostools.py
Lib/test/test_pep352.py
Lib/test/test_re.py
Lib/test/test_sundry.py
Lib/test/test_symtable.py
Lib/test/test_urllibnet.py
Lib/test/test_warnings.py
Lib/test/test_zipimport_support.py

index a36c04115f1c18e4b7d55e77f2a736dfac44e025..23816b53c4c6141085848666621ce5a21fedbe67 100644 (file)
@@ -1,7 +1,6 @@
 import copy
-import warnings
 import unittest
-from test.test_support import run_unittest, TestFailed
+from test.test_support import run_unittest, TestFailed, check_warnings
 
 # Fake a number that implements numeric methods through __coerce__
 class CoerceNumber:
@@ -223,12 +222,6 @@ def process_infix_results():
             infix_results[key] = res
 
 
-with warnings.catch_warnings():
-    warnings.filterwarnings("ignore", "classic int division",
-                            DeprecationWarning)
-    process_infix_results()
-# now infix_results has two lists of results for every pairing.
-
 prefix_binops = [ 'divmod' ]
 prefix_results = [
     [(1,0), (1L,0L), (0.0,2.0), ((1+0j),0j), TE, TE, TE, TE, (1,0)],
@@ -339,11 +332,13 @@ class CoercionTest(unittest.TestCase):
             raise exc
 
 def test_main():
-    with warnings.catch_warnings():
-        warnings.filterwarnings("ignore", "complex divmod.., // and % "
-                                "are deprecated", DeprecationWarning)
-        warnings.filterwarnings("ignore", "classic (int|long) division",
-                                DeprecationWarning)
+    with check_warnings(("complex divmod.., // and % are deprecated",
+                         DeprecationWarning),
+                        ("classic (int|long) division", DeprecationWarning),
+                        quiet=True):
+        process_infix_results()
+        # now infix_results has two lists of results for every pairing.
+
         run_unittest(CoercionTest)
 
 if __name__ == "__main__":
index dc1a598b4185e810a93af00401361b68f52b4b83..5cb6e86b29cc3fcf7cf709e6d332600658c41ccb 100644 (file)
@@ -4,13 +4,11 @@
 '''
 import unittest
 import os, tempfile, re
-import warnings
 
-warnings.filterwarnings('ignore', r".*commands.getstatus.. is deprecated",
-                        DeprecationWarning)
+from test.test_support import run_unittest, reap_children, import_module, \
+                              check_warnings
 
 from test.test_support import TestSkipped, run_unittest, reap_children, import_module
-
 # Silence Py3k warning
 import_module('commands', deprecated=True)
 from commands import *
@@ -60,7 +58,11 @@ class CommandTests(unittest.TestCase):
                   /\.          # and end with the name of the file.
                '''
 
-        self.assert_(re.match(pat, getstatus("/."), re.VERBOSE))
+        with check_warnings((".*commands.getstatus.. is deprecated",
+                             DeprecationWarning),
+                            ("in 3.x, mkarg has been removed",
+                             DeprecationWarning),):
+            self.assertTrue(re.match(pat, getstatus("/."), re.VERBOSE))
 
 
 def test_main():
index 000dd9d141097105e1c72802b80caa5a0a4cccb6..6342501d305b412c5d438dd89f37f5673e1e097e 100644 (file)
@@ -1,13 +1,6 @@
-import unittest, os
+import unittest
 from test import test_support
 
-import warnings
-warnings.filterwarnings(
-    "ignore",
-    category=DeprecationWarning,
-    message=".*complex divmod.*are deprecated"
-)
-
 from random import random
 from math import atan2
 
@@ -371,10 +364,7 @@ class ComplexTest(unittest.TestCase):
         finally:
             if (fo is not None) and (not fo.closed):
                 fo.close()
-            try:
-                os.remove(test_support.TESTFN)
-            except (OSError, IOError):
-                pass
+            test_support.unlink(test_support.TESTFN)
 
     def test_getnewargs(self):
         self.assertEqual((1+2j).__getnewargs__(), (1.0, 2.0))
@@ -392,7 +382,9 @@ class ComplexTest(unittest.TestCase):
             self.assertEquals(atan2(z2.imag, -1.), atan2(-0., -1.))
 
 def test_main():
-    test_support.run_unittest(ComplexTest)
+    with test_support.check_warnings(("complex divmod.., // and % are "
+                                      "deprecated", DeprecationWarning)):
+        test_support.run_unittest(ComplexTest)
 
 if __name__ == "__main__":
     test_main()
index 4d029dc39560330cad0f9859f0133c5b1e2406fb..c8a45916332cd43d0c3e2c0694a2596f39bbc7cb 100644 (file)
@@ -1,6 +1,5 @@
 """Unit tests for contextlib.py, and other context managers."""
 
-
 import sys
 import os
 import decimal
@@ -139,7 +138,7 @@ class NestedTestCase(unittest.TestCase):
             with nested(a(), b()) as (x, y):
                 state.append(x)
                 state.append(y)
-                1/0
+                1 // 0
         except ZeroDivisionError:
             self.assertEqual(state, [1, 4, 2, 5, 6, 3])
         else:
@@ -160,7 +159,7 @@ class NestedTestCase(unittest.TestCase):
                     pass
         try:
             with nested(a(), b()) as (x, y):
-                1/0
+                1 // 0
         except ZeroDivisionError:
             self.assertEqual((x, y), (1, 2))
         except Exception:
@@ -181,7 +180,7 @@ class NestedTestCase(unittest.TestCase):
                 pass
         try:
             with nested(a(), b()):
-                1/0
+                1 // 0
         except ZeroDivisionError:
             self.fail("Didn't swallow ZeroDivisionError")
 
@@ -247,7 +246,7 @@ class ClosingTestCase(unittest.TestCase):
         try:
             with closing(x) as y:
                 self.assertEqual(x, y)
-                1/0
+                1 // 0
         except ZeroDivisionError:
             self.assertEqual(state, [1])
         else:
@@ -268,7 +267,7 @@ class FileContextTestCase(unittest.TestCase):
                 with open(tfn, "r") as f:
                     self.failIf(f.closed)
                     self.assertEqual(f.read(), "Booh\n")
-                    1/0
+                    1 // 0
             except ZeroDivisionError:
                 self.failUnless(f.closed)
             else:
@@ -289,7 +288,7 @@ class LockContextTestCase(unittest.TestCase):
         try:
             with lock:
                 self.failUnless(locked())
-                1/0
+                1 // 0
         except ZeroDivisionError:
             self.failIf(locked())
         else:
@@ -333,5 +332,6 @@ class LockContextTestCase(unittest.TestCase):
 def test_main():
     test_support.run_unittest(__name__)
 
+
 if __name__ == "__main__":
     test_main()
index 474b856506b6c7b2508951adc3dda994645b8e17..839e3e076ce98ad2e55a2c36d84be2412f696174 100644 (file)
@@ -1,13 +1,9 @@
 # Simple test suite for Cookie.py
 
-from test.test_support import run_unittest, run_doctest
+from test.test_support import run_unittest, run_doctest, check_warnings
 import unittest
 import Cookie
 
-import warnings
-warnings.filterwarnings("ignore",
-                        ".* class is insecure.*",
-                        DeprecationWarning)
 
 class CookieTests(unittest.TestCase):
     # Currently this only tests SimpleCookie
@@ -86,7 +82,9 @@ class CookieTests(unittest.TestCase):
 
 def test_main():
     run_unittest(CookieTests)
-    run_doctest(Cookie)
+    with check_warnings(('.+Cookie class is insecure; do not use it',
+                         DeprecationWarning)):
+        run_doctest(Cookie)
 
 if __name__ == '__main__':
     test_main()
index a88a23f7be3091fa4a3ddbfc3e922b9b5693cb2a..0bd2ed6642f089719bc6899e215f2a3c6df77970 100644 (file)
@@ -7,7 +7,7 @@ import_module('_ctypes')
 
 def test_main():
     with _check_py3k_warnings(("buffer.. not supported", DeprecationWarning),
-                             ("classic (int|long) division", DeprecationWarning)):
+                              ("classic (int|long) division", DeprecationWarning),):
         import ctypes.test
         skipped, testcases = ctypes.test.get_tests(ctypes.test, "test_*.py", verbosity=0)
         suites = [unittest.makeSuite(t) for t in testcases]
index 6d76214e378a7abf6051ab05416a65bda40e4fad..55c5266268676c45dc7d8b34ca955c2f8e1d0ec7 100644 (file)
@@ -1,7 +1,7 @@
 import __builtin__
+import sys
 import types
 import unittest
-import warnings
 
 from copy import deepcopy
 from test import test_support
@@ -58,15 +58,6 @@ class OperatorsTest(unittest.TestCase):
                 expr = '%s a' % expr
             self.unops[name] = expr
 
-    def setUp(self):
-        self.original_filters = warnings.filters[:]
-        warnings.filterwarnings("ignore",
-                 r'complex divmod\(\), // and % are deprecated$',
-                 DeprecationWarning, r'(<string>|%s)$' % __name__)
-
-    def tearDown(self):
-        warnings.filters = self.original_filters
-
     def unop_test(self, a, res, expr="len(a)", meth="__len__"):
         d = {'a': a}
         self.assertEqual(eval(expr, d), res)
@@ -4433,10 +4424,14 @@ class PTypesLongInitTest(unittest.TestCase):
 
 
 def test_main():
-    with test_support._check_py3k_warnings(
+    deprecations = [(r'complex divmod\(\), // and % are deprecated$',
+                     DeprecationWarning)]
+    if sys.py3kwarning:
+        deprecations += [
             ("classic (int|long) division", DeprecationWarning),
             ("coerce.. not supported", DeprecationWarning),
-            (".+__(get|set|del)slice__ has been removed", DeprecationWarning)):
+            (".+__(get|set|del)slice__ has been removed", DeprecationWarning)]
+    with test_support.check_warnings(*deprecations):
         # Run all local test cases, with PTypesLongInitTest first.
         test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
                                   ClassPropertiesAndMethods, DictProxyTests)
index 74f107bb3ddf3c51c2384c0064ab685552864d19..a7477f2c436a6782c626f70f6c2052bb592409b7 100644 (file)
@@ -3,9 +3,9 @@
 Test script for doctest.
 """
 
+import sys
 from test import test_support
 import doctest
-import warnings
 
 # NOTE: There are some additional tests relating to interaction with
 #       zipimport in the test_zipimport_support test module.
@@ -2511,12 +2511,12 @@ def test_main():
     test_support.run_doctest(doctest, verbosity=True)
 
     from test import test_doctest
-    with test_support._check_py3k_warnings(
-            ("backquote not supported", SyntaxWarning),
-            ("execfile.. not supported", DeprecationWarning)):
-        # Ignore all warnings about the use of class Tester in this module.
-        warnings.filterwarnings("ignore", "class Tester is deprecated",
-                                DeprecationWarning)
+    # Ignore all warnings about the use of class Tester in this module.
+    deprecations = [("class Tester is deprecated", DeprecationWarning)]
+    if sys.py3kwarning:
+        deprecations += [("backquote not supported", SyntaxWarning),
+                         ("execfile.. not supported", DeprecationWarning)]
+    with test_support.check_warnings(*deprecations):
         # Check the doctest cases defined here:
         test_support.run_doctest(test_doctest, verbosity=True)
 
index 43de4de9aa3c775b24538443aae3de7d95abfb27..dcdd885debddcd457bb863d930bb420fb4ba93ad 100644 (file)
@@ -4,9 +4,9 @@ import os
 import sys
 import unittest
 import pickle, cPickle
-import warnings
 
-from test.test_support import TESTFN, unlink, run_unittest, captured_output
+from test.test_support import (TESTFN, unlink, run_unittest, captured_output,
+                               check_warnings)
 from test.test_pep352 import ignore_deprecation_warnings
 
 # XXX This is not really enough, each *operation* should be tested!
@@ -308,23 +308,19 @@ class ExceptionTests(unittest.TestCase):
         # Accessing BaseException.message and relying on its value set by
         # BaseException.__init__ triggers a deprecation warning.
         exc = BaseException("foo")
-        with warnings.catch_warnings(record=True) as w:
-            self.assertEquals(exc.message, "foo")
-        self.assertEquals(len(w), 1)
-        self.assertEquals(w[0].category, DeprecationWarning)
-        self.assertEquals(
-            str(w[0].message),
-            "BaseException.message has been deprecated as of Python 2.6")
-
+        with check_warnings(("BaseException.message has been deprecated "
+                             "as of Python 2.6", DeprecationWarning)) as w:
+            self.assertEqual(exc.message, "foo")
+        self.assertEqual(len(w.warnings), 1)
 
     def testRegularMessageAttribute(self):
         # Accessing BaseException.message after explicitly setting a value
         # for it does not trigger a deprecation warning.
         exc = BaseException("foo")
         exc.message = "bar"
-        with warnings.catch_warnings(record=True) as w:
-            self.assertEquals(exc.message, "bar")
-        self.assertEquals(len(w), 0)
+        with check_warnings(quiet=True) as w:
+            self.assertEqual(exc.message, "bar")
+        self.assertEqual(len(w.warnings), 0)
         # Deleting the message is supported, too.
         del exc.message
         self.assertRaises(AttributeError, getattr, exc, "message")
index 22e4b254c2228de9f4a43e53a194cbddb403019c..abcb193e5eef8ef0c44e9ea1b80cb33603a68eb9 100644 (file)
@@ -2,9 +2,8 @@
 
 from test.test_support import run_unittest, check_syntax_error
 import unittest
-
 import warnings
-warnings.filterwarnings("error", module="<test string>")
+
 
 class GlobalTests(unittest.TestCase):
 
@@ -45,7 +44,9 @@ x = 2
 
 
 def test_main():
-    run_unittest(GlobalTests)
+    with warnings.catch_warnings():
+        warnings.filterwarnings("error", module="<test string>")
+        run_unittest(GlobalTests)
 
 if __name__ == "__main__":
     test_main()
index ef376ac7a32c59b0874256510351fc15e7845bac..e65cc7c7c040913098bd270e3943a2397dcd0141 100644 (file)
@@ -6,9 +6,6 @@ This is complex because of changes due to PEP 237.
 import unittest
 from test import test_support
 
-import warnings
-warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning,
-                        "<string>")
 
 class TestHexOctBin(unittest.TestCase):
 
index 0d471d2fcb07922355f55be3f9c3c49e96f1fc33..e7579922fa04b35031d5a494ae2ba4aeed1d8aba 100644 (file)
@@ -9,7 +9,7 @@ import array
 import threading
 import random
 import unittest
-from itertools import chain, cycle
+from itertools import cycle, count
 from test import test_support
 
 import codecs
index ac965acd40b072c27bcf536c3b00eb3e048a6c3b..aa6591911f1312c78a1bc0268e323bfa4eaaad5e 100644 (file)
@@ -21,14 +21,8 @@ class TestMacostools(unittest.TestCase):
         rfp.close()
 
     def tearDown(self):
-        try:
-            os.unlink(test_support.TESTFN)
-        except:
-            pass
-        try:
-            os.unlink(TESTFN2)
-        except:
-            pass
+        test_support.unlink(test_support.TESTFN)
+        test_support.unlink(TESTFN2)
 
     def compareData(self):
         fp = open(test_support.TESTFN, 'r')
@@ -51,36 +45,25 @@ class TestMacostools(unittest.TestCase):
 
     def test_touched(self):
         # This really only tests that nothing unforeseen happens.
-        import warnings
-        with warnings.catch_warnings():
-            warnings.filterwarnings('ignore', 'macostools.touched*',
-                                    DeprecationWarning)
+        with test_support.check_warnings(('macostools.touched*',
+                                          DeprecationWarning), quiet=True):
             macostools.touched(test_support.TESTFN)
 
     if sys.maxint < 2**32:
         def test_copy(self):
-            try:
-                os.unlink(TESTFN2)
-            except:
-                pass
+            test_support.unlink(TESTFN2)
             macostools.copy(test_support.TESTFN, TESTFN2)
             self.assertEqual(self.compareData(), '')
 
     if sys.maxint < 2**32:
         def test_mkalias(self):
-            try:
-                os.unlink(TESTFN2)
-            except:
-                pass
+            test_support.unlink(TESTFN2)
             macostools.mkalias(test_support.TESTFN, TESTFN2)
             fss, _, _ = Carbon.File.ResolveAliasFile(TESTFN2, 0)
             self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN))
 
         def test_mkalias_relative(self):
-            try:
-                os.unlink(TESTFN2)
-            except:
-                pass
+            test_support.unlink(TESTFN2)
             # If the directory doesn't exist, then chances are this is a new
             # install of Python so don't create it since the user might end up
             # running ``sudo make install`` and creating the directory here won't
index 666d6c92a823fc72f819f8174a4e8d58205c14cd..3f23af5addeb68254e3d1148ac4dcf245bd600d9 100644 (file)
@@ -2,7 +2,7 @@ import unittest
 import __builtin__
 import exceptions
 import warnings
-from test.test_support import run_unittest
+from test.test_support import run_unittest, check_warnings
 import os
 import sys
 from platform import system as platform_system
@@ -15,14 +15,13 @@ if sys.py3kwarning:
          "catching classes that don't inherit from BaseException is not allowed",
          "__get(item|slice)__ not supported for exception classes"])
 
+_deprecations = [(msg, DeprecationWarning) for msg in DEPRECATION_WARNINGS]
+
 # 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)
+        with check_warnings(*_deprecations, quiet=True):
             return func(*args, **kw)
     return wrapper
 
@@ -139,16 +138,8 @@ class ExceptionClassTests(unittest.TestCase):
 
     def test_message_deprecation(self):
         # As of Python 2.6, BaseException.message is deprecated.
-        with warnings.catch_warnings():
-            warnings.resetwarnings()
-            warnings.filterwarnings('error')
-
-            try:
-                BaseException().message
-            except DeprecationWarning:
-                pass
-            else:
-                self.fail("BaseException.message not deprecated")
+        with check_warnings(("", DeprecationWarning)):
+            BaseException().message
 
 
 class UsageTests(unittest.TestCase):
index 6e302334efc64997c2f1beedcd0b6ab391d8f059..f8a564762f4a487eabf0244eb6c38e547fbbea39 100644 (file)
@@ -1,7 +1,4 @@
-import sys
-sys.path = ['.'] + sys.path
-
-from test.test_support import verbose, run_unittest
+from test.test_support import verbose, run_unittest, import_module
 import re
 from re import Scanner
 import sys, os, traceback
@@ -450,11 +447,8 @@ class ReTests(unittest.TestCase):
         import cPickle
         self.pickle_test(cPickle)
         # old pickles expect the _compile() reconstructor in sre module
-        import warnings
-        with warnings.catch_warnings():
-            warnings.filterwarnings("ignore", "The sre module is deprecated",
-                                    DeprecationWarning)
-            from sre import _compile
+        import_module("sre", deprecated=True)
+        from sre import _compile
 
     def pickle_test(self, pickle):
         oldpat = re.compile('a(?:b|(c|e){1,2}?|d)+?(.)')
index 3b91d656c2196f841027b6d8e3748adc8eacef06..9ffd39bbebacfedd74089412c70aae28c51d3d2a 100644 (file)
@@ -3,12 +3,11 @@
 from test import test_support
 import sys
 import unittest
-import warnings
 
 
 class TestUntestedModules(unittest.TestCase):
     def test_at_least_import_untested_modules(self):
-        with warnings.catch_warnings():
+        with test_support.check_warnings(quiet=True):
             import CGIHTTPServer
             import audiodev
             import bdb
index 3b61a959acb020a33ef867a2b1f9baf7b08e1657..0b4190d2d5ba68c60980f7e4513c0566f9d508a6 100644 (file)
@@ -44,9 +44,8 @@ def find_block(block, name):
 
 class SymtableTest(unittest.TestCase):
 
-    with warnings.catch_warnings():
-        # Ignore warnings about "from blank import *"
-        warnings.simplefilter("ignore", SyntaxWarning)
+    with test_support.check_warnings(
+            ("import \* only allowed at module level", SyntaxWarning)):
         top = symtable.symtable(TEST_CODE, "?", "exec")
     # These correspond to scopes in TEST_CODE
     Mine = find_block(top, "Mine")
index dc46c210d2eac9a89349be4c72382cbe6b742c6e..d7ba5d9a80aae023e7f824a34cdf1cdbacf2de68 100644 (file)
@@ -193,10 +193,8 @@ class urlretrieveNetworkTests(unittest.TestCase):
 
 def test_main():
     test_support.requires('network')
-    from warnings import filterwarnings, catch_warnings
-    with catch_warnings():
-        filterwarnings('ignore', '.*urllib\.urlopen.*Python 3.0',
-                        DeprecationWarning)
+    with test_support.check_py3k_warnings(
+            ("urllib.urlopen.. has been removed", DeprecationWarning)):
         test_support.run_unittest(URLTimeoutTest,
                                   urlopenNetworkTests,
                                   urlretrieveNetworkTests)
index b1e2010fbcd20661cbdeaa103bbe08b848aafe78..f55502a3a4584b74baddb36d3c190df14ca8fae7 100644 (file)
@@ -620,14 +620,21 @@ class CatchWarningTests(BaseTest):
         with test_support.check_warnings(('foo', UserWarning)):
             wmod.warn("foo")
 
-        with self.assertRaises(AssertionError):
+        try:
             with test_support.check_warnings(('', RuntimeWarning)):
                 # defaults to quiet=False with argument
                 pass
-        with self.assertRaises(AssertionError):
+        except AssertionError:
+            pass
+        else:
+            self.fail("Dind't raise AssertionError")
+        try:
             with test_support.check_warnings(('foo', RuntimeWarning)):
                 wmod.warn("foo")
-
+        except AssertionError:
+            pass
+        else:
+            self.fail("Dind't raise AssertionError")
 
 class CCatchWarningTests(CatchWarningTests):
     module = c_warnings
index 914719b55f0708aa220cfc331807ce4911c42704..b2cf6b7ec9520925f2d2a0d638e0c19cd0422778 100644 (file)
@@ -172,12 +172,14 @@ class ZipSupportTests(ImportHooksBaseTestCase):
                 test_zipped_doctest.test_unittest_reportflags,
             ]
             # Needed for test_DocTestParser and test_debug
-            with test.test_support._check_py3k_warnings(
-                    ("backquote not supported", SyntaxWarning),
-                    ("execfile.. not supported", DeprecationWarning)):
+            deprecations = [
                 # Ignore all warnings about the use of class Tester in this module.
-                warnings.filterwarnings("ignore", "class Tester is deprecated",
-                                        DeprecationWarning)
+                ("class Tester is deprecated", DeprecationWarning)]
+            if sys.py3kwarning:
+                deprecations += [
+                    ("backquote not supported", SyntaxWarning),
+                    ("execfile.. not supported", DeprecationWarning)]
+            with test.test_support.check_warnings(*deprecations):
                 for obj in known_good_tests:
                     _run_object_doctest(obj, test_zipped_doctest)