]> granicus.if.org Git - python/commitdiff
Replace catch_warnings with check_warnings when it makes sense. Use assertRaises...
authorFlorent Xicluna <florent.xicluna@gmail.com>
Wed, 31 Mar 2010 22:01:03 +0000 (22:01 +0000)
committerFlorent Xicluna <florent.xicluna@gmail.com>
Wed, 31 Mar 2010 22:01:03 +0000 (22:01 +0000)
21 files changed:
Lib/test/test___all__.py
Lib/test/test_argparse.py
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_descr.py
Lib/test/test_doctest.py
Lib/test/test_exceptions.py
Lib/test/test_global.py
Lib/test/test_hmac.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_zipimport_support.py

index 8662bcb2ce3473d72b1e31f05c9ef1de34fc6e7c..596ad7964063b5718addf82f2cab7bbc34a11c44 100644 (file)
@@ -4,7 +4,6 @@ import unittest
 from test import test_support as support
 import os
 import sys
-import warnings
 
 
 class NoAll(RuntimeError):
@@ -18,9 +17,8 @@ class AllTest(unittest.TestCase):
 
     def check_all(self, modname):
         names = {}
-        with warnings.catch_warnings():
-            warnings.filterwarnings("ignore", ".* (module|package)",
-                                    DeprecationWarning)
+        with support.check_warnings((".* (module|package)",
+                                     DeprecationWarning), quiet=True):
             try:
                 exec "import %s" % modname in names
             except:
index efe175d5a26dbbb5a1f2d0322605508a835b1275..cefae25cb5397121442d077cf25c5730dc31e5a4 100644 (file)
@@ -7,7 +7,6 @@ import sys
 import textwrap
 import tempfile
 import unittest
-import warnings
 import argparse
 
 from StringIO import StringIO
@@ -4160,21 +4159,12 @@ class TestImportStar(TestCase):
             self.assertTrue(hasattr(argparse, name))
 
 def test_main():
-    with warnings.catch_warnings():
-        # silence warnings about version argument - these are expected
-        warnings.filterwarnings(
-            action='ignore',
-            message='The "version" argument to ArgumentParser is deprecated.',
-            category=DeprecationWarning)
-        warnings.filterwarnings(
-            action='ignore',
-            message='The format_version method is deprecated',
-            category=DeprecationWarning)
-        warnings.filterwarnings(
-            action='ignore',
-            message='The print_version method is deprecated',
-            category=DeprecationWarning)
-
+    # silence warnings about version argument - these are expected
+    with test_support.check_warnings(
+            ('The "version" argument to ArgumentParser is deprecated.',
+             DeprecationWarning),
+            ('The (format|print)_version method is deprecated',
+             DeprecationWarning)):
         test_support.run_unittest(__name__)
     # Remove global references to avoid looking like we have refleaks.
     RFile.seen = {}
index 34eb19e6dccb4d7e0706f439b92a97d907e3be19..8a74b5159f3c9a2d1288dbbe4efb90d670b64ae9 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 4e482d2fa375b307468e694d4f415f49109fcf96..2d10dea3a30591a78e3948224f30aa4713321944 100644 (file)
@@ -4,12 +4,9 @@
 '''
 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
+from test.test_support import run_unittest, reap_children, import_module, \
+                              check_warnings
 
 # Silence Py3k warning
 commands = import_module('commands', deprecated=True)
@@ -59,7 +56,9 @@ class CommandTests(unittest.TestCase):
                   /\.          # and end with the name of the file.
                '''
 
-        self.assertTrue(re.match(pat, commands.getstatus("/."), re.VERBOSE))
+        with check_warnings((".*commands.getstatus.. is deprecated",
+                             DeprecationWarning)):
+            self.assertTrue(re.match(pat, commands.getstatus("/."), re.VERBOSE))
 
 
 def test_main():
index eb04856cc55d67a59300699dca9ba62964fef4fe..fc47b23682176bc91e3a7029c9fd889b22ae9e8b 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, isnan, copysign
 
@@ -464,10 +457,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))
@@ -613,7 +603,9 @@ class ComplexTest(unittest.TestCase):
         self.assertEqual('{0:F}'.format(complex(NAN, NAN)), 'NAN+NANj')
 
 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 4d233dad34a05e0d52579827e27b7a421cc2b2bc..42b90b612de0e07aaa14a27cf1782b87ff91ee1e 100644 (file)
@@ -1,14 +1,12 @@
 """Unit tests for contextlib.py, and other context managers."""
 
-
-import os
 import sys
 import tempfile
 import unittest
 import threading
 from contextlib import *  # Tests __all__
 from test import test_support
-import warnings
+
 
 class ContextManagerTestCase(unittest.TestCase):
 
@@ -34,16 +32,12 @@ class ContextManagerTestCase(unittest.TestCase):
                 yield 42
             finally:
                 state.append(999)
-        try:
+        with self.assertRaises(ZeroDivisionError):
             with woohoo() as x:
                 self.assertEqual(state, [1])
                 self.assertEqual(x, 42)
                 state.append(x)
                 raise ZeroDivisionError()
-        except ZeroDivisionError:
-            pass
-        else:
-            self.fail("Expected ZeroDivisionError")
         self.assertEqual(state, [1, 42, 999])
 
     def test_contextmanager_no_reraise(self):
@@ -144,15 +138,12 @@ class NestedTestCase(unittest.TestCase):
                 yield 5
             finally:
                 state.append(6)
-        try:
+        with self.assertRaises(ZeroDivisionError):
             with nested(a(), b()) as (x, y):
                 state.append(x)
                 state.append(y)
-                1/0
-        except ZeroDivisionError:
-            self.assertEqual(state, [1, 4, 2, 5, 6, 3])
-        else:
-            self.fail("Didn't raise ZeroDivisionError")
+                1 // 0
+        self.assertEqual(state, [1, 4, 2, 5, 6, 3])
 
     def test_nested_right_exception(self):
         @contextmanager
@@ -166,15 +157,10 @@ class NestedTestCase(unittest.TestCase):
                     raise Exception()
                 except:
                     pass
-        try:
+        with self.assertRaises(ZeroDivisionError):
             with nested(a(), b()) as (x, y):
-                1/0
-        except ZeroDivisionError:
-            self.assertEqual((x, y), (1, 2))
-        except Exception:
-            self.fail("Reraised wrong exception")
-        else:
-            self.fail("Didn't raise ZeroDivisionError")
+                1 // 0
+        self.assertEqual((x, y), (1, 2))
 
     def test_nested_b_swallows(self):
         @contextmanager
@@ -189,7 +175,7 @@ class NestedTestCase(unittest.TestCase):
                 pass
         try:
             with nested(a(), b()):
-                1/0
+                1 // 0
         except ZeroDivisionError:
             self.fail("Didn't swallow ZeroDivisionError")
 
@@ -252,14 +238,11 @@ class ClosingTestCase(unittest.TestCase):
                 state.append(1)
         x = C()
         self.assertEqual(state, [])
-        try:
+        with self.assertRaises(ZeroDivisionError):
             with closing(x) as y:
                 self.assertEqual(x, y)
-                1/0
-        except ZeroDivisionError:
-            self.assertEqual(state, [1])
-        else:
-            self.fail("Didn't raise ZeroDivisionError")
+                1 // 0
+        self.assertEqual(state, [1])
 
 class FileContextTestCase(unittest.TestCase):
 
@@ -272,20 +255,14 @@ class FileContextTestCase(unittest.TestCase):
                 f.write("Booh\n")
             self.assertTrue(f.closed)
             f = None
-            try:
+            with self.assertRaises(ZeroDivisionError):
                 with open(tfn, "r") as f:
                     self.assertFalse(f.closed)
                     self.assertEqual(f.read(), "Booh\n")
-                    1/0
-            except ZeroDivisionError:
-                self.assertTrue(f.closed)
-            else:
-                self.fail("Didn't raise ZeroDivisionError")
+                    1 // 0
+            self.assertTrue(f.closed)
         finally:
-            try:
-                os.remove(tfn)
-            except os.error:
-                pass
+            test_support.unlink(tfn)
 
 class LockContextTestCase(unittest.TestCase):
 
@@ -294,14 +271,11 @@ class LockContextTestCase(unittest.TestCase):
         with lock:
             self.assertTrue(locked())
         self.assertFalse(locked())
-        try:
+        with self.assertRaises(ZeroDivisionError):
             with lock:
                 self.assertTrue(locked())
-                1/0
-        except ZeroDivisionError:
-            self.assertFalse(locked())
-        else:
-            self.fail("Didn't raise ZeroDivisionError")
+                1 // 0
+        self.assertFalse(locked())
 
     def testWithLock(self):
         lock = threading.Lock()
@@ -339,8 +313,9 @@ class LockContextTestCase(unittest.TestCase):
 
 # This is needed to make the test actually run under regrtest.py!
 def test_main():
-    with warnings.catch_warnings():
-        warnings.simplefilter('ignore')
+    with test_support.check_warnings(("With-statements now directly support "
+                                      "multiple context managers",
+                                      DeprecationWarning)):
         test_support.run_unittest(__name__)
 
 if __name__ == "__main__":
index 1cd538ce40d4a5f1d90662d07f3c55a7697bd057..6523b9b98d8b2516e56863f9010a20aa30cfb5ae 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
@@ -76,7 +72,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 bff88bcb3c8ac98aca254bd251b6625779baffe9..d450eed585f9f74489547a25cc76554e81683633 100644 (file)
@@ -2,7 +2,6 @@ import __builtin__
 import sys
 import types
 import unittest
-import warnings
 
 from copy import deepcopy
 from test import test_support
@@ -59,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)
@@ -4622,11 +4612,15 @@ 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),
             ("Overriding __cmp__ ", 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 faa99ac1cdb41de9b1ef4cdee9581cc47938ffd0..4fc2f9f40658a29696456ef85e4ce7089da4ca89 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.
@@ -2458,12 +2458,13 @@ 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 8a0f30f50ec1577471b7f69d26bf27bd4e812756..89e5758419fc8adc082a49bbe212b808d2b9ac10 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,24 +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:
-            warnings.simplefilter('default')
-            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
         with self.assertRaises(AttributeError):
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 30bb4fe222b67c8c9df9ac5280e60c1ff9a0e924..cd148e9d0a1e7eaf89d05e38144f2115208b2c09 100644 (file)
@@ -213,19 +213,13 @@ class TestVectorsTestCase(unittest.TestCase):
 
         with warnings.catch_warnings():
             warnings.simplefilter('error', RuntimeWarning)
-            try:
+            with self.assertRaises(RuntimeWarning):
                 hmac.HMAC('a', 'b', digestmod=MockCrazyHash)
-            except RuntimeWarning:
-                pass
-            else:
                 self.fail('Expected warning about missing block_size')
 
             MockCrazyHash.block_size = 1
-            try:
+            with self.assertRaises(RuntimeWarning):
                 hmac.HMAC('a', 'b', digestmod=MockCrazyHash)
-            except RuntimeWarning:
-                pass
-            else:
                 self.fail('Expected warning about small block_size')
 
 
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 0c335a3dd117b6434e0fc748f4ad675402b162f2..9ffe646ea9fd2b67e8765efd9f1dad69862f0bdc 100644 (file)
@@ -29,7 +29,6 @@ import array
 import threading
 import random
 import unittest
-import warnings
 import weakref
 import abc
 from itertools import cycle, count
index 642a584c1dc49436e2bde490607d492a1dd66224..4f159829795fdb3a8a1852018b4fba5be18f9012 100644 (file)
@@ -23,14 +23,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')
@@ -53,36 +47,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 4654e26fc192735c2f587ae7c03ca634de9cfba8..88b3136651e88383a2285f555b1db1617156376b 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):
@@ -224,28 +215,19 @@ class UsageTests(unittest.TestCase):
             warnings.resetwarnings()
             warnings.filterwarnings("error")
             str_exc = "spam"
-            try:
+            with self.assertRaises(DeprecationWarning):
                 try:
                     raise StandardError
                 except str_exc:
                     pass
-            except DeprecationWarning:
-                pass
-            except StandardError:
-                self.fail("catching a string exception did not raise "
-                            "DeprecationWarning")
+
             # Make sure that even if the string exception is listed in a tuple
             # that a warning is raised.
-            try:
+            with self.assertRaises(DeprecationWarning):
                 try:
                     raise StandardError
                 except (AssertionError, str_exc):
                     pass
-            except DeprecationWarning:
-                pass
-            except StandardError:
-                self.fail("catching a string exception specified in a tuple did "
-                            "not raise DeprecationWarning")
 
 
 def test_main():
index ba2f521a6feaeba3a13fb1c0b25e19b01f4991d8..f978086dbc738d995f150f6771c224820f721f8a 100644 (file)
@@ -1,4 +1,4 @@
-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, traceback
@@ -447,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 cef155bb2aec9940554c0267dc9f952bd05d84da..3aade6d57d32fe52c22a767cb41212274597eb1d 100644 (file)
@@ -3,13 +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():
-            warnings.simplefilter("ignore")
+        with test_support.check_warnings(quiet=True):
             import CGIHTTPServer
             import audiodev
             import bdb
index c9d20547555af4d395db3eeff7e32c492fadf575..71994ad227891dbb49311906ba2311a0be18b36f 100644 (file)
@@ -3,7 +3,6 @@ Test the API of the symtable module.
 """
 import symtable
 import unittest
-import warnings
 
 from test import test_support
 
@@ -44,9 +43,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 77b544552dc7844569437782c7c2e4c4dc5caf00..8eb01e577e02b35a8d97905b67d8a6274e2c1e16 100644 (file)
@@ -182,10 +182,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 960f3c3c31b1958e649876e0c9b5bbfe4f38efe1..4f41518d704690d3794eaf9ee456559276b2f1d7 100644 (file)
@@ -168,12 +168,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)