Cleanup some test cases using check_warnings and check_py3k_warnings.

This commit is contained in:
Florent Xicluna 2010-03-17 19:15:56 +00:00
parent 2b73c21bed
commit 945a8ba635
6 changed files with 53 additions and 79 deletions

View file

@ -17,7 +17,7 @@ class FormatDeprecationTests(unittest.TestCase):
PyOS_ascii_formatd = pythonapi.PyOS_ascii_formatd PyOS_ascii_formatd = pythonapi.PyOS_ascii_formatd
buf = create_string_buffer(' ' * 100) buf = create_string_buffer(' ' * 100)
with check_warnings(): with check_warnings(quiet=False):
PyOS_ascii_formatd(byref(buf), sizeof(buf), '%+.10f', PyOS_ascii_formatd(byref(buf), sizeof(buf), '%+.10f',
c_double(10.0)) c_double(10.0))
self.assertEqual(buf.value, '+10.0000000000') self.assertEqual(buf.value, '+10.0000000000')
@ -46,7 +46,7 @@ class FormatTests(unittest.TestCase):
('%-e', 1.234), ('%-e', 1.234),
] ]
with check_warnings(): with check_warnings(quiet=False):
for format, val in tests: for format, val in tests:
PyOS_ascii_formatd(byref(buf), sizeof(buf), format, PyOS_ascii_formatd(byref(buf), sizeof(buf), format,
c_double(val)) c_double(val))

View file

@ -115,7 +115,7 @@ def gen_result(data, environ):
result = {} result = {}
for k, v in dict(form).items(): for k, v in dict(form).items():
result[k] = type(v) is list and form.getlist(k) or v.value result[k] = isinstance(v, list) and form.getlist(k) or v.value
return result return result
@ -133,7 +133,7 @@ class CgiTests(unittest.TestCase):
fcd = cgi.FormContentDict(env) fcd = cgi.FormContentDict(env)
sd = cgi.SvFormContentDict(env) sd = cgi.SvFormContentDict(env)
fs = cgi.FieldStorage(environ=env) fs = cgi.FieldStorage(environ=env)
if type(expect) == type({}): if isinstance(expect, dict):
# test dict interface # test dict interface
self.assertEqual(len(expect), len(fcd)) self.assertEqual(len(expect), len(fcd))
self.assertSameElements(expect.keys(), fcd.keys()) self.assertSameElements(expect.keys(), fcd.keys())
@ -340,13 +340,13 @@ this is the content of the fake file
self.assertEqual(result, v) self.assertEqual(result, v)
def test_deprecated_parse_qs(self): def test_deprecated_parse_qs(self):
with check_warnings(): with check_warnings(quiet=False):
# this func is moved to urlparse, this is just a sanity check # this func is moved to urlparse, this is just a sanity check
self.assertEqual({'a': ['A1'], 'B': ['B3'], 'b': ['B2']}, self.assertEqual({'a': ['A1'], 'B': ['B3'], 'b': ['B2']},
cgi.parse_qs('a=A1&b=B2&B=B3')) cgi.parse_qs('a=A1&b=B2&B=B3'))
def test_deprecated_parse_qsl(self): def test_deprecated_parse_qsl(self):
with check_warnings(): with check_warnings(quiet=False):
# this func is moved to urlparse, this is just a sanity check # this func is moved to urlparse, this is just a sanity check
self.assertEqual([('a', 'A1'), ('b', 'B2'), ('B', 'B3')], self.assertEqual([('a', 'A1'), ('b', 'B2'), ('B', 'B3')],
cgi.parse_qsl('a=A1&b=B2&B=B3')) cgi.parse_qsl('a=A1&b=B2&B=B3'))

View file

@ -1054,14 +1054,9 @@ class BufferedWriterTest(unittest.TestCase, CommonBufferedTests):
self.assertRaises(IOError, bufio.write, b"abcdef") self.assertRaises(IOError, bufio.write, b"abcdef")
def test_max_buffer_size_deprecation(self): def test_max_buffer_size_deprecation(self):
with support.check_warnings() as w: with support.check_warnings(("max_buffer_size is deprecated",
warnings.simplefilter("always", DeprecationWarning) DeprecationWarning)):
self.tp(self.MockRawIO(), 8, 12) self.tp(self.MockRawIO(), 8, 12)
self.assertEqual(len(w.warnings), 1)
warning = w.warnings[0]
self.assertTrue(warning.category is DeprecationWarning)
self.assertEqual(str(warning.message),
"max_buffer_size is deprecated")
class CBufferedWriterTest(BufferedWriterTest): class CBufferedWriterTest(BufferedWriterTest):
@ -1117,14 +1112,9 @@ class BufferedRWPairTest(unittest.TestCase):
self.assertRaises(self.UnsupportedOperation, pair.detach) self.assertRaises(self.UnsupportedOperation, pair.detach)
def test_constructor_max_buffer_size_deprecation(self): def test_constructor_max_buffer_size_deprecation(self):
with support.check_warnings() as w: with support.check_warnings(("max_buffer_size is deprecated",
warnings.simplefilter("always", DeprecationWarning) DeprecationWarning)):
self.tp(self.MockRawIO(), self.MockRawIO(), 8, 12) self.tp(self.MockRawIO(), self.MockRawIO(), 8, 12)
self.assertEqual(len(w.warnings), 1)
warning = w.warnings[0]
self.assertTrue(warning.category is DeprecationWarning)
self.assertEqual(str(warning.message),
"max_buffer_size is deprecated")
def test_constructor_with_not_readable(self): def test_constructor_with_not_readable(self):
class NotReadable(MockRawIO): class NotReadable(MockRawIO):

View file

@ -1,6 +1,6 @@
import unittest import unittest
import sys import sys
from test.test_support import check_warnings, CleanImport, run_unittest from test.test_support import check_py3k_warnings, CleanImport, run_unittest
import warnings import warnings
if not sys.py3kwarning: if not sys.py3kwarning:
@ -41,21 +41,19 @@ class TestPy3KWarnings(unittest.TestCase):
def test_backquote(self): def test_backquote(self):
expected = 'backquote not supported in 3.x; use repr()' expected = 'backquote not supported in 3.x; use repr()'
with check_warnings() as w: with check_py3k_warnings((expected, SyntaxWarning)):
exec "`2`" in {} exec "`2`" in {}
self.assertWarning(None, w, expected)
def test_paren_arg_names(self): def test_paren_arg_names(self):
expected = 'parenthesized argument names are invalid in 3.x' expected = 'parenthesized argument names are invalid in 3.x'
def check(s): def check(s):
exec s in {} with check_py3k_warnings((expected, SyntaxWarning)):
self.assertWarning(None, w, expected) exec s in {}
with check_warnings() as w: check("def f((x)): pass")
check("def f((x)): pass") check("def f((((x))), (y)): pass")
check("def f((((x))), (y)): pass") check("def f((x), (((y))), m=32): pass")
check("def f((x), (((y))), m=32): pass") # Something like def f((a, (b))): pass will raise the tuple
# Something like def f((a, (b))): pass will raise the tuple # unpacking warning.
# unpacking warning.
def test_forbidden_names(self): def test_forbidden_names(self):
# So we don't screw up our globals # So we don't screw up our globals
@ -66,7 +64,7 @@ class TestPy3KWarnings(unittest.TestCase):
tests = [("True", "assignment to True or False is forbidden in 3.x"), tests = [("True", "assignment to True or False is forbidden in 3.x"),
("False", "assignment to True or False is forbidden in 3.x"), ("False", "assignment to True or False is forbidden in 3.x"),
("nonlocal", "nonlocal is a keyword in 3.x")] ("nonlocal", "nonlocal is a keyword in 3.x")]
with check_warnings() as w: with check_py3k_warnings(('', SyntaxWarning)) as w:
for keyword, expected in tests: for keyword, expected in tests:
safe_exec("{0} = False".format(keyword)) safe_exec("{0} = False".format(keyword))
self.assertWarning(None, w, expected) self.assertWarning(None, w, expected)
@ -90,21 +88,21 @@ class TestPy3KWarnings(unittest.TestCase):
def test_type_inequality_comparisons(self): def test_type_inequality_comparisons(self):
expected = 'type inequality comparisons not supported in 3.x' expected = 'type inequality comparisons not supported in 3.x'
with check_warnings() as w: with check_py3k_warnings() as w:
self.assertWarning(int < str, w, expected) self.assertWarning(int < str, w, expected)
w.reset() w.reset()
self.assertWarning(type < object, w, expected) self.assertWarning(type < object, w, expected)
def test_object_inequality_comparisons(self): def test_object_inequality_comparisons(self):
expected = 'comparing unequal types not supported in 3.x' expected = 'comparing unequal types not supported in 3.x'
with check_warnings() as w: with check_py3k_warnings() as w:
self.assertWarning(str < [], w, expected) self.assertWarning(str < [], w, expected)
w.reset() w.reset()
self.assertWarning(object() < (1, 2), w, expected) self.assertWarning(object() < (1, 2), w, expected)
def test_dict_inequality_comparisons(self): def test_dict_inequality_comparisons(self):
expected = 'dict inequality comparisons not supported in 3.x' expected = 'dict inequality comparisons not supported in 3.x'
with check_warnings() as w: with check_py3k_warnings() as w:
self.assertWarning({} < {2:3}, w, expected) self.assertWarning({} < {2:3}, w, expected)
w.reset() w.reset()
self.assertWarning({} <= {}, w, expected) self.assertWarning({} <= {}, w, expected)
@ -121,7 +119,7 @@ class TestPy3KWarnings(unittest.TestCase):
return g return g
cell0, = f(0).func_closure cell0, = f(0).func_closure
cell1, = f(1).func_closure cell1, = f(1).func_closure
with check_warnings() as w: with check_py3k_warnings() as w:
self.assertWarning(cell0 == cell1, w, expected) self.assertWarning(cell0 == cell1, w, expected)
w.reset() w.reset()
self.assertWarning(cell0 < cell1, w, expected) self.assertWarning(cell0 < cell1, w, expected)
@ -132,7 +130,7 @@ class TestPy3KWarnings(unittest.TestCase):
pass pass
def g(x): def g(x):
pass pass
with check_warnings() as w: with check_py3k_warnings() as w:
self.assertWarning(f.func_code < g.func_code, w, expected) self.assertWarning(f.func_code < g.func_code, w, expected)
w.reset() w.reset()
self.assertWarning(f.func_code <= g.func_code, w, expected) self.assertWarning(f.func_code <= g.func_code, w, expected)
@ -146,7 +144,7 @@ class TestPy3KWarnings(unittest.TestCase):
'order comparisons not supported in 3.x') 'order comparisons not supported in 3.x')
func = eval func = eval
meth = {}.get meth = {}.get
with check_warnings() as w: with check_py3k_warnings() as w:
self.assertWarning(func < meth, w, expected) self.assertWarning(func < meth, w, expected)
w.reset() w.reset()
self.assertWarning(func > meth, w, expected) self.assertWarning(func > meth, w, expected)
@ -166,7 +164,7 @@ class TestPy3KWarnings(unittest.TestCase):
f = sys._getframe(0) f = sys._getframe(0)
for attr in ("f_exc_traceback", "f_exc_value", "f_exc_type"): for attr in ("f_exc_traceback", "f_exc_value", "f_exc_type"):
expected = template % attr expected = template % attr
with check_warnings() as w: with check_py3k_warnings() as w:
self.assertWarning(getattr(f, attr), w, expected) self.assertWarning(getattr(f, attr), w, expected)
w.reset() w.reset()
self.assertWarning(setattr(f, attr, None), w, expected) self.assertWarning(setattr(f, attr, None), w, expected)
@ -176,7 +174,7 @@ class TestPy3KWarnings(unittest.TestCase):
lst = range(5) lst = range(5)
cmp = lambda x,y: -1 cmp = lambda x,y: -1
with check_warnings() as w: with check_py3k_warnings() as w:
self.assertWarning(lst.sort(cmp=cmp), w, expected) self.assertWarning(lst.sort(cmp=cmp), w, expected)
w.reset() w.reset()
self.assertWarning(sorted(lst, cmp=cmp), w, expected) self.assertWarning(sorted(lst, cmp=cmp), w, expected)
@ -187,7 +185,7 @@ class TestPy3KWarnings(unittest.TestCase):
def test_sys_exc_clear(self): def test_sys_exc_clear(self):
expected = 'sys.exc_clear() not supported in 3.x; use except clauses' expected = 'sys.exc_clear() not supported in 3.x; use except clauses'
with check_warnings() as w: with check_py3k_warnings() as w:
self.assertWarning(sys.exc_clear(), w, expected) self.assertWarning(sys.exc_clear(), w, expected)
def test_methods_members(self): def test_methods_members(self):
@ -196,17 +194,17 @@ class TestPy3KWarnings(unittest.TestCase):
__methods__ = ['a'] __methods__ = ['a']
__members__ = ['b'] __members__ = ['b']
c = C() c = C()
with check_warnings() as w: with check_py3k_warnings() as w:
self.assertWarning(dir(c), w, expected) self.assertWarning(dir(c), w, expected)
def test_softspace(self): def test_softspace(self):
expected = 'file.softspace not supported in 3.x' expected = 'file.softspace not supported in 3.x'
with file(__file__) as f: with file(__file__) as f:
with check_warnings() as w: with check_py3k_warnings() as w:
self.assertWarning(f.softspace, w, expected) self.assertWarning(f.softspace, w, expected)
def set(): def set():
f.softspace = 0 f.softspace = 0
with check_warnings() as w: with check_py3k_warnings() as w:
self.assertWarning(set(), w, expected) self.assertWarning(set(), w, expected)
def test_slice_methods(self): def test_slice_methods(self):
@ -222,7 +220,7 @@ class TestPy3KWarnings(unittest.TestCase):
expected = "in 3.x, __{0}slice__ has been removed; use __{0}item__" expected = "in 3.x, __{0}slice__ has been removed; use __{0}item__"
for obj in (Spam(), Egg()): for obj in (Spam(), Egg()):
with check_warnings() as w: with check_py3k_warnings() as w:
self.assertWarning(obj[1:2], w, expected.format('get')) self.assertWarning(obj[1:2], w, expected.format('get'))
w.reset() w.reset()
del obj[3:4] del obj[3:4]
@ -233,24 +231,23 @@ class TestPy3KWarnings(unittest.TestCase):
def test_tuple_parameter_unpacking(self): def test_tuple_parameter_unpacking(self):
expected = "tuple parameter unpacking has been removed in 3.x" expected = "tuple parameter unpacking has been removed in 3.x"
with check_warnings() as w: with check_py3k_warnings((expected, SyntaxWarning)):
exec "def f((a, b)): pass" exec "def f((a, b)): pass"
self.assertWarning(None, w, expected)
def test_buffer(self): def test_buffer(self):
expected = 'buffer() not supported in 3.x' expected = 'buffer() not supported in 3.x'
with check_warnings() as w: with check_py3k_warnings() as w:
self.assertWarning(buffer('a'), w, expected) self.assertWarning(buffer('a'), w, expected)
def test_file_xreadlines(self): def test_file_xreadlines(self):
expected = ("f.xreadlines() not supported in 3.x, " expected = ("f.xreadlines() not supported in 3.x, "
"try 'for line in f' instead") "try 'for line in f' instead")
with file(__file__) as f: with file(__file__) as f:
with check_warnings() as w: with check_py3k_warnings() as w:
self.assertWarning(f.xreadlines(), w, expected) self.assertWarning(f.xreadlines(), w, expected)
def test_hash_inheritance(self): def test_hash_inheritance(self):
with check_warnings() as w: with check_py3k_warnings() as w:
# With object as the base class # With object as the base class
class WarnOnlyCmp(object): class WarnOnlyCmp(object):
def __cmp__(self, other): pass def __cmp__(self, other): pass
@ -313,7 +310,7 @@ class TestPy3KWarnings(unittest.TestCase):
"Use hasattr(obj, '__call__').") "Use hasattr(obj, '__call__').")
seq_warn = ("operator.sequenceIncludes() is not supported " seq_warn = ("operator.sequenceIncludes() is not supported "
"in 3.x. Use operator.contains().") "in 3.x. Use operator.contains().")
with check_warnings() as w: with check_py3k_warnings() as w:
self.assertWarning(isCallable(self), w, callable_warn) self.assertWarning(isCallable(self), w, callable_warn)
w.reset() w.reset()
self.assertWarning(sequenceIncludes(range(3), 2), w, seq_warn) self.assertWarning(sequenceIncludes(range(3), 2), w, seq_warn)
@ -400,7 +397,7 @@ class TestStdlibRemovals(unittest.TestCase):
for path_mod in ("ntpath", "macpath", "os2emxpath", "posixpath"): for path_mod in ("ntpath", "macpath", "os2emxpath", "posixpath"):
mod = __import__(path_mod) mod = __import__(path_mod)
reset_module_registry(mod) reset_module_registry(mod)
with check_warnings() as w: with check_py3k_warnings() as w:
mod.walk("crashers", dumbo, None) mod.walk("crashers", dumbo, None)
self.assertEquals(str(w.message), msg) self.assertEquals(str(w.message), msg)

View file

@ -462,30 +462,26 @@ class TestShutil(unittest.TestCase):
old_dir = os.getcwd() old_dir = os.getcwd()
os.chdir(tmpdir) os.chdir(tmpdir)
try: try:
with captured_stdout() as s: with captured_stdout() as s, check_warnings(quiet=False) as w:
with check_warnings() as w: _make_tarball(base_name, 'dist', compress='compress')
warnings.simplefilter("always")
_make_tarball(base_name, 'dist', compress='compress')
finally: finally:
os.chdir(old_dir) os.chdir(old_dir)
tarball = base_name + '.tar.Z' tarball = base_name + '.tar.Z'
self.assertTrue(os.path.exists(tarball)) self.assertTrue(os.path.exists(tarball))
self.assertEquals(len(w.warnings), 1) self.assertEqual(len(w.warnings), 1)
# same test with dry_run # same test with dry_run
os.remove(tarball) os.remove(tarball)
old_dir = os.getcwd() old_dir = os.getcwd()
os.chdir(tmpdir) os.chdir(tmpdir)
try: try:
with captured_stdout() as s: with captured_stdout() as s, check_warnings(quiet=False) as w:
with check_warnings() as w: _make_tarball(base_name, 'dist', compress='compress',
warnings.simplefilter("always") dry_run=True)
_make_tarball(base_name, 'dist', compress='compress',
dry_run=True)
finally: finally:
os.chdir(old_dir) os.chdir(old_dir)
self.assertTrue(not os.path.exists(tarball)) self.assertFalse(os.path.exists(tarball))
self.assertEquals(len(w.warnings), 1) self.assertEqual(len(w.warnings), 1)
@unittest.skipUnless(zlib, "Requires zlib") @unittest.skipUnless(zlib, "Requires zlib")
@unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run') @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')

View file

@ -65,39 +65,30 @@ class ReadWriteTests(unittest.TestCase):
class TestWarnings(unittest.TestCase): class TestWarnings(unittest.TestCase):
def has_warned(self, w):
self.assertEqual(w.category, RuntimeWarning)
def test_byte_max(self): def test_byte_max(self):
with test_support.check_warnings() as w: with test_support.check_warnings(('', RuntimeWarning)):
ts.T_BYTE = CHAR_MAX+1 ts.T_BYTE = CHAR_MAX+1
self.has_warned(w)
def test_byte_min(self): def test_byte_min(self):
with test_support.check_warnings() as w: with test_support.check_warnings(('', RuntimeWarning)):
ts.T_BYTE = CHAR_MIN-1 ts.T_BYTE = CHAR_MIN-1
self.has_warned(w)
def test_ubyte_max(self): def test_ubyte_max(self):
with test_support.check_warnings() as w: with test_support.check_warnings(('', RuntimeWarning)):
ts.T_UBYTE = UCHAR_MAX+1 ts.T_UBYTE = UCHAR_MAX+1
self.has_warned(w)
def test_short_max(self): def test_short_max(self):
with test_support.check_warnings() as w: with test_support.check_warnings(('', RuntimeWarning)):
ts.T_SHORT = SHRT_MAX+1 ts.T_SHORT = SHRT_MAX+1
self.has_warned(w)
def test_short_min(self): def test_short_min(self):
with test_support.check_warnings() as w: with test_support.check_warnings(('', RuntimeWarning)):
ts.T_SHORT = SHRT_MIN-1 ts.T_SHORT = SHRT_MIN-1
self.has_warned(w)
def test_ushort_max(self): def test_ushort_max(self):
with test_support.check_warnings() as w: with test_support.check_warnings(('', RuntimeWarning)):
ts.T_USHORT = USHRT_MAX+1 ts.T_USHORT = USHRT_MAX+1
self.has_warned(w)
def test_main(verbose=None): def test_main(verbose=None):