Commit 3efafd77 authored by Ezio Melotti's avatar Ezio Melotti

Merged revisions 77942,79023 via svnmerge from

svn+ssh://pythondev@svn.python.org/python/trunk

........
  r77942 | ezio.melotti | 2010-02-03 07:37:26 +0200 (Wed, 03 Feb 2010) | 1 line

  #7092: Silence more py3k warnings. Patch by Florent Xicluna.
........
  r79023 | ezio.melotti | 2010-03-17 15:52:48 +0200 (Wed, 17 Mar 2010) | 1 line

  #7092: silence some more py3k warnings.
........
parent 5ff2745f
...@@ -24,7 +24,7 @@ class memoryview(object): ...@@ -24,7 +24,7 @@ class memoryview(object):
else: else:
size = sizeof(ob) size = sizeof(ob)
for dim in self.shape: for dim in self.shape:
size /= dim size //= dim
self.itemsize = size self.itemsize = size
self.strides = None self.strides = None
self.readonly = False self.readonly = False
......
...@@ -367,11 +367,11 @@ class StructureTestCase(unittest.TestCase): ...@@ -367,11 +367,11 @@ class StructureTestCase(unittest.TestCase):
_fields_ = [("d", c_int), ("e", c_int), ("f", c_int)] _fields_ = [("d", c_int), ("e", c_int), ("f", c_int)]
z = Z(1, 2, 3, 4, 5, 6) z = Z(1, 2, 3, 4, 5, 6)
self.failUnlessEqual((z.a, z.b, z.c, z.d, z.e, z.f), self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f),
(1, 2, 3, 4, 5, 6)) (1, 2, 3, 4, 5, 6))
z = Z(1) z = Z(1)
self.failUnlessEqual((z.a, z.b, z.c, z.d, z.e, z.f), self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f),
(1, 0, 0, 0, 0, 0)) (1, 0, 0, 0, 0, 0))
self.assertRaises(TypeError, lambda: Z(1, 2, 3, 4, 5, 6, 7)) self.assertRaises(TypeError, lambda: Z(1, 2, 3, 4, 5, 6, 7))
class PointerMemberTestCase(unittest.TestCase): class PointerMemberTestCase(unittest.TestCase):
......
...@@ -1086,7 +1086,7 @@ This is the dingus fish. ...@@ -1086,7 +1086,7 @@ This is the dingus fish.
sign = '-' sign = '-'
else: else:
sign = '+' sign = '+'
tzoffset = ' %s%04d' % (sign, tzsecs / 36) tzoffset = ' %s%04d' % (sign, tzsecs // 36)
container['Date'] = time.strftime( container['Date'] = time.strftime(
'%a, %d %b %Y %H:%M:%S', '%a, %d %b %Y %H:%M:%S',
time.localtime(now)) + tzoffset time.localtime(now)) + tzoffset
......
...@@ -1044,7 +1044,7 @@ This is the dingus fish. ...@@ -1044,7 +1044,7 @@ This is the dingus fish.
sign = '-' sign = '-'
else: else:
sign = '+' sign = '+'
tzoffset = ' %s%04d' % (sign, tzsecs / 36) tzoffset = ' %s%04d' % (sign, tzsecs // 36)
container['Date'] = time.strftime( container['Date'] = time.strftime(
'%a, %d %b %Y %H:%M:%S', '%a, %d %b %Y %H:%M:%S',
time.localtime(now)) + tzoffset time.localtime(now)) + tzoffset
......
...@@ -226,7 +226,7 @@ class ColNamesTests(unittest.TestCase): ...@@ -226,7 +226,7 @@ class ColNamesTests(unittest.TestCase):
sqlite.converters["FOO"] = lambda x: "[%s]" % x sqlite.converters["FOO"] = lambda x: "[%s]" % x
sqlite.converters["BAR"] = lambda x: "<%s>" % x sqlite.converters["BAR"] = lambda x: "<%s>" % x
sqlite.converters["EXC"] = lambda x: 5/0 sqlite.converters["EXC"] = lambda x: 5 // 0
sqlite.converters["B1B1"] = lambda x: "MARKER" sqlite.converters["B1B1"] = lambda x: "MARKER"
def tearDown(self): def tearDown(self):
......
...@@ -38,7 +38,7 @@ def func_returnnull(): ...@@ -38,7 +38,7 @@ def func_returnnull():
def func_returnblob(): def func_returnblob():
return buffer("blob") return buffer("blob")
def func_raiseexception(): def func_raiseexception():
5/0 5 // 0
def func_isstring(v): def func_isstring(v):
return type(v) is unicode return type(v) is unicode
...@@ -67,7 +67,7 @@ class AggrNoFinalize: ...@@ -67,7 +67,7 @@ class AggrNoFinalize:
class AggrExceptionInInit: class AggrExceptionInInit:
def __init__(self): def __init__(self):
5/0 5 // 0
def step(self, x): def step(self, x):
pass pass
...@@ -80,7 +80,7 @@ class AggrExceptionInStep: ...@@ -80,7 +80,7 @@ class AggrExceptionInStep:
pass pass
def step(self, x): def step(self, x):
5/0 5 // 0
def finalize(self): def finalize(self):
return 42 return 42
...@@ -93,7 +93,7 @@ class AggrExceptionInFinalize: ...@@ -93,7 +93,7 @@ class AggrExceptionInFinalize:
pass pass
def finalize(self): def finalize(self):
5/0 5 // 0
class AggrCheckType: class AggrCheckType:
def __init__(self): def __init__(self):
......
...@@ -3,5 +3,6 @@ ...@@ -3,5 +3,6 @@
# reload()ing. This module is imported by test_import.py:test_infinite_reload # reload()ing. This module is imported by test_import.py:test_infinite_reload
# to make sure this doesn't happen any more. # to make sure this doesn't happen any more.
import imp
import infinite_reload import infinite_reload
reload(infinite_reload) imp.reload(infinite_reload)
...@@ -15,7 +15,7 @@ def eggs(x, y): ...@@ -15,7 +15,7 @@ def eggs(x, y):
fr = inspect.currentframe() fr = inspect.currentframe()
st = inspect.stack() st = inspect.stack()
p = x p = x
q = y / 0 q = y // 0
# line 20 # line 20
class StupidGit: class StupidGit:
......
...@@ -133,6 +133,7 @@ import warnings ...@@ -133,6 +133,7 @@ import warnings
# keep a reference to the ascii module to workaround #7140 bug # keep a reference to the ascii module to workaround #7140 bug
# (see issue #7027) # (see issue #7027)
import encodings.ascii import encodings.ascii
import imp
# I see no other way to suppress these warnings; # I see no other way to suppress these warnings;
# putting them in test_grammar.py has no effect: # putting them in test_grammar.py has no effect:
...@@ -657,7 +658,7 @@ def dash_R(the_module, test, indirect_test, huntrleaks): ...@@ -657,7 +658,7 @@ def dash_R(the_module, test, indirect_test, huntrleaks):
indirect_test() indirect_test()
else: else:
def run_the_test(): def run_the_test():
reload(the_module) imp.reload(the_module)
deltas = [] deltas = []
nwarmup, ntracked, fname = huntrleaks nwarmup, ntracked, fname = huntrleaks
......
...@@ -207,6 +207,9 @@ class Rat(object): ...@@ -207,6 +207,9 @@ class Rat(object):
"""Compare two Rats for inequality.""" """Compare two Rats for inequality."""
return not self == other return not self == other
# Silence Py3k warning
__hash__ = None
class RatTestCase(unittest.TestCase): class RatTestCase(unittest.TestCase):
"""Unit tests for Rat class and its support utilities.""" """Unit tests for Rat class and its support utilities."""
......
...@@ -75,7 +75,7 @@ class CompilerTest(unittest.TestCase): ...@@ -75,7 +75,7 @@ class CompilerTest(unittest.TestCase):
def testTryExceptFinally(self): def testTryExceptFinally(self):
# Test that except and finally clauses in one try stmt are recognized # Test that except and finally clauses in one try stmt are recognized
c = compiler.compile("try:\n 1/0\nexcept:\n e = 1\nfinally:\n f = 1", c = compiler.compile("try:\n 1//0\nexcept:\n e = 1\nfinally:\n f = 1",
"<string>", "exec") "<string>", "exec")
dct = {} dct = {}
exec c in dct exec c in dct
......
...@@ -66,7 +66,7 @@ dictionaries, such as the locals/globals dictionaries for the exec ...@@ -66,7 +66,7 @@ dictionaries, such as the locals/globals dictionaries for the exec
statement or the built-in function eval(): statement or the built-in function eval():
>>> def sorted(seq): >>> def sorted(seq):
... seq.sort() ... seq.sort(key=str)
... return seq ... return seq
>>> print sorted(a.keys()) >>> print sorted(a.keys())
[1, 2] [1, 2]
......
...@@ -582,11 +582,14 @@ class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol): ...@@ -582,11 +582,14 @@ class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol):
type2test = Dict type2test = Dict
def test_main(): def test_main():
test_support.run_unittest( with test_support._check_py3k_warnings(
DictTest, ('dict(.has_key..| inequality comparisons) not supported in 3.x',
GeneralMappingTests, DeprecationWarning)):
SubclassMappingTests, test_support.run_unittest(
) DictTest,
GeneralMappingTests,
SubclassMappingTests,
)
if __name__ == "__main__": if __name__ == "__main__":
test_main() test_main()
...@@ -118,7 +118,7 @@ class AutoFileTests(unittest.TestCase): ...@@ -118,7 +118,7 @@ class AutoFileTests(unittest.TestCase):
self.assertEquals(self.f.__exit__(None, None, None), None) self.assertEquals(self.f.__exit__(None, None, None), None)
# it must also return None if an exception was given # it must also return None if an exception was given
try: try:
1/0 1 // 0
except: except:
self.assertEquals(self.f.__exit__(*sys.exc_info()), None) self.assertEquals(self.f.__exit__(*sys.exc_info()), None)
......
...@@ -90,7 +90,8 @@ class DummyFTPHandler(asynchat.async_chat): ...@@ -90,7 +90,8 @@ class DummyFTPHandler(asynchat.async_chat):
sock.listen(5) sock.listen(5)
sock.settimeout(2) sock.settimeout(2)
ip, port = sock.getsockname()[:2] ip, port = sock.getsockname()[:2]
ip = ip.replace('.', ','); p1 = port / 256; p2 = port % 256 ip = ip.replace('.', ',')
p1, p2 = divmod(port, 256)
self.push('227 entering passive mode (%s,%d,%d)' %(ip, p1, p2)) self.push('227 entering passive mode (%s,%d,%d)' %(ip, p1, p2))
conn, addr = sock.accept() conn, addr = sock.accept()
self.dtp = DummyDTPHandler(conn, baseclass=self) self.dtp = DummyDTPHandler(conn, baseclass=self)
......
...@@ -119,7 +119,7 @@ class TestPartial(unittest.TestCase): ...@@ -119,7 +119,7 @@ class TestPartial(unittest.TestCase):
def test_error_propagation(self): def test_error_propagation(self):
def f(x, y): def f(x, y):
x / y x // y
self.assertRaises(ZeroDivisionError, self.thetype(f, 1, 0)) self.assertRaises(ZeroDivisionError, self.thetype(f, 1, 0))
self.assertRaises(ZeroDivisionError, self.thetype(f, 1), 0) self.assertRaises(ZeroDivisionError, self.thetype(f, 1), 0)
self.assertRaises(ZeroDivisionError, self.thetype(f), 1, 0) self.assertRaises(ZeroDivisionError, self.thetype(f), 1, 0)
......
...@@ -8,7 +8,8 @@ ...@@ -8,7 +8,8 @@
# regression test, the filterwarnings() call has been added to # regression test, the filterwarnings() call has been added to
# regrtest.py. # regrtest.py.
from test.test_support import run_unittest, check_syntax_error from test.test_support import (run_unittest, check_syntax_error,
_check_py3k_warnings)
import unittest import unittest
import sys import sys
# testing import * # testing import *
...@@ -152,8 +153,9 @@ class GrammarTests(unittest.TestCase): ...@@ -152,8 +153,9 @@ class GrammarTests(unittest.TestCase):
f1(*(), **{}) f1(*(), **{})
def f2(one_argument): pass def f2(one_argument): pass
def f3(two, arguments): pass def f3(two, arguments): pass
def f4(two, (compound, (argument, list))): pass # Silence Py3k warning
def f5((compound, first), two): pass exec('def f4(two, (compound, (argument, list))): pass')
exec('def f5((compound, first), two): pass')
self.assertEquals(f2.func_code.co_varnames, ('one_argument',)) self.assertEquals(f2.func_code.co_varnames, ('one_argument',))
self.assertEquals(f3.func_code.co_varnames, ('two', 'arguments')) self.assertEquals(f3.func_code.co_varnames, ('two', 'arguments'))
if sys.platform.startswith('java'): if sys.platform.startswith('java'):
...@@ -172,7 +174,8 @@ class GrammarTests(unittest.TestCase): ...@@ -172,7 +174,8 @@ class GrammarTests(unittest.TestCase):
def v0(*rest): pass def v0(*rest): pass
def v1(a, *rest): pass def v1(a, *rest): pass
def v2(a, b, *rest): pass def v2(a, b, *rest): pass
def v3(a, (b, c), *rest): return a, b, c, rest # Silence Py3k warning
exec('def v3(a, (b, c), *rest): return a, b, c, rest')
f1() f1()
f2(1) f2(1)
...@@ -277,9 +280,10 @@ class GrammarTests(unittest.TestCase): ...@@ -277,9 +280,10 @@ class GrammarTests(unittest.TestCase):
d22v(*(1, 2, 3, 4)) d22v(*(1, 2, 3, 4))
d22v(1, 2, *(3, 4, 5)) d22v(1, 2, *(3, 4, 5))
d22v(1, *(2, 3), **{'d': 4}) d22v(1, *(2, 3), **{'d': 4})
def d31v((x)): pass # Silence Py3k warning
exec('def d31v((x)): pass')
exec('def d32v((x,)): pass')
d31v(1) d31v(1)
def d32v((x,)): pass
d32v((1,)) d32v((1,))
# keyword arguments after *arglist # keyword arguments after *arglist
...@@ -474,7 +478,7 @@ hello world ...@@ -474,7 +478,7 @@ hello world
continue continue
except: except:
raise raise
if count > 2 or big_hippo <> 1: if count > 2 or big_hippo != 1:
self.fail("continue then break in try/except in loop broken!") self.fail("continue then break in try/except in loop broken!")
test_inner() test_inner()
...@@ -536,7 +540,7 @@ hello world ...@@ -536,7 +540,7 @@ hello world
if z != 2: self.fail('exec u\'z=1+1\'')""" if z != 2: self.fail('exec u\'z=1+1\'')"""
g = {} g = {}
exec 'z = 1' in g exec 'z = 1' in g
if g.has_key('__builtins__'): del g['__builtins__'] if '__builtins__' in g: del g['__builtins__']
if g != {'z': 1}: self.fail('exec \'z = 1\' in g') if g != {'z': 1}: self.fail('exec \'z = 1\' in g')
g = {} g = {}
l = {} l = {}
...@@ -544,8 +548,8 @@ hello world ...@@ -544,8 +548,8 @@ hello world
import warnings import warnings
warnings.filterwarnings("ignore", "global statement", module="<string>") warnings.filterwarnings("ignore", "global statement", module="<string>")
exec 'global a; a = 1; b = 2' in g, l exec 'global a; a = 1; b = 2' in g, l
if g.has_key('__builtins__'): del g['__builtins__'] if '__builtins__' in g: del g['__builtins__']
if l.has_key('__builtins__'): del l['__builtins__'] if '__builtins__' in l: del l['__builtins__']
if (g, l) != ({'a':1}, {'b':2}): if (g, l) != ({'a':1}, {'b':2}):
self.fail('exec ... in g (%s), l (%s)' %(g,l)) self.fail('exec ... in g (%s), l (%s)' %(g,l))
...@@ -677,7 +681,6 @@ hello world ...@@ -677,7 +681,6 @@ hello world
x = (1 == 1) x = (1 == 1)
if 1 == 1: pass if 1 == 1: pass
if 1 != 1: pass if 1 != 1: pass
if 1 <> 1: pass
if 1 < 1: pass if 1 < 1: pass
if 1 > 1: pass if 1 > 1: pass
if 1 <= 1: pass if 1 <= 1: pass
...@@ -686,7 +689,10 @@ hello world ...@@ -686,7 +689,10 @@ hello world
if 1 is not 1: pass if 1 is not 1: pass
if 1 in (): pass if 1 in (): pass
if 1 not in (): pass if 1 not in (): pass
if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass
# Silence Py3k warning
if eval('1 <> 1'): pass
if eval('1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1'): pass
def testBinaryMaskOps(self): def testBinaryMaskOps(self):
x = 1 & 1 x = 1 & 1
...@@ -769,9 +775,10 @@ hello world ...@@ -769,9 +775,10 @@ hello world
x = {'one': 1, 'two': 2,} x = {'one': 1, 'two': 2,}
x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
x = `x` # Silence Py3k warning
x = `1 or 2 or 3` x = eval('`x`')
self.assertEqual(`1,2`, '(1, 2)') x = eval('`1 or 2 or 3`')
self.assertEqual(eval('`1,2`'), '(1, 2)')
x = x x = x
x = 'x' x = 'x'
...@@ -948,7 +955,13 @@ hello world ...@@ -948,7 +955,13 @@ hello world
def test_main(): def test_main():
run_unittest(TokenTests, GrammarTests) with _check_py3k_warnings(
("backquote not supported", SyntaxWarning),
("tuple parameter unpacking has been removed", SyntaxWarning),
("parenthesized argument names are invalid", SyntaxWarning),
("classic int division", DeprecationWarning),
(".+ not supported in 3.x", DeprecationWarning)):
run_unittest(TokenTests, GrammarTests)
if __name__ == '__main__': if __name__ == '__main__':
test_main() test_main()
...@@ -7,6 +7,7 @@ import sys ...@@ -7,6 +7,7 @@ import sys
import py_compile import py_compile
import warnings import warnings
import marshal import marshal
import imp
from test.test_support import (unlink, TESTFN, unload, run_unittest, from test.test_support import (unlink, TESTFN, unload, run_unittest,
check_warnings, TestFailed) check_warnings, TestFailed)
...@@ -56,11 +57,10 @@ class ImportTest(unittest.TestCase): ...@@ -56,11 +57,10 @@ class ImportTest(unittest.TestCase):
f.close() f.close()
try: try:
try: mod = __import__(TESTFN)
mod = __import__(TESTFN) except ImportError, err:
except ImportError, err: self.fail("import from %s failed: %s" % (ext, err))
self.fail("import from %s failed: %s" % (ext, err)) else:
self.assertEquals(mod.a, a, self.assertEquals(mod.a, a,
"module loaded (%s) but contents invalid" % mod) "module loaded (%s) but contents invalid" % mod)
self.assertEquals(mod.b, b, self.assertEquals(mod.b, b,
...@@ -69,10 +69,9 @@ class ImportTest(unittest.TestCase): ...@@ -69,10 +69,9 @@ class ImportTest(unittest.TestCase):
os.unlink(source) os.unlink(source)
try: try:
try: imp.reload(mod)
reload(mod) except ImportError, err:
except ImportError, err: self.fail("import from .pyc/.pyo failed: %s" % err)
self.fail("import from .pyc/.pyo failed: %s" % err)
finally: finally:
try: try:
os.unlink(pyc) os.unlink(pyc)
...@@ -159,7 +158,7 @@ class ImportTest(unittest.TestCase): ...@@ -159,7 +158,7 @@ class ImportTest(unittest.TestCase):
def test_failing_import_sticks(self): def test_failing_import_sticks(self):
source = TESTFN + os.extsep + "py" source = TESTFN + os.extsep + "py"
f = open(source, "w") f = open(source, "w")
print >> f, "a = 1/0" print >> f, "a = 1 // 0"
f.close() f.close()
# New in 2.4, we shouldn't be able to import that no matter how often # New in 2.4, we shouldn't be able to import that no matter how often
...@@ -205,7 +204,7 @@ class ImportTest(unittest.TestCase): ...@@ -205,7 +204,7 @@ class ImportTest(unittest.TestCase):
print >> f, "b = 20//0" print >> f, "b = 20//0"
f.close() f.close()
self.assertRaises(ZeroDivisionError, reload, mod) self.assertRaises(ZeroDivisionError, imp.reload, mod)
# But we still expect the module to be in sys.modules. # But we still expect the module to be in sys.modules.
mod = sys.modules.get(TESTFN) mod = sys.modules.get(TESTFN)
......
...@@ -180,7 +180,7 @@ class ImportHooksTestCase(ImportHooksBaseTestCase): ...@@ -180,7 +180,7 @@ class ImportHooksTestCase(ImportHooksBaseTestCase):
self.failIf(hasattr(reloadmodule,'reloaded')) self.failIf(hasattr(reloadmodule,'reloaded'))
TestImporter.modules['reloadmodule'] = (False, reload_co) TestImporter.modules['reloadmodule'] = (False, reload_co)
reload(reloadmodule) imp.reload(reloadmodule)
self.failUnless(hasattr(reloadmodule,'reloaded')) self.failUnless(hasattr(reloadmodule,'reloaded'))
import hooktestpackage.oldabs import hooktestpackage.oldabs
...@@ -247,9 +247,10 @@ class ImportHooksTestCase(ImportHooksBaseTestCase): ...@@ -247,9 +247,10 @@ class ImportHooksTestCase(ImportHooksBaseTestCase):
for n in sys.modules.keys(): for n in sys.modules.keys():
if n.startswith(parent): if n.startswith(parent):
del sys.modules[n] del sys.modules[n]
for mname in mnames: with test_support._check_py3k_warnings():
m = __import__(mname, globals(), locals(), ["__dummy__"]) for mname in mnames:
m.__loader__ # to make sure we actually handled the import m = __import__(mname, globals(), locals(), ["__dummy__"])
m.__loader__ # to make sure we actually handled the import
def test_main(): def test_main():
......
...@@ -119,7 +119,7 @@ class TestInterpreterStack(IsTestBase): ...@@ -119,7 +119,7 @@ class TestInterpreterStack(IsTestBase):
self.assertEqual(git.tr[1][1:], (modfile, 9, 'spam', self.assertEqual(git.tr[1][1:], (modfile, 9, 'spam',
[' eggs(b + d, c + f)\n'], 0)) [' eggs(b + d, c + f)\n'], 0))
self.assertEqual(git.tr[2][1:], (modfile, 18, 'eggs', self.assertEqual(git.tr[2][1:], (modfile, 18, 'eggs',
[' q = y / 0\n'], 0)) [' q = y // 0\n'], 0))
def test_frame(self): def test_frame(self):
args, varargs, varkw, locals = inspect.getargvalues(mod.fr) args, varargs, varkw, locals = inspect.getargvalues(mod.fr)
......
...@@ -248,11 +248,11 @@ class IOTest(unittest.TestCase): ...@@ -248,11 +248,11 @@ class IOTest(unittest.TestCase):
f = None f = None
try: try:
with open(test_support.TESTFN, "wb", bufsize) as f: with open(test_support.TESTFN, "wb", bufsize) as f:
1/0 1 // 0
except ZeroDivisionError: except ZeroDivisionError:
self.assertEqual(f.closed, True) self.assertEqual(f.closed, True)
else: else:
self.fail("1/0 didn't raise an exception") self.fail("1 // 0 didn't raise an exception")
# issue 5008 # issue 5008
def test_append_mode_tell(self): def test_append_mode_tell(self):
......
...@@ -7,6 +7,7 @@ import operator ...@@ -7,6 +7,7 @@ import operator
import random import random
import copy import copy
import pickle import pickle
from functools import reduce
maxsize = test_support.MAX_Py_ssize_t maxsize = test_support.MAX_Py_ssize_t
minsize = -maxsize-1 minsize = -maxsize-1
...@@ -112,7 +113,7 @@ class TestBasicOps(unittest.TestCase): ...@@ -112,7 +113,7 @@ class TestBasicOps(unittest.TestCase):
values = [5*x-12 for x in range(n)] values = [5*x-12 for x in range(n)]
for r in range(n+2): for r in range(n+2):
result = list(combinations(values, r)) result = list(combinations(values, r))
self.assertEqual(len(result), 0 if r>n else fact(n) / fact(r) / fact(n-r)) # right number of combs self.assertEqual(len(result), 0 if r>n else fact(n) // fact(r) // fact(n-r)) # right number of combs
self.assertEqual(len(result), len(set(result))) # no repeats self.assertEqual(len(result), len(set(result))) # no repeats
self.assertEqual(result, sorted(result)) # lexicographic order self.assertEqual(result, sorted(result)) # lexicographic order
for c in result: for c in result:
...@@ -176,7 +177,7 @@ class TestBasicOps(unittest.TestCase): ...@@ -176,7 +177,7 @@ class TestBasicOps(unittest.TestCase):
values = [5*x-12 for x in range(n)] values = [5*x-12 for x in range(n)]
for r in range(n+2): for r in range(n+2):
result = list(permutations(values, r)) result = list(permutations(values, r))
self.assertEqual(len(result), 0 if r>n else fact(n) / fact(n-r)) # right number of perms self.assertEqual(len(result), 0 if r>n else fact(n) // fact(n-r)) # right number of perms
self.assertEqual(len(result), len(set(result))) # no repeats self.assertEqual(len(result), len(set(result))) # no repeats
self.assertEqual(result, sorted(result)) # lexicographic order self.assertEqual(result, sorted(result)) # lexicographic order
for p in result: for p in result:
...@@ -370,7 +371,10 @@ class TestBasicOps(unittest.TestCase): ...@@ -370,7 +371,10 @@ class TestBasicOps(unittest.TestCase):
[range(1000), range(0), range(3000,3050), range(1200), range(1500)], [range(1000), range(0), range(3000,3050), range(1200), range(1500)],
[range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)], [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)],
]: ]:
target = map(None, *args) # target = map(None, *args) <- this raises a py3k warning
# this is the replacement:
target = [tuple([arg[i] if i < len(arg) else None for arg in args])
for i in range(max(map(len, args)))]
self.assertEqual(list(izip_longest(*args)), target) self.assertEqual(list(izip_longest(*args)), target)
self.assertEqual(list(izip_longest(*args, **{})), target) self.assertEqual(list(izip_longest(*args, **{})), target)
target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X' target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X'
...@@ -382,7 +386,8 @@ class TestBasicOps(unittest.TestCase): ...@@ -382,7 +386,8 @@ class TestBasicOps(unittest.TestCase):
self.assertEqual(list(izip_longest([])), zip([])) self.assertEqual(list(izip_longest([])), zip([]))
self.assertEqual(list(izip_longest('abcdef')), zip('abcdef')) self.assertEqual(list(izip_longest('abcdef')), zip('abcdef'))
self.assertEqual(list(izip_longest('abc', 'defg', **{})), map(None, 'abc', 'defg')) # empty keyword dict self.assertEqual(list(izip_longest('abc', 'defg', **{})),
zip(list('abc') + [None], 'defg')) # empty keyword dict
self.assertRaises(TypeError, izip_longest, 3) self.assertRaises(TypeError, izip_longest, 3)
self.assertRaises(TypeError, izip_longest, range(3), 3) self.assertRaises(TypeError, izip_longest, range(3), 3)
...@@ -1228,7 +1233,7 @@ Samuele ...@@ -1228,7 +1233,7 @@ Samuele
# is differencing with a range so that consecutive numbers all appear in # is differencing with a range so that consecutive numbers all appear in
# same group. # same group.
>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
>>> for k, g in groupby(enumerate(data), lambda (i,x):i-x): >>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
... print map(operator.itemgetter(1), g) ... print map(operator.itemgetter(1), g)
... ...
[1] [1]
......
...@@ -210,7 +210,7 @@ class Machiavelli: ...@@ -210,7 +210,7 @@ class Machiavelli:
# Tim sez: "luck of the draw; crashes with or without for me." # Tim sez: "luck of the draw; crashes with or without for me."
print >> f print >> f
return `"machiavelli"` return repr("machiavelli")
def __hash__(self): def __hash__(self):
return 0 return 0
......
# Python test set -- part 2, opcodes # Python test set -- part 2, opcodes
from test.test_support import run_unittest from test.test_support import run_unittest, _check_py3k_warnings
import unittest import unittest
class OpcodeTest(unittest.TestCase): class OpcodeTest(unittest.TestCase):
...@@ -9,7 +9,7 @@ class OpcodeTest(unittest.TestCase): ...@@ -9,7 +9,7 @@ class OpcodeTest(unittest.TestCase):
n = 0 n = 0
for i in range(10): for i in range(10):
n = n+i n = n+i
try: 1/0 try: 1 // 0
except NameError: pass except NameError: pass
except ZeroDivisionError: pass except ZeroDivisionError: pass
except TypeError: pass except TypeError: pass
...@@ -104,7 +104,12 @@ class OpcodeTest(unittest.TestCase): ...@@ -104,7 +104,12 @@ class OpcodeTest(unittest.TestCase):
def test_main(): def test_main():
run_unittest(OpcodeTest) with _check_py3k_warnings(("exceptions must derive from BaseException",
DeprecationWarning),
("catching classes that don't inherit "
"from BaseException is not allowed",
DeprecationWarning)):
run_unittest(OpcodeTest)
if __name__ == '__main__': if __name__ == '__main__':
test_main() test_main()
...@@ -26,12 +26,6 @@ from optparse import make_option, Option, IndentedHelpFormatter, \ ...@@ -26,12 +26,6 @@ from optparse import make_option, Option, IndentedHelpFormatter, \
from optparse import _match_abbrev from optparse import _match_abbrev
from optparse import _parse_num from optparse import _parse_num
# Do the right thing with boolean values for all known Python versions.
try:
True, False
except NameError:
(True, False) = (1, 0)
retype = type(re.compile('')) retype = type(re.compile(''))
class InterceptedError(Exception): class InterceptedError(Exception):
......
...@@ -44,7 +44,8 @@ class OSSAudioDevTests(unittest.TestCase): ...@@ -44,7 +44,8 @@ class OSSAudioDevTests(unittest.TestCase):
try: try:
dsp = ossaudiodev.open('w') dsp = ossaudiodev.open('w')
except IOError, msg: except IOError, msg:
if msg[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY): if msg.args[0] in (errno.EACCES, errno.ENOENT,
errno.ENODEV, errno.EBUSY):
raise TestSkipped(msg) raise TestSkipped(msg)
raise raise
...@@ -70,7 +71,7 @@ class OSSAudioDevTests(unittest.TestCase): ...@@ -70,7 +71,7 @@ class OSSAudioDevTests(unittest.TestCase):
self.fail("dsp.%s not read-only" % attr) self.fail("dsp.%s not read-only" % attr)
# Compute expected running time of sound sample (in seconds). # Compute expected running time of sound sample (in seconds).
expected_time = float(len(data)) / (ssize/8) / nchannels / rate expected_time = float(len(data)) / (ssize//8) / nchannels / rate
# set parameters based on .au file headers # set parameters based on .au file headers
dsp.setparameters(AFMT_S16_NE, nchannels, rate) dsp.setparameters(AFMT_S16_NE, nchannels, rate)
...@@ -161,7 +162,8 @@ def test_main(): ...@@ -161,7 +162,8 @@ def test_main():
try: try:
dsp = ossaudiodev.open('w') dsp = ossaudiodev.open('w')
except (ossaudiodev.error, IOError), msg: except (ossaudiodev.error, IOError), msg:
if msg[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY): if msg.args[0] in (errno.EACCES, errno.ENOENT,
errno.ENODEV, errno.EBUSY):
raise TestSkipped(msg) raise TestSkipped(msg)
raise raise
dsp.close() dsp.close()
......
...@@ -6,14 +6,14 @@ class TestImport(unittest.TestCase): ...@@ -6,14 +6,14 @@ class TestImport(unittest.TestCase):
def __init__(self, *args, **kw): def __init__(self, *args, **kw):
self.package_name = 'PACKAGE_' self.package_name = 'PACKAGE_'
while sys.modules.has_key(self.package_name): while self.package_name in sys.modules:
self.package_name += random.choose(string.letters) self.package_name += random.choose(string.letters)
self.module_name = self.package_name + '.foo' self.module_name = self.package_name + '.foo'
unittest.TestCase.__init__(self, *args, **kw) unittest.TestCase.__init__(self, *args, **kw)
def remove_modules(self): def remove_modules(self):
for module_name in (self.package_name, self.module_name): for module_name in (self.package_name, self.module_name):
if sys.modules.has_key(module_name): if module_name in sys.modules:
del sys.modules[module_name] del sys.modules[module_name]
def setUp(self): def setUp(self):
...@@ -52,8 +52,8 @@ class TestImport(unittest.TestCase): ...@@ -52,8 +52,8 @@ class TestImport(unittest.TestCase):
try: __import__(self.module_name) try: __import__(self.module_name)
except SyntaxError: pass except SyntaxError: pass
else: raise RuntimeError, 'Failed to induce SyntaxError' else: raise RuntimeError, 'Failed to induce SyntaxError'
self.assert_(not sys.modules.has_key(self.module_name) and self.assertTrue(self.module_name not in sys.modules)
not hasattr(sys.modules[self.package_name], 'foo')) self.assertFalse(hasattr(sys.modules[self.package_name], 'foo'))
# ...make up a variable name that isn't bound in __builtins__ # ...make up a variable name that isn't bound in __builtins__
var = 'a' var = 'a'
......
...@@ -554,7 +554,7 @@ class ChardataBufferTest(unittest.TestCase): ...@@ -554,7 +554,7 @@ class ChardataBufferTest(unittest.TestCase):
self.n=0 self.n=0
parser.Parse(xml1, 0) parser.Parse(xml1, 0)
parser.buffer_size /= 2 parser.buffer_size //= 2
self.assertEquals(parser.buffer_size, 1024) self.assertEquals(parser.buffer_size, 1024)
parser.Parse(xml2, 1) parser.Parse(xml2, 1)
self.assertEquals(self.n, 4) self.assertEquals(self.n, 4)
......
...@@ -102,21 +102,23 @@ class BaseQueueTest(unittest.TestCase, BlockingTestMixin): ...@@ -102,21 +102,23 @@ class BaseQueueTest(unittest.TestCase, BlockingTestMixin):
q.put(i) q.put(i)
self.assert_(not q.empty(), "Queue should not be empty") self.assert_(not q.empty(), "Queue should not be empty")
self.assert_(not q.full(), "Queue should not be full") self.assert_(not q.full(), "Queue should not be full")
q.put("last") last = 2 * QUEUE_SIZE
full = 3 * 2 * QUEUE_SIZE
q.put(last)
self.assert_(q.full(), "Queue should be full") self.assert_(q.full(), "Queue should be full")
try: try:
q.put("full", block=0) q.put(full, block=0)
self.fail("Didn't appear to block with a full queue") self.fail("Didn't appear to block with a full queue")
except Queue.Full: except Queue.Full:
pass pass
try: try:
q.put("full", timeout=0.01) q.put(full, timeout=0.01)
self.fail("Didn't appear to time-out with a full queue") self.fail("Didn't appear to time-out with a full queue")
except Queue.Full: except Queue.Full:
pass pass
# Test a blocking put # Test a blocking put
self.do_blocking_test(q.put, ("full",), q.get, ()) self.do_blocking_test(q.put, (full,), q.get, ())
self.do_blocking_test(q.put, ("full", True, 10), q.get, ()) self.do_blocking_test(q.put, (full, True, 10), q.get, ())
# Empty it # Empty it
for i in range(QUEUE_SIZE): for i in range(QUEUE_SIZE):
q.get() q.get()
......
...@@ -6,6 +6,7 @@ import time ...@@ -6,6 +6,7 @@ import time
import pickle import pickle
import warnings import warnings
from math import log, exp, sqrt, pi, fsum as msum from math import log, exp, sqrt, pi, fsum as msum
from functools import reduce
from test import test_support from test import test_support
class TestBasicOps(unittest.TestCase): class TestBasicOps(unittest.TestCase):
......
...@@ -8,7 +8,7 @@ import os ...@@ -8,7 +8,7 @@ import os
import shutil import shutil
import unittest import unittest
from test.test_support import run_unittest from test.test_support import run_unittest, _check_py3k_warnings
from repr import repr as r # Don't shadow builtin repr from repr import repr as r # Don't shadow builtin repr
from repr import Repr from repr import Repr
...@@ -174,7 +174,8 @@ class ReprTests(unittest.TestCase): ...@@ -174,7 +174,8 @@ class ReprTests(unittest.TestCase):
def test_buffer(self): def test_buffer(self):
# XXX doesn't test buffers with no b_base or read-write buffers (see # XXX doesn't test buffers with no b_base or read-write buffers (see
# bufferobject.c). The test is fairly incomplete too. Sigh. # bufferobject.c). The test is fairly incomplete too. Sigh.
x = buffer('foo') with _check_py3k_warnings():
x = buffer('foo')
self.failUnless(repr(x).startswith('<read-only buffer for 0x')) self.failUnless(repr(x).startswith('<read-only buffer for 0x'))
def test_cell(self): def test_cell(self):
......
...@@ -46,9 +46,9 @@ class MessageTestCase(unittest.TestCase): ...@@ -46,9 +46,9 @@ class MessageTestCase(unittest.TestCase):
continue continue
i = i + 1 i = i + 1
self.assertEqual(mn, n, self.assertEqual(mn, n,
"Un-expected name: %s != %s" % (`mn`, `n`)) "Un-expected name: %r != %r" % (mn, n))
self.assertEqual(ma, a, self.assertEqual(ma, a,
"Un-expected address: %s != %s" % (`ma`, `a`)) "Un-expected address: %r != %r" % (ma, a))
if mn == n and ma == a: if mn == n and ma == a:
pass pass
else: else:
......
...@@ -196,7 +196,7 @@ class ImportSideEffectTests(unittest.TestCase): ...@@ -196,7 +196,7 @@ class ImportSideEffectTests(unittest.TestCase):
site.abs__file__() site.abs__file__()
for module in (sys, os, __builtin__): for module in (sys, os, __builtin__):
try: try:
self.failUnless(os.path.isabs(module.__file__), `module`) self.assertTrue(os.path.isabs(module.__file__), repr(module))
except AttributeError: except AttributeError:
continue continue
# We could try everything in sys.modules; however, when regrtest.py # We could try everything in sys.modules; however, when regrtest.py
...@@ -248,7 +248,7 @@ class ImportSideEffectTests(unittest.TestCase): ...@@ -248,7 +248,7 @@ class ImportSideEffectTests(unittest.TestCase):
def test_sitecustomize_executed(self): def test_sitecustomize_executed(self):
# If sitecustomize is available, it should have been imported. # If sitecustomize is available, it should have been imported.
if not sys.modules.has_key("sitecustomize"): if "sitecustomize" not in sys.modules:
try: try:
import sitecustomize import sitecustomize
except ImportError: except ImportError:
......
...@@ -75,7 +75,8 @@ class SysModuleTest(unittest.TestCase): ...@@ -75,7 +75,8 @@ class SysModuleTest(unittest.TestCase):
self.assert_(value is exc) self.assert_(value is exc)
self.assert_(traceback is not None) self.assert_(traceback is not None)
sys.exc_clear() with test.test_support._check_py3k_warnings():
sys.exc_clear()
typ, value, traceback = sys.exc_info() typ, value, traceback = sys.exc_info()
self.assert_(typ is None) self.assert_(typ is None)
...@@ -498,7 +499,8 @@ class SizeofTest(unittest.TestCase): ...@@ -498,7 +499,8 @@ class SizeofTest(unittest.TestCase):
# bool # bool
check(True, size(h + 'l')) check(True, size(h + 'l'))
# buffer # buffer
check(buffer(''), size(h + '2P2Pil')) with test.test_support._check_py3k_warnings():
check(buffer(''), size(h + '2P2Pil'))
# builtin_function_or_method # builtin_function_or_method
check(len, size(h + '3P')) check(len, size(h + '3P'))
# bytearray # bytearray
......
...@@ -14,7 +14,7 @@ process_pid = os.getpid() ...@@ -14,7 +14,7 @@ process_pid = os.getpid()
signalled_all=thread.allocate_lock() signalled_all=thread.allocate_lock()
def registerSignals((for_usr1, for_usr2, for_alrm)): def registerSignals(for_usr1, for_usr2, for_alrm):
usr1 = signal.signal(signal.SIGUSR1, for_usr1) usr1 = signal.signal(signal.SIGUSR1, for_usr1)
usr2 = signal.signal(signal.SIGUSR2, for_usr2) usr2 = signal.signal(signal.SIGUSR2, for_usr2)
alrm = signal.signal(signal.SIGALRM, for_alrm) alrm = signal.signal(signal.SIGALRM, for_alrm)
...@@ -74,11 +74,11 @@ def test_main(): ...@@ -74,11 +74,11 @@ def test_main():
signal.SIGUSR2 : {'tripped': 0, 'tripped_by': 0 }, signal.SIGUSR2 : {'tripped': 0, 'tripped_by': 0 },
signal.SIGALRM : {'tripped': 0, 'tripped_by': 0 } } signal.SIGALRM : {'tripped': 0, 'tripped_by': 0 } }
oldsigs = registerSignals((handle_signals, handle_signals, handle_signals)) oldsigs = registerSignals(handle_signals, handle_signals, handle_signals)
try: try:
run_unittest(ThreadSignals) run_unittest(ThreadSignals)
finally: finally:
registerSignals(oldsigs) registerSignals(*oldsigs)
if __name__ == '__main__': if __name__ == '__main__':
test_main() test_main()
...@@ -401,7 +401,7 @@ class RaisingTraceFuncTestCase(unittest.TestCase): ...@@ -401,7 +401,7 @@ class RaisingTraceFuncTestCase(unittest.TestCase):
we're testing, so that the 'exception' trace event fires.""" we're testing, so that the 'exception' trace event fires."""
if self.raiseOnEvent == 'exception': if self.raiseOnEvent == 'exception':
x = 0 x = 0
y = 1/x y = 1 // x
else: else:
return 1 return 1
......
...@@ -4,6 +4,7 @@ from _testcapi import traceback_print ...@@ -4,6 +4,7 @@ from _testcapi import traceback_print
from StringIO import StringIO from StringIO import StringIO
import sys import sys
import unittest import unittest
from imp import reload
from test.test_support import run_unittest, is_jython, Error from test.test_support import run_unittest, is_jython, Error
import traceback import traceback
...@@ -158,7 +159,7 @@ def test(): ...@@ -158,7 +159,7 @@ def test():
def test_format_exception_only_bad__str__(self): def test_format_exception_only_bad__str__(self):
class X(Exception): class X(Exception):
def __str__(self): def __str__(self):
1/0 1 // 0
err = traceback.format_exception_only(X, X()) err = traceback.format_exception_only(X, X())
self.assertEqual(len(err), 1) self.assertEqual(len(err), 1)
str_value = '<unprintable %s object>' % X.__name__ str_value = '<unprintable %s object>' % X.__name__
......
...@@ -529,7 +529,7 @@ class ExceptionalTestCase(unittest.TestCase, ContextmanagerAssertionMixin): ...@@ -529,7 +529,7 @@ class ExceptionalTestCase(unittest.TestCase, ContextmanagerAssertionMixin):
self.assertRaises(AssertionError, falseAsBool) self.assertRaises(AssertionError, falseAsBool)
def failAsBool(): def failAsBool():
with cm(lambda: 1//0): with cm(lambda: 1 // 0):
self.fail("Should NOT see this") self.fail("Should NOT see this")
self.assertRaises(ZeroDivisionError, failAsBool) self.assertRaises(ZeroDivisionError, failAsBool)
...@@ -637,7 +637,7 @@ class ExitSwallowsExceptionTestCase(unittest.TestCase): ...@@ -637,7 +637,7 @@ class ExitSwallowsExceptionTestCase(unittest.TestCase):
def __exit__(self, t, v, tb): return True def __exit__(self, t, v, tb): return True
try: try:
with AfricanSwallow(): with AfricanSwallow():
1/0 1 // 0
except ZeroDivisionError: except ZeroDivisionError:
self.fail("ZeroDivisionError should have been swallowed") self.fail("ZeroDivisionError should have been swallowed")
...@@ -647,7 +647,7 @@ class ExitSwallowsExceptionTestCase(unittest.TestCase): ...@@ -647,7 +647,7 @@ class ExitSwallowsExceptionTestCase(unittest.TestCase):
def __exit__(self, t, v, tb): return False def __exit__(self, t, v, tb): return False
try: try:
with EuropeanSwallow(): with EuropeanSwallow():
1/0 1 // 0
except ZeroDivisionError: except ZeroDivisionError:
pass pass
else: else:
......
...@@ -432,10 +432,10 @@ class HandlerTests(TestCase): ...@@ -432,10 +432,10 @@ class HandlerTests(TestCase):
env = handler.environ env = handler.environ
from os import environ from os import environ
for k,v in environ.items(): for k,v in environ.items():
if not empty.has_key(k): if k not in empty:
self.assertEqual(env[k],v) self.assertEqual(env[k],v)
for k,v in empty.items(): for k,v in empty.items():
self.failUnless(env.has_key(k)) self.assertTrue(k in env)
def testEnviron(self): def testEnviron(self):
h = TestHandler(X="Y") h = TestHandler(X="Y")
...@@ -448,7 +448,7 @@ class HandlerTests(TestCase): ...@@ -448,7 +448,7 @@ class HandlerTests(TestCase):
h = BaseCGIHandler(None,None,None,{}) h = BaseCGIHandler(None,None,None,{})
h.setup_environ() h.setup_environ()
for key in 'wsgi.url_scheme', 'wsgi.input', 'wsgi.errors': for key in 'wsgi.url_scheme', 'wsgi.input', 'wsgi.errors':
self.assert_(h.environ.has_key(key)) self.assertTrue(key in h.environ)
def testScheme(self): def testScheme(self):
h=TestHandler(HTTPS="on"); h.setup_environ() h=TestHandler(HTTPS="on"); h.setup_environ()
......
...@@ -37,7 +37,7 @@ def sanity(): ...@@ -37,7 +37,7 @@ def sanity():
""" """
def check_method(method): def check_method(method):
if not callable(method): if not hasattr(method, '__call__'):
print method, "not callable" print method, "not callable"
def serialize(ET, elem, encoding=None): def serialize(ET, elem, encoding=None):
......
...@@ -35,7 +35,7 @@ def sanity(): ...@@ -35,7 +35,7 @@ def sanity():
""" """
def check_method(method): def check_method(method):
if not callable(method): if not hasattr(method, '__call__'):
print method, "not callable" print method, "not callable"
def serialize(ET, elem, encoding=None): def serialize(ET, elem, encoding=None):
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment