]> granicus.if.org Git - python/commitdiff
Raise statement normalization in Lib/test/.
authorCollin Winter <collinw@gmail.com>
Wed, 29 Aug 2007 23:37:32 +0000 (23:37 +0000)
committerCollin Winter <collinw@gmail.com>
Wed, 29 Aug 2007 23:37:32 +0000 (23:37 +0000)
47 files changed:
Lib/test/leakers/test_gestalt.py
Lib/test/pickletester.py
Lib/test/test_binop.py
Lib/test/test_capi.py
Lib/test/test_cgi.py
Lib/test/test_contains.py
Lib/test/test_copy.py
Lib/test/test_curses.py
Lib/test/test_dbm.py
Lib/test/test_descr.py
Lib/test/test_descrtut.py
Lib/test/test_dl.py
Lib/test/test_doctest.py
Lib/test/test_exception_variations.py
Lib/test/test_extcall.py
Lib/test/test_fork1.py
Lib/test/test_format.py
Lib/test/test_funcattrs.py
Lib/test/test_gdbm.py
Lib/test/test_importhooks.py
Lib/test/test_iter.py
Lib/test/test_largefile.py
Lib/test/test_locale.py
Lib/test/test_logging.py
Lib/test/test_openpty.py
Lib/test/test_pep277.py
Lib/test/test_pkgimport.py
Lib/test/test_poll.py
Lib/test/test_posix.py
Lib/test/test_pty.py
Lib/test/test_queue.py
Lib/test/test_re.py
Lib/test/test_richcmp.py
Lib/test/test_scope.py
Lib/test/test_socket.py
Lib/test/test_socketserver.py
Lib/test/test_struct.py
Lib/test/test_thread.py
Lib/test/test_threadsignals.py
Lib/test/test_trace.py
Lib/test/test_traceback.py
Lib/test/test_unicode_file.py
Lib/test/test_univnewlines.py
Lib/test/test_wait3.py
Lib/test/test_wait4.py
Lib/test/test_wave.py
Lib/test/time_hashlib.py

index 46bfcc806dc6c5207631c7544e75d62a428be512..e0081c1fc51025277820f5af25733d31329e11d6 100644 (file)
@@ -1,7 +1,7 @@
 import sys
 
 if sys.platform != 'darwin':
-    raise ValueError, "This test only leaks on Mac OS X"
+    raise ValueError("This test only leaks on Mac OS X")
 
 def leak():
     # taken from platform._mac_ver_lookup()
index bc360b82d20205f7f0044283443dc3a7142120a0..0b1cf5a0574a1a23bc366e1d3f171b84d32bb608 100644 (file)
@@ -868,7 +868,7 @@ class REX_three(object):
         self._proto = proto
         return REX_two, ()
     def __reduce__(self):
-        raise TestFailed, "This __reduce__ shouldn't be called"
+        raise TestFailed("This __reduce__ shouldn't be called")
 
 class REX_four(object):
     _proto = None
index 5aeb1185581e986bae96bba3784d34987c3a2531..f0433fbd7efaa4784f47abf787a4f15b814f2fc3 100644 (file)
@@ -35,12 +35,12 @@ class Rat(object):
 
         The arguments must be ints or longs, and default to (0, 1)."""
         if not isint(num):
-            raise TypeError, "Rat numerator must be int or long (%r)" % num
+            raise TypeError("Rat numerator must be int or long (%r)" % num)
         if not isint(den):
-            raise TypeError, "Rat denominator must be int or long (%r)" % den
+            raise TypeError("Rat denominator must be int or long (%r)" % den)
         # But the zero is always on
         if den == 0:
-            raise ZeroDivisionError, "zero denominator"
+            raise ZeroDivisionError("zero denominator")
         g = gcd(den, num)
         self.__num = int(num//g)
         self.__den = int(den//g)
@@ -73,15 +73,15 @@ class Rat(object):
             try:
                 return int(self.__num)
             except OverflowError:
-                raise OverflowError("%s too large to convert to int" %
+                raise OverflowError("%s too large to convert to int" %
                                       repr(self))
-        raise ValueError, "can't convert %s to int" % repr(self)
+        raise ValueError("can't convert %s to int" % repr(self))
 
     def __long__(self):
         """Convert a Rat to an long; self.den must be 1."""
         if self.__den == 1:
             return int(self.__num)
-        raise ValueError, "can't convert %s to long" % repr(self)
+        raise ValueError("can't convert %s to long" % repr(self))
 
     def __add__(self, other):
         """Add two Rats, or a Rat and a number."""
index 074f5815a89a013b427a09993a235566e3dde155..107d4b42768a5ca0207510c6e70a7a693677dc3c 100644 (file)
@@ -12,10 +12,7 @@ def test_main():
             test = getattr(_testcapi, name)
             if test_support.verbose:
                 print("internal", name)
-            try:
-                test()
-            except _testcapi.error:
-                raise test_support.TestFailed, sys.exc_info()[1]
+            test()
 
     # some extra thread-state tests driven via _testcapi
     def TestThreadState():
@@ -35,8 +32,8 @@ def test_main():
         time.sleep(1)
         # Check our main thread is in the list exactly 3 times.
         if idents.count(thread.get_ident()) != 3:
-            raise test_support.TestFailed, \
-                  "Couldn't find main thread correctly in the list"
+            raise test_support.TestFailed(
+                        "Couldn't find main thread correctly in the list")
 
     try:
         _testcapi._test_thread_state
index 439982bf45e65d7b11961d1ee237b4cae6efebe9..b1102cf97b1505a6a662d07dfa92173028d3c23a 100644 (file)
@@ -47,7 +47,7 @@ def do_test(buf, method):
         env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
         env['CONTENT_LENGTH'] = str(len(buf))
     else:
-        raise ValueError, "unknown method: %s" % method
+        raise ValueError("unknown method: %s" % method)
     try:
         return cgi.parse(fp, env, strict_parsing=1)
     except Exception as err:
index 7cae480c95c110e4853206ef9280d8b975af7dba..b55057de79dfe299deb6ddb68f954f3da94c4642 100644 (file)
@@ -17,7 +17,7 @@ class seq(base_set):
 
 def check(ok, *args):
     if not ok:
-        raise TestFailed, " ".join(map(str, args))
+        raise TestFailed(" ".join(map(str, args)))
 
 a = base_set(1)
 b = set(1)
@@ -95,7 +95,7 @@ class Deviant2:
 
     def __cmp__(self, other):
         if other == 4:
-            raise RuntimeError, "gotcha"
+            raise RuntimeError("gotcha")
 
 try:
     check(Deviant2() not in a, "oops")
index dfdea845ecdcb477a809efa637013df803b2f0f6..cf945939c97cc03750c10dd756b201e8c3a1de31 100644 (file)
@@ -51,7 +51,7 @@ class TestCopy(unittest.TestCase):
             def __reduce_ex__(self, proto):
                 return ""
             def __reduce__(self):
-                raise test_support.TestFailed, "shouldn't call this"
+                raise test_support.TestFailed("shouldn't call this")
         x = C()
         y = copy.copy(x)
         self.assert_(y is x)
@@ -68,7 +68,7 @@ class TestCopy(unittest.TestCase):
         class C(object):
             def __getattribute__(self, name):
                 if name.startswith("__reduce"):
-                    raise AttributeError, name
+                    raise AttributeError(name)
                 return object.__getattribute__(self, name)
         x = C()
         self.assertRaises(copy.Error, copy.copy, x)
@@ -224,7 +224,7 @@ class TestCopy(unittest.TestCase):
             def __reduce_ex__(self, proto):
                 return ""
             def __reduce__(self):
-                raise test_support.TestFailed, "shouldn't call this"
+                raise test_support.TestFailed("shouldn't call this")
         x = C()
         y = copy.deepcopy(x)
         self.assert_(y is x)
@@ -241,7 +241,7 @@ class TestCopy(unittest.TestCase):
         class C(object):
             def __getattribute__(self, name):
                 if name.startswith("__reduce"):
-                    raise AttributeError, name
+                    raise AttributeError(name)
                 return object.__getattribute__(self, name)
         x = C()
         self.assertRaises(copy.Error, copy.deepcopy, x)
@@ -565,7 +565,7 @@ class TestCopy(unittest.TestCase):
     def test_getstate_exc(self):
         class EvilState(object):
             def __getstate__(self):
-                raise ValueError, "ain't got no stickin' state"
+                raise ValueError("ain't got no stickin' state")
         self.assertRaises(ValueError, copy.copy, EvilState())
 
     def test_copy_function(self):
index ee679e762ee3a132c19d5cf4e10ef38f7cdb6899..64d6536ed03ea2f4b44af857e381a6ceb7b46146 100644 (file)
@@ -22,7 +22,7 @@ requires('curses')
 # XXX: if newterm was supported we could use it instead of initscr and not exit
 term = os.environ.get('TERM')
 if not term or term == 'unknown':
-    raise TestSkipped, "$TERM=%r, calling initscr() may cause exit" % term
+    raise TestSkipped("$TERM=%r, calling initscr() may cause exit" % term)
 
 if sys.platform == "cygwin":
     raise TestSkipped("cygwin's curses mostly just hangs")
@@ -72,7 +72,7 @@ def window_funcs(stdscr):
     except TypeError:
         pass
     else:
-        raise RuntimeError, "Expected win.border() to raise TypeError"
+        raise RuntimeError("Expected win.border() to raise TypeError")
 
     stdscr.clearok(1)
 
@@ -243,7 +243,7 @@ def test_userptr_without_set(stdscr):
     # try to access userptr() before calling set_userptr() -- segfaults
     try:
         p.userptr()
-        raise RuntimeError, 'userptr should fail since not set'
+        raise RuntimeError('userptr should fail since not set')
     except curses.panel.error:
         pass
 
@@ -253,7 +253,7 @@ def test_resize_term(stdscr):
         curses.resizeterm(lines - 1, cols + 1)
 
         if curses.LINES != lines - 1 or curses.COLS != cols + 1:
-            raise RuntimeError, "Expected resizeterm to update LINES and COLS"
+            raise RuntimeError("Expected resizeterm to update LINES and COLS")
 
 def main(stdscr):
     curses.savetty()
index 88b0bf6cc7ba322f390fdbe036aa48fd3a043f81..806125f70d7f0ab136ab58e8c6982ff7d229d09f 100755 (executable)
@@ -21,7 +21,7 @@ def cleanup():
             # if we can't delete the file because of permissions,
             # nothing will work, so skip the test
             if errno == 1:
-                raise TestSkipped, 'unable to remove: ' + filename + suffix
+                raise TestSkipped('unable to remove: ' + filename + suffix)
 
 def test_keys():
     d = dbm.open(filename, 'c')
index 74b4081f83578005630521a111122dd0dde22d5f..69400eedfd3d931d91d38946ab31fb9fd6043983 100644 (file)
@@ -12,7 +12,7 @@ warnings.filterwarnings("ignore",
 
 def veris(a, b):
     if a is not b:
-        raise TestFailed, "%r is %r" % (a, b)
+        raise TestFailed("%r is %r" % (a, b))
 
 def testunop(a, res, expr="len(a)", meth="__len__"):
     if verbose: print("checking", expr)
@@ -430,7 +430,7 @@ def ints():
     except TypeError:
         pass
     else:
-        raise TestFailed, "NotImplemented should have caused TypeError"
+        raise TestFailed("NotImplemented should have caused TypeError")
 
 def longs():
     if verbose: print("Testing long operations...")
@@ -775,7 +775,7 @@ def metaclass():
     c = C()
     try: c()
     except TypeError: pass
-    else: raise TestFailed, "calling object w/o call method should raise TypeError"
+    else: raise TestFailed("calling object w/o call method should raise TypeError")
 
     # Testing code to find most derived baseclass
     class A(type):
@@ -897,13 +897,13 @@ def diamond():
     except TypeError:
         pass
     else:
-        raise TestFailed, "expected MRO order disagreement (F)"
+        raise TestFailed("expected MRO order disagreement (F)")
     try:
         class G(E, D): pass
     except TypeError:
         pass
     else:
-        raise TestFailed, "expected MRO order disagreement (G)"
+        raise TestFailed("expected MRO order disagreement (G)")
 
 
 # see thread python-dev/2002-October/029035.html
@@ -965,10 +965,10 @@ def mro_disagreement():
             callable(*args)
         except exc as msg:
             if not str(msg).startswith(expected):
-                raise TestFailed"Message %r, expected %r" % (str(msg),
-                                                               expected)
+                raise TestFailed("Message %r, expected %r" % (str(msg),
+                                                               expected))
         else:
-            raise TestFailed, "Expected %s" % exc
+            raise TestFailed("Expected %s" % exc)
     class A(object): pass
     class B(A): pass
     class C(object): pass
@@ -1062,7 +1062,7 @@ def slots():
     except AttributeError:
         pass
     else:
-        raise TestFailed, "Double underscored names not mangled"
+        raise TestFailed("Double underscored names not mangled")
 
     # Make sure slot names are proper identifiers
     try:
@@ -1071,35 +1071,35 @@ def slots():
     except TypeError:
         pass
     else:
-        raise TestFailed, "[None] slots not caught"
+        raise TestFailed("[None] slots not caught")
     try:
         class C(object):
             __slots__ = ["foo bar"]
     except TypeError:
         pass
     else:
-        raise TestFailed, "['foo bar'] slots not caught"
+        raise TestFailed("['foo bar'] slots not caught")
     try:
         class C(object):
             __slots__ = ["foo\0bar"]
     except TypeError:
         pass
     else:
-        raise TestFailed, "['foo\\0bar'] slots not caught"
+        raise TestFailed("['foo\\0bar'] slots not caught")
     try:
         class C(object):
             __slots__ = ["1"]
     except TypeError:
         pass
     else:
-        raise TestFailed, "['1'] slots not caught"
+        raise TestFailed("['1'] slots not caught")
     try:
         class C(object):
             __slots__ = [""]
     except TypeError:
         pass
     else:
-        raise TestFailed, "[''] slots not caught"
+        raise TestFailed("[''] slots not caught")
     class C(object):
         __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
     # XXX(nnorwitz): was there supposed to be something tested
@@ -1135,7 +1135,7 @@ def slots():
     except (TypeError, UnicodeEncodeError):
         pass
     else:
-        raise TestFailed, "[unichr(128)] slots not caught"
+        raise TestFailed("[unichr(128)] slots not caught")
 
     # Test leaks
     class Counted(object):
@@ -1232,7 +1232,7 @@ def slotspecials():
     except AttributeError:
         pass
     else:
-        raise TestFailed, "shouldn't be allowed to set a.foo"
+        raise TestFailed("shouldn't be allowed to set a.foo")
 
     class C1(W, D):
         __slots__ = []
@@ -1434,7 +1434,7 @@ def classmethods():
     except TypeError:
         pass
     else:
-        raise TestFailed, "classmethod should check for callability"
+        raise TestFailed("classmethod should check for callability")
 
     # Verify that classmethod() doesn't allow keyword args
     try:
@@ -1442,7 +1442,7 @@ def classmethods():
     except TypeError:
         pass
     else:
-        raise TestFailed, "classmethod shouldn't accept keyword args"
+        raise TestFailed("classmethod shouldn't accept keyword args")
 
 def classmethods_in_c():
     if verbose: print("Testing C-based class methods...")
@@ -1595,7 +1595,7 @@ def altmro():
     except TypeError:
         pass
     else:
-        raise TestFailed, "devious mro() return not caught"
+        raise TestFailed("devious mro() return not caught")
 
     try:
         class _metaclass(type):
@@ -1606,7 +1606,7 @@ def altmro():
     except TypeError:
         pass
     else:
-        raise TestFailed, "non-class mro() return not caught"
+        raise TestFailed("non-class mro() return not caught")
 
     try:
         class _metaclass(type):
@@ -1617,7 +1617,7 @@ def altmro():
     except TypeError:
         pass
     else:
-        raise TestFailed, "non-sequence mro() return not caught"
+        raise TestFailed("non-sequence mro() return not caught")
 
 
 def overloading():
@@ -1956,7 +1956,7 @@ def properties():
     except ZeroDivisionError:
         pass
     else:
-        raise TestFailed, "expected ZeroDivisionError from bad property"
+        raise TestFailed("expected ZeroDivisionError from bad property")
 
     class E(object):
         def getter(self):
@@ -2037,28 +2037,28 @@ def supers():
     except TypeError:
         pass
     else:
-        raise TestFailed, "shouldn't allow super(D, 42)"
+        raise TestFailed("shouldn't allow super(D, 42)")
 
     try:
         super(D, C())
     except TypeError:
         pass
     else:
-        raise TestFailed, "shouldn't allow super(D, C())"
+        raise TestFailed("shouldn't allow super(D, C())")
 
     try:
         super(D).__get__(12)
     except TypeError:
         pass
     else:
-        raise TestFailed, "shouldn't allow super(D).__get__(12)"
+        raise TestFailed("shouldn't allow super(D).__get__(12)")
 
     try:
         super(D).__get__(C())
     except TypeError:
         pass
     else:
-        raise TestFailed, "shouldn't allow super(D).__get__(C())"
+        raise TestFailed("shouldn't allow super(D).__get__(C())")
 
     # Make sure data descriptors can be overridden and accessed via super
     # (new feature in Python 2.3)
@@ -2094,7 +2094,7 @@ def supers():
     except TypeError:
         pass
     else:
-        raise TestFailed, "super shouldn't accept keyword args"
+        raise TestFailed("super shouldn't accept keyword args")
 
 def inherits():
     if verbose: print("Testing inheritance from basic types...")
@@ -2573,7 +2573,7 @@ def rich_comparisons():
             def __init__(self, value):
                 self.value = int(value)
             def __cmp__(self, other):
-                raise TestFailed, "shouldn't call __cmp__"
+                raise TestFailed("shouldn't call __cmp__")
             def __eq__(self, other):
                 if isinstance(other, C):
                     return self.value == other.value
@@ -2652,13 +2652,13 @@ def setclass():
         except TypeError:
             pass
         else:
-            raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
+            raise TestFailed("shouldn't allow %r.__class__ = %r" % (x, C))
         try:
             delattr(x, "__class__")
         except TypeError:
             pass
         else:
-            raise TestFailed, "shouldn't allow del %r.__class__" % x
+            raise TestFailed("shouldn't allow del %r.__class__" % x)
     cant(C(), list)
     cant(list(), C)
     cant(C(), 1)
@@ -2726,7 +2726,7 @@ def setdict():
         except (AttributeError, TypeError):
             pass
         else:
-            raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
+            raise TestFailed("shouldn't allow %r.__dict__ = %r" % (x, dict))
     cant(a, None)
     cant(a, [])
     cant(a, 1)
@@ -2744,14 +2744,14 @@ def setdict():
         except (AttributeError, TypeError):
             pass
         else:
-            raise TestFailed, "shouldn't allow del %r.__dict__" % x
+            raise TestFailed("shouldn't allow del %r.__dict__" % x)
         dict_descr = Base.__dict__["__dict__"]
         try:
             dict_descr.__set__(x, {})
         except (AttributeError, TypeError):
             pass
         else:
-            raise TestFailed, "dict_descr allowed access to %r's dict" % x
+            raise TestFailed("dict_descr allowed access to %r's dict" % x)
 
     # Classes don't allow __dict__ assignment and have readonly dicts
     class Meta1(type, Base):
@@ -2770,7 +2770,7 @@ def setdict():
         except TypeError:
             pass
         else:
-            raise TestFailed, "%r's __dict__ can be modified" % cls
+            raise TestFailed("%r's __dict__ can be modified" % cls)
 
     # Modules also disallow __dict__ assignment
     class Module1(types.ModuleType, Base):
@@ -2796,7 +2796,7 @@ def setdict():
         except (TypeError, AttributeError):
             pass
         else:
-            raise TestFaied, "%r's __dict__ can be deleted" % e
+            raise TestFaied("%r's __dict__ can be deleted" % e)
 
 
 def pickles():
@@ -2931,13 +2931,13 @@ def pickleslots():
         except TypeError:
             pass
         else:
-            raise TestFailed, "should fail: pickle C instance - %s" % base
+            raise TestFailed("should fail: pickle C instance - %s" % base)
         try:
             pickle.dumps(C(), 0)
         except TypeError:
             pass
         else:
-            raise TestFailed, "should fail: pickle D instance - %s" % base
+            raise TestFailed("should fail: pickle D instance - %s" % base)
         # Give C a nice generic __getstate__ and __setstate__
         class C(base):
             __slots__ = ['a']
@@ -3073,7 +3073,7 @@ def subclasspropagation():
     def __getattr__(self, name):
         if name in ("spam", "foo", "bar"):
             return "hello"
-        raise AttributeError, name
+        raise AttributeError(name)
     B.__getattr__ = __getattr__
     vereq(d.spam, "hello")
     vereq(d.foo, 24)
@@ -3089,7 +3089,7 @@ def subclasspropagation():
     except AttributeError:
         pass
     else:
-        raise TestFailed, "d.foo should be undefined now"
+        raise TestFailed("d.foo should be undefined now")
 
     # Test a nasty bug in recurse_down_subclasses()
     import gc
@@ -3200,7 +3200,7 @@ def delhook():
     d = D()
     try: del d[0]
     except TypeError: pass
-    else: raise TestFailed, "invalid del() didn't raise TypeError"
+    else: raise TestFailed("invalid del() didn't raise TypeError")
 
 def hashinherit():
     if verbose: print("Testing hash of mutable subclasses...")
@@ -3213,7 +3213,7 @@ def hashinherit():
     except TypeError:
         pass
     else:
-        raise TestFailed, "hash() of dict subclass should fail"
+        raise TestFailed("hash() of dict subclass should fail")
 
     class mylist(list):
         pass
@@ -3223,48 +3223,48 @@ def hashinherit():
     except TypeError:
         pass
     else:
-        raise TestFailed, "hash() of list subclass should fail"
+        raise TestFailed("hash() of list subclass should fail")
 
 def strops():
     try: 'a' + 5
     except TypeError: pass
-    else: raise TestFailed, "'' + 5 doesn't raise TypeError"
+    else: raise TestFailed("'' + 5 doesn't raise TypeError")
 
     try: ''.split('')
     except ValueError: pass
-    else: raise TestFailed, "''.split('') doesn't raise ValueError"
+    else: raise TestFailed("''.split('') doesn't raise ValueError")
 
     try: ''.join([0])
     except TypeError: pass
-    else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
+    else: raise TestFailed("''.join([0]) doesn't raise TypeError")
 
     try: ''.rindex('5')
     except ValueError: pass
-    else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
+    else: raise TestFailed("''.rindex('5') doesn't raise ValueError")
 
     try: '%(n)s' % None
     except TypeError: pass
-    else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
+    else: raise TestFailed("'%(n)s' % None doesn't raise TypeError")
 
     try: '%(n' % {}
     except ValueError: pass
-    else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
+    else: raise TestFailed("'%(n' % {} '' doesn't raise ValueError")
 
     try: '%*s' % ('abc')
     except TypeError: pass
-    else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
+    else: raise TestFailed("'%*s' % ('abc') doesn't raise TypeError")
 
     try: '%*.*s' % ('abc', 5)
     except TypeError: pass
-    else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
+    else: raise TestFailed("'%*.*s' % ('abc', 5) doesn't raise TypeError")
 
     try: '%s' % (1, 2)
     except TypeError: pass
-    else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
+    else: raise TestFailed("'%s' % (1, 2) doesn't raise TypeError")
 
     try: '%' % None
     except ValueError: pass
-    else: raise TestFailed, "'%' % None doesn't raise ValueError"
+    else: raise TestFailed("'%' % None doesn't raise ValueError")
 
     vereq('534253'.isdigit(), 1)
     vereq('534253x'.isdigit(), 0)
@@ -3595,14 +3595,14 @@ def test_mutable_bases():
     except TypeError:
         pass
     else:
-        raise TestFailed, "shouldn't turn list subclass into dict subclass"
+        raise TestFailed("shouldn't turn list subclass into dict subclass")
 
     try:
         list.__bases__ = (dict,)
     except TypeError:
         pass
     else:
-        raise TestFailed, "shouldn't be able to assign to list.__bases__"
+        raise TestFailed("shouldn't be able to assign to list.__bases__")
 
     try:
         D.__bases__ = (C2, list)
@@ -3616,15 +3616,15 @@ def test_mutable_bases():
     except TypeError:
         pass
     else:
-        raise TestFailed, "shouldn't be able to delete .__bases__"
+        raise TestFailed("shouldn't be able to delete .__bases__")
 
     try:
         D.__bases__ = ()
     except TypeError as msg:
         if str(msg) == "a new-style class can't have only classic bases":
-            raise TestFailed, "wrong error message for .__bases__ = ()"
+            raise TestFailed("wrong error message for .__bases__ = ()")
     else:
-        raise TestFailed, "shouldn't be able to set .__bases__ to ()"
+        raise TestFailed("shouldn't be able to set .__bases__ to ()")
 
     try:
         D.__bases__ = (D,)
@@ -3632,21 +3632,21 @@ def test_mutable_bases():
         pass
     else:
         # actually, we'll have crashed by here...
-        raise TestFailed, "shouldn't be able to create inheritance cycles"
+        raise TestFailed("shouldn't be able to create inheritance cycles")
 
     try:
         D.__bases__ = (C, C)
     except TypeError:
         pass
     else:
-        raise TestFailed, "didn't detect repeated base classes"
+        raise TestFailed("didn't detect repeated base classes")
 
     try:
         D.__bases__ = (E,)
     except TypeError:
         pass
     else:
-        raise TestFailed, "shouldn't be able to create inheritance cycles"
+        raise TestFailed("shouldn't be able to create inheritance cycles")
 
 def test_mutable_bases_with_failing_mro():
     if verbose:
@@ -3657,7 +3657,7 @@ def test_mutable_bases_with_failing_mro():
             return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
         def mro(self):
             if self.flag > 0:
-                raise RuntimeError, "bozo"
+                raise RuntimeError("bozo")
             else:
                 self.flag += 1
                 return type.mro(self)
@@ -3701,7 +3701,7 @@ def test_mutable_bases_with_failing_mro():
         vereq(E.__mro__, E_mro_before)
         vereq(D.__mro__, D_mro_before)
     else:
-        raise TestFailed, "exception not propagated"
+        raise TestFailed("exception not propagated")
 
 def test_mutable_bases_catch_mro_conflict():
     if verbose:
@@ -3726,7 +3726,7 @@ def test_mutable_bases_catch_mro_conflict():
     except TypeError:
         pass
     else:
-        raise TestFailed, "didn't catch MRO conflict"
+        raise TestFailed("didn't catch MRO conflict")
 
 def mutable_names():
     if verbose:
@@ -3828,25 +3828,25 @@ def meth_class_get():
     except TypeError:
         pass
     else:
-        raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
+        raise TestFailed("shouldn't have allowed descr.__get__(None, None)")
     try:
         descr.__get__(42)
     except TypeError:
         pass
     else:
-        raise TestFailed, "shouldn't have allowed descr.__get__(42)"
+        raise TestFailed("shouldn't have allowed descr.__get__(42)")
     try:
         descr.__get__(None, 42)
     except TypeError:
         pass
     else:
-        raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
+        raise TestFailed("shouldn't have allowed descr.__get__(None, 42)")
     try:
         descr.__get__(None, int)
     except TypeError:
         pass
     else:
-        raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
+        raise TestFailed("shouldn't have allowed descr.__get__(None, int)")
 
 def isinst_isclass():
     if verbose:
@@ -3920,13 +3920,13 @@ def carloverre():
     except TypeError:
         pass
     else:
-        raise TestFailed, "Carlo Verre __setattr__ suceeded!"
+        raise TestFailed("Carlo Verre __setattr__ suceeded!")
     try:
         object.__delattr__(str, "lower")
     except TypeError:
         pass
     else:
-        raise TestFailed, "Carlo Verre __delattr__ succeeded!"
+        raise TestFailed("Carlo Verre __delattr__ succeeded!")
 
 def weakref_segfault():
     # SF 742911
@@ -4012,7 +4012,7 @@ def test_init():
     except TypeError:
         pass
     else:
-        raise TestFailed, "did not test __init__() for None return"
+        raise TestFailed("did not test __init__() for None return")
 
 def methodwrapper():
     # <type 'method-wrapper'> did not support any reflection before 2.5
index d2f9720604a3d2435330e55dd9957f2176fca4b3..8080e412005ee159858e8df41072cd7daec31689 100644 (file)
@@ -313,7 +313,7 @@ Attributes defined by get/set methods
     ...
     ...     def __set__(self, inst, value):
     ...         if self.__set is None:
-    ...             raise AttributeError, "this attribute is read-only"
+    ...             raise AttributeError("this attribute is read-only")
     ...         return self.__set(inst, value)
 
 Now let's define a class with an attribute x defined by a pair of methods,
index ba5d8bd3d3411a2bde9a1be35d3fbdb114fb4ac4..606da46c8bb963a6712d6425836a5e3924eef814 100755 (executable)
@@ -31,4 +31,4 @@ for s, func in sharedlibs:
             print('worked!')
         break
 else:
-    raise TestSkipped, 'Could not open any shared libraries'
+    raise TestSkipped('Could not open any shared libraries')
index 718f7b2783df1c33d2f77df8772062fd12830ab8..ab0e1d09cb7308ed5e824501253775ef8ff530b6 100644 (file)
@@ -811,7 +811,7 @@ Exception messages may contain newlines:
 
     >>> def f(x):
     ...     r'''
-    ...     >>> raise ValueError, 'multi\nline\nmessage'
+    ...     >>> raise ValueError('multi\nline\nmessage')
     ...     Traceback (most recent call last):
     ...     ValueError: multi
     ...     line
@@ -826,7 +826,7 @@ message is raised, then it is reported as a failure:
 
     >>> def f(x):
     ...     r'''
-    ...     >>> raise ValueError, 'message'
+    ...     >>> raise ValueError('message')
     ...     Traceback (most recent call last):
     ...     ValueError: wrong message
     ...     '''
@@ -836,7 +836,7 @@ message is raised, then it is reported as a failure:
     **********************************************************************
     File ..., line 3, in f
     Failed example:
-        raise ValueError, 'message'
+        raise ValueError('message')
     Expected:
         Traceback (most recent call last):
         ValueError: wrong message
@@ -851,7 +851,7 @@ detail:
 
     >>> def f(x):
     ...     r'''
-    ...     >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
+    ...     >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
     ...     Traceback (most recent call last):
     ...     ValueError: wrong message
     ...     '''
@@ -863,7 +863,7 @@ But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
 
     >>> def f(x):
     ...     r'''
-    ...     >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
+    ...     >>> raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
     ...     Traceback (most recent call last):
     ...     TypeError: wrong type
     ...     '''
@@ -873,7 +873,7 @@ But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
     **********************************************************************
     File ..., line 3, in f
     Failed example:
-        raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
+        raise ValueError('message') #doctest: +IGNORE_EXCEPTION_DETAIL
     Expected:
         Traceback (most recent call last):
         TypeError: wrong type
index 8fe75e8fcc43e38ce9aa5be59dcbe1bafa0a952d..5bcb8fce0a8aaa78d17e617b02553fa1eb22462a 100644 (file)
@@ -9,7 +9,7 @@ class ExceptionTestCase(unittest.TestCase):
         hit_finally = False
 
         try:
-            raise Exception, 'nyaa!'
+            raise Exception('nyaa!')
         except:
             hit_except = True
         else:
@@ -44,7 +44,7 @@ class ExceptionTestCase(unittest.TestCase):
         hit_finally = False
 
         try:
-            raise Exception, 'yarr!'
+            raise Exception('yarr!')
         except:
             hit_except = True
         finally:
@@ -71,7 +71,7 @@ class ExceptionTestCase(unittest.TestCase):
         hit_except = False
 
         try:
-            raise Exception, 'ahoy!'
+            raise Exception('ahoy!')
         except:
             hit_except = True
 
@@ -92,7 +92,7 @@ class ExceptionTestCase(unittest.TestCase):
         hit_else = False
 
         try:
-            raise Exception, 'foo!'
+            raise Exception('foo!')
         except:
             hit_except = True
         else:
@@ -132,7 +132,7 @@ class ExceptionTestCase(unittest.TestCase):
 
         try:
             try:
-                raise Exception, 'inner exception'
+                raise Exception('inner exception')
             except:
                 hit_inner_except = True
             finally:
@@ -159,7 +159,7 @@ class ExceptionTestCase(unittest.TestCase):
             else:
                 hit_inner_else = True
 
-            raise Exception, 'outer exception'
+            raise Exception('outer exception')
         except:
             hit_except = True
         else:
index 40ebad0bcf5b7ed14a168927148c9ef1aac90067..56a207af59e8b9ee865fd04e6f5e450da744b483 100644 (file)
@@ -90,7 +90,7 @@ class Nothing:
         if i < 3:
             return i
         else:
-            raise IndexError, i
+            raise IndexError(i)
 g(*Nothing())
 
 class Nothing:
@@ -253,7 +253,7 @@ try:
 except TypeError:
     pass
 else:
-    raise TestFailed, 'expected TypeError; no exception raised'
+    raise TestFailed('expected TypeError; no exception raised')
 
 a, b, d, e, v, k = 'A', 'B', 'D', 'E', 'V', 'K'
 funcs = []
index e64e3989999db11ff170688a9cac621cdd012747..221a14d27354bbff4a9c961444947a84f8599235 100644 (file)
@@ -9,7 +9,7 @@ from test.test_support import TestSkipped, run_unittest, reap_children
 try:
     os.fork
 except AttributeError:
-    raise TestSkipped, "os.fork not defined -- skipping test_fork1"
+    raise TestSkipped("os.fork not defined -- skipping test_fork1")
 
 class ForkTest(ForkWait):
     def wait_impl(self, cpid):
index ade31322c851b8407c4914a1686e0c5cf84af544..4c3d36e59ec8f97f1c96a657e2485e40a9da4d61 100644 (file)
@@ -216,7 +216,7 @@ def test_exc(formatstr, args, exception, excmsg):
         print('Unexpected exception')
         raise
     else:
-        raise TestFailed, 'did not get expected exception: %s' % excmsg
+        raise TestFailed('did not get expected exception: %s' % excmsg)
 
 test_exc('abc %a', 1, ValueError,
          "unsupported format character 'a' (0x61) at index 5")
@@ -241,4 +241,4 @@ if maxsize == 2**31-1:
     except MemoryError:
         pass
     else:
-        raise TestFailed, '"%*d"%(maxsize, -127) should fail'
+        raise TestFailed('"%*d"%(maxsize, -127) should fail')
index 528ca18ad76b96cb6a1d04547a771ca052dc38ca..66ba9cb999743ee4da44de0137e8582e5a02e3f5 100644 (file)
@@ -17,40 +17,40 @@ verify(verify.__module__ == "test.test_support")
 try:
     b.publish
 except AttributeError: pass
-else: raise TestFailed, 'expected AttributeError'
+else: raise TestFailed('expected AttributeError')
 
 if b.__dict__ != {}:
-    raise TestFailed, 'expected unassigned func.__dict__ to be {}'
+    raise TestFailed('expected unassigned func.__dict__ to be {}')
 
 b.publish = 1
 if b.publish != 1:
-    raise TestFailed, 'function attribute not set to expected value'
+    raise TestFailed('function attribute not set to expected value')
 
 docstring = 'its docstring'
 b.__doc__ = docstring
 if b.__doc__ != docstring:
-    raise TestFailed, 'problem with setting __doc__ attribute'
+    raise TestFailed('problem with setting __doc__ attribute')
 
 if 'publish' not in dir(b):
-    raise TestFailed, 'attribute not in dir()'
+    raise TestFailed('attribute not in dir()')
 
 try:
     del b.__dict__
 except TypeError: pass
-else: raise TestFailed, 'del func.__dict__ expected TypeError'
+else: raise TestFailed('del func.__dict__ expected TypeError')
 
 b.publish = 1
 try:
     b.__dict__ = None
 except TypeError: pass
-else: raise TestFailed, 'func.__dict__ = None expected TypeError'
+else: raise TestFailed('func.__dict__ = None expected TypeError')
 
 d = {'hello': 'world'}
 b.__dict__ = d
 if b.__dict__ is not d:
-    raise TestFailed, 'func.__dict__ assignment to dictionary failed'
+    raise TestFailed('func.__dict__ assignment to dictionary failed')
 if b.hello != 'world':
-    raise TestFailed, 'attribute after func.__dict__ assignment failed'
+    raise TestFailed('attribute after func.__dict__ assignment failed')
 
 f1 = F()
 f2 = F()
@@ -58,45 +58,45 @@ f2 = F()
 try:
     F.a.publish
 except AttributeError: pass
-else: raise TestFailed, 'expected AttributeError'
+else: raise TestFailed('expected AttributeError')
 
 try:
     f1.a.publish
 except AttributeError: pass
-else: raise TestFailed, 'expected AttributeError'
+else: raise TestFailed('expected AttributeError')
 
 # In Python 2.1 beta 1, we disallowed setting attributes on unbound methods
 # (it was already disallowed on bound methods).  See the PEP for details.
 try:
     F.a.publish = 1
 except (AttributeError, TypeError): pass
-else: raise TestFailed, 'expected AttributeError or TypeError'
+else: raise TestFailed('expected AttributeError or TypeError')
 
 # But setting it explicitly on the underlying function object is okay.
 F.a.im_func.publish = 1
 
 if F.a.publish != 1:
-    raise TestFailed, 'unbound method attribute not set to expected value'
+    raise TestFailed('unbound method attribute not set to expected value')
 
 if f1.a.publish != 1:
-    raise TestFailed, 'bound method attribute access did not work'
+    raise TestFailed('bound method attribute access did not work')
 
 if f2.a.publish != 1:
-    raise TestFailed, 'bound method attribute access did not work'
+    raise TestFailed('bound method attribute access did not work')
 
 if 'publish' not in dir(F.a):
-    raise TestFailed, 'attribute not in dir()'
+    raise TestFailed('attribute not in dir()')
 
 try:
     f1.a.publish = 0
 except (AttributeError, TypeError): pass
-else: raise TestFailed, 'expected AttributeError or TypeError'
+else: raise TestFailed('expected AttributeError or TypeError')
 
 # See the comment above about the change in semantics for Python 2.1b1
 try:
     F.a.myclass = F
 except (AttributeError, TypeError): pass
-else: raise TestFailed, 'expected AttributeError or TypeError'
+else: raise TestFailed('expected AttributeError or TypeError')
 
 F.a.im_func.myclass = F
 
@@ -107,18 +107,18 @@ F.a.myclass
 
 if f1.a.myclass is not f2.a.myclass or \
        f1.a.myclass is not F.a.myclass:
-    raise TestFailed, 'attributes were not the same'
+    raise TestFailed('attributes were not the same')
 
 # try setting __dict__
 try:
     F.a.__dict__ = (1, 2, 3)
 except (AttributeError, TypeError): pass
-else: raise TestFailed, 'expected TypeError or AttributeError'
+else: raise TestFailed('expected TypeError or AttributeError')
 
 F.a.im_func.__dict__ = {'one': 11, 'two': 22, 'three': 33}
 
 if f1.a.two != 22:
-    raise TestFailed, 'setting __dict__'
+    raise TestFailed('setting __dict__')
 
 from UserDict import UserDict
 d = UserDict({'four': 44, 'five': 55})
@@ -225,13 +225,13 @@ def cantset(obj, name, value, exception=(AttributeError, TypeError)):
     except exception:
         pass
     else:
-        raise TestFailed, "shouldn't be able to set %s to %r" % (name, value)
+        raise TestFailed("shouldn't be able to set %s to %r" % (name, value))
     try:
         delattr(obj, name)
     except (AttributeError, TypeError):
         pass
     else:
-        raise TestFailed, "shouldn't be able to del %s" % name
+        raise TestFailed("shouldn't be able to del %s" % name)
 
 def test_func_closure():
     a = 12
@@ -298,7 +298,7 @@ def test_func_defaults():
     except TypeError:
         pass
     else:
-        raise TestFailed, "shouldn't be allowed to call g() w/o defaults"
+        raise TestFailed("shouldn't be allowed to call g() w/o defaults")
 
 def test_func_dict():
     def f(): pass
index c76b95bc70d60b45ce3ba35abddfadf987912df1..ee6827717e5bda89c95de3bfaf4d03ef1a1b8e75 100755 (executable)
@@ -24,7 +24,7 @@ try:
 except error:
     pass
 else:
-    raise TestFailed, "expected gdbm.error accessing closed database"
+    raise TestFailed("expected gdbm.error accessing closed database")
 g = gdbm.open(filename, 'r')
 g.close()
 g = gdbm.open(filename, 'w')
@@ -37,7 +37,7 @@ try:
 except error:
     pass
 else:
-    raise TestFailed, "expected gdbm.error when passing invalid open flags"
+    raise TestFailed("expected gdbm.error when passing invalid open flags")
 
 try:
     import os
index 18f3fc40b9a118e9da2a9070ec6a12af7186de2d..3108bd6d25a87e2884de661dd09886815374fc36 100644 (file)
@@ -105,7 +105,7 @@ class ImportBlocker:
             return self
         return None
     def load_module(self, fullname):
-        raise ImportError, "I dare you"
+        raise ImportError("I dare you")
 
 
 class ImpWrapper:
index b92c50aad773aba170b83415ea76df52cc026c35..07a3bf2e23ba9736020a04a315ce1eb236fee6a3 100644 (file)
@@ -825,7 +825,7 @@ class TestCase(unittest.TestCase):
             i = state[0]
             state[0] = i+1
             if i == 10:
-                raise AssertionError, "shouldn't have gotten this far"
+                raise AssertionError("shouldn't have gotten this far")
             return i
         b = iter(spam, 5)
         self.assertEqual(list(b), list(range(5)))
index a0933fead30ac671961261627fa383941a4775b1..a54a833bb75b0ec668f24732d68d2e483627ac58 100644 (file)
@@ -44,8 +44,8 @@ else:
     except (IOError, OverflowError):
         f.close()
         os.unlink(test_support.TESTFN)
-        raise test_support.TestSkipped, \
-              "filesystem does not have largefile support"
+        raise test_support.TestSkipped(
+                                "filesystem does not have largefile support")
     else:
         f.close()
 
@@ -56,8 +56,8 @@ def expect(got_this, expect_this):
     if got_this != expect_this:
         if test_support.verbose:
             print('no')
-        raise test_support.TestFailed, 'got %r, but expected %r' %\
-              (got_this, expect_this)
+        raise test_support.TestFailed('got %r, but expected %r'
+                                      % (got_this, expect_this))
     else:
         if test_support.verbose:
             print('yes')
index 2dd6510887e43beb240fc7775b9f04fa76b0b903..1bfb3b33b9b5708d27c7ea576fd45c1c47276a66 100644 (file)
@@ -3,7 +3,8 @@ import locale
 import sys
 
 if sys.platform == 'darwin':
-    raise TestSkipped("Locale support on MacOSX is minimal and cannot be tested")
+    raise TestSkipped(
+            "Locale support on MacOSX is minimal and cannot be tested")
 oldlocale = locale.setlocale(locale.LC_NUMERIC)
 
 if sys.platform.startswith("win"):
@@ -18,20 +19,22 @@ for tloc in tlocs:
     except locale.Error:
         continue
 else:
-    raise ImportError, "test locale not supported (tried %s)"%(', '.join(tlocs))
+    raise ImportError(
+            "test locale not supported (tried %s)" % (', '.join(tlocs)))
 
 def testformat(formatstr, value, grouping = 0, output=None, func=locale.format):
     if verbose:
         if output:
-            print("%s %% %s =? %s ..." %\
-                (repr(formatstr), repr(value), repr(output)), end=' ')
+            print("%s %% %s =? %s ..." %
+                  (repr(formatstr), repr(value), repr(output)), end=' ')
         else:
-            print("%s %% %s works? ..." % (repr(formatstr), repr(value)), end=' ')
+            print("%s %% %s works? ..." % (repr(formatstr), repr(value)),
+                  end=' ')
     result = func(formatstr, value, grouping = grouping)
     if output and result != output:
         if verbose:
             print('no')
-        print("%s %% %s == %s != %s" %\
+        print("%s %% %s == %s != %s" %
               (repr(formatstr), repr(value), repr(result), repr(output)))
     else:
         if verbose:
index 1073cdd67823eb082bfdf43aa01a1e706a3356a0..127cf84442baa4af564cbc5a137c474ddc3aa101 100644 (file)
@@ -595,7 +595,7 @@ def test_main_inner():
         else:
             break
     else:
-        raise ImportError, "Could not find unused port"
+        raise ImportError("Could not find unused port")
 
 
     #Set up a handler such that all events are sent via a socket to the log
index cc9e907987389ae040a99f63ee997c2ba90c15e6..f9354967ab50be3339f98e71d754daed4dad4a32 100644 (file)
@@ -4,7 +4,7 @@ import os, unittest
 from test.test_support import run_unittest, TestSkipped
 
 if not hasattr(os, "openpty"):
-    raise TestSkipped, "No openpty() available."
+    raise TestSkipped("No openpty() available.")
 
 
 class OpenptyTest(unittest.TestCase):
index 5574c7dce13b37b87cc915a1ab6158aec3a860a1..794de0dae221b2c28ed2a5277e77837f4f8e7cf3 100644 (file)
@@ -3,7 +3,7 @@
 import sys, os, unittest
 from test import test_support
 if not os.path.supports_unicode_filenames:
-    raise test_support.TestSkipped, "test works only on NT+"
+    raise test_support.TestSkipped("test works only on NT+")
 
 filenames = [
     'abc',
index 574d1db257194fe2caefe5a93ae45d90ada8ebb3..316ea832a51deadef3a045430c2e160f243f67c5 100644 (file)
@@ -51,7 +51,7 @@ class TestImport(unittest.TestCase):
         self.rewrite_file('for')
         try: __import__(self.module_name)
         except SyntaxError: pass
-        else: raise RuntimeError, 'Failed to induce SyntaxError'
+        else: raise RuntimeError('Failed to induce SyntaxError')
         self.assert_(self.module_name not in sys.modules and
                      not hasattr(sys.modules[self.package_name], 'foo'))
 
@@ -65,7 +65,7 @@ class TestImport(unittest.TestCase):
 
         try: __import__(self.module_name)
         except NameError: pass
-        else: raise RuntimeError, 'Failed to induce NameError.'
+        else: raise RuntimeError('Failed to induce NameError.')
 
         # ...now  change  the module  so  that  the NameError  doesn't
         # happen
index 4801640d3e89bf73df8b5ff97937a7b14ef4d1b2..a6110e623f25e0289662e9861cc07c6e18e06956 100644 (file)
@@ -6,7 +6,7 @@ from test.test_support import TestSkipped, TESTFN, run_unittest
 try:
     select.poll
 except AttributeError:
-    raise TestSkipped, "select.poll not defined -- skipping test_poll"
+    raise TestSkipped("select.poll not defined -- skipping test_poll")
 
 
 def find_ready_matching(ready, flag):
@@ -47,14 +47,14 @@ class PollTests(unittest.TestCase):
             ready = p.poll()
             ready_writers = find_ready_matching(ready, select.POLLOUT)
             if not ready_writers:
-                raise RuntimeError, "no pipes ready for writing"
+                raise RuntimeError("no pipes ready for writing")
             wr = random.choice(ready_writers)
             os.write(wr, MSG)
 
             ready = p.poll()
             ready_readers = find_ready_matching(ready, select.POLLIN)
             if not ready_readers:
-                raise RuntimeError, "no pipes ready for reading"
+                raise RuntimeError("no pipes ready for reading")
             rd = random.choice(ready_readers)
             buf = os.read(rd, MSG_LEN)
             self.assertEqual(len(buf), MSG_LEN)
index 7207de54eafa57f4f1f49cc8c137c19eeddd9741..22ec748ead4d3de6c9df86b45df566857563dae8 100644 (file)
@@ -5,7 +5,7 @@ from test import test_support
 try:
     import posix
 except ImportError:
-    raise test_support.TestSkipped, "posix is not available"
+    raise test_support.TestSkipped("posix is not available")
 
 import time
 import os
index bfabc2aa5f6ae917d9276dc66acb39eece94b706..e2058abcf22065f7d6fefe3b806af19efd4ad721 100644 (file)
@@ -69,7 +69,7 @@ class PtyTest(unittest.TestCase):
             debug("Got slave_fd '%d'" % slave_fd)
         except OSError:
             # " An optional feature could not be imported " ... ?
-            raise TestSkipped, "Pseudo-terminals (seemingly) not functional."
+            raise TestSkipped("Pseudo-terminals (seemingly) not functional.")
 
         self.assertTrue(os.isatty(slave_fd), 'slave_fd is not a tty')
 
index bfa5596cbb3c0e5a8cb62230d2d49f246836d48e..0b2f31a209818299dc4b511a5c579053b3079e57 100644 (file)
@@ -87,17 +87,17 @@ class FailingQueue(Queue.Queue):
     def _put(self, item):
         if self.fail_next_put:
             self.fail_next_put = False
-            raise FailingQueueException, "You Lose"
+            raise FailingQueueException("You Lose")
         return Queue.Queue._put(self, item)
     def _get(self):
         if self.fail_next_get:
             self.fail_next_get = False
-            raise FailingQueueException, "You Lose"
+            raise FailingQueueException("You Lose")
         return Queue.Queue._get(self)
 
 def FailingQueueTest(q):
     if not q.empty():
-        raise RuntimeError, "Call this function with an empty queue"
+        raise RuntimeError("Call this function with an empty queue")
     for i in range(QUEUE_SIZE-1):
         q.put(i)
     # Test a failing non-blocking put.
@@ -178,7 +178,7 @@ def FailingQueueTest(q):
 
 def SimpleQueueTest(q):
     if not q.empty():
-        raise RuntimeError, "Call this function with an empty queue"
+        raise RuntimeError("Call this function with an empty queue")
     # I guess we better check things actually queue correctly a little :)
     q.put(111)
     q.put(222)
index f166188fb48c389d3c76bb40eea1e112d6a8ef3b..3b1f7c6180f1b114f22049af392ad049c593722a 100644 (file)
@@ -612,7 +612,7 @@ def run_re_tests():
         elif len(t) == 3:
             pattern, s, outcome = t
         else:
-            raise ValueError('Test tuples should have 3 or 5 fields', t)
+            raise ValueError('Test tuples should have 3 or 5 fields', t)
 
         try:
             obj = re.compile(pattern)
index 180440e4c3142f1e8562c1cdb669f5333785b34c..efe69239894000b9201364f35532191b79f80b53 100644 (file)
@@ -29,7 +29,7 @@ class Number:
         return self.x >= other
 
     def __cmp__(self, other):
-        raise test_support.TestFailed, "Number.__cmp__() should not be called"
+        raise test_support.TestFailed("Number.__cmp__() should not be called")
 
     def __repr__(self):
         return "Number(%r)" % (self.x, )
@@ -49,13 +49,13 @@ class Vector:
         self.data[i] = v
 
     def __hash__(self):
-        raise TypeError, "Vectors cannot be hashed"
+        raise TypeError("Vectors cannot be hashed")
 
     def __bool__(self):
-        raise TypeError, "Vectors cannot be used in Boolean contexts"
+        raise TypeError("Vectors cannot be used in Boolean contexts")
 
     def __cmp__(self, other):
-        raise test_support.TestFailed, "Vector.__cmp__() should not be called"
+        raise test_support.TestFailed("Vector.__cmp__() should not be called")
 
     def __repr__(self):
         return "Vector(%r)" % (self.data, )
@@ -82,7 +82,7 @@ class Vector:
         if isinstance(other, Vector):
             other = other.data
         if len(self.data) != len(other):
-            raise ValueError, "Cannot compare vectors of different length"
+            raise ValueError("Cannot compare vectors of different length")
         return other
 
 opmap = {
@@ -196,10 +196,10 @@ class MiscTest(unittest.TestCase):
             def __lt__(self, other): return 0
             def __gt__(self, other): return 0
             def __eq__(self, other): return 0
-            def __le__(self, other): raise TestFailed, "This shouldn't happen"
-            def __ge__(self, other): raise TestFailed, "This shouldn't happen"
-            def __ne__(self, other): raise TestFailed, "This shouldn't happen"
-            def __cmp__(self, other): raise RuntimeError, "expected"
+            def __le__(self, other): raise TestFailed("This shouldn't happen")
+            def __ge__(self, other): raise TestFailed("This shouldn't happen")
+            def __ne__(self, other): raise TestFailed("This shouldn't happen")
+            def __cmp__(self, other): raise RuntimeError("expected")
         a = Misb()
         b = Misb()
         self.assertEqual(a<b, 0)
index 567053b1b31859b203a40f82ad2d3ece976850b6..22f254a321e57deac5ee0425d18597edb0c501df 100644 (file)
@@ -177,7 +177,7 @@ class ScopeTests(unittest.TestCase):
             if x >= 0:
                 return fact(x)
             else:
-                raise ValueError, "x must be >= 0"
+                raise ValueError("x must be >= 0")
 
         self.assertEqual(f(6), 720)
 
index e955bffa320435629459bd69ffd0408f38b2ebc9..36f148eaea106b5f184f748a7e40f29cb6446356 100644 (file)
@@ -125,7 +125,7 @@ class ThreadableTest:
         self.client_ready.set()
         self.clientSetUp()
         if not hasattr(test_func, '__call__'):
-            raise TypeError, "test_func must be a callable function"
+            raise TypeError("test_func must be a callable function")
         try:
             test_func()
         except Exception as strerror:
@@ -133,7 +133,7 @@ class ThreadableTest:
         self.clientTearDown()
 
     def clientSetUp(self):
-        raise NotImplementedError, "clientSetUp must be implemented."
+        raise NotImplementedError("clientSetUp must be implemented.")
 
     def clientTearDown(self):
         self.done.set()
index 0abd7ba7b71029d900bd5001ce0b80e4a3080be9..3e0c7a47d8e7721f76b5355a10aa9b1b0c392a74 100644 (file)
@@ -45,7 +45,7 @@ def receive(sock, n, timeout=20):
     if sock in r:
         return sock.recv(n)
     else:
-        raise RuntimeError, "timed out on %r" % (sock,)
+        raise RuntimeError("timed out on %r" % (sock,))
 
 def testdgram(proto, addr):
     s = socket.socket(proto, socket.SOCK_DGRAM)
index d3b78570a1f6b9e2da32f9077ac3fc8e8c71daea..c7019a4a7252efa00b1704ad612c3977b3bbc2d3 100644 (file)
@@ -36,8 +36,8 @@ def simple_err(func, *args):
     except struct.error:
         pass
     else:
-        raise TestFailed"%s%s did not raise struct.error" % (
-            func.__name__, args)
+        raise TestFailed("%s%s did not raise struct.error" % (
+            func.__name__, args))
 
 def any_err(func, *args):
     try:
@@ -45,8 +45,8 @@ def any_err(func, *args):
     except (struct.error, TypeError):
         pass
     else:
-        raise TestFailed"%s%s did not raise error" % (
-            func.__name__, args)
+        raise TestFailed("%s%s did not raise error" % (
+            func.__name__, args))
 
 def with_warning_restore(func):
     def _with_warning_restore(*args, **kw):
@@ -70,11 +70,11 @@ def deprecated_err(func, *args):
         pass
     except DeprecationWarning:
         if not PY_STRUCT_OVERFLOW_MASKING:
-            raise TestFailed"%s%s expected to raise struct.error" % (
-                func.__name__, args)
+            raise TestFailed("%s%s expected to raise struct.error" % (
+                func.__name__, args))
     else:
-        raise TestFailed"%s%s did not raise error" % (
-            func.__name__, args)
+        raise TestFailed("%s%s did not raise error" % (
+            func.__name__, args))
 deprecated_err = with_warning_restore(deprecated_err)
 
 
@@ -82,15 +82,15 @@ simple_err(struct.calcsize, 'Z')
 
 sz = struct.calcsize('i')
 if sz * 3 != struct.calcsize('iii'):
-    raise TestFailed, 'inconsistent sizes'
+    raise TestFailed('inconsistent sizes')
 
 fmt = 'cbxxxxxxhhhhiillffdt'
 fmt3 = '3c3b18x12h6i6l6f3d3t'
 sz = struct.calcsize(fmt)
 sz3 = struct.calcsize(fmt3)
 if sz * 3 != sz3:
-    raise TestFailed'inconsistent sizes (3*%r -> 3*%d = %d, %r -> %d)' % (
-        fmt, sz, 3*sz, fmt3, sz3)
+    raise TestFailed('inconsistent sizes (3*%r -> 3*%d = %d, %r -> %d)' % (
+        fmt, sz, 3*sz, fmt3, sz3))
 
 simple_err(struct.pack, 'iii', 3)
 simple_err(struct.pack, 'i', 3, 3, 3)
@@ -121,8 +121,8 @@ for prefix in ('', '@', '<', '>', '=', '!'):
             int(100 * fp) != int(100 * f) or int(100 * dp) != int(100 * d) or
                         tp != t):
             # ^^^ calculate only to two decimal places
-            raise TestFailed"unpack/pack not transitive (%s, %s)" % (
-                str(format), str((cp, bp, hp, ip, lp, fp, dp, tp)))
+            raise TestFailed("unpack/pack not transitive (%s, %s)" % (
+                str(format), str((cp, bp, hp, ip, lp, fp, dp, tp))))
 
 # Test some of the new features in detail
 
@@ -176,16 +176,16 @@ for fmt, arg, big, lil, asy in tests:
                         ('='+fmt, ISBIGENDIAN and big or lil)]:
         res = struct.pack(xfmt, arg)
         if res != exp:
-            raise TestFailed"pack(%r, %r) -> %r # expected %r" % (
-                fmt, arg, res, exp)
+            raise TestFailed("pack(%r, %r) -> %r # expected %r" % (
+                fmt, arg, res, exp))
         n = struct.calcsize(xfmt)
         if n != len(res):
-            raise TestFailed"calcsize(%r) -> %d # expected %d" % (
-                xfmt, n, len(res))
+            raise TestFailed("calcsize(%r) -> %d # expected %d" % (
+                xfmt, n, len(res)))
         rev = struct.unpack(xfmt, res)[0]
         if rev != arg and not asy:
-            raise TestFailed"unpack(%r, %r) -> (%r,) # expected (%r,)" % (
-                fmt, res, rev, arg)
+            raise TestFailed("unpack(%r, %r) -> (%r,) # expected (%r,)" % (
+                fmt, res, rev, arg))
 
 ###########################################################################
 # Simple native q/Q tests.
index 57057986c9a9b0776b1dd656bd8d23d6c6c798c5..577d4cbc9ac8db60a9b5b29824a470e6a8373405 100644 (file)
@@ -108,7 +108,7 @@ def task2(ident):
 
 print('\n*** Barrier Test ***')
 if done.acquire(0):
-    raise ValueError, "'done' should have remained acquired"
+    raise ValueError("'done' should have remained acquired")
 bar = barrier(numtasks)
 running = numtasks
 for i in range(numtasks):
@@ -119,11 +119,11 @@ print('all tasks done')
 # not all platforms support changing thread stack size
 print('\n*** Changing thread stack size ***')
 if thread.stack_size() != 0:
-    raise ValueError, "initial stack_size not 0"
+    raise ValueError("initial stack_size not 0")
 
 thread.stack_size(0)
 if thread.stack_size() != 0:
-    raise ValueError, "stack_size not reset to default"
+    raise ValueError("stack_size not reset to default")
 
 from os import name as os_name
 if os_name in ("nt", "os2", "posix"):
@@ -143,7 +143,7 @@ if os_name in ("nt", "os2", "posix"):
         for tss in (262144, 0x100000, 0):
             thread.stack_size(tss)
             if failed(thread.stack_size(), tss):
-                raise ValueError, fail_msg % tss
+                raise ValueError(fail_msg % tss)
             print('successfully set stack_size(%d)' % tss)
 
         for tss in (262144, 0x100000):
index 9f076efb5c947d69511847679a1bc2aac6294cda..2f014e146ba2c5d7fe424d3e2ac88394d5af9a4d 100644 (file)
@@ -8,7 +8,7 @@ import sys
 from test.test_support import run_unittest, TestSkipped
 
 if sys.platform[:3] in ('win', 'os2'):
-    raise TestSkipped, "Can't test signal on %s" % sys.platform
+    raise TestSkipped("Can't test signal on %s" % sys.platform)
 
 process_pid = os.getpid()
 signalled_all=thread.allocate_lock()
index 05e6e9e3968b1a5f5d6d5d0bea0dfdf0788d76c3..f67da770aa098f23968579635a9ee42b6573a6e2 100644 (file)
@@ -314,7 +314,7 @@ class RaisingTraceFuncTestCase(unittest.TestCase):
         def g(frame, why, extra):
             if (why == 'line' and
                 frame.f_lineno == f.__code__.co_firstlineno + 2):
-                raise RuntimeError, "i am crashing"
+                raise RuntimeError("i am crashing")
             return g
 
         sys.settrace(g)
@@ -558,7 +558,7 @@ def no_jump_without_trace_function():
             raise
     else:
         # Something's wrong - the expected exception wasn't raised.
-        raise RuntimeError, "Trace-function-less jump failed to fail"
+        raise RuntimeError("Trace-function-less jump failed to fail")
 
 
 class JumpTestCase(unittest.TestCase):
index 84d7290b7488e7525e2adb85d14450825c41690c..36ea06782f0128ca170ad5cc65ffc4e38b8956b4 100644 (file)
@@ -15,7 +15,7 @@ class TracebackCases(unittest.TestCase):
         except exc as value:
             return traceback.format_exception_only(exc, value)
         else:
-            raise ValueError, "call did not raise exception"
+            raise ValueError("call did not raise exception")
 
     def syntax_error_with_caret(self):
         compile("def fact(x):\n\treturn x!\n", "?", "exec")
index efa4ad11251f8f105daee79e7ccfcc9c1a688ea7..ef118df8ee1ae57e65ca781634bb461ce7a65ba6 100644 (file)
@@ -25,7 +25,7 @@ if TESTFN_ENCODED.decode(TESTFN_ENCODING) != TESTFN_UNICODE:
         TESTFN_ENCODED = TESTFN_UNICODE.encode(TESTFN_ENCODING)
         if '?' in TESTFN_ENCODED:
             # MBCS will not report the error properly
-            raise UnicodeError, "mbcs encoding problem"
+            raise UnicodeError("mbcs encoding problem")
     except (UnicodeError, TypeError):
         raise TestSkipped("Cannot find a suitable filename")
 
index 4ca1a27e76ff44864338c9e3d6d0533054e75763..22fd26633e33b113bac0629217c9abac7c469777 100644 (file)
@@ -5,8 +5,8 @@ import sys
 from test import test_support
 
 if not hasattr(sys.stdin, 'newlines'):
-    raise test_support.TestSkipped, \
-        "This Python does not have universal newline support"
+    raise test_support.TestSkipped(
+                       "This Python does not have universal newline support")
 
 FATX = 'x' * (2**14)
 
index 9de64b21ea328eb34c1daf754c3dac0b27f852ab..3adbec4abc33ffbc54d98531725dab73356d29ac 100644 (file)
@@ -9,12 +9,12 @@ from test.test_support import TestSkipped, run_unittest, reap_children
 try:
     os.fork
 except AttributeError:
-    raise TestSkipped, "os.fork not defined -- skipping test_wait3"
+    raise TestSkipped("os.fork not defined -- skipping test_wait3")
 
 try:
     os.wait3
 except AttributeError:
-    raise TestSkipped, "os.wait3 not defined -- skipping test_wait3"
+    raise TestSkipped("os.wait3 not defined -- skipping test_wait3")
 
 class Wait3Test(ForkWait):
     def wait_impl(self, cpid):
index 9f7fc14a64af3cb95315874ea58d2499dde3b23a..c85944d06a18c3eeac06349578825d28893cb9b1 100644 (file)
@@ -9,12 +9,12 @@ from test.test_support import TestSkipped, run_unittest, reap_children
 try:
     os.fork
 except AttributeError:
-    raise TestSkipped, "os.fork not defined -- skipping test_wait4"
+    raise TestSkipped("os.fork not defined -- skipping test_wait4")
 
 try:
     os.wait4
 except AttributeError:
-    raise TestSkipped, "os.wait4 not defined -- skipping test_wait4"
+    raise TestSkipped("os.wait4 not defined -- skipping test_wait4")
 
 class Wait4Test(ForkWait):
     def wait_impl(self, cpid):
index 85f55669b8a114070761fe32744b85a8d5d00424..271f0a893edd16fa4b620222fdc656ffff2af858 100644 (file)
@@ -4,7 +4,7 @@ import wave
 
 def check(t, msg=None):
     if not t:
-        raise TestFailed, msg
+        raise TestFailed(msg)
 
 nchannels = 2
 sampwidth = 2
index df12f83d9743214758a553f3bd6183d104c13de4..d9394630638d7186b09a151c76715fd249ae06aa 100644 (file)
@@ -6,7 +6,7 @@ import hashlib
 
 
 def creatorFunc():
-    raise RuntimeError, "eek, creatorFunc not overridden"
+    raise RuntimeError("eek, creatorFunc not overridden")
 
 def test_scaled_msg(scale, name):
     iterations = 106201/scale * 20