Reverting the Revision: 77368. I committed Flox's big patch for tests by

mistake. ( It may come in for sure tough)
This commit is contained in:
Senthil Kumaran 2010-01-08 19:04:16 +00:00
parent 3ddc435af6
commit ce8e33a095
107 changed files with 436 additions and 794 deletions

View file

@ -3,6 +3,5 @@
# 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
imp.reload(infinite_reload) reload(infinite_reload)

View file

@ -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:

View file

@ -4,7 +4,7 @@ Tests common to list and UserList.UserList
import sys import sys
import os import os
import warnings
from test import test_support, seq_tests from test import test_support, seq_tests
class CommonTest(seq_tests.CommonTest): class CommonTest(seq_tests.CommonTest):
@ -36,9 +36,7 @@ class CommonTest(seq_tests.CommonTest):
self.assertEqual(str(a0), str(l0)) self.assertEqual(str(a0), str(l0))
self.assertEqual(repr(a0), repr(l0)) self.assertEqual(repr(a0), repr(l0))
# Silence Py3k warning self.assertEqual(`a2`, `l2`)
with test_support.check_warnings():
self.assertEqual(eval('`a2`'), eval('`l2`'))
self.assertEqual(str(a2), "[0, 1, 2]") self.assertEqual(str(a2), "[0, 1, 2]")
self.assertEqual(repr(a2), "[0, 1, 2]") self.assertEqual(repr(a2), "[0, 1, 2]")
@ -423,13 +421,6 @@ class CommonTest(seq_tests.CommonTest):
self.assertRaises(TypeError, u.reverse, 42) self.assertRaises(TypeError, u.reverse, 42)
def test_sort(self): def test_sort(self):
with warnings.catch_warnings():
# Silence Py3k warning
warnings.filterwarnings("ignore", "the cmp argument is not supported",
DeprecationWarning)
self._test_sort()
def _test_sort(self):
u = self.type2test([1, 0]) u = self.type2test([1, 0])
u.sort() u.sort()
self.assertEqual(u, [0, 1]) self.assertEqual(u, [0, 1])

View file

@ -1,7 +1,6 @@
# tests common to dict and UserDict # tests common to dict and UserDict
import unittest import unittest
import UserDict import UserDict
import test_support
class BasicTestMappingProtocol(unittest.TestCase): class BasicTestMappingProtocol(unittest.TestCase):
@ -55,18 +54,13 @@ class BasicTestMappingProtocol(unittest.TestCase):
#len #len
self.assertEqual(len(p), 0) self.assertEqual(len(p), 0)
self.assertEqual(len(d), len(self.reference)) self.assertEqual(len(d), len(self.reference))
#in #has_key
for k in self.reference: for k in self.reference:
self.assertTrue(d.has_key(k))
self.assertTrue(k in d) self.assertTrue(k in d)
for k in self.other: for k in self.other:
self.assertFalse(d.has_key(k))
self.assertFalse(k in d) self.assertFalse(k in d)
#has_key
# Silence Py3k warning
with test_support.check_warnings():
for k in self.reference:
self.assertTrue(d.has_key(k))
for k in self.other:
self.assertFalse(d.has_key(k))
#cmp #cmp
self.assertEqual(cmp(p,p), 0) self.assertEqual(cmp(p,p), 0)
self.assertEqual(cmp(d,d), 0) self.assertEqual(cmp(d,d), 0)

View file

@ -150,6 +150,7 @@ option '-uall,-bsddb'.
import cStringIO import cStringIO
import getopt import getopt
import itertools import itertools
import json
import os import os
import random import random
import re import re
@ -159,13 +160,15 @@ import traceback
import warnings import warnings
import unittest import unittest
with warnings.catch_warnings(): # I see no other way to suppress these warnings;
# Silence Py3k warnings # putting them in test_grammar.py has no effect:
warnings.filterwarnings("ignore", "tuple parameter unpacking " warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning,
"has been removed", SyntaxWarning) ".*test.test_grammar$")
warnings.filterwarnings("ignore", "assignment to True or False " if sys.maxint > 0x7fffffff:
"is forbidden", SyntaxWarning) # Also suppress them in <string>, because for 64-bit platforms,
import json # that's where test_grammar.py hides them.
warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning,
"<string>")
# Ignore ImportWarnings that only occur in the source tree, # Ignore ImportWarnings that only occur in the source tree,
# (because of modules with the same name as source-directories in Modules/) # (because of modules with the same name as source-directories in Modules/)

View file

@ -4,7 +4,6 @@ Tests common to tuple, list and UserList.UserList
import unittest import unittest
import sys import sys
import test_support
# Various iterables # Various iterables
# This is used for checking the constructor (here and in test_deque.py) # This is used for checking the constructor (here and in test_deque.py)
@ -197,9 +196,7 @@ class CommonTest(unittest.TestCase):
self.assertEqual(a[ -pow(2,128L): 3 ], self.type2test([0,1,2])) self.assertEqual(a[ -pow(2,128L): 3 ], self.type2test([0,1,2]))
self.assertEqual(a[ 3: pow(2,145L) ], self.type2test([3,4])) self.assertEqual(a[ 3: pow(2,145L) ], self.type2test([3,4]))
# Silence Py3k warning self.assertRaises(TypeError, u.__getslice__)
with test_support.check_warnings():
self.assertRaises(TypeError, u.__getslice__)
def test_contains(self): def test_contains(self):
u = self.type2test([0, 1, 2]) u = self.type2test([0, 1, 2])

View file

@ -137,10 +137,12 @@ class TestBuffercStringIO(TestcStringIO):
def test_main(): def test_main():
test_support.run_unittest(TestStringIO, TestcStringIO) test_support.run_unittest(
# Silence Py3k warning TestStringIO,
with test_support.check_warnings(): TestcStringIO,
test_support.run_unittest(TestBufferStringIO, TestBuffercStringIO) TestBufferStringIO,
TestBuffercStringIO
)
if __name__ == '__main__': if __name__ == '__main__':
test_main() test_main()

View file

@ -5,14 +5,12 @@
import os import os
import unittest import unittest
import anydbm
import glob import glob
from test import test_support from test import test_support
_fname = test_support.TESTFN _fname = test_support.TESTFN
# Silence Py3k warning
anydbm = test_support.import_module('anydbm', deprecated=True)
def _delete_files(): def _delete_files():
# we don't know the precise name the underlying database uses # we don't know the precise name the underlying database uses
# so we use glob to locate all names # so we use glob to locate all names

View file

@ -749,9 +749,7 @@ class BaseTest(unittest.TestCase):
def test_buffer(self): def test_buffer(self):
a = array.array(self.typecode, self.example) a = array.array(self.typecode, self.example)
# Silence Py3k warning b = buffer(a)
with test_support.check_warnings():
b = buffer(a)
self.assertEqual(b[0], a.tostring()[0]) self.assertEqual(b[0], a.tostring()[0])
def test_weakref(self): def test_weakref(self):

View file

@ -1,7 +1,6 @@
import sys, itertools, unittest import sys, itertools, unittest
from test import test_support from test import test_support
import ast import ast
import warnings
def to_tuple(t): def to_tuple(t):
if t is None or isinstance(t, (basestring, int, long, complex)): if t is None or isinstance(t, (basestring, int, long, complex)):
@ -303,11 +302,7 @@ class ASTHelpers_Test(unittest.TestCase):
def test_main(): def test_main():
with warnings.catch_warnings(): test_support.run_unittest(AST_Tests, ASTHelpers_Test)
# Silence Py3k warning
warnings.filterwarnings("ignore", "backquote not supported",
SyntaxWarning)
test_support.run_unittest(AST_Tests, ASTHelpers_Test)
def main(): def main():
if __name__ != '__main__': if __name__ != '__main__':

View file

@ -2,7 +2,6 @@
from test.test_support import run_unittest from test.test_support import run_unittest
import unittest import unittest
import warnings
class AugAssignTest(unittest.TestCase): class AugAssignTest(unittest.TestCase):
@ -325,11 +324,7 @@ __ilshift__ called
'''.splitlines()) '''.splitlines())
def test_main(): def test_main():
with warnings.catch_warnings(): run_unittest(AugAssignTest)
# Silence Py3k warning
warnings.filterwarnings("ignore", "classic int division",
DeprecationWarning)
run_unittest(AugAssignTest)
if __name__ == '__main__': if __name__ == '__main__':
test_main() test_main()

View file

@ -97,21 +97,21 @@ class StrTest(unittest.TestCase):
def test_encode(self, size): def test_encode(self, size):
return self.basic_encode_test(size, 'utf-8') return self.basic_encode_test(size, 'utf-8')
@precisionbigmemtest(size=_4G // 6 + 2, memuse=2) @precisionbigmemtest(size=_4G / 6 + 2, memuse=2)
def test_encode_raw_unicode_escape(self, size): def test_encode_raw_unicode_escape(self, size):
try: try:
return self.basic_encode_test(size, 'raw_unicode_escape') return self.basic_encode_test(size, 'raw_unicode_escape')
except MemoryError: except MemoryError:
pass # acceptable on 32-bit pass # acceptable on 32-bit
@precisionbigmemtest(size=_4G // 5 + 70, memuse=3) @precisionbigmemtest(size=_4G / 5 + 70, memuse=3)
def test_encode_utf7(self, size): def test_encode_utf7(self, size):
try: try:
return self.basic_encode_test(size, 'utf7') return self.basic_encode_test(size, 'utf7')
except MemoryError: except MemoryError:
pass # acceptable on 32-bit pass # acceptable on 32-bit
@precisionbigmemtest(size=_4G // 4 + 5, memuse=6) @precisionbigmemtest(size=_4G / 4 + 5, memuse=6)
def test_encode_utf32(self, size): def test_encode_utf32(self, size):
try: try:
return self.basic_encode_test(size, 'utf32', expectedsize=4*size+4) return self.basic_encode_test(size, 'utf32', expectedsize=4*size+4)
@ -122,7 +122,7 @@ class StrTest(unittest.TestCase):
def test_decodeascii(self, size): def test_decodeascii(self, size):
return self.basic_encode_test(size, 'ascii', c='A') return self.basic_encode_test(size, 'ascii', c='A')
@precisionbigmemtest(size=_4G // 5, memuse=6+2) @precisionbigmemtest(size=_4G / 5, memuse=6+2)
def test_unicode_repr_oflw(self, size): def test_unicode_repr_oflw(self, size):
try: try:
s = u"\uAAAA"*size s = u"\uAAAA"*size
@ -516,7 +516,7 @@ class StrTest(unittest.TestCase):
self.assertEquals(s.count('\\'), size) self.assertEquals(s.count('\\'), size)
self.assertEquals(s.count('0'), size * 2) self.assertEquals(s.count('0'), size * 2)
@bigmemtest(minsize=2**32 // 5, memuse=6+2) @bigmemtest(minsize=2**32 / 5, memuse=6+2)
def test_unicode_repr(self, size): def test_unicode_repr(self, size):
s = u"\uAAAA" * size s = u"\uAAAA" * size
self.assertTrue(len(repr(s)) > size) self.assertTrue(len(repr(s)) > size)
@ -1053,9 +1053,7 @@ class BufferTest(unittest.TestCase):
@precisionbigmemtest(size=_1G, memuse=4) @precisionbigmemtest(size=_1G, memuse=4)
def test_repeat(self, size): def test_repeat(self, size):
try: try:
# Silence Py3k warning b = buffer("AAAA")*size
with test_support.check_warnings():
b = buffer("AAAA")*size
except MemoryError: except MemoryError:
pass # acceptable on 32-bit pass # acceptable on 32-bit
else: else:

View file

@ -26,10 +26,10 @@ class BinASCIITest(unittest.TestCase):
prefixes.extend(["crc_", "rlecode_", "rledecode_"]) prefixes.extend(["crc_", "rlecode_", "rledecode_"])
for prefix in prefixes: for prefix in prefixes:
name = prefix + suffix name = prefix + suffix
self.assertTrue(hasattr(getattr(binascii, name), '__call__')) self.assertTrue(callable(getattr(binascii, name)))
self.assertRaises(TypeError, getattr(binascii, name)) self.assertRaises(TypeError, getattr(binascii, name))
for name in ("hexlify", "unhexlify"): for name in ("hexlify", "unhexlify"):
self.assertTrue(hasattr(getattr(binascii, name), '__call__')) self.assertTrue(callable(getattr(binascii, name)))
self.assertRaises(TypeError, getattr(binascii, name)) self.assertRaises(TypeError, getattr(binascii, name))
def test_base64valid(self): def test_base64valid(self):

View file

@ -207,9 +207,6 @@ 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."""

View file

@ -91,10 +91,10 @@ class BoolTest(unittest.TestCase):
self.assertEqual(False*1, 0) self.assertEqual(False*1, 0)
self.assertIsNot(False*1, False) self.assertIsNot(False*1, False)
self.assertEqual(True//1, 1) self.assertEqual(True/1, 1)
self.assertIsNot(True//1, True) self.assertIsNot(True/1, True)
self.assertEqual(False//1, 0) self.assertEqual(False/1, 0)
self.assertIsNot(False//1, False) self.assertIsNot(False/1, False)
for b in False, True: for b in False, True:
for i in 0, 1, 2: for i in 0, 1, 2:
@ -168,8 +168,8 @@ class BoolTest(unittest.TestCase):
self.assertIs(hasattr([], "wobble"), False) self.assertIs(hasattr([], "wobble"), False)
def test_callable(self): def test_callable(self):
self.assertTrue(hasattr(len, '__call__'), True) self.assertIs(callable(len), True)
self.assertFalse(hasattr(1, '__call__'), False) self.assertIs(callable(1), False)
def test_isinstance(self): def test_isinstance(self):
self.assertIs(isinstance(True, bool), True) self.assertIs(isinstance(True, bool), True)
@ -184,12 +184,8 @@ class BoolTest(unittest.TestCase):
self.assertIs(issubclass(int, bool), False) self.assertIs(issubclass(int, bool), False)
def test_haskey(self): def test_haskey(self):
self.assertIs(1 in {}, False) self.assertIs({}.has_key(1), False)
self.assertIs(1 in {1:1}, True) self.assertIs({1:1}.has_key(1), True)
# Silence Py3k warning
with test_support.check_warnings():
self.assertIs({}.has_key(1), False)
self.assertIs({1:1}.has_key(1), True)
def test_string(self): def test_string(self):
self.assertIs("xyz".endswith("z"), True) self.assertIs("xyz".endswith("z"), True)
@ -261,10 +257,8 @@ class BoolTest(unittest.TestCase):
import operator import operator
self.assertIs(operator.truth(0), False) self.assertIs(operator.truth(0), False)
self.assertIs(operator.truth(1), True) self.assertIs(operator.truth(1), True)
# Silence Py3k warning self.assertIs(operator.isCallable(0), False)
with test_support.check_warnings(): self.assertIs(operator.isCallable(len), True)
self.assertIs(operator.isCallable(0), False)
self.assertIs(operator.isCallable(len), True)
self.assertIs(operator.isNumberType(None), False) self.assertIs(operator.isNumberType(None), False)
self.assertIs(operator.isNumberType(0), True) self.assertIs(operator.isNumberType(0), True)
self.assertIs(operator.not_(1), False) self.assertIs(operator.not_(1), False)

View file

@ -6,7 +6,6 @@ For now, tests just new or changed functionality.
import unittest import unittest
from test import test_support from test import test_support
import warnings
class BufferTests(unittest.TestCase): class BufferTests(unittest.TestCase):
@ -24,11 +23,7 @@ class BufferTests(unittest.TestCase):
def test_main(): def test_main():
with warnings.catch_warnings(): test_support.run_unittest(BufferTests)
# Silence Py3k warning
warnings.filterwarnings("ignore", "buffer.. not supported",
DeprecationWarning)
test_support.run_unittest(BufferTests)
if __name__ == "__main__": if __name__ == "__main__":
test_main() test_main()

View file

@ -7,6 +7,10 @@ from test.test_support import fcmp, have_unicode, TESTFN, unlink, \
from operator import neg from operator import neg
import sys, warnings, cStringIO, random, fractions, UserDict import sys, warnings, cStringIO, random, fractions, UserDict
warnings.filterwarnings("ignore", "hex../oct.. of negative int",
FutureWarning, __name__)
warnings.filterwarnings("ignore", "integer argument expected",
DeprecationWarning, "unittest")
# count the number of test runs. # count the number of test runs.
# used to skip running test_execfile() multiple times # used to skip running test_execfile() multiple times
@ -415,11 +419,7 @@ class BuiltinTest(unittest.TestCase):
f.write('z = z+1\n') f.write('z = z+1\n')
f.write('z = z*2\n') f.write('z = z*2\n')
f.close() f.close()
with warnings.catch_warnings(): execfile(TESTFN)
# Silence Py3k warning
warnings.filterwarnings("ignore", ".+ not supported in 3.x",
DeprecationWarning)
execfile(TESTFN)
def test_execfile(self): def test_execfile(self):
global numruns global numruns
@ -1542,30 +1542,17 @@ class TestSorted(unittest.TestCase):
data = 'The quick Brown fox Jumped over The lazy Dog'.split() data = 'The quick Brown fox Jumped over The lazy Dog'.split()
self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0) self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0)
def _run_unittest(*args):
with warnings.catch_warnings():
# Silence Py3k warnings
warnings.filterwarnings("ignore", ".+ not supported in 3.x",
DeprecationWarning)
warnings.filterwarnings("ignore", ".+ is renamed to imp.reload",
DeprecationWarning)
warnings.filterwarnings("ignore", "integer argument expected, got float",
DeprecationWarning)
warnings.filterwarnings("ignore", "classic int division",
DeprecationWarning)
run_unittest(*args)
def test_main(verbose=None): def test_main(verbose=None):
test_classes = (BuiltinTest, TestSorted) test_classes = (BuiltinTest, TestSorted)
_run_unittest(*test_classes) run_unittest(*test_classes)
# verify reference counting # verify reference counting
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
import gc import gc
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in xrange(len(counts)):
_run_unittest(*test_classes) run_unittest(*test_classes)
gc.collect() gc.collect()
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()
print counts print counts

View file

@ -12,9 +12,7 @@ class CFunctionCalls(unittest.TestCase):
self.assertRaises(TypeError, {}.has_key) self.assertRaises(TypeError, {}.has_key)
def test_varargs1(self): def test_varargs1(self):
# Silence Py3k warning {}.has_key(0)
with test_support.check_warnings():
{}.has_key(0)
def test_varargs2(self): def test_varargs2(self):
self.assertRaises(TypeError, {}.has_key, 0, 1) self.assertRaises(TypeError, {}.has_key, 0, 1)
@ -26,15 +24,11 @@ class CFunctionCalls(unittest.TestCase):
pass pass
def test_varargs1_ext(self): def test_varargs1_ext(self):
# Silence Py3k warning {}.has_key(*(0,))
with test_support.check_warnings():
{}.has_key(*(0,))
def test_varargs2_ext(self): def test_varargs2_ext(self):
try: try:
# Silence Py3k warning {}.has_key(*(1, 2))
with test_support.check_warnings():
{}.has_key(*(1, 2))
except TypeError: except TypeError:
pass pass
else: else:

View file

@ -55,7 +55,7 @@ class TestPendingCalls(unittest.TestCase):
context = foo() context = foo()
context.l = [] context.l = []
context.n = 2 #submits per thread context.n = 2 #submits per thread
context.nThreads = n // context.n context.nThreads = n / context.n
context.nFinished = 0 context.nFinished = 0
context.lock = threading.Lock() context.lock = threading.Lock()
context.event = threading.Event() context.event = threading.Event()

View file

@ -104,7 +104,7 @@ parse_strict_test_cases = [
def norm(list): def norm(list):
if type(list) == type([]): if type(list) == type([]):
list.sort(key=str) list.sort()
return list return list
def first_elts(list): def first_elts(list):

View file

@ -1,7 +1,7 @@
"Test the functionality of Python classes implementing operators." "Test the functionality of Python classes implementing operators."
import unittest import unittest
import warnings
from test import test_support from test import test_support
testmeths = [ testmeths = [
@ -407,7 +407,7 @@ class ClassTests(unittest.TestCase):
self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (testme, 1))]) self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (testme, 1))])
callLst[:] = [] callLst[:] = []
eval('testme <> 1') # XXX kill this in py3k testme <> 1 # XXX kill this in py3k
self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (testme, 1))]) self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (testme, 1))])
callLst[:] = [] callLst[:] = []
@ -427,7 +427,7 @@ class ClassTests(unittest.TestCase):
self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (1, testme))]) self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (1, testme))])
callLst[:] = [] callLst[:] = []
eval('1 <> testme') 1 <> testme
self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (1, testme))]) self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (1, testme))])
callLst[:] = [] callLst[:] = []
@ -616,15 +616,7 @@ class ClassTests(unittest.TestCase):
hash(a.f) hash(a.f)
def test_main(): def test_main():
with warnings.catch_warnings(): test_support.run_unittest(ClassTests)
# Silence Py3k warnings
warnings.filterwarnings("ignore", ".+slice__ has been removed",
DeprecationWarning)
warnings.filterwarnings("ignore", "classic int division",
DeprecationWarning)
warnings.filterwarnings("ignore", "<> not supported",
DeprecationWarning)
test_support.run_unittest(ClassTests)
if __name__=='__main__': if __name__=='__main__':
test_main() test_main()

View file

@ -223,11 +223,8 @@ def process_infix_results():
infix_results[key] = res infix_results[key] = res
with warnings.catch_warnings():
# Silence Py3k warning process_infix_results()
warnings.filterwarnings("ignore", "classic int division",
DeprecationWarning)
process_infix_results()
# now infix_results has two lists of results for every pairing. # now infix_results has two lists of results for every pairing.
prefix_binops = [ 'divmod' ] prefix_binops = [ 'divmod' ]
@ -340,14 +337,11 @@ class CoercionTest(unittest.TestCase):
raise exc raise exc
def test_main(): def test_main():
with warnings.catch_warnings(): warnings.filterwarnings("ignore",
# Silence Py3k warnings r'complex divmod\(\), // and % are deprecated',
warnings.filterwarnings("ignore", DeprecationWarning,
"complex divmod.., // and % are deprecated", r'test.test_coercion$')
DeprecationWarning) run_unittest(CoercionTest)
warnings.filterwarnings("ignore", "classic .+ division",
DeprecationWarning)
run_unittest(CoercionTest)
if __name__ == "__main__": if __name__ == "__main__":
test_main() test_main()

View file

@ -510,10 +510,8 @@ class TestCounter(unittest.TestCase):
[('a', 3), ('b', 2), ('c', 1)]) [('a', 3), ('b', 2), ('c', 1)])
self.assertEqual(c['b'], 2) self.assertEqual(c['b'], 2)
self.assertEqual(c['z'], 0) self.assertEqual(c['z'], 0)
# Silence Py3k warning self.assertEqual(c.has_key('c'), True)
with test_support.check_warnings(): self.assertEqual(c.has_key('z'), False)
self.assertEqual(c.has_key('c'), True)
self.assertEqual(c.has_key('z'), False)
self.assertEqual(c.__contains__('c'), True) self.assertEqual(c.__contains__('c'), True)
self.assertEqual(c.__contains__('z'), False) self.assertEqual(c.__contains__('z'), False)
self.assertEqual(c.get('b', 10), 2) self.assertEqual(c.get('b', 10), 2)

View file

@ -9,10 +9,7 @@ import warnings
warnings.filterwarnings('ignore', r".*commands.getstatus.. is deprecated", warnings.filterwarnings('ignore', r".*commands.getstatus.. is deprecated",
DeprecationWarning) DeprecationWarning)
from test.test_support import run_unittest, reap_children, import_module from test.test_support import run_unittest, reap_children
# Silence Py3k warning
import_module('commands', deprecated=True)
from commands import * from commands import *
# The module says: # The module says:

View file

@ -2,7 +2,6 @@ import unittest
import sys import sys
import _ast import _ast
from test import test_support from test import test_support
import textwrap
class TestSpecifics(unittest.TestCase): class TestSpecifics(unittest.TestCase):
@ -142,9 +141,7 @@ def f(x):
self.assertEqual(f(5), 0) self.assertEqual(f(5), 0)
def test_complex_args(self): def test_complex_args(self):
# Silence Py3k warning
with test_support.check_warnings():
exec textwrap.dedent('''
def comp_args((a, b)): def comp_args((a, b)):
return a,b return a,b
self.assertEqual(comp_args((1, 2)), (1, 2)) self.assertEqual(comp_args((1, 2)), (1, 2))
@ -162,7 +159,6 @@ def f(x):
return a, b, c return a, b, c
self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3)) self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))
self.assertEqual(comp_args(), (2, 3, 4)) self.assertEqual(comp_args(), (2, 3, 4))
''')
def test_argument_order(self): def test_argument_order(self):
try: try:

View file

@ -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

View file

@ -1,31 +1,23 @@
import unittest import unittest
from test import test_support from test import test_support
import textwrap
import warnings
class ComplexArgsTestCase(unittest.TestCase): class ComplexArgsTestCase(unittest.TestCase):
def check(self, func, expected, *args): def check(self, func, expected, *args):
self.assertEqual(func(*args), expected) self.assertEqual(func(*args), expected)
# These functions are tested below as lambdas too. If you add a # These functions are tested below as lambdas too. If you add a function test,
# function test, also add a similar lambda test. # also add a similar lambda test.
# Functions are wrapped in "exec" statements in order to
# silence Py3k warnings
def test_func_parens_no_unpacking(self): def test_func_parens_no_unpacking(self):
exec textwrap.dedent("""
def f(((((x))))): return x def f(((((x))))): return x
self.check(f, 1, 1) self.check(f, 1, 1)
# Inner parens are elided, same as: f(x,) # Inner parens are elided, same as: f(x,)
def f(((x)),): return x def f(((x)),): return x
self.check(f, 2, 2) self.check(f, 2, 2)
""")
def test_func_1(self): def test_func_1(self):
exec textwrap.dedent("""
def f(((((x),)))): return x def f(((((x),)))): return x
self.check(f, 3, (3,)) self.check(f, 3, (3,))
def f(((((x)),))): return x def f(((((x)),))): return x
@ -34,22 +26,16 @@ class ComplexArgsTestCase(unittest.TestCase):
self.check(f, 5, (5,)) self.check(f, 5, (5,))
def f(((x),)): return x def f(((x),)): return x
self.check(f, 6, (6,)) self.check(f, 6, (6,))
""")
def test_func_2(self): def test_func_2(self):
exec textwrap.dedent("""
def f(((((x)),),)): return x def f(((((x)),),)): return x
self.check(f, 2, ((2,),)) self.check(f, 2, ((2,),))
""")
def test_func_3(self): def test_func_3(self):
exec textwrap.dedent("""
def f((((((x)),),),)): return x def f((((((x)),),),)): return x
self.check(f, 3, (((3,),),)) self.check(f, 3, (((3,),),))
""")
def test_func_complex(self): def test_func_complex(self):
exec textwrap.dedent("""
def f((((((x)),),),), a, b, c): return x, a, b, c def f((((((x)),),),), a, b, c): return x, a, b, c
self.check(f, (3, 9, 8, 7), (((3,),),), 9, 8, 7) self.check(f, (3, 9, 8, 7), (((3,),),), 9, 8, 7)
@ -58,22 +44,18 @@ class ComplexArgsTestCase(unittest.TestCase):
def f(a, b, c, ((((((x)),)),),)): return a, b, c, x def f(a, b, c, ((((((x)),)),),)): return a, b, c, x
self.check(f, (9, 8, 7, 3), 9, 8, 7, (((3,),),)) self.check(f, (9, 8, 7, 3), 9, 8, 7, (((3,),),))
""")
# Duplicate the tests above, but for lambda. If you add a lambda test, # Duplicate the tests above, but for lambda. If you add a lambda test,
# also add a similar function test above. # also add a similar function test above.
def test_lambda_parens_no_unpacking(self): def test_lambda_parens_no_unpacking(self):
exec textwrap.dedent("""
f = lambda (((((x))))): x f = lambda (((((x))))): x
self.check(f, 1, 1) self.check(f, 1, 1)
# Inner parens are elided, same as: f(x,) # Inner parens are elided, same as: f(x,)
f = lambda ((x)),: x f = lambda ((x)),: x
self.check(f, 2, 2) self.check(f, 2, 2)
""")
def test_lambda_1(self): def test_lambda_1(self):
exec textwrap.dedent("""
f = lambda (((((x),)))): x f = lambda (((((x),)))): x
self.check(f, 3, (3,)) self.check(f, 3, (3,))
f = lambda (((((x)),))): x f = lambda (((((x)),))): x
@ -82,22 +64,16 @@ class ComplexArgsTestCase(unittest.TestCase):
self.check(f, 5, (5,)) self.check(f, 5, (5,))
f = lambda (((x),)): x f = lambda (((x),)): x
self.check(f, 6, (6,)) self.check(f, 6, (6,))
""")
def test_lambda_2(self): def test_lambda_2(self):
exec textwrap.dedent("""
f = lambda (((((x)),),)): x f = lambda (((((x)),),)): x
self.check(f, 2, ((2,),)) self.check(f, 2, ((2,),))
""")
def test_lambda_3(self): def test_lambda_3(self):
exec textwrap.dedent("""
f = lambda ((((((x)),),),)): x f = lambda ((((((x)),),),)): x
self.check(f, 3, (((3,),),)) self.check(f, 3, (((3,),),))
""")
def test_lambda_complex(self): def test_lambda_complex(self):
exec textwrap.dedent("""
f = lambda (((((x)),),),), a, b, c: (x, a, b, c) f = lambda (((((x)),),),), a, b, c: (x, a, b, c)
self.check(f, (3, 9, 8, 7), (((3,),),), 9, 8, 7) self.check(f, (3, 9, 8, 7), (((3,),),), 9, 8, 7)
@ -106,17 +82,10 @@ class ComplexArgsTestCase(unittest.TestCase):
f = lambda a, b, c, ((((((x)),)),),): (a, b, c, x) f = lambda a, b, c, ((((((x)),)),),): (a, b, c, x)
self.check(f, (9, 8, 7, 3), 9, 8, 7, (((3,),),)) self.check(f, (9, 8, 7, 3), 9, 8, 7, (((3,),),))
""")
def test_main(): def test_main():
with warnings.catch_warnings(): test_support.run_unittest(ComplexArgsTestCase)
# Silence Py3k warnings
warnings.filterwarnings("ignore", "tuple parameter unpacking "
"has been removed", SyntaxWarning)
warnings.filterwarnings("ignore", "parenthesized argument names "
"are invalid", SyntaxWarning)
test_support.run_unittest(ComplexArgsTestCase)
if __name__ == "__main__": if __name__ == "__main__":
test_main() test_main()

View file

@ -661,7 +661,7 @@ class TestCopy(unittest.TestCase):
v = copy.deepcopy(u) v = copy.deepcopy(u)
self.assertNotEqual(v, u) self.assertNotEqual(v, u)
self.assertEqual(len(v), 2) self.assertEqual(len(v), 2)
(x, y), (z, t) = sorted(v.items(), key=lambda k: k[0].i) (x, y), (z, t) = sorted(v.items(), key=lambda (k, v): k.i)
self.assertFalse(x is a) self.assertFalse(x is a)
self.assertEqual(x.i, a.i) self.assertEqual(x.i, a.i)
self.assertTrue(y is b) self.assertTrue(y is b)

View file

@ -4,19 +4,12 @@ from test.test_support import run_unittest, import_module
#Skip tests if _ctypes module does not exist #Skip tests if _ctypes module does not exist
import_module('_ctypes') import_module('_ctypes')
import warnings
import ctypes.test import ctypes.test
def test_main(): def test_main():
skipped, testcases = ctypes.test.get_tests(ctypes.test, "test_*.py", verbosity=0) skipped, testcases = ctypes.test.get_tests(ctypes.test, "test_*.py", verbosity=0)
suites = [unittest.makeSuite(t) for t in testcases] suites = [unittest.makeSuite(t) for t in testcases]
with warnings.catch_warnings(): run_unittest(unittest.TestSuite(suites))
# Silence Py3k warnings
warnings.filterwarnings("ignore", "buffer.. not supported",
DeprecationWarning)
warnings.filterwarnings("ignore", "classic long division",
DeprecationWarning)
run_unittest(unittest.TestSuite(suites))
if __name__ == "__main__": if __name__ == "__main__":
test_main() test_main()

View file

@ -31,8 +31,7 @@ import pickle, copy
import unittest import unittest
from decimal import * from decimal import *
import numbers import numbers
from test.test_support import (run_unittest, run_doctest, from test.test_support import (run_unittest, run_doctest, is_resource_enabled)
is_resource_enabled, check_warnings)
import random import random
try: try:
import threading import threading
@ -203,7 +202,7 @@ class DecimalTest(unittest.TestCase):
if skip_expected: if skip_expected:
raise unittest.SkipTest raise unittest.SkipTest
return return
for line in open(file): for line in open(file).xreadlines():
line = line.replace('\r\n', '').replace('\n', '') line = line.replace('\r\n', '').replace('\n', '')
#print line #print line
try: try:
@ -362,10 +361,8 @@ class DecimalTest(unittest.TestCase):
myexceptions = self.getexceptions() myexceptions = self.getexceptions()
self.context.clear_flags() self.context.clear_flags()
# Silence Py3k warning myexceptions.sort()
with check_warnings(): theirexceptions.sort()
myexceptions.sort()
theirexceptions.sort()
self.assertEqual(result, ans, self.assertEqual(result, ans,
'Incorrect answer for ' + s + ' -- got ' + result) 'Incorrect answer for ' + s + ' -- got ' + result)
@ -620,14 +617,12 @@ class DecimalImplicitConstructionTest(unittest.TestCase):
('//', '__floordiv__', '__rfloordiv__'), ('//', '__floordiv__', '__rfloordiv__'),
('**', '__pow__', '__rpow__') ('**', '__pow__', '__rpow__')
] ]
# Silence Py3k warning if 1/2 == 0:
with check_warnings(): # testing with classic division, so add __div__
if 1/2 == 0: oplist.append(('/', '__div__', '__rdiv__'))
# testing with classic division, so add __div__ else:
oplist.append(('/', '__div__', '__rdiv__')) # testing with -Qnew, so add __truediv__
else: oplist.append(('/', '__truediv__', '__rtruediv__'))
# testing with -Qnew, so add __truediv__
oplist.append(('/', '__truediv__', '__rtruediv__'))
for sym, lop, rop in oplist: for sym, lop, rop in oplist:
setattr(E, lop, lambda self, other: 'str' + lop + str(other)) setattr(E, lop, lambda self, other: 'str' + lop + str(other))
@ -1199,10 +1194,8 @@ class DecimalUsabilityTest(unittest.TestCase):
self.assertEqual(a, b) self.assertEqual(a, b)
# with None # with None
# Silence Py3k warning self.assertFalse(Decimal(1) < None)
with check_warnings(): self.assertTrue(Decimal(1) > None)
self.assertFalse(Decimal(1) < None)
self.assertTrue(Decimal(1) > None)
def test_copy_and_deepcopy_methods(self): def test_copy_and_deepcopy_methods(self):
d = Decimal('43.24') d = Decimal('43.24')
@ -1711,14 +1704,11 @@ class ContextFlags(unittest.TestCase):
for flag in extra_flags: for flag in extra_flags:
if flag not in expected_flags: if flag not in expected_flags:
expected_flags.append(flag) expected_flags.append(flag)
expected_flags.sort()
# flags we actually got # flags we actually got
new_flags = [k for k,v in context.flags.items() if v] new_flags = [k for k,v in context.flags.items() if v]
new_flags.sort()
# Silence Py3k warning
with check_warnings():
expected_flags.sort()
new_flags.sort()
self.assertEqual(ans, new_ans, self.assertEqual(ans, new_ans,
"operation produces different answers depending on flags set: " + "operation produces different answers depending on flags set: " +

View file

@ -4598,19 +4598,9 @@ class PTypesLongInitTest(unittest.TestCase):
def test_main(): def test_main():
with warnings.catch_warnings(): # Run all local test cases, with PTypesLongInitTest first.
# Silence Py3k warnings test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
warnings.filterwarnings("ignore", "classic .+ division", ClassPropertiesAndMethods, DictProxyTests)
DeprecationWarning)
warnings.filterwarnings("ignore", "coerce.. not supported",
DeprecationWarning)
warnings.filterwarnings("ignore", "Overriding __cmp__ ",
DeprecationWarning)
warnings.filterwarnings("ignore", ".+slice__ has been removed",
DeprecationWarning)
# Run all local test cases, with PTypesLongInitTest first.
test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
ClassPropertiesAndMethods, DictProxyTests)
if __name__ == "__main__": if __name__ == "__main__":
test_main() test_main()

View file

@ -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(key=str) ... seq.sort()
... return seq ... return seq
>>> print sorted(a.keys()) >>> print sorted(a.keys())
[1, 2] [1, 2]

View file

@ -33,12 +33,8 @@ class DictTest(unittest.TestCase):
self.assertEqual(d.keys(), []) self.assertEqual(d.keys(), [])
d = {'a': 1, 'b': 2} d = {'a': 1, 'b': 2}
k = d.keys() k = d.keys()
self.assertTrue('a' in d) self.assertTrue(d.has_key('a'))
self.assertTrue('b' in d) self.assertTrue(d.has_key('b'))
# Silence Py3k warning
with test_support.check_warnings():
self.assertTrue(d.has_key('a'))
self.assertTrue(d.has_key('b'))
self.assertRaises(TypeError, d.keys, None) self.assertRaises(TypeError, d.keys, None)
@ -61,16 +57,14 @@ class DictTest(unittest.TestCase):
def test_has_key(self): def test_has_key(self):
d = {} d = {}
self.assertTrue('a' not in d) self.assertTrue(not d.has_key('a'))
# Silence Py3k warning
with test_support.check_warnings():
self.assertTrue(not d.has_key('a'))
self.assertRaises(TypeError, d.has_key)
d = {'a': 1, 'b': 2} d = {'a': 1, 'b': 2}
k = d.keys() k = d.keys()
k.sort() k.sort()
self.assertEqual(k, ['a', 'b']) self.assertEqual(k, ['a', 'b'])
self.assertRaises(TypeError, d.has_key)
def test_contains(self): def test_contains(self):
d = {} d = {}
self.assertTrue(not ('a' in d)) self.assertTrue(not ('a' in d))
@ -401,6 +395,8 @@ class DictTest(unittest.TestCase):
self.assertRaises(Exc, repr, d) self.assertRaises(Exc, repr, d)
def test_le(self): def test_le(self):
self.assertTrue(not ({} < {}))
self.assertTrue(not ({1: 2} < {1L: 2L}))
class Exc(Exception): pass class Exc(Exception): pass
@ -412,18 +408,12 @@ class DictTest(unittest.TestCase):
d1 = {BadCmp(): 1} d1 = {BadCmp(): 1}
d2 = {1: 1} d2 = {1: 1}
try:
# Silence Py3k warning d1 < d2
with test_support.check_warnings(): except Exc:
self.assertTrue(not ({} < {})) pass
self.assertTrue(not ({1: 2} < {1L: 2L})) else:
self.fail("< didn't raise Exc")
try:
d1 < d2
except Exc:
pass
else:
self.fail("< didn't raise Exc")
def test_missing(self): def test_missing(self):
# Make sure dict doesn't have a __missing__ method # Make sure dict doesn't have a __missing__ method
@ -511,9 +501,7 @@ class DictTest(unittest.TestCase):
'd.pop(x2)', 'd.pop(x2)',
'd.update({x2: 2})']: 'd.update({x2: 2})']:
try: try:
# Silence Py3k warning exec stmt in locals()
with test_support.check_warnings():
exec stmt in locals()
except CustomException: except CustomException:
pass pass
else: else:
@ -561,7 +549,7 @@ class DictTest(unittest.TestCase):
# Bug #3537: if an empty but presized dict with a size larger # Bug #3537: if an empty but presized dict with a size larger
# than 7 was in the freelist, it triggered an assertion failure # than 7 was in the freelist, it triggered an assertion failure
try: try:
d = {'a': 1 // 0, 'b': None, 'c': None, 'd': None, 'e': None, d = {'a': 1/0, 'b': None, 'c': None, 'd': None, 'e': None,
'f': None, 'g': None, 'h': None} 'f': None, 'g': None, 'h': None}
except ZeroDivisionError: except ZeroDivisionError:
pass pass

View file

@ -7,7 +7,7 @@ import pickle, cPickle
import warnings import warnings
from test.test_support import TESTFN, unlink, run_unittest, captured_output from test.test_support import TESTFN, unlink, run_unittest, captured_output
from test.test_pep352 import ignore_deprecation_warnings from test.test_pep352 import ignore_message_warning
# XXX This is not really enough, each *operation* should be tested! # XXX This is not really enough, each *operation* should be tested!
@ -17,7 +17,6 @@ class ExceptionTests(unittest.TestCase):
# Reloading the built-in exceptions module failed prior to Py2.2, while it # Reloading the built-in exceptions module failed prior to Py2.2, while it
# should act the same as reloading built-in sys. # should act the same as reloading built-in sys.
try: try:
from imp import reload
import exceptions import exceptions
reload(exceptions) reload(exceptions)
except ImportError, e: except ImportError, e:
@ -109,11 +108,11 @@ class ExceptionTests(unittest.TestCase):
self.assertRaises(ValueError, chr, 10000) self.assertRaises(ValueError, chr, 10000)
self.raise_catch(ZeroDivisionError, "ZeroDivisionError") self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
try: x = 1 // 0 try: x = 1/0
except ZeroDivisionError: pass except ZeroDivisionError: pass
self.raise_catch(Exception, "Exception") self.raise_catch(Exception, "Exception")
try: x = 1 // 0 try: x = 1/0
except Exception, e: pass except Exception, e: pass
def testSyntaxErrorMessage(self): def testSyntaxErrorMessage(self):
@ -198,7 +197,6 @@ class ExceptionTests(unittest.TestCase):
self.assertEqual(WindowsError(1001, "message").errno, 22) self.assertEqual(WindowsError(1001, "message").errno, 22)
self.assertEqual(WindowsError(1001, "message").winerror, 1001) self.assertEqual(WindowsError(1001, "message").winerror, 1001)
@ignore_deprecation_warnings
def testAttributes(self): def testAttributes(self):
# test that exception attributes are happy # test that exception attributes are happy
@ -276,32 +274,34 @@ class ExceptionTests(unittest.TestCase):
except NameError: except NameError:
pass pass
for exc, args, expected in exceptionList: with warnings.catch_warnings():
try: ignore_message_warning()
raise exc(*args) for exc, args, expected in exceptionList:
except BaseException, e: try:
if type(e) is not exc: raise exc(*args)
raise except BaseException, e:
# Verify module name if type(e) is not exc:
self.assertEquals(type(e).__module__, 'exceptions') raise
# Verify no ref leaks in Exc_str() # Verify module name
s = str(e) self.assertEquals(type(e).__module__, 'exceptions')
for checkArgName in expected: # Verify no ref leaks in Exc_str()
self.assertEquals(repr(getattr(e, checkArgName)), s = str(e)
repr(expected[checkArgName]), for checkArgName in expected:
'exception "%s", attribute "%s"' % self.assertEquals(repr(getattr(e, checkArgName)),
(repr(e), checkArgName)) repr(expected[checkArgName]),
'exception "%s", attribute "%s"' %
(repr(e), checkArgName))
# test for pickling support # test for pickling support
for p in pickle, cPickle: for p in pickle, cPickle:
for protocol in range(p.HIGHEST_PROTOCOL + 1): for protocol in range(p.HIGHEST_PROTOCOL + 1):
new = p.loads(p.dumps(e, protocol)) new = p.loads(p.dumps(e, protocol))
for checkArgName in expected: for checkArgName in expected:
got = repr(getattr(new, checkArgName)) got = repr(getattr(new, checkArgName))
want = repr(expected[checkArgName]) want = repr(expected[checkArgName])
self.assertEquals(got, want, self.assertEquals(got, want,
'pickled "%r", attribute "%s"' % 'pickled "%r", attribute "%s"' %
(e, checkArgName)) (e, checkArgName))
def testDeprecatedMessageAttribute(self): def testDeprecatedMessageAttribute(self):
@ -330,7 +330,6 @@ class ExceptionTests(unittest.TestCase):
with self.assertRaises(AttributeError): with self.assertRaises(AttributeError):
exc.message exc.message
@ignore_deprecation_warnings
def testPickleMessageAttribute(self): def testPickleMessageAttribute(self):
# Pickling with message attribute must work, as well. # Pickling with message attribute must work, as well.
e = Exception("foo") e = Exception("foo")
@ -338,7 +337,9 @@ class ExceptionTests(unittest.TestCase):
f.message = "bar" f.message = "bar"
for p in pickle, cPickle: for p in pickle, cPickle:
ep = p.loads(p.dumps(e)) ep = p.loads(p.dumps(e))
self.assertEqual(ep.message, "foo") with warnings.catch_warnings():
ignore_message_warning()
self.assertEqual(ep.message, "foo")
fp = p.loads(p.dumps(f)) fp = p.loads(p.dumps(f))
self.assertEqual(fp.message, "bar") self.assertEqual(fp.message, "bar")
@ -347,12 +348,7 @@ class ExceptionTests(unittest.TestCase):
# going through the 'args' attribute. # going through the 'args' attribute.
args = (1, 2, 3) args = (1, 2, 3)
exc = BaseException(*args) exc = BaseException(*args)
self.assertEqual(exc.args[:], args) self.assertEqual(exc[:], args)
with warnings.catch_warnings():
# Silence Py3k warning
warnings.filterwarnings("ignore", "__getslice__ not supported for "
"exception classes", DeprecationWarning)
self.assertEqual(exc[:], args)
def testKeywordArgs(self): def testKeywordArgs(self):
# test that builtin exception don't take keyword args, # test that builtin exception don't take keyword args,

View file

@ -127,7 +127,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)

View file

@ -34,17 +34,13 @@ class AutoFileTests(unittest.TestCase):
def testAttributes(self): def testAttributes(self):
# verify expected attributes exist # verify expected attributes exist
f = self.f f = self.f
# Silence Py3k warning softspace = f.softspace
with test_support.check_warnings():
softspace = f.softspace
f.name # merely shouldn't blow up f.name # merely shouldn't blow up
f.mode # ditto f.mode # ditto
f.closed # ditto f.closed # ditto
# Silence Py3k warning # verify softspace is writable
with test_support.check_warnings(): f.softspace = softspace # merely shouldn't blow up
# verify softspace is writable
f.softspace = softspace # merely shouldn't blow up
# verify the others aren't # verify the others aren't
for attr in 'name', 'mode', 'closed': for attr in 'name', 'mode', 'closed':
@ -102,8 +98,7 @@ class AutoFileTests(unittest.TestCase):
def testMethods(self): def testMethods(self):
methods = ['fileno', 'flush', 'isatty', 'next', 'read', 'readinto', methods = ['fileno', 'flush', 'isatty', 'next', 'read', 'readinto',
'readline', 'readlines', 'seek', 'tell', 'truncate', 'readline', 'readlines', 'seek', 'tell', 'truncate',
'write', '__iter__'] 'write', 'xreadlines', '__iter__']
deprecated_methods = ['xreadlines']
if sys.platform.startswith('atheos'): if sys.platform.startswith('atheos'):
methods.remove('truncate') methods.remove('truncate')
@ -115,18 +110,13 @@ class AutoFileTests(unittest.TestCase):
method = getattr(self.f, methodname) method = getattr(self.f, methodname)
# should raise on closed file # should raise on closed file
self.assertRaises(ValueError, method) self.assertRaises(ValueError, method)
# Silence Py3k warning
with test_support.check_warnings():
for methodname in deprecated_methods:
method = getattr(self.f, methodname)
self.assertRaises(ValueError, method)
self.assertRaises(ValueError, self.f.writelines, []) self.assertRaises(ValueError, self.f.writelines, [])
# file is closed, __exit__ shouldn't do anything # file is closed, __exit__ shouldn't do anything
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)
@ -192,12 +182,12 @@ class OtherFileTests(unittest.TestCase):
try: try:
f = open(TESTFN, bad_mode) f = open(TESTFN, bad_mode)
except ValueError, msg: except ValueError, msg:
if msg.args[0] != 0: if msg[0] != 0:
s = str(msg) s = str(msg)
if s.find(TESTFN) != -1 or s.find(bad_mode) == -1: if s.find(TESTFN) != -1 or s.find(bad_mode) == -1:
self.fail("bad error message for invalid mode: %s" % s) self.fail("bad error message for invalid mode: %s" % s)
# if msg.args[0] == 0, we're probably on Windows where there may # if msg[0] == 0, we're probably on Windows where there may be
# be no obvious way to discover why open() failed. # no obvious way to discover why open() failed.
else: else:
f.close() f.close()
self.fail("no error for invalid mode: %s" % bad_mode) self.fail("no error for invalid mode: %s" % bad_mode)

View file

@ -43,10 +43,6 @@ class DummyFloat(object):
assert False, "__sub__ should not be invoked for comparisons" assert False, "__sub__ should not be invoked for comparisons"
__rsub__ = __sub__ __rsub__ = __sub__
# Silence Py3k warning
def __hash__(self):
assert False, "__hash__ should not be invoked for comparisons"
class DummyRational(object): class DummyRational(object):
"""Test comparison of Fraction with a naive rational implementation.""" """Test comparison of Fraction with a naive rational implementation."""
@ -80,11 +76,6 @@ class DummyRational(object):
def __float__(self): def __float__(self):
assert False, "__float__ should not be invoked" assert False, "__float__ should not be invoked"
# Silence Py3k warning
def __hash__(self):
assert False, "__hash__ should not be invoked for comparisons"
class GcdTest(unittest.TestCase): class GcdTest(unittest.TestCase):
def testMisc(self): def testMisc(self):

View file

@ -100,7 +100,7 @@ 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, p2 = divmod(port, 256) ip = ip.replace('.', ','); p1 = port / 256; p2 = 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 = self.dtp_handler(conn, baseclass=self) self.dtp = self.dtp_handler(conn, baseclass=self)

View file

@ -116,7 +116,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)

View file

@ -11,7 +11,6 @@
from test.test_support import run_unittest, check_syntax_error from test.test_support import run_unittest, check_syntax_error
import unittest import unittest
import sys import sys
import warnings
# testing import * # testing import *
from sys import * from sys import *
@ -153,9 +152,8 @@ 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
# Silence Py3k warning def f4(two, (compound, (argument, list))): pass
exec('def f4(two, (compound, (argument, list))): pass') def f5((compound, first), two): 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'):
@ -174,8 +172,7 @@ 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
# Silence Py3k warning def v3(a, (b, c), *rest): return a, b, c, rest
exec('def v3(a, (b, c), *rest): return a, b, c, rest')
f1() f1()
f2(1) f2(1)
@ -280,10 +277,9 @@ 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})
# Silence Py3k warning def d31v((x)): pass
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
@ -478,7 +474,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()
@ -681,6 +677,7 @@ 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
@ -689,10 +686,7 @@ 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 in 1 not in 1 is 1 is not 1: pass if 1 < 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
@ -775,10 +769,9 @@ 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}
# Silence Py3k warning x = `x`
x = eval('`x`') x = `1 or 2 or 3`
x = eval('`1 or 2 or 3`') self.assertEqual(`1,2`, '(1, 2)')
self.assertEqual(eval('`1,2`'), '(1, 2)')
x = x x = x
x = 'x' x = 'x'
@ -983,19 +976,7 @@ hello world
def test_main(): def test_main():
with warnings.catch_warnings(): run_unittest(TokenTests, GrammarTests)
# Silence Py3k warnings
warnings.filterwarnings("ignore", "backquote not supported",
SyntaxWarning)
warnings.filterwarnings("ignore", "tuple parameter unpacking has been removed",
SyntaxWarning)
warnings.filterwarnings("ignore", "parenthesized argument names are invalid",
SyntaxWarning)
warnings.filterwarnings("ignore", "classic int division",
DeprecationWarning)
warnings.filterwarnings("ignore", ".+ not supported in 3.x",
DeprecationWarning)
run_unittest(TokenTests, GrammarTests)
if __name__ == '__main__': if __name__ == '__main__':
test_main() test_main()

View file

@ -246,11 +246,11 @@ class TestGzip(unittest.TestCase):
self.fail("__enter__ on a closed file didn't raise an exception") self.fail("__enter__ on a closed file didn't raise an exception")
try: try:
with gzip.GzipFile(self.filename, "wb") as f: with gzip.GzipFile(self.filename, "wb") as f:
1 // 0 1/0
except ZeroDivisionError: except ZeroDivisionError:
pass pass
else: else:
self.fail("1 // 0 didn't raise an exception") self.fail("1/0 didn't raise an exception")
def test_main(verbose=None): def test_main(verbose=None):
test_support.run_unittest(TestGzip) test_support.run_unittest(TestGzip)

View file

@ -356,8 +356,7 @@ class TestErrorHandling(unittest.TestCase):
for f in (self.module.nlargest, self.module.nsmallest): for f in (self.module.nlargest, self.module.nsmallest):
for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
for g in (G, I, Ig, L, R): for g in (G, I, Ig, L, R):
with test_support.check_warnings(): self.assertEqual(f(2, g(s)), f(2,s))
self.assertEqual(f(2, g(s)), f(2,s))
self.assertEqual(f(2, S(s)), []) self.assertEqual(f(2, S(s)), [])
self.assertRaises(TypeError, f, 2, X(s)) self.assertRaises(TypeError, f, 2, X(s))
self.assertRaises(TypeError, f, 2, N(s)) self.assertRaises(TypeError, f, 2, N(s))

View file

@ -1,3 +1,5 @@
import hotshot
import hotshot.log
import os import os
import pprint import pprint
import unittest import unittest
@ -7,8 +9,6 @@ import gc
from test import test_support from test import test_support
# Silence Py3k warning
hotshot = test_support.import_module('hotshot', deprecated=True)
from hotshot.log import ENTER, EXIT, LINE from hotshot.log import ENTER, EXIT, LINE

View file

@ -7,7 +7,6 @@ import sys
import py_compile import py_compile
import warnings import warnings
import marshal import marshal
from imp import reload
from test.test_support import (unlink, TESTFN, unload, run_unittest, from test.test_support import (unlink, TESTFN, unload, run_unittest,
check_warnings, TestFailed, EnvironmentVarGuard) check_warnings, TestFailed, EnvironmentVarGuard)
@ -57,10 +56,11 @@ class ImportTest(unittest.TestCase):
f.close() f.close()
try: try:
mod = __import__(TESTFN) try:
except ImportError, err: mod = __import__(TESTFN)
self.fail("import from %s failed: %s" % (ext, err)) except ImportError, err:
else: self.fail("import from %s failed: %s" % (ext, err))
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,9 +69,10 @@ class ImportTest(unittest.TestCase):
os.unlink(source) os.unlink(source)
try: try:
reload(mod) try:
except ImportError, err: reload(mod)
self.fail("import from .pyc/.pyo failed: %s" % err) except ImportError, err:
self.fail("import from .pyc/.pyo failed: %s" % err)
finally: finally:
try: try:
os.unlink(pyc) os.unlink(pyc)
@ -171,7 +172,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

View file

@ -180,7 +180,7 @@ class ImportHooksTestCase(ImportHooksBaseTestCase):
self.assertFalse(hasattr(reloadmodule,'reloaded')) self.assertFalse(hasattr(reloadmodule,'reloaded'))
TestImporter.modules['reloadmodule'] = (False, reload_co) TestImporter.modules['reloadmodule'] = (False, reload_co)
imp.reload(reloadmodule) reload(reloadmodule)
self.assertTrue(hasattr(reloadmodule,'reloaded')) self.assertTrue(hasattr(reloadmodule,'reloaded'))
import hooktestpackage.oldabs import hooktestpackage.oldabs
@ -247,11 +247,9 @@ 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]
# Silence Py3k warning for mname in mnames:
with test_support.check_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():

View file

@ -4,11 +4,10 @@ import unittest
import inspect import inspect
import datetime import datetime
from test.test_support import TESTFN, run_unittest, check_warnings from test.test_support import TESTFN, run_unittest
with check_warnings(): from test import inspect_fodder as mod
from test import inspect_fodder as mod from test import inspect_fodder2 as mod2
from test import inspect_fodder2 as mod2
# C module for test_findsource_binary # C module for test_findsource_binary
import unicodedata import unicodedata
@ -30,7 +29,7 @@ if modfile.endswith(('c', 'o')):
import __builtin__ import __builtin__
try: try:
1 // 0 1/0
except: except:
tb = sys.exc_traceback tb = sys.exc_traceback
@ -168,7 +167,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)
@ -419,13 +418,11 @@ class TestClassesAndFunctions(unittest.TestCase):
self.assertArgSpecEquals(A.m, ['self']) self.assertArgSpecEquals(A.m, ['self'])
def test_getargspec_sublistofone(self): def test_getargspec_sublistofone(self):
# Silence Py3k warning def sublistOfOne((foo,)): return 1
with check_warnings(): self.assertArgSpecEquals(sublistOfOne, [['foo']])
exec 'def sublistOfOne((foo,)): return 1'
self.assertArgSpecEquals(sublistOfOne, [['foo']])
exec 'def fakeSublistOfOne((foo)): return 1' def fakeSublistOfOne((foo)): return 1
self.assertArgSpecEquals(fakeSublistOfOne, ['foo']) self.assertArgSpecEquals(fakeSublistOfOne, ['foo'])
def test_classify_oldstyle(self): def test_classify_oldstyle(self):
class A: class A:

View file

@ -381,11 +381,11 @@ class IOTest(unittest.TestCase):
f = None f = None
try: try:
with self.open(support.TESTFN, "wb", bufsize) as f: with self.open(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):

View file

@ -1,8 +1,7 @@
# Test iterators. # Test iterators.
import unittest import unittest
from test.test_support import run_unittest, TESTFN, unlink, have_unicode, \ from test.test_support import run_unittest, TESTFN, unlink, have_unicode
check_warnings
# Test result of triple loop (too big to inline) # Test result of triple loop (too big to inline)
TRIPLETS = [(0, 0, 0), (0, 0, 1), (0, 0, 2), TRIPLETS = [(0, 0, 0), (0, 0, 1), (0, 0, 2),
@ -396,12 +395,7 @@ class TestCase(unittest.TestCase):
pass pass
# Test map()'s use of iterators. # Test map()'s use of iterators.
def test_deprecated_builtin_map(self): def test_builtin_map(self):
# Silence Py3k warning
with check_warnings():
self._test_builtin_map()
def _test_builtin_map(self):
self.assertEqual(map(None, SequenceClass(5)), range(5)) self.assertEqual(map(None, SequenceClass(5)), range(5))
self.assertEqual(map(lambda x: x+1, SequenceClass(5)), range(1, 6)) self.assertEqual(map(lambda x: x+1, SequenceClass(5)), range(1, 6))
@ -512,12 +506,7 @@ class TestCase(unittest.TestCase):
self.assertEqual(zip(x, y), expected) self.assertEqual(zip(x, y), expected)
# Test reduces()'s use of iterators. # Test reduces()'s use of iterators.
def test_deprecated_builtin_reduce(self): def test_builtin_reduce(self):
# Silence Py3k warning
with check_warnings():
self._test_builtin_reduce()
def _test_builtin_reduce(self):
from operator import add from operator import add
self.assertEqual(reduce(add, SequenceClass(5)), 10) self.assertEqual(reduce(add, SequenceClass(5)), 10)
self.assertEqual(reduce(add, SequenceClass(5), 42), 52) self.assertEqual(reduce(add, SequenceClass(5), 42), 52)

View file

@ -9,7 +9,6 @@ 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
@ -123,7 +122,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:
@ -179,7 +178,7 @@ class TestBasicOps(unittest.TestCase):
def numcombs(n, r): def numcombs(n, r):
if not n: if not n:
return 0 if r else 1 return 0 if r else 1
return fact(n+r-1) // fact(r) // fact(n-1) return fact(n+r-1) / fact(r)/ fact(n-1)
for n in range(7): for n in range(7):
values = [5*x-12 for x in range(n)] values = [5*x-12 for x in range(n)]
@ -258,7 +257,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:
@ -289,9 +288,9 @@ class TestBasicOps(unittest.TestCase):
# Check size # Check size
self.assertEquals(len(prod), n**r) self.assertEquals(len(prod), n**r)
self.assertEquals(len(cwr), (fact(n+r-1) // fact(r) // fact(n-1)) if n else (not r)) self.assertEquals(len(cwr), (fact(n+r-1) / fact(r)/ fact(n-1)) if n else (not r))
self.assertEquals(len(perm), 0 if r>n else fact(n) // fact(n-r)) self.assertEquals(len(perm), 0 if r>n else fact(n) / fact(n-r))
self.assertEquals(len(comb), 0 if r>n else fact(n) // fact(r) // fact(n-r)) self.assertEquals(len(comb), 0 if r>n else fact(n) / fact(r) / fact(n-r))
# Check lexicographic order without repeated tuples # Check lexicographic order without repeated tuples
self.assertEquals(prod, sorted(set(prod))) self.assertEquals(prod, sorted(set(prod)))
@ -544,8 +543,7 @@ 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 = [tuple([arg[i] if i < len(arg) else None for arg in args]) target = map(None, *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'
@ -557,8 +555,7 @@ 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', **{})), self.assertEqual(list(izip_longest('abc', 'defg', **{})), map(None, 'abc', 'defg')) # empty keyword dict
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)
@ -1434,7 +1431,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 t:t[0]-t[1]): >>> for k, g in groupby(enumerate(data), lambda (i,x):i-x):
... print map(operator.itemgetter(1), g) ... print map(operator.itemgetter(1), g)
... ...
[1] [1]

View file

@ -7,15 +7,10 @@ be run.
import json.tests import json.tests
import test.test_support import test.test_support
import warnings
def test_main(): def test_main():
with warnings.catch_warnings(): test.test_support.run_unittest(json.tests.test_suite())
# Silence Py3k warning
warnings.filterwarnings("ignore", "comparing unequal types "
"not supported", DeprecationWarning)
test.test_support.run_unittest(json.tests.test_suite())
if __name__ == "__main__": if __name__ == "__main__":

View file

@ -4,13 +4,12 @@ test_support.requires('audio')
from test.test_support import findfile, run_unittest from test.test_support import findfile, run_unittest
import errno import errno
linuxaudiodev = test_support.import_module('linuxaudiodev', deprecated=True)
import sys import sys
import sunaudio
import audioop import audioop
import unittest import unittest
linuxaudiodev = test_support.import_module('linuxaudiodev', deprecated=True)
sunaudio = test_support.import_module('sunaudio', deprecated=True)
SND_FORMAT_MULAW_8 = 1 SND_FORMAT_MULAW_8 = 1
class LinuxAudioDevTests(unittest.TestCase): class LinuxAudioDevTests(unittest.TestCase):

View file

@ -575,13 +575,11 @@ class LongTest(unittest.TestCase):
def __getslice__(self, i, j): def __getslice__(self, i, j):
return i, j return i, j
# Silence Py3k warning self.assertEqual(X()[-5L:7L], (-5, 7))
with test_support.check_warnings(): # use the clamping effect to test the smallest and largest longs
self.assertEqual(X()[-5L:7L], (-5, 7)) # that fit a Py_ssize_t
# use the clamping effect to test the smallest and largest longs slicemin, slicemax = X()[-2L**100:2L**100]
# that fit a Py_ssize_t self.assertEqual(X()[slicemin:slicemax], (slicemin, slicemax))
slicemin, slicemax = X()[-2L**100:2L**100]
self.assertEqual(X()[slicemin:slicemax], (slicemin, slicemax))
# ----------------------------------- tests of auto int->long conversion # ----------------------------------- tests of auto int->long conversion
@ -621,10 +619,8 @@ class LongTest(unittest.TestCase):
checkit(x, '*', y) checkit(x, '*', y)
if y: if y:
# Silence Py3k warning expected = longx / longy
with test_support.check_warnings(): got = x / y
expected = longx / longy
got = x / y
checkit(x, '/', y) checkit(x, '/', y)
expected = longx // longy expected = longx // longy

View file

@ -5,6 +5,7 @@ import stat
import socket import socket
import email import email
import email.message import email.message
import rfc822
import re import re
import StringIO import StringIO
from test import test_support from test import test_support
@ -16,8 +17,6 @@ try:
except ImportError: except ImportError:
pass pass
# Silence Py3k warning
rfc822 = test_support.import_module('rfc822')
class TestBase(unittest.TestCase): class TestBase(unittest.TestCase):

View file

@ -129,9 +129,7 @@ class StringTestCase(unittest.TestCase):
def test_buffer(self): def test_buffer(self):
for s in ["", "Andrè Previn", "abc", " "*10000]: for s in ["", "Andrè Previn", "abc", " "*10000]:
# Silence Py3k warning b = buffer(s)
with test_support.check_warnings():
b = buffer(s)
new = marshal.loads(marshal.dumps(b)) new = marshal.loads(marshal.dumps(b))
self.assertEqual(s, new) self.assertEqual(s, new)
marshal.dump(b, file(test_support.TESTFN, "wb")) marshal.dump(b, file(test_support.TESTFN, "wb"))

View file

@ -307,7 +307,7 @@ class TestBase_Mapping(unittest.TestCase):
continue continue
unich = unichrs(data[1]) unich = unichrs(data[1])
if ord(unich) == 0xfffd or unich in urt_wa: if ord(unich) == 0xfffd or urt_wa.has_key(unich):
continue continue
urt_wa[unich] = csetch urt_wa[unich] = csetch

View file

@ -1,5 +1,5 @@
from test import test_support from test import test_support
mimetools = test_support.import_module("mimetools", deprecated=True) import mimetools
multifile = test_support.import_module('multifile', deprecated=True) multifile = test_support.import_module('multifile', deprecated=True)
import cStringIO import cStringIO

View file

@ -19,7 +19,6 @@ import random
import logging import logging
from test import test_support from test import test_support
from StringIO import StringIO from StringIO import StringIO
import warnings
_multiprocessing = test_support.import_module('_multiprocessing') _multiprocessing = test_support.import_module('_multiprocessing')
@ -1992,11 +1991,7 @@ def test_main(run=None):
loadTestsFromTestCase = unittest.defaultTestLoader.loadTestsFromTestCase loadTestsFromTestCase = unittest.defaultTestLoader.loadTestsFromTestCase
suite = unittest.TestSuite(loadTestsFromTestCase(tc) for tc in testcases) suite = unittest.TestSuite(loadTestsFromTestCase(tc) for tc in testcases)
with warnings.catch_warnings(): run(suite)
# Silence Py3k warnings
warnings.filterwarnings("ignore", ".+slice__ has been removed",
DeprecationWarning)
run(suite)
ThreadsMixin.pool.terminate() ThreadsMixin.pool.terminate()
ProcessesMixin.pool.terminate() ProcessesMixin.pool.terminate()

View file

@ -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 repr("machiavelli") return `"machiavelli"`
def __hash__(self): def __hash__(self):
return 0 return 0

View file

@ -2,7 +2,6 @@
from test.test_support import run_unittest from test.test_support import run_unittest
import unittest import unittest
import warnings
class OpcodeTest(unittest.TestCase): class OpcodeTest(unittest.TestCase):
@ -10,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
@ -111,14 +110,7 @@ class OpcodeTest(unittest.TestCase):
def test_main(): def test_main():
with warnings.catch_warnings(): run_unittest(OpcodeTest)
# Silence Py3k warning
warnings.filterwarnings("ignore", "exceptions must derive from "
"BaseException", DeprecationWarning)
warnings.filterwarnings("ignore", "catching classes that don't "
"inherit from BaseException is not allowed",
DeprecationWarning)
run_unittest(OpcodeTest)
if __name__ == '__main__': if __name__ == '__main__':
test_main() test_main()

View file

@ -192,12 +192,11 @@ class OperatorTestCase(unittest.TestCase):
class C: class C:
pass pass
def check(self, o, v): def check(self, o, v):
with test_support.check_warnings(): self.assertTrue(operator.isCallable(o) == callable(o) == v)
self.assertTrue(operator.isCallable(o) == callable(o) == v) check(self, 4, 0)
check(self, 4, False) check(self, operator.isCallable, 1)
check(self, operator.isCallable, True) check(self, C, 1)
check(self, C, True) check(self, C(), 0)
check(self, C(), False)
def test_isMappingType(self): def test_isMappingType(self):
self.assertRaises(TypeError, operator.isMappingType) self.assertRaises(TypeError, operator.isMappingType)
@ -307,10 +306,8 @@ class OperatorTestCase(unittest.TestCase):
self.assertRaises(TypeError, operator.contains, None, None) self.assertRaises(TypeError, operator.contains, None, None)
self.assertTrue(operator.contains(range(4), 2)) self.assertTrue(operator.contains(range(4), 2))
self.assertFalse(operator.contains(range(4), 5)) self.assertFalse(operator.contains(range(4), 5))
# Silence Py3k warning self.assertTrue(operator.sequenceIncludes(range(4), 2))
with test_support.check_warnings(): self.assertFalse(operator.sequenceIncludes(range(4), 5))
self.assertTrue(operator.sequenceIncludes(range(4), 2))
self.assertFalse(operator.sequenceIncludes(range(4), 5))
def test_setitem(self): def test_setitem(self):
a = range(3) a = range(3)

View file

@ -26,6 +26,12 @@ 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):

View file

@ -71,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)

View file

@ -205,24 +205,18 @@ class TestTranforms(unittest.TestCase):
def test_main(verbose=None): def test_main(verbose=None):
import sys import sys
from test import test_support from test import test_support
import warnings
test_classes = (TestTranforms,) test_classes = (TestTranforms,)
test_support.run_unittest(*test_classes)
with warnings.catch_warnings(): # verify reference counting
# Silence Py3k warning if verbose and hasattr(sys, "gettotalrefcount"):
warnings.filterwarnings("ignore", "backquote not supported", import gc
SyntaxWarning) counts = [None] * 5
test_support.run_unittest(*test_classes) for i in xrange(len(counts)):
test_support.run_unittest(*test_classes)
# verify reference counting gc.collect()
if verbose and hasattr(sys, "gettotalrefcount"): counts[i] = sys.gettotalrefcount()
import gc print counts
counts = [None] * 5
for i in xrange(len(counts)):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
print counts
if __name__ == "__main__": if __name__ == "__main__":
test_main(verbose=True) test_main(verbose=True)

View file

@ -6,23 +6,12 @@ from test.test_support import run_unittest
import os import os
from platform import system as platform_system from platform import system as platform_system
DEPRECATION_WARNINGS = ( def ignore_message_warning():
"BaseException.message has been deprecated", """Ignore the DeprecationWarning for BaseException.message."""
"exceptions must derive from BaseException", warnings.resetwarnings()
"catching classes that don't inherit from BaseException is not allowed", warnings.filterwarnings("ignore", "BaseException.message",
"__getitem__ not supported for exception classes", DeprecationWarning)
)
# Silence Py3k and other deprecation warnings
def ignore_deprecation_warnings(func):
"""Ignore the known DeprecationWarnings."""
def wrapper(*args, **kw):
with warnings.catch_warnings():
warnings.resetwarnings()
for text in DEPRECATION_WARNINGS:
warnings.filterwarnings("ignore", text, DeprecationWarning)
return func(*args, **kw)
return wrapper
class ExceptionClassTests(unittest.TestCase): class ExceptionClassTests(unittest.TestCase):
@ -32,12 +21,14 @@ class ExceptionClassTests(unittest.TestCase):
def test_builtins_new_style(self): def test_builtins_new_style(self):
self.assertTrue(issubclass(Exception, object)) self.assertTrue(issubclass(Exception, object))
@ignore_deprecation_warnings
def verify_instance_interface(self, ins): def verify_instance_interface(self, ins):
for attr in ("args", "message", "__str__", "__repr__", "__getitem__"): with warnings.catch_warnings():
self.assertTrue(hasattr(ins, attr), ignore_message_warning()
"%s missing %s attribute" % for attr in ("args", "message", "__str__", "__repr__",
(ins.__class__.__name__, attr)) "__getitem__"):
self.assertTrue(hasattr(ins, attr),
"%s missing %s attribute" %
(ins.__class__.__name__, attr))
def test_inheritance(self): def test_inheritance(self):
# Make sure the inheritance hierarchy matches the documentation # Make sure the inheritance hierarchy matches the documentation
@ -100,39 +91,43 @@ class ExceptionClassTests(unittest.TestCase):
self.assertEqual(given, expected, "%s: %s != %s" % (test_name, self.assertEqual(given, expected, "%s: %s != %s" % (test_name,
given, expected)) given, expected))
@ignore_deprecation_warnings
def test_interface_single_arg(self): def test_interface_single_arg(self):
# Make sure interface works properly when given a single argument # Make sure interface works properly when given a single argument
arg = "spam" arg = "spam"
exc = Exception(arg) exc = Exception(arg)
results = ([len(exc.args), 1], [exc.args[0], arg], [exc.message, arg], with warnings.catch_warnings():
[str(exc), str(arg)], [unicode(exc), unicode(arg)], ignore_message_warning()
[repr(exc), exc.__class__.__name__ + repr(exc.args)], results = ([len(exc.args), 1], [exc.args[0], arg],
[exc[0], arg]) [exc.message, arg],
self.interface_test_driver(results) [str(exc), str(arg)], [unicode(exc), unicode(arg)],
[repr(exc), exc.__class__.__name__ + repr(exc.args)], [exc[0],
arg])
self.interface_test_driver(results)
@ignore_deprecation_warnings
def test_interface_multi_arg(self): def test_interface_multi_arg(self):
# Make sure interface correct when multiple arguments given # Make sure interface correct when multiple arguments given
arg_count = 3 arg_count = 3
args = tuple(range(arg_count)) args = tuple(range(arg_count))
exc = Exception(*args) exc = Exception(*args)
results = ([len(exc.args), arg_count], [exc.args, args], with warnings.catch_warnings():
[exc.message, ''], [str(exc), str(args)], ignore_message_warning()
[unicode(exc), unicode(args)], results = ([len(exc.args), arg_count], [exc.args, args],
[repr(exc), exc.__class__.__name__ + repr(exc.args)], [exc.message, ''], [str(exc), str(args)],
[exc[-1], args[-1]]) [unicode(exc), unicode(args)],
self.interface_test_driver(results) [repr(exc), exc.__class__.__name__ + repr(exc.args)],
[exc[-1], args[-1]])
self.interface_test_driver(results)
@ignore_deprecation_warnings
def test_interface_no_arg(self): def test_interface_no_arg(self):
# Make sure that with no args that interface is correct # Make sure that with no args that interface is correct
exc = Exception() exc = Exception()
results = ([len(exc.args), 0], [exc.args, tuple()], with warnings.catch_warnings():
[exc.message, ''], ignore_message_warning()
[str(exc), ''], [unicode(exc), u''], results = ([len(exc.args), 0], [exc.args, tuple()],
[repr(exc), exc.__class__.__name__ + '()'], [True, True]) [exc.message, ''],
self.interface_test_driver(results) [str(exc), ''], [unicode(exc), u''],
[repr(exc), exc.__class__.__name__ + '()'], [True, True])
self.interface_test_driver(results)
def test_message_deprecation(self): def test_message_deprecation(self):
@ -184,7 +179,6 @@ class UsageTests(unittest.TestCase):
self.fail("TypeError expected when catching %s as specified in a " self.fail("TypeError expected when catching %s as specified in a "
"tuple" % type(object_)) "tuple" % type(object_))
@ignore_deprecation_warnings
def test_raise_classic(self): def test_raise_classic(self):
# Raising a classic class is okay (for now). # Raising a classic class is okay (for now).
class ClassicClass: class ClassicClass:

View file

@ -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 self.package_name in sys.modules: while sys.modules.has_key(self.package_name):
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 module_name in sys.modules: if sys.modules.has_key(module_name):
del sys.modules[module_name] del sys.modules[module_name]
def setUp(self): def setUp(self):
@ -52,7 +52,7 @@ 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.assertTrue(self.module_name not in sys.modules and self.assertTrue(not sys.modules.has_key(self.module_name) and
not hasattr(sys.modules[self.package_name], 'foo')) not 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__

View file

@ -2,7 +2,7 @@
Test cases for pyclbr.py Test cases for pyclbr.py
Nick Mathewson Nick Mathewson
''' '''
from test.test_support import run_unittest, import_module from test.test_support import run_unittest
import sys import sys
from types import ClassType, FunctionType, MethodType, BuiltinFunctionType from types import ClassType, FunctionType, MethodType, BuiltinFunctionType
import pyclbr import pyclbr
@ -13,8 +13,6 @@ ClassMethodType = type(classmethod(lambda c: None))
# This next line triggers an error on old versions of pyclbr. # This next line triggers an error on old versions of pyclbr.
# Silence Py3k warning
import_module('commands', deprecated=True)
from commands import getstatus from commands import getstatus
# Here we test the python class browser code. # Here we test the python class browser code.
@ -42,11 +40,11 @@ class PyclbrTest(TestCase):
def assertHaskey(self, obj, key, ignore): def assertHaskey(self, obj, key, ignore):
''' succeed iff key in obj or key in ignore. ''' ''' succeed iff obj.has_key(key) or key in ignore. '''
if key in ignore: return if key in ignore: return
if key not in obj: if not obj.has_key(key):
print >>sys.stderr, "***", key print >>sys.stderr, "***",key
self.assertTrue(key in obj) self.assertTrue(obj.has_key(key))
def assertEqualsOrIgnored(self, a, b, ignore): def assertEqualsOrIgnored(self, a, b, ignore):
''' succeed iff a == b or a in ignore or b in ignore ''' ''' succeed iff a == b or a in ignore or b in ignore '''
@ -151,9 +149,7 @@ class PyclbrTest(TestCase):
def test_easy(self): def test_easy(self):
self.checkModule('pyclbr') self.checkModule('pyclbr')
self.checkModule('doctest', ignore=("DocTestCase",)) self.checkModule('doctest', ignore=("DocTestCase",))
# Silence Py3k warning self.checkModule('rfc822')
rfc822 = import_module('rfc822', deprecated=True)
self.checkModule('rfc822', rfc822)
self.checkModule('difflib') self.checkModule('difflib')
def test_decorators(self): def test_decorators(self):

View file

@ -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)

View file

@ -7,8 +7,7 @@ import time
import unittest import unittest
from test import test_support from test import test_support
QUEUE_SIZE = LAST = 5 QUEUE_SIZE = 5
FULL = LAST+1
# A thread to run a function that unclogs a blocked Queue. # A thread to run a function that unclogs a blocked Queue.
class _TriggerThread(threading.Thread): class _TriggerThread(threading.Thread):
@ -103,21 +102,21 @@ class BaseQueueTest(unittest.TestCase, BlockingTestMixin):
q.put(i) q.put(i)
self.assertTrue(not q.empty(), "Queue should not be empty") self.assertTrue(not q.empty(), "Queue should not be empty")
self.assertTrue(not q.full(), "Queue should not be full") self.assertTrue(not q.full(), "Queue should not be full")
q.put(LAST) q.put("last")
self.assertTrue(q.full(), "Queue should be full") self.assertTrue(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()

View file

@ -6,7 +6,6 @@ import time
import pickle import pickle
import warnings import warnings
from math import log, exp, sqrt, pi, fsum, sin from math import log, exp, sqrt, pi, fsum, sin
from functools import reduce
from test import test_support from test import test_support
class TestBasicOps(unittest.TestCase): class TestBasicOps(unittest.TestCase):

View file

@ -8,7 +8,7 @@ import os
import shutil import shutil
import unittest import unittest
from test.test_support import run_unittest, check_warnings from test.test_support import run_unittest
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,9 +174,7 @@ 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.
# Silence the Py3k warning x = buffer('foo')
with check_warnings():
x = buffer('foo')
self.assertTrue(repr(x).startswith('<read-only buffer for 0x')) self.assertTrue(repr(x).startswith('<read-only buffer for 0x'))
def test_cell(self): def test_cell(self):

View file

@ -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: %r != %r" % (mn, n)) "Un-expected name: %s != %s" % (`mn`, `n`))
self.assertEqual(ma, a, self.assertEqual(ma, a,
"Un-expected address: %r != %r" % (ma, a)) "Un-expected address: %s != %s" % (`ma`, `a`))
if mn == n and ma == a: if mn == n and ma == a:
pass pass
else: else:

View file

@ -2,7 +2,6 @@
import unittest import unittest
from test import test_support from test import test_support
import warnings
import operator import operator
@ -331,13 +330,7 @@ class ListTest(unittest.TestCase):
self.assertIs(op(x, y), True) self.assertIs(op(x, y), True)
def test_main(): def test_main():
test_support.run_unittest(VectorTest, NumberTest, MiscTest, ListTest) test_support.run_unittest(VectorTest, NumberTest, MiscTest, DictTest, ListTest)
with warnings.catch_warnings():
# Silence Py3k warning
warnings.filterwarnings("ignore", "dict inequality comparisons "
"not supported in 3.x", DeprecationWarning)
test_support.run_unittest(DictTest)
if __name__ == "__main__": if __name__ == "__main__":
test_main() test_main()

View file

@ -321,16 +321,10 @@ else:
self.assertEqual(makeReturner2(a=11)()['a'], 11) self.assertEqual(makeReturner2(a=11)()['a'], 11)
with warnings.catch_warnings(): def makeAddPair((a, b)):
# Silence Py3k warning def addPair((c, d)):
warnings.filterwarnings("ignore", "tuple parameter unpacking " return (a + c, b + d)
"has been removed", SyntaxWarning) return addPair
exec """\
def makeAddPair((a, b)):
def addPair((c, d)):
return (a + c, b + d)
return addPair
""" in locals()
self.assertEqual(makeAddPair((1, 2))((100, 200)), (101,202)) self.assertEqual(makeAddPair((1, 2))((100, 200)), (101,202))
@ -477,7 +471,7 @@ self.assertTrue(X.passed)
return g return g
d = f(2)(4) d = f(2)(4)
self.assertTrue('h' in d) self.assertTrue(d.has_key('h'))
del d['h'] del d['h']
self.assertEqual(d, {'x': 2, 'y': 7, 'w': 6}) self.assertEqual(d, {'x': 2, 'y': 7, 'w': 6})

View file

@ -1218,16 +1218,15 @@ class TestOnlySetsInBinaryOps(unittest.TestCase):
self.assertEqual(self.set != self.other, True) self.assertEqual(self.set != self.other, True)
def test_ge_gt_le_lt(self): def test_ge_gt_le_lt(self):
with test_support.check_warnings(): self.assertRaises(TypeError, lambda: self.set < self.other)
self.assertRaises(TypeError, lambda: self.set < self.other) self.assertRaises(TypeError, lambda: self.set <= self.other)
self.assertRaises(TypeError, lambda: self.set <= self.other) self.assertRaises(TypeError, lambda: self.set > self.other)
self.assertRaises(TypeError, lambda: self.set > self.other) self.assertRaises(TypeError, lambda: self.set >= self.other)
self.assertRaises(TypeError, lambda: self.set >= self.other)
self.assertRaises(TypeError, lambda: self.other < self.set) self.assertRaises(TypeError, lambda: self.other < self.set)
self.assertRaises(TypeError, lambda: self.other <= self.set) self.assertRaises(TypeError, lambda: self.other <= self.set)
self.assertRaises(TypeError, lambda: self.other > self.set) self.assertRaises(TypeError, lambda: self.other > self.set)
self.assertRaises(TypeError, lambda: self.other >= self.set) self.assertRaises(TypeError, lambda: self.other >= self.set)
def test_update_operator(self): def test_update_operator(self):
try: try:
@ -1380,20 +1379,20 @@ class TestCopying(unittest.TestCase):
def test_copy(self): def test_copy(self):
dup = self.set.copy() dup = self.set.copy()
dup_list = list(dup) dup_list = list(dup); dup_list.sort()
set_list = list(self.set) set_list = list(self.set); set_list.sort()
self.assertEqual(len(dup_list), len(set_list)) self.assertEqual(len(dup_list), len(set_list))
for elt in dup_list: for i in range(len(dup_list)):
self.assertTrue(elt in set_list) self.assertTrue(dup_list[i] is set_list[i])
def test_deep_copy(self): def test_deep_copy(self):
dup = copy.deepcopy(self.set) dup = copy.deepcopy(self.set)
##print type(dup), repr(dup) ##print type(dup), repr(dup)
dup_list = list(dup) dup_list = list(dup); dup_list.sort()
set_list = list(self.set) set_list = list(self.set); set_list.sort()
self.assertEqual(len(dup_list), len(set_list)) self.assertEqual(len(dup_list), len(set_list))
for elt in dup_list: for i in range(len(dup_list)):
self.assertTrue(elt in set_list) self.assertEqual(dup_list[i], set_list[i])
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -1553,7 +1552,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
for cons in (set, frozenset): for cons in (set, frozenset):
for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
for g in (G, I, Ig, S, L, R): for g in (G, I, Ig, S, L, R):
self.assertSameElements(cons(g(s)), g(s)) self.assertEqual(sorted(cons(g(s))), sorted(g(s)))
self.assertRaises(TypeError, cons , X(s)) self.assertRaises(TypeError, cons , X(s))
self.assertRaises(TypeError, cons , N(s)) self.assertRaises(TypeError, cons , N(s))
self.assertRaises(ZeroDivisionError, cons , E(s)) self.assertRaises(ZeroDivisionError, cons , E(s))
@ -1568,7 +1567,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
if isinstance(expected, bool): if isinstance(expected, bool):
self.assertEqual(actual, expected) self.assertEqual(actual, expected)
else: else:
self.assertSameElements(actual, expected) self.assertEqual(sorted(actual), sorted(expected))
self.assertRaises(TypeError, meth, X(s)) self.assertRaises(TypeError, meth, X(s))
self.assertRaises(TypeError, meth, N(s)) self.assertRaises(TypeError, meth, N(s))
self.assertRaises(ZeroDivisionError, meth, E(s)) self.assertRaises(ZeroDivisionError, meth, E(s))
@ -1582,7 +1581,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
t = s.copy() t = s.copy()
getattr(s, methname)(list(g(data))) getattr(s, methname)(list(g(data)))
getattr(t, methname)(g(data)) getattr(t, methname)(g(data))
self.assertSameElements(s, t) self.assertEqual(sorted(s), sorted(t))
self.assertRaises(TypeError, getattr(set('january'), methname), X(data)) self.assertRaises(TypeError, getattr(set('january'), methname), X(data))
self.assertRaises(TypeError, getattr(set('january'), methname), N(data)) self.assertRaises(TypeError, getattr(set('january'), methname), N(data))

View file

@ -510,17 +510,15 @@ class TestOnlySetsInBinaryOps(unittest.TestCase):
self.assertEqual(self.set != self.other, True) self.assertEqual(self.set != self.other, True)
def test_ge_gt_le_lt(self): def test_ge_gt_le_lt(self):
# Silence Py3k warning self.assertRaises(TypeError, lambda: self.set < self.other)
with test_support.check_warnings(): self.assertRaises(TypeError, lambda: self.set <= self.other)
self.assertRaises(TypeError, lambda: self.set < self.other) self.assertRaises(TypeError, lambda: self.set > self.other)
self.assertRaises(TypeError, lambda: self.set <= self.other) self.assertRaises(TypeError, lambda: self.set >= self.other)
self.assertRaises(TypeError, lambda: self.set > self.other)
self.assertRaises(TypeError, lambda: self.set >= self.other)
self.assertRaises(TypeError, lambda: self.other < self.set) self.assertRaises(TypeError, lambda: self.other < self.set)
self.assertRaises(TypeError, lambda: self.other <= self.set) self.assertRaises(TypeError, lambda: self.other <= self.set)
self.assertRaises(TypeError, lambda: self.other > self.set) self.assertRaises(TypeError, lambda: self.other > self.set)
self.assertRaises(TypeError, lambda: self.other >= self.set) self.assertRaises(TypeError, lambda: self.other >= self.set)
def test_union_update_operator(self): def test_union_update_operator(self):
try: try:
@ -681,20 +679,20 @@ class TestCopying(unittest.TestCase):
def test_copy(self): def test_copy(self):
dup = self.set.copy() dup = self.set.copy()
dup_list = list(dup) dup_list = list(dup); dup_list.sort()
set_list = list(self.set) set_list = list(self.set); set_list.sort()
self.assertEqual(len(dup_list), len(set_list)) self.assertEqual(len(dup_list), len(set_list))
for elt in dup_list: for i in range(len(dup_list)):
self.assertTrue(elt in set_list) self.assertTrue(dup_list[i] is set_list[i])
def test_deep_copy(self): def test_deep_copy(self):
dup = copy.deepcopy(self.set) dup = copy.deepcopy(self.set)
##print type(dup), repr(dup) ##print type(dup), repr(dup)
dup_list = list(dup) dup_list = list(dup); dup_list.sort()
set_list = list(self.set) set_list = list(self.set); set_list.sort()
self.assertEqual(len(dup_list), len(set_list)) self.assertEqual(len(dup_list), len(set_list))
for elt in dup_list: for i in range(len(dup_list)):
self.assertTrue(elt in set_list) self.assertEqual(dup_list[i], set_list[i])
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------

View file

@ -4,8 +4,6 @@ import shelve
import glob import glob
from test import test_support from test import test_support
test_support.import_module('anydbm', deprecated=True)
class TestCase(unittest.TestCase): class TestCase(unittest.TestCase):
fn = "shelftemp" + os.extsep + "db" fn = "shelftemp" + os.extsep + "db"

View file

@ -258,7 +258,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.assertTrue(os.path.isabs(module.__file__), repr(module)) self.assertTrue(os.path.isabs(module.__file__), `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
@ -310,7 +310,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 "sitecustomize" not in sys.modules: if not sys.modules.has_key("sitecustomize"):
try: try:
import sitecustomize import sitecustomize
except ImportError: except ImportError:

View file

@ -115,9 +115,7 @@ class SliceTest(unittest.TestCase):
tmp.append((i, j, k)) tmp.append((i, j, k))
x = X() x = X()
# Silence Py3k warning x[1:2] = 42
with test_support.check_warnings():
x[1:2] = 42
self.assertEquals(tmp, [(1, 2, 42)]) self.assertEquals(tmp, [(1, 2, 42)])
def test_pickle(self): def test_pickle(self):

View file

@ -123,7 +123,7 @@ class ThreadableTest:
self.server_ready.wait() self.server_ready.wait()
self.client_ready.set() self.client_ready.set()
self.clientSetUp() self.clientSetUp()
if not hasattr(test_func, '__call__'): if not callable(test_func):
raise TypeError, "test_func must be a callable function" raise TypeError, "test_func must be a callable function"
try: try:
test_func() test_func()
@ -282,7 +282,7 @@ class GeneralModuleTests(unittest.TestCase):
orig = sys.getrefcount(__name__) orig = sys.getrefcount(__name__)
socket.getnameinfo(__name__,0) socket.getnameinfo(__name__,0)
except TypeError: except TypeError:
if sys.getrefcount(__name__) != orig: if sys.getrefcount(__name__) <> orig:
self.fail("socket.getnameinfo loses a reference") self.fail("socket.getnameinfo loses a reference")
def testInterpreterCrash(self): def testInterpreterCrash(self):
@ -1234,9 +1234,7 @@ class BufferIOTest(SocketConnectedTest):
self.assertEqual(msg, MSG) self.assertEqual(msg, MSG)
def _testRecvInto(self): def _testRecvInto(self):
# Silence Py3k warning buf = buffer(MSG)
with test_support.check_warnings():
buf = buffer(MSG)
self.serv_conn.send(buf) self.serv_conn.send(buf)
def testRecvFromInto(self): def testRecvFromInto(self):
@ -1247,9 +1245,7 @@ class BufferIOTest(SocketConnectedTest):
self.assertEqual(msg, MSG) self.assertEqual(msg, MSG)
def _testRecvFromInto(self): def _testRecvFromInto(self):
# Silence Py3k warning buf = buffer(MSG)
with test_support.check_warnings():
buf = buffer(MSG)
self.serv_conn.send(buf) self.serv_conn.send(buf)

View file

@ -2,7 +2,6 @@ from test import test_support
import random import random
import sys import sys
import unittest import unittest
import warnings
verbose = test_support.verbose verbose = test_support.verbose
nerrors = 0 nerrors = 0
@ -186,7 +185,7 @@ class TestDecorateSortUndecorate(unittest.TestCase):
def test_stability(self): def test_stability(self):
data = [(random.randrange(100), i) for i in xrange(200)] data = [(random.randrange(100), i) for i in xrange(200)]
copy = data[:] copy = data[:]
data.sort(key=lambda x: x[0]) # sort on the random first field data.sort(key=lambda (x,y): x) # sort on the random first field
copy.sort() # sort using both fields copy.sort() # sort using both fields
self.assertEqual(data, copy) # should get the same result self.assertEqual(data, copy) # should get the same result
@ -208,7 +207,7 @@ class TestDecorateSortUndecorate(unittest.TestCase):
# Verify that the wrapper has been removed # Verify that the wrapper has been removed
data = range(-2,2) data = range(-2,2)
dup = data[:] dup = data[:]
self.assertRaises(ZeroDivisionError, data.sort, None, lambda x: 1 // x) self.assertRaises(ZeroDivisionError, data.sort, None, lambda x: 1/x)
self.assertEqual(data, dup) self.assertEqual(data, dup)
def test_key_with_mutation(self): def test_key_with_mutation(self):
@ -275,21 +274,17 @@ def test_main(verbose=None):
TestBugs, TestBugs,
) )
with warnings.catch_warnings(): test_support.run_unittest(*test_classes)
# Silence Py3k warning
warnings.filterwarnings("ignore", "the cmp argument is not supported",
DeprecationWarning)
test_support.run_unittest(*test_classes)
# verify reference counting # verify reference counting
if verbose and hasattr(sys, "gettotalrefcount"): if verbose and hasattr(sys, "gettotalrefcount"):
import gc import gc
counts = [None] * 5 counts = [None] * 5
for i in xrange(len(counts)): for i in xrange(len(counts)):
test_support.run_unittest(*test_classes) test_support.run_unittest(*test_classes)
gc.collect() gc.collect()
counts[i] = sys.gettotalrefcount() counts[i] = sys.gettotalrefcount()
print counts print counts
if __name__ == "__main__": if __name__ == "__main__":
test_main(verbose=True) test_main(verbose=True)

View file

@ -4,21 +4,14 @@ from test.test_support import run_unittest, import_module
# Skip test if _sqlite3 module was not built. # Skip test if _sqlite3 module was not built.
import_module('_sqlite3') import_module('_sqlite3')
import warnings
from sqlite3.test import (dbapi, types, userfunctions, py25tests, from sqlite3.test import (dbapi, types, userfunctions, py25tests,
factory, transactions, hooks, regression, factory, transactions, hooks, regression,
dump) dump)
def test_main(): def test_main():
with warnings.catch_warnings(): run_unittest(dbapi.suite(), types.suite(), userfunctions.suite(),
# Silence Py3k warnings py25tests.suite(), factory.suite(), transactions.suite(),
warnings.filterwarnings("ignore", "buffer.. not supported", hooks.suite(), regression.suite(), dump.suite())
DeprecationWarning)
warnings.filterwarnings("ignore", "classic int division",
DeprecationWarning)
run_unittest(dbapi.suite(), types.suite(), userfunctions.suite(),
py25tests.suite(), factory.suite(), transactions.suite(),
hooks.suite(), regression.suite(), dump.suite())
if __name__ == "__main__": if __name__ == "__main__":
test_main() test_main()

View file

@ -808,7 +808,7 @@ else:
if test_support.verbose: if test_support.verbose:
sys.stdout.write(pprint.pformat(cert) + '\n') sys.stdout.write(pprint.pformat(cert) + '\n')
sys.stdout.write("Connection cipher is " + str(cipher) + '.\n') sys.stdout.write("Connection cipher is " + str(cipher) + '.\n')
if 'subject' not in cert: if not cert.has_key('subject'):
raise test_support.TestFailed( raise test_support.TestFailed(
"No subject field in certificate: %s." % "No subject field in certificate: %s." %
pprint.pformat(cert)) pprint.pformat(cert))
@ -970,9 +970,7 @@ else:
# now fetch the same data from the HTTPS server # now fetch the same data from the HTTPS server
url = 'https://127.0.0.1:%d/%s' % ( url = 'https://127.0.0.1:%d/%s' % (
server.port, os.path.split(CERTFILE)[1]) server.port, os.path.split(CERTFILE)[1])
# Silence Py3k warning f = urllib.urlopen(url)
with test_support.check_warnings():
f = urllib.urlopen(url)
dlen = f.info().getheader("content-length") dlen = f.info().getheader("content-length")
if dlen and (int(dlen) > 0): if dlen and (int(dlen) > 0):
d2 = f.read(int(dlen)) d2 = f.read(int(dlen))

View file

@ -471,7 +471,7 @@ class StructTest(unittest.TestCase):
def test_bool(self): def test_bool(self):
for prefix in tuple("<>!=")+('',): for prefix in tuple("<>!=")+('',):
false = (), [], [], '', 0 false = (), [], [], '', 0
true = [1], 'test', 5, -1, 0xffffffffL+1, 0xffffffff//2 true = [1], 'test', 5, -1, 0xffffffffL+1, 0xffffffff/2
falseFormat = prefix + '?' * len(false) falseFormat = prefix + '?' * len(false)
packedFalse = struct.pack(falseFormat, *false) packedFalse = struct.pack(falseFormat, *false)
@ -507,11 +507,7 @@ class StructTest(unittest.TestCase):
def test_main(): def test_main():
with warnings.catch_warnings(): run_unittest(StructTest)
# Silence Py3k warnings
warnings.filterwarnings("ignore", "buffer.. not supported",
DeprecationWarning)
run_unittest(StructTest)
if __name__ == '__main__': if __name__ == '__main__':
test_main() test_main()

View file

@ -552,11 +552,7 @@ class SyntaxTestCase(unittest.TestCase):
def test_main(): def test_main():
test_support.run_unittest(SyntaxTestCase) test_support.run_unittest(SyntaxTestCase)
from test import test_syntax from test import test_syntax
with warnings.catch_warnings(): test_support.run_doctest(test_syntax, verbosity=True)
# Silence Py3k warning
warnings.filterwarnings("ignore", "backquote not supported",
SyntaxWarning)
test_support.run_doctest(test_syntax, verbosity=True)
if __name__ == "__main__": if __name__ == "__main__":
test_main() test_main()

View file

@ -68,9 +68,7 @@ class SysModuleTest(unittest.TestCase):
# Python/pythonrun.c::PyErr_PrintEx() is tricky. # Python/pythonrun.c::PyErr_PrintEx() is tricky.
def test_exc_clear(self): def test_exc_clear(self):
# Silence Py3k warning self.assertRaises(TypeError, sys.exc_clear, 42)
with test.test_support.check_warnings():
self.assertRaises(TypeError, sys.exc_clear, 42)
# Verify that exc_info is present and matches exc, then clear it, and # Verify that exc_info is present and matches exc, then clear it, and
# check that it worked. # check that it worked.
@ -80,9 +78,7 @@ class SysModuleTest(unittest.TestCase):
self.assertTrue(value is exc) self.assertTrue(value is exc)
self.assertTrue(traceback is not None) self.assertTrue(traceback is not None)
# Silence Py3k warning sys.exc_clear()
with test.test_support.check_warnings():
sys.exc_clear()
typ, value, traceback = sys.exc_info() typ, value, traceback = sys.exc_info()
self.assertTrue(typ is None) self.assertTrue(typ is None)
@ -488,9 +484,7 @@ class SizeofTest(unittest.TestCase):
# bool # bool
check(True, size(h + 'l')) check(True, size(h + 'l'))
# buffer # buffer
# Silence Py3k warning check(buffer(''), size(h + '2P2Pil'))
with test.test_support.check_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

View file

@ -712,9 +712,7 @@ class WriteTest(WriteTestBase):
return os.path.isfile(name) return os.path.isfile(name)
tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1") tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
# Silence Py3k warning tar.add(tempdir, arcname="empty_dir", exclude=exclude)
with test_support.check_warnings():
tar.add(tempdir, arcname="empty_dir", exclude=exclude)
tar.close() tar.close()
tar = tarfile.open(tmpname, "r") tar = tarfile.open(tmpname, "r")

View file

@ -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():
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()

View file

@ -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

View file

@ -4,7 +4,6 @@ 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
@ -149,7 +148,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__

View file

@ -1,8 +1,5 @@
import unittest import unittest
from test import test_support from test import test_support
# Silence Py3k warning
test_support.import_module('compiler', deprecated=True)
from compiler import transformer, ast from compiler import transformer, ast
from compiler import compile from compiler import compile

View file

@ -4,7 +4,6 @@ from test.test_support import run_unittest, have_unicode, run_with_locale
import unittest import unittest
import sys import sys
import locale import locale
import warnings
class TypesTests(unittest.TestCase): class TypesTests(unittest.TestCase):
@ -711,13 +710,7 @@ class TypesTests(unittest.TestCase):
self.assertRaises(ValueError, format, 0, ',' + code) self.assertRaises(ValueError, format, 0, ',' + code)
def test_main(): def test_main():
with warnings.catch_warnings(): run_unittest(TypesTests)
# Silence Py3k warnings
warnings.filterwarnings("ignore", "buffer.. not supported",
DeprecationWarning)
warnings.filterwarnings("ignore", "classic long division",
DeprecationWarning)
run_unittest(TypesTests)
if __name__ == '__main__': if __name__ == '__main__':
test_main() test_main()

View file

@ -1,4 +1,4 @@
from test.test_support import run_unittest, check_warnings from test.test_support import run_unittest, have_unicode
import unittest import unittest
import sys import sys
@ -33,9 +33,7 @@ class TestImplementationComparisons(unittest.TestCase):
self.assertTrue(g_cell != h_cell) self.assertTrue(g_cell != h_cell)
def test_main(): def test_main():
# Silence Py3k warnings run_unittest(TestImplementationComparisons)
with check_warnings():
run_unittest(TestImplementationComparisons)
if __name__ == '__main__': if __name__ == '__main__':
test_main() test_main()

View file

@ -3056,7 +3056,7 @@ class Test_Assertions(TestCase):
try: try:
self.assertRaises(KeyError, lambda: None) self.assertRaises(KeyError, lambda: None)
except self.failureException as e: except self.failureException as e:
self.assert_("KeyError not raised" in e.args, str(e)) self.assert_("KeyError not raised" in e, str(e))
else: else:
self.fail("assertRaises() didn't fail") self.fail("assertRaises() didn't fail")
try: try:
@ -3073,7 +3073,7 @@ class Test_Assertions(TestCase):
with self.assertRaises(KeyError): with self.assertRaises(KeyError):
pass pass
except self.failureException as e: except self.failureException as e:
self.assert_("KeyError not raised" in e.args, str(e)) self.assert_("KeyError not raised" in e, str(e))
else: else:
self.fail("assertRaises() didn't fail") self.fail("assertRaises() didn't fail")
try: try:
@ -3591,9 +3591,6 @@ class TestDiscovery(TestCase):
def __eq__(self, other): def __eq__(self, other):
return self.path == other.path return self.path == other.path
# Silence Py3k warning
__hash__ = None
loader._get_module_from_name = lambda name: Module(name) loader._get_module_from_name = lambda name: Module(name)
def loadTestsFromModule(module, use_load_tests): def loadTestsFromModule(module, use_load_tests):
if use_load_tests: if use_load_tests:

View file

@ -80,9 +80,7 @@ class TestGenericUnivNewlines(unittest.TestCase):
def test_execfile(self): def test_execfile(self):
namespace = {} namespace = {}
# Silence Py3k warning execfile(test_support.TESTFN, namespace)
with test_support.check_warnings():
execfile(test_support.TESTFN, namespace)
func = namespace['line3'] func = namespace['line3']
self.assertEqual(func.func_code.co_firstlineno, 3) self.assertEqual(func.func_code.co_firstlineno, 3)
self.assertEqual(namespace['line4'], FATX) self.assertEqual(namespace['line4'], FATX)

View file

@ -6,7 +6,6 @@ import unittest
from test import test_support from test import test_support
import os import os
import mimetools import mimetools
import random
import tempfile import tempfile
import StringIO import StringIO
@ -102,7 +101,7 @@ class ProxyTests(unittest.TestCase):
# Records changes to env vars # Records changes to env vars
self.env = test_support.EnvironmentVarGuard() self.env = test_support.EnvironmentVarGuard()
# Delete all proxy related env vars # Delete all proxy related env vars
for k in os.environ.keys(): for k, v in os.environ.iteritems():
if 'proxy' in k.lower(): if 'proxy' in k.lower():
self.env.unset(k) self.env.unset(k)
@ -410,13 +409,6 @@ class QuotingTests(unittest.TestCase):
self.assertEqual(urllib.quote_plus('alpha+beta gamma', '+'), self.assertEqual(urllib.quote_plus('alpha+beta gamma', '+'),
'alpha+beta+gamma') 'alpha+beta+gamma')
def test_quote_leak(self):
# bug 5596 - highlight the refleak in the internal _safemaps cache
safe = ''.join(chr(random.randrange(128)) for i in '123456')
text = 'abcdefghijklmnopqrstuvwxyz'
result = urllib.quote(text, safe=safe)
self.assertEqual(result, text)
class UnquotingTests(unittest.TestCase): class UnquotingTests(unittest.TestCase):
"""Tests for unquote() and unquote_plus() """Tests for unquote() and unquote_plus()

View file

@ -1,5 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
import mimetools
import threading import threading
import urlparse import urlparse
import urllib2 import urllib2
@ -7,7 +8,6 @@ import BaseHTTPServer
import unittest import unittest
import hashlib import hashlib
from test import test_support from test import test_support
mimetools = test_support.import_module('mimetools', deprecated=True)
# Loopback http server infrastructure # Loopback http server infrastructure
@ -154,13 +154,13 @@ class DigestAuthHandler:
if len(self._users) == 0: if len(self._users) == 0:
return True return True
if 'Proxy-Authorization' not in request_handler.headers: if not request_handler.headers.has_key('Proxy-Authorization'):
return self._return_auth_challenge(request_handler) return self._return_auth_challenge(request_handler)
else: else:
auth_dict = self._create_auth_dict( auth_dict = self._create_auth_dict(
request_handler.headers['Proxy-Authorization'] request_handler.headers['Proxy-Authorization']
) )
if auth_dict["username"] in self._users: if self._users.has_key(auth_dict["username"]):
password = self._users[ auth_dict["username"] ] password = self._users[ auth_dict["username"] ]
else: else:
return self._return_auth_challenge(request_handler) return self._return_auth_challenge(request_handler)

View file

@ -7,7 +7,7 @@ import socket
import urllib import urllib
import sys import sys
import os import os
mimetools = test_support.import_module("mimetools", deprecated=True) import mimetools
def _open_with_retry(func, host, *args, **kwargs): def _open_with_retry(func, host, *args, **kwargs):

View file

@ -45,9 +45,7 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol):
# Test __repr__ # Test __repr__
self.assertEqual(str(u0), str(d0)) self.assertEqual(str(u0), str(d0))
self.assertEqual(repr(u1), repr(d1)) self.assertEqual(repr(u1), repr(d1))
# Silence Py3k warning self.assertEqual(`u2`, `d2`)
with test_support.check_warnings():
self.assertEqual(eval('`u2`'), eval('`d2`'))
# Test __cmp__ and __len__ # Test __cmp__ and __len__
all = [d0, d1, d2, u, u0, u1, u2, uu, uu0, uu1, uu2] all = [d0, d1, d2, u, u0, u1, u2, uu, uu0, uu1, uu2]
@ -97,14 +95,12 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol):
# Test has_key and "in". # Test has_key and "in".
for i in u2.keys(): for i in u2.keys():
self.assertTrue(u2.has_key(i))
self.assertTrue(i in u2) self.assertTrue(i in u2)
self.assertEqual(u1.has_key(i), d1.has_key(i))
self.assertEqual(i in u1, i in d1) self.assertEqual(i in u1, i in d1)
self.assertEqual(u0.has_key(i), d0.has_key(i))
self.assertEqual(i in u0, i in d0) self.assertEqual(i in u0, i in d0)
# Silence Py3k warning
with test_support.check_warnings():
self.assertTrue(u2.has_key(i))
self.assertEqual(u1.has_key(i), d1.has_key(i))
self.assertEqual(u0.has_key(i), d0.has_key(i))
# Test update # Test update
t = UserDict.UserDict() t = UserDict.UserDict()

View file

@ -2,7 +2,6 @@
from UserList import UserList from UserList import UserList
from test import test_support, list_tests from test import test_support, list_tests
import warnings
class UserListTest(list_tests.CommonTest): class UserListTest(list_tests.CommonTest):
type2test = UserList type2test = UserList
@ -54,11 +53,7 @@ class UserListTest(list_tests.CommonTest):
self.assertEqual(iter(T((1,2))).next(), "0!!!") self.assertEqual(iter(T((1,2))).next(), "0!!!")
def test_main(): def test_main():
with warnings.catch_warnings(): test_support.run_unittest(UserListTest)
# Silence Py3k warnings
warnings.filterwarnings("ignore", ".+slice__ has been removed",
DeprecationWarning)
test_support.run_unittest(UserListTest)
if __name__ == "__main__": if __name__ == "__main__":
test_main() test_main()

View file

@ -136,11 +136,8 @@ class MutableStringTest(UserStringTest):
def test_main(): def test_main():
with warnings.catch_warnings(): with warnings.catch_warnings():
# Silence Py3k warnings
warnings.filterwarnings("ignore", ".*MutableString", warnings.filterwarnings("ignore", ".*MutableString",
DeprecationWarning) DeprecationWarning)
warnings.filterwarnings("ignore", ".+slice__ has been removed",
DeprecationWarning)
test_support.run_unittest(UserStringTest, MutableStringTest) test_support.run_unittest(UserStringTest, MutableStringTest)
if __name__ == "__main__": if __name__ == "__main__":

Some files were not shown because too many files have changed in this diff Show more