diff options
author | Benjamin Peterson <benjamin@python.org> | 2009-06-30 22:57:08 (GMT) |
---|---|---|
committer | Benjamin Peterson <benjamin@python.org> | 2009-06-30 22:57:08 (GMT) |
commit | 5c8da86f3a515ce1a6d5f27fd15e3c5f4d8e931e (patch) | |
tree | 41f38aca16748628d53906337f06fdf087f52314 | |
parent | be96cf608fa656d7e53144cf85082ed5661e8c13 (diff) | |
download | cpython-5c8da86f3a515ce1a6d5f27fd15e3c5f4d8e931e.zip cpython-5c8da86f3a515ce1a6d5f27fd15e3c5f4d8e931e.tar.gz cpython-5c8da86f3a515ce1a6d5f27fd15e3c5f4d8e931e.tar.bz2 |
convert usage of fail* to assert*
268 files changed, 5021 insertions, 5021 deletions
diff --git a/Lib/ctypes/test/test_anon.py b/Lib/ctypes/test/test_anon.py index 99e02cb..d892b59 100644 --- a/Lib/ctypes/test/test_anon.py +++ b/Lib/ctypes/test/test_anon.py @@ -14,22 +14,22 @@ class AnonTest(unittest.TestCase): ("y", c_int)] _anonymous_ = ["_"] - self.failUnlessEqual(Y.a.offset, sizeof(c_int)) - self.failUnlessEqual(Y.b.offset, sizeof(c_int)) + self.assertEqual(Y.a.offset, sizeof(c_int)) + self.assertEqual(Y.b.offset, sizeof(c_int)) - self.failUnlessEqual(ANON.a.offset, 0) - self.failUnlessEqual(ANON.b.offset, 0) + self.assertEqual(ANON.a.offset, 0) + self.assertEqual(ANON.b.offset, 0) def test_anon_nonseq(self): # TypeError: _anonymous_ must be a sequence - self.failUnlessRaises(TypeError, + self.assertRaises(TypeError, lambda: type(Structure)("Name", (Structure,), {"_fields_": [], "_anonymous_": 42})) def test_anon_nonmember(self): # AttributeError: type object 'Name' has no attribute 'x' - self.failUnlessRaises(AttributeError, + self.assertRaises(AttributeError, lambda: type(Structure)("Name", (Structure,), {"_fields_": [], @@ -50,11 +50,11 @@ class AnonTest(unittest.TestCase): ("y", c_int)] _anonymous_ = ["_"] - self.failUnlessEqual(Y.x.offset, 0) - self.failUnlessEqual(Y.a.offset, sizeof(c_int)) - self.failUnlessEqual(Y.b.offset, sizeof(c_int)) - self.failUnlessEqual(Y._.offset, sizeof(c_int)) - self.failUnlessEqual(Y.y.offset, sizeof(c_int) * 2) + self.assertEqual(Y.x.offset, 0) + self.assertEqual(Y.a.offset, sizeof(c_int)) + self.assertEqual(Y.b.offset, sizeof(c_int)) + self.assertEqual(Y._.offset, sizeof(c_int)) + self.assertEqual(Y.y.offset, sizeof(c_int) * 2) if __name__ == "__main__": unittest.main() diff --git a/Lib/ctypes/test/test_array_in_pointer.py b/Lib/ctypes/test/test_array_in_pointer.py index 3ed310c..c313aa6 100644 --- a/Lib/ctypes/test/test_array_in_pointer.py +++ b/Lib/ctypes/test/test_array_in_pointer.py @@ -26,7 +26,7 @@ class Test(unittest.TestCase): c.pvalues = val_array # memory contains 4 NUL bytes now, that's correct - self.failUnlessEqual("00-00-00-00", dump(val_array)) + self.assertEqual("00-00-00-00", dump(val_array)) # set the values of the array through the pointer: for i in range(4): @@ -35,7 +35,7 @@ class Test(unittest.TestCase): values = [c.pvalues[i].val for i in range(4)] # These are the expected results: here s the bug! - self.failUnlessEqual( + self.assertEqual( (values, dump(val_array)), ([1, 2, 3, 4], "01-02-03-04") ) @@ -45,7 +45,7 @@ class Test(unittest.TestCase): val_array = (Value * 4)() # memory contains 4 NUL bytes now, that's correct - self.failUnlessEqual("00-00-00-00", dump(val_array)) + self.assertEqual("00-00-00-00", dump(val_array)) ptr = cast(val_array, POINTER(Value)) # set the values of the array through the pointer: @@ -55,7 +55,7 @@ class Test(unittest.TestCase): values = [ptr[i].val for i in range(4)] # These are the expected results: here s the bug! - self.failUnlessEqual( + self.assertEqual( (values, dump(val_array)), ([1, 2, 3, 4], "01-02-03-04") ) diff --git a/Lib/ctypes/test/test_arrays.py b/Lib/ctypes/test/test_arrays.py index 7ee16c1..433a1ff 100644 --- a/Lib/ctypes/test/test_arrays.py +++ b/Lib/ctypes/test/test_arrays.py @@ -19,23 +19,23 @@ class ArrayTestCase(unittest.TestCase): ia = int_array(*init) # length of instance ok? - self.failUnlessEqual(len(ia), alen) + self.assertEqual(len(ia), alen) # slot values ok? values = [ia[i] for i in range(len(init))] - self.failUnlessEqual(values, init) + self.assertEqual(values, init) # change the items from operator import setitem new_values = range(42, 42+alen) [setitem(ia, n, new_values[n]) for n in range(alen)] values = [ia[i] for i in range(len(init))] - self.failUnlessEqual(values, new_values) + self.assertEqual(values, new_values) # are the items initialized to 0? ia = int_array() values = [ia[i] for i in range(len(init))] - self.failUnlessEqual(values, [0] * len(init)) + self.assertEqual(values, [0] * len(init)) # Too many in itializers should be caught self.assertRaises(IndexError, int_array, *range(alen*2)) @@ -48,14 +48,14 @@ class ArrayTestCase(unittest.TestCase): # CharArray("abc") self.assertRaises(TypeError, CharArray, "abc") - self.failUnlessEqual(ca[0], "a") - self.failUnlessEqual(ca[1], "b") - self.failUnlessEqual(ca[2], "c") - self.failUnlessEqual(ca[-3], "a") - self.failUnlessEqual(ca[-2], "b") - self.failUnlessEqual(ca[-1], "c") + self.assertEqual(ca[0], "a") + self.assertEqual(ca[1], "b") + self.assertEqual(ca[2], "c") + self.assertEqual(ca[-3], "a") + self.assertEqual(ca[-2], "b") + self.assertEqual(ca[-1], "c") - self.failUnlessEqual(len(ca), 3) + self.assertEqual(len(ca), 3) # slicing is now supported, but not extended slicing (3-argument)! from operator import getslice, delitem @@ -72,34 +72,34 @@ class ArrayTestCase(unittest.TestCase): na = numarray() values = [na[i] for i in range(alen)] - self.failUnlessEqual(values, [0] * alen) + self.assertEqual(values, [0] * alen) na = numarray(*[c_int()] * alen) values = [na[i] for i in range(alen)] - self.failUnlessEqual(values, [0]*alen) + self.assertEqual(values, [0]*alen) na = numarray(1, 2, 3, 4, 5) values = [i for i in na] - self.failUnlessEqual(values, [1, 2, 3, 4, 5]) + self.assertEqual(values, [1, 2, 3, 4, 5]) na = numarray(*map(c_int, (1, 2, 3, 4, 5))) values = [i for i in na] - self.failUnlessEqual(values, [1, 2, 3, 4, 5]) + self.assertEqual(values, [1, 2, 3, 4, 5]) def test_classcache(self): - self.failUnless(not ARRAY(c_int, 3) is ARRAY(c_int, 4)) - self.failUnless(ARRAY(c_int, 3) is ARRAY(c_int, 3)) + self.assertTrue(not ARRAY(c_int, 3) is ARRAY(c_int, 4)) + self.assertTrue(ARRAY(c_int, 3) is ARRAY(c_int, 3)) def test_from_address(self): # Failed with 0.9.8, reported by JUrner p = create_string_buffer("foo") sz = (c_char * 3).from_address(addressof(p)) - self.failUnlessEqual(sz[:], "foo") - self.failUnlessEqual(sz[::], "foo") - self.failUnlessEqual(sz[::-1], "oof") - self.failUnlessEqual(sz[::3], "f") - self.failUnlessEqual(sz[1:4:2], "o") - self.failUnlessEqual(sz.value, "foo") + self.assertEqual(sz[:], "foo") + self.assertEqual(sz[::], "foo") + self.assertEqual(sz[::-1], "oof") + self.assertEqual(sz[::3], "f") + self.assertEqual(sz[1:4:2], "o") + self.assertEqual(sz.value, "foo") try: create_unicode_buffer @@ -109,12 +109,12 @@ class ArrayTestCase(unittest.TestCase): def test_from_addressW(self): p = create_unicode_buffer("foo") sz = (c_wchar * 3).from_address(addressof(p)) - self.failUnlessEqual(sz[:], "foo") - self.failUnlessEqual(sz[::], "foo") - self.failUnlessEqual(sz[::-1], "oof") - self.failUnlessEqual(sz[::3], "f") - self.failUnlessEqual(sz[1:4:2], "o") - self.failUnlessEqual(sz.value, "foo") + self.assertEqual(sz[:], "foo") + self.assertEqual(sz[::], "foo") + self.assertEqual(sz[::-1], "oof") + self.assertEqual(sz[::3], "f") + self.assertEqual(sz[1:4:2], "o") + self.assertEqual(sz.value, "foo") def test_cache(self): # Array types are cached internally in the _ctypes extension, @@ -128,7 +128,7 @@ class ArrayTestCase(unittest.TestCase): # Create a new array type based on it: t1 = my_int * 1 t2 = my_int * 1 - self.failUnless(t1 is t2) + self.assertTrue(t1 is t2) if __name__ == '__main__': unittest.main() diff --git a/Lib/ctypes/test/test_as_parameter.py b/Lib/ctypes/test/test_as_parameter.py index 0581059..f2539b1 100644 --- a/Lib/ctypes/test/test_as_parameter.py +++ b/Lib/ctypes/test/test_as_parameter.py @@ -25,8 +25,8 @@ class BasicWrapTestCase(unittest.TestCase): f = dll._testfunc_i_bhilfd f.argtypes = [c_byte, c_wchar, c_int, c_long, c_float, c_double] result = f(self.wrap(1), self.wrap(u"x"), self.wrap(3), self.wrap(4), self.wrap(5.0), self.wrap(6.0)) - self.failUnlessEqual(result, 139) - self.failUnless(type(result), int) + self.assertEqual(result, 139) + self.assertTrue(type(result), int) def test_pointers(self): f = dll._testfunc_p_p @@ -39,18 +39,18 @@ class BasicWrapTestCase(unittest.TestCase): v = c_int(42) - self.failUnlessEqual(pointer(v).contents.value, 42) + self.assertEqual(pointer(v).contents.value, 42) result = f(self.wrap(pointer(v))) - self.failUnlessEqual(type(result), POINTER(c_int)) - self.failUnlessEqual(result.contents.value, 42) + self.assertEqual(type(result), POINTER(c_int)) + self.assertEqual(result.contents.value, 42) # This on works... result = f(self.wrap(pointer(v))) - self.failUnlessEqual(result.contents.value, v.value) + self.assertEqual(result.contents.value, v.value) p = pointer(c_int(99)) result = f(self.wrap(p)) - self.failUnlessEqual(result.contents.value, 99) + self.assertEqual(result.contents.value, 99) def test_shorts(self): f = dll._testfunc_callback_i_if @@ -67,7 +67,7 @@ class BasicWrapTestCase(unittest.TestCase): cb = CallBack(callback) f(self.wrap(2**18), self.wrap(cb)) - self.failUnlessEqual(args, expected) + self.assertEqual(args, expected) ################################################################ @@ -84,17 +84,17 @@ class BasicWrapTestCase(unittest.TestCase): cb = MyCallback(callback) result = f(self.wrap(-10), self.wrap(cb)) - self.failUnlessEqual(result, -18) + self.assertEqual(result, -18) # test with prototype f.argtypes = [c_int, MyCallback] cb = MyCallback(callback) result = f(self.wrap(-10), self.wrap(cb)) - self.failUnlessEqual(result, -18) + self.assertEqual(result, -18) result = f(self.wrap(-10), self.wrap(cb)) - self.failUnlessEqual(result, -18) + self.assertEqual(result, -18) AnotherCallback = CALLBACK_FUNCTYPE(c_int, c_int, c_int, c_int, c_int) @@ -116,12 +116,12 @@ class BasicWrapTestCase(unittest.TestCase): def callback(value): #print "called back with", value - self.failUnlessEqual(type(value), int) + self.assertEqual(type(value), int) return value cb = MyCallback(callback) result = f(self.wrap(-10), self.wrap(cb)) - self.failUnlessEqual(result, -18) + self.assertEqual(result, -18) def test_longlong_callbacks(self): @@ -133,12 +133,12 @@ class BasicWrapTestCase(unittest.TestCase): f.argtypes = [c_longlong, MyCallback] def callback(value): - self.failUnless(isinstance(value, (int, long))) + self.assertTrue(isinstance(value, (int, long))) return value & 0x7FFFFFFF cb = MyCallback(callback) - self.failUnlessEqual(13577625587, int(f(self.wrap(1000000000000), self.wrap(cb)))) + self.assertEqual(13577625587, int(f(self.wrap(1000000000000), self.wrap(cb)))) def test_byval(self): # without prototype @@ -148,7 +148,7 @@ class BasicWrapTestCase(unittest.TestCase): result = dll._testfunc_byval(ptin, byref(ptout)) got = result, ptout.x, ptout.y expected = 3, 1, 2 - self.failUnlessEqual(got, expected) + self.assertEqual(got, expected) # with prototype ptin = POINT(101, 102) @@ -158,7 +158,7 @@ class BasicWrapTestCase(unittest.TestCase): result = dll._testfunc_byval(self.wrap(ptin), byref(ptout)) got = result, ptout.x, ptout.y expected = 203, 101, 102 - self.failUnlessEqual(got, expected) + self.assertEqual(got, expected) def test_struct_return_2H(self): class S2H(Structure): @@ -168,7 +168,7 @@ class BasicWrapTestCase(unittest.TestCase): dll.ret_2h_func.argtypes = [S2H] inp = S2H(99, 88) s2h = dll.ret_2h_func(self.wrap(inp)) - self.failUnlessEqual((s2h.x, s2h.y), (99*2, 88*3)) + self.assertEqual((s2h.x, s2h.y), (99*2, 88*3)) def test_struct_return_8H(self): class S8I(Structure): @@ -184,7 +184,7 @@ class BasicWrapTestCase(unittest.TestCase): dll.ret_8i_func.argtypes = [S8I] inp = S8I(9, 8, 7, 6, 5, 4, 3, 2) s8i = dll.ret_8i_func(self.wrap(inp)) - self.failUnlessEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h), + self.assertEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h), (9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9)) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/Lib/ctypes/test/test_bitfields.py b/Lib/ctypes/test/test_bitfields.py index 96cd7c6..e9c46c2 100644 --- a/Lib/ctypes/test/test_bitfields.py +++ b/Lib/ctypes/test/test_bitfields.py @@ -37,14 +37,14 @@ class C_Test(unittest.TestCase): for name in "ABCDEFGHI": b = BITS() setattr(b, name, i) - self.failUnlessEqual((name, i, getattr(b, name)), (name, i, func(byref(b), name))) + self.assertEqual((name, i, getattr(b, name)), (name, i, func(byref(b), name))) def test_shorts(self): for i in range(256): for name in "MNOPQRS": b = BITS() setattr(b, name, i) - self.failUnlessEqual((name, i, getattr(b, name)), (name, i, func(byref(b), name))) + self.assertEqual((name, i, getattr(b, name)), (name, i, func(byref(b), name))) signed_int_types = (c_byte, c_short, c_int, c_long, c_longlong) unsigned_int_types = (c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong) @@ -58,10 +58,10 @@ class BitFieldTest(unittest.TestCase): ("b", c_longlong, 62), ("c", c_longlong, 1)] - self.failUnlessEqual(sizeof(X), sizeof(c_longlong)) + self.assertEqual(sizeof(X), sizeof(c_longlong)) x = X() x.a, x.b, x.c = -1, 7, -1 - self.failUnlessEqual((x.a, x.b, x.c), (-1, 7, -1)) + self.assertEqual((x.a, x.b, x.c), (-1, 7, -1)) def test_ulonglong(self): class X(Structure): @@ -69,11 +69,11 @@ class BitFieldTest(unittest.TestCase): ("b", c_ulonglong, 62), ("c", c_ulonglong, 1)] - self.failUnlessEqual(sizeof(X), sizeof(c_longlong)) + self.assertEqual(sizeof(X), sizeof(c_longlong)) x = X() - self.failUnlessEqual((x.a, x.b, x.c), (0, 0, 0)) + self.assertEqual((x.a, x.b, x.c), (0, 0, 0)) x.a, x.b, x.c = 7, 7, 7 - self.failUnlessEqual((x.a, x.b, x.c), (1, 7, 1)) + self.assertEqual((x.a, x.b, x.c), (1, 7, 1)) def test_signed(self): for c_typ in signed_int_types: @@ -82,14 +82,14 @@ class BitFieldTest(unittest.TestCase): ("a", c_typ, 3), ("b", c_typ, 3), ("c", c_typ, 1)] - self.failUnlessEqual(sizeof(X), sizeof(c_typ)*2) + self.assertEqual(sizeof(X), sizeof(c_typ)*2) x = X() - self.failUnlessEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 0, 0)) + self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 0, 0)) x.a = -1 - self.failUnlessEqual((c_typ, x.a, x.b, x.c), (c_typ, -1, 0, 0)) + self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, -1, 0, 0)) x.a, x.b = 0, -1 - self.failUnlessEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, -1, 0)) + self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, -1, 0)) def test_unsigned(self): @@ -98,14 +98,14 @@ class BitFieldTest(unittest.TestCase): _fields_ = [("a", c_typ, 3), ("b", c_typ, 3), ("c", c_typ, 1)] - self.failUnlessEqual(sizeof(X), sizeof(c_typ)) + self.assertEqual(sizeof(X), sizeof(c_typ)) x = X() - self.failUnlessEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 0, 0)) + self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 0, 0)) x.a = -1 - self.failUnlessEqual((c_typ, x.a, x.b, x.c), (c_typ, 7, 0, 0)) + self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 7, 0, 0)) x.a, x.b = 0, -1 - self.failUnlessEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 7, 0)) + self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 7, 0)) def fail_fields(self, *fields): @@ -115,17 +115,17 @@ class BitFieldTest(unittest.TestCase): def test_nonint_types(self): # bit fields are not allowed on non-integer types. result = self.fail_fields(("a", c_char_p, 1)) - self.failUnlessEqual(result, (TypeError, 'bit fields not allowed for type c_char_p')) + self.assertEqual(result, (TypeError, 'bit fields not allowed for type c_char_p')) result = self.fail_fields(("a", c_void_p, 1)) - self.failUnlessEqual(result, (TypeError, 'bit fields not allowed for type c_void_p')) + self.assertEqual(result, (TypeError, 'bit fields not allowed for type c_void_p')) if c_int != c_long: result = self.fail_fields(("a", POINTER(c_int), 1)) - self.failUnlessEqual(result, (TypeError, 'bit fields not allowed for type LP_c_int')) + self.assertEqual(result, (TypeError, 'bit fields not allowed for type LP_c_int')) result = self.fail_fields(("a", c_char, 1)) - self.failUnlessEqual(result, (TypeError, 'bit fields not allowed for type c_char')) + self.assertEqual(result, (TypeError, 'bit fields not allowed for type c_char')) try: c_wchar @@ -133,59 +133,59 @@ class BitFieldTest(unittest.TestCase): pass else: result = self.fail_fields(("a", c_wchar, 1)) - self.failUnlessEqual(result, (TypeError, 'bit fields not allowed for type c_wchar')) + self.assertEqual(result, (TypeError, 'bit fields not allowed for type c_wchar')) class Dummy(Structure): _fields_ = [] result = self.fail_fields(("a", Dummy, 1)) - self.failUnlessEqual(result, (TypeError, 'bit fields not allowed for type Dummy')) + self.assertEqual(result, (TypeError, 'bit fields not allowed for type Dummy')) def test_single_bitfield_size(self): for c_typ in int_types: result = self.fail_fields(("a", c_typ, -1)) - self.failUnlessEqual(result, (ValueError, 'number of bits invalid for bit field')) + self.assertEqual(result, (ValueError, 'number of bits invalid for bit field')) result = self.fail_fields(("a", c_typ, 0)) - self.failUnlessEqual(result, (ValueError, 'number of bits invalid for bit field')) + self.assertEqual(result, (ValueError, 'number of bits invalid for bit field')) class X(Structure): _fields_ = [("a", c_typ, 1)] - self.failUnlessEqual(sizeof(X), sizeof(c_typ)) + self.assertEqual(sizeof(X), sizeof(c_typ)) class X(Structure): _fields_ = [("a", c_typ, sizeof(c_typ)*8)] - self.failUnlessEqual(sizeof(X), sizeof(c_typ)) + self.assertEqual(sizeof(X), sizeof(c_typ)) result = self.fail_fields(("a", c_typ, sizeof(c_typ)*8 + 1)) - self.failUnlessEqual(result, (ValueError, 'number of bits invalid for bit field')) + self.assertEqual(result, (ValueError, 'number of bits invalid for bit field')) def test_multi_bitfields_size(self): class X(Structure): _fields_ = [("a", c_short, 1), ("b", c_short, 14), ("c", c_short, 1)] - self.failUnlessEqual(sizeof(X), sizeof(c_short)) + self.assertEqual(sizeof(X), sizeof(c_short)) class X(Structure): _fields_ = [("a", c_short, 1), ("a1", c_short), ("b", c_short, 14), ("c", c_short, 1)] - self.failUnlessEqual(sizeof(X), sizeof(c_short)*3) - self.failUnlessEqual(X.a.offset, 0) - self.failUnlessEqual(X.a1.offset, sizeof(c_short)) - self.failUnlessEqual(X.b.offset, sizeof(c_short)*2) - self.failUnlessEqual(X.c.offset, sizeof(c_short)*2) + self.assertEqual(sizeof(X), sizeof(c_short)*3) + self.assertEqual(X.a.offset, 0) + self.assertEqual(X.a1.offset, sizeof(c_short)) + self.assertEqual(X.b.offset, sizeof(c_short)*2) + self.assertEqual(X.c.offset, sizeof(c_short)*2) class X(Structure): _fields_ = [("a", c_short, 3), ("b", c_short, 14), ("c", c_short, 14)] - self.failUnlessEqual(sizeof(X), sizeof(c_short)*3) - self.failUnlessEqual(X.a.offset, sizeof(c_short)*0) - self.failUnlessEqual(X.b.offset, sizeof(c_short)*1) - self.failUnlessEqual(X.c.offset, sizeof(c_short)*2) + self.assertEqual(sizeof(X), sizeof(c_short)*3) + self.assertEqual(X.a.offset, sizeof(c_short)*0) + self.assertEqual(X.b.offset, sizeof(c_short)*1) + self.assertEqual(X.c.offset, sizeof(c_short)*2) def get_except(self, func, *args, **kw): @@ -199,21 +199,21 @@ class BitFieldTest(unittest.TestCase): _fields_ = [("a", c_byte, 4), ("b", c_int, 4)] if os.name in ("nt", "ce"): - self.failUnlessEqual(sizeof(X), sizeof(c_int)*2) + self.assertEqual(sizeof(X), sizeof(c_int)*2) else: - self.failUnlessEqual(sizeof(X), sizeof(c_int)) + self.assertEqual(sizeof(X), sizeof(c_int)) def test_mixed_2(self): class X(Structure): _fields_ = [("a", c_byte, 4), ("b", c_int, 32)] - self.failUnlessEqual(sizeof(X), sizeof(c_int)*2) + self.assertEqual(sizeof(X), sizeof(c_int)*2) def test_mixed_3(self): class X(Structure): _fields_ = [("a", c_byte, 4), ("b", c_ubyte, 4)] - self.failUnlessEqual(sizeof(X), sizeof(c_byte)) + self.assertEqual(sizeof(X), sizeof(c_byte)) def test_mixed_4(self): class X(Structure): @@ -227,9 +227,9 @@ class BitFieldTest(unittest.TestCase): # does (unless GCC is run with '-mms-bitfields' which # produces code compatible with MSVC). if os.name in ("nt", "ce"): - self.failUnlessEqual(sizeof(X), sizeof(c_int) * 4) + self.assertEqual(sizeof(X), sizeof(c_int) * 4) else: - self.failUnlessEqual(sizeof(X), sizeof(c_int) * 2) + self.assertEqual(sizeof(X), sizeof(c_int) * 2) def test_anon_bitfields(self): # anonymous bit-fields gave a strange error message diff --git a/Lib/ctypes/test/test_buffers.py b/Lib/ctypes/test/test_buffers.py index 5b96d12..bf931ab 100644 --- a/Lib/ctypes/test/test_buffers.py +++ b/Lib/ctypes/test/test_buffers.py @@ -5,32 +5,32 @@ class StringBufferTestCase(unittest.TestCase): def test_buffer(self): b = create_string_buffer(32) - self.failUnlessEqual(len(b), 32) - self.failUnlessEqual(sizeof(b), 32 * sizeof(c_char)) - self.failUnless(type(b[0]) is str) + self.assertEqual(len(b), 32) + self.assertEqual(sizeof(b), 32 * sizeof(c_char)) + self.assertTrue(type(b[0]) is str) b = create_string_buffer("abc") - self.failUnlessEqual(len(b), 4) # trailing nul char - self.failUnlessEqual(sizeof(b), 4 * sizeof(c_char)) - self.failUnless(type(b[0]) is str) - self.failUnlessEqual(b[0], "a") - self.failUnlessEqual(b[:], "abc\0") - self.failUnlessEqual(b[::], "abc\0") - self.failUnlessEqual(b[::-1], "\0cba") - self.failUnlessEqual(b[::2], "ac") - self.failUnlessEqual(b[::5], "a") + self.assertEqual(len(b), 4) # trailing nul char + self.assertEqual(sizeof(b), 4 * sizeof(c_char)) + self.assertTrue(type(b[0]) is str) + self.assertEqual(b[0], "a") + self.assertEqual(b[:], "abc\0") + self.assertEqual(b[::], "abc\0") + self.assertEqual(b[::-1], "\0cba") + self.assertEqual(b[::2], "ac") + self.assertEqual(b[::5], "a") def test_string_conversion(self): b = create_string_buffer(u"abc") - self.failUnlessEqual(len(b), 4) # trailing nul char - self.failUnlessEqual(sizeof(b), 4 * sizeof(c_char)) - self.failUnless(type(b[0]) is str) - self.failUnlessEqual(b[0], "a") - self.failUnlessEqual(b[:], "abc\0") - self.failUnlessEqual(b[::], "abc\0") - self.failUnlessEqual(b[::-1], "\0cba") - self.failUnlessEqual(b[::2], "ac") - self.failUnlessEqual(b[::5], "a") + self.assertEqual(len(b), 4) # trailing nul char + self.assertEqual(sizeof(b), 4 * sizeof(c_char)) + self.assertTrue(type(b[0]) is str) + self.assertEqual(b[0], "a") + self.assertEqual(b[:], "abc\0") + self.assertEqual(b[::], "abc\0") + self.assertEqual(b[::-1], "\0cba") + self.assertEqual(b[::2], "ac") + self.assertEqual(b[::5], "a") try: c_wchar @@ -39,32 +39,32 @@ class StringBufferTestCase(unittest.TestCase): else: def test_unicode_buffer(self): b = create_unicode_buffer(32) - self.failUnlessEqual(len(b), 32) - self.failUnlessEqual(sizeof(b), 32 * sizeof(c_wchar)) - self.failUnless(type(b[0]) is unicode) + self.assertEqual(len(b), 32) + self.assertEqual(sizeof(b), 32 * sizeof(c_wchar)) + self.assertTrue(type(b[0]) is unicode) b = create_unicode_buffer(u"abc") - self.failUnlessEqual(len(b), 4) # trailing nul char - self.failUnlessEqual(sizeof(b), 4 * sizeof(c_wchar)) - self.failUnless(type(b[0]) is unicode) - self.failUnlessEqual(b[0], u"a") - self.failUnlessEqual(b[:], "abc\0") - self.failUnlessEqual(b[::], "abc\0") - self.failUnlessEqual(b[::-1], "\0cba") - self.failUnlessEqual(b[::2], "ac") - self.failUnlessEqual(b[::5], "a") + self.assertEqual(len(b), 4) # trailing nul char + self.assertEqual(sizeof(b), 4 * sizeof(c_wchar)) + self.assertTrue(type(b[0]) is unicode) + self.assertEqual(b[0], u"a") + self.assertEqual(b[:], "abc\0") + self.assertEqual(b[::], "abc\0") + self.assertEqual(b[::-1], "\0cba") + self.assertEqual(b[::2], "ac") + self.assertEqual(b[::5], "a") def test_unicode_conversion(self): b = create_unicode_buffer("abc") - self.failUnlessEqual(len(b), 4) # trailing nul char - self.failUnlessEqual(sizeof(b), 4 * sizeof(c_wchar)) - self.failUnless(type(b[0]) is unicode) - self.failUnlessEqual(b[0], u"a") - self.failUnlessEqual(b[:], "abc\0") - self.failUnlessEqual(b[::], "abc\0") - self.failUnlessEqual(b[::-1], "\0cba") - self.failUnlessEqual(b[::2], "ac") - self.failUnlessEqual(b[::5], "a") + self.assertEqual(len(b), 4) # trailing nul char + self.assertEqual(sizeof(b), 4 * sizeof(c_wchar)) + self.assertTrue(type(b[0]) is unicode) + self.assertEqual(b[0], u"a") + self.assertEqual(b[:], "abc\0") + self.assertEqual(b[::], "abc\0") + self.assertEqual(b[::-1], "\0cba") + self.assertEqual(b[::2], "ac") + self.assertEqual(b[::5], "a") if __name__ == "__main__": unittest.main() diff --git a/Lib/ctypes/test/test_byteswap.py b/Lib/ctypes/test/test_byteswap.py index 1f68992..e64fd45 100644 --- a/Lib/ctypes/test/test_byteswap.py +++ b/Lib/ctypes/test/test_byteswap.py @@ -23,131 +23,131 @@ class Test(unittest.TestCase): def test_endian_short(self): if sys.byteorder == "little": - self.failUnless(c_short.__ctype_le__ is c_short) - self.failUnless(c_short.__ctype_be__.__ctype_le__ is c_short) + self.assertTrue(c_short.__ctype_le__ is c_short) + self.assertTrue(c_short.__ctype_be__.__ctype_le__ is c_short) else: - self.failUnless(c_short.__ctype_be__ is c_short) - self.failUnless(c_short.__ctype_le__.__ctype_be__ is c_short) + self.assertTrue(c_short.__ctype_be__ is c_short) + self.assertTrue(c_short.__ctype_le__.__ctype_be__ is c_short) s = c_short.__ctype_be__(0x1234) - self.failUnlessEqual(bin(struct.pack(">h", 0x1234)), "1234") - self.failUnlessEqual(bin(s), "1234") - self.failUnlessEqual(s.value, 0x1234) + self.assertEqual(bin(struct.pack(">h", 0x1234)), "1234") + self.assertEqual(bin(s), "1234") + self.assertEqual(s.value, 0x1234) s = c_short.__ctype_le__(0x1234) - self.failUnlessEqual(bin(struct.pack("<h", 0x1234)), "3412") - self.failUnlessEqual(bin(s), "3412") - self.failUnlessEqual(s.value, 0x1234) + self.assertEqual(bin(struct.pack("<h", 0x1234)), "3412") + self.assertEqual(bin(s), "3412") + self.assertEqual(s.value, 0x1234) s = c_ushort.__ctype_be__(0x1234) - self.failUnlessEqual(bin(struct.pack(">h", 0x1234)), "1234") - self.failUnlessEqual(bin(s), "1234") - self.failUnlessEqual(s.value, 0x1234) + self.assertEqual(bin(struct.pack(">h", 0x1234)), "1234") + self.assertEqual(bin(s), "1234") + self.assertEqual(s.value, 0x1234) s = c_ushort.__ctype_le__(0x1234) - self.failUnlessEqual(bin(struct.pack("<h", 0x1234)), "3412") - self.failUnlessEqual(bin(s), "3412") - self.failUnlessEqual(s.value, 0x1234) + self.assertEqual(bin(struct.pack("<h", 0x1234)), "3412") + self.assertEqual(bin(s), "3412") + self.assertEqual(s.value, 0x1234) def test_endian_int(self): if sys.byteorder == "little": - self.failUnless(c_int.__ctype_le__ is c_int) - self.failUnless(c_int.__ctype_be__.__ctype_le__ is c_int) + self.assertTrue(c_int.__ctype_le__ is c_int) + self.assertTrue(c_int.__ctype_be__.__ctype_le__ is c_int) else: - self.failUnless(c_int.__ctype_be__ is c_int) - self.failUnless(c_int.__ctype_le__.__ctype_be__ is c_int) + self.assertTrue(c_int.__ctype_be__ is c_int) + self.assertTrue(c_int.__ctype_le__.__ctype_be__ is c_int) s = c_int.__ctype_be__(0x12345678) - self.failUnlessEqual(bin(struct.pack(">i", 0x12345678)), "12345678") - self.failUnlessEqual(bin(s), "12345678") - self.failUnlessEqual(s.value, 0x12345678) + self.assertEqual(bin(struct.pack(">i", 0x12345678)), "12345678") + self.assertEqual(bin(s), "12345678") + self.assertEqual(s.value, 0x12345678) s = c_int.__ctype_le__(0x12345678) - self.failUnlessEqual(bin(struct.pack("<i", 0x12345678)), "78563412") - self.failUnlessEqual(bin(s), "78563412") - self.failUnlessEqual(s.value, 0x12345678) + self.assertEqual(bin(struct.pack("<i", 0x12345678)), "78563412") + self.assertEqual(bin(s), "78563412") + self.assertEqual(s.value, 0x12345678) s = c_uint.__ctype_be__(0x12345678) - self.failUnlessEqual(bin(struct.pack(">I", 0x12345678)), "12345678") - self.failUnlessEqual(bin(s), "12345678") - self.failUnlessEqual(s.value, 0x12345678) + self.assertEqual(bin(struct.pack(">I", 0x12345678)), "12345678") + self.assertEqual(bin(s), "12345678") + self.assertEqual(s.value, 0x12345678) s = c_uint.__ctype_le__(0x12345678) - self.failUnlessEqual(bin(struct.pack("<I", 0x12345678)), "78563412") - self.failUnlessEqual(bin(s), "78563412") - self.failUnlessEqual(s.value, 0x12345678) + self.assertEqual(bin(struct.pack("<I", 0x12345678)), "78563412") + self.assertEqual(bin(s), "78563412") + self.assertEqual(s.value, 0x12345678) def test_endian_longlong(self): if sys.byteorder == "little": - self.failUnless(c_longlong.__ctype_le__ is c_longlong) - self.failUnless(c_longlong.__ctype_be__.__ctype_le__ is c_longlong) + self.assertTrue(c_longlong.__ctype_le__ is c_longlong) + self.assertTrue(c_longlong.__ctype_be__.__ctype_le__ is c_longlong) else: - self.failUnless(c_longlong.__ctype_be__ is c_longlong) - self.failUnless(c_longlong.__ctype_le__.__ctype_be__ is c_longlong) + self.assertTrue(c_longlong.__ctype_be__ is c_longlong) + self.assertTrue(c_longlong.__ctype_le__.__ctype_be__ is c_longlong) s = c_longlong.__ctype_be__(0x1234567890ABCDEF) - self.failUnlessEqual(bin(struct.pack(">q", 0x1234567890ABCDEF)), "1234567890ABCDEF") - self.failUnlessEqual(bin(s), "1234567890ABCDEF") - self.failUnlessEqual(s.value, 0x1234567890ABCDEF) + self.assertEqual(bin(struct.pack(">q", 0x1234567890ABCDEF)), "1234567890ABCDEF") + self.assertEqual(bin(s), "1234567890ABCDEF") + self.assertEqual(s.value, 0x1234567890ABCDEF) s = c_longlong.__ctype_le__(0x1234567890ABCDEF) - self.failUnlessEqual(bin(struct.pack("<q", 0x1234567890ABCDEF)), "EFCDAB9078563412") - self.failUnlessEqual(bin(s), "EFCDAB9078563412") - self.failUnlessEqual(s.value, 0x1234567890ABCDEF) + self.assertEqual(bin(struct.pack("<q", 0x1234567890ABCDEF)), "EFCDAB9078563412") + self.assertEqual(bin(s), "EFCDAB9078563412") + self.assertEqual(s.value, 0x1234567890ABCDEF) s = c_ulonglong.__ctype_be__(0x1234567890ABCDEF) - self.failUnlessEqual(bin(struct.pack(">Q", 0x1234567890ABCDEF)), "1234567890ABCDEF") - self.failUnlessEqual(bin(s), "1234567890ABCDEF") - self.failUnlessEqual(s.value, 0x1234567890ABCDEF) + self.assertEqual(bin(struct.pack(">Q", 0x1234567890ABCDEF)), "1234567890ABCDEF") + self.assertEqual(bin(s), "1234567890ABCDEF") + self.assertEqual(s.value, 0x1234567890ABCDEF) s = c_ulonglong.__ctype_le__(0x1234567890ABCDEF) - self.failUnlessEqual(bin(struct.pack("<Q", 0x1234567890ABCDEF)), "EFCDAB9078563412") - self.failUnlessEqual(bin(s), "EFCDAB9078563412") - self.failUnlessEqual(s.value, 0x1234567890ABCDEF) + self.assertEqual(bin(struct.pack("<Q", 0x1234567890ABCDEF)), "EFCDAB9078563412") + self.assertEqual(bin(s), "EFCDAB9078563412") + self.assertEqual(s.value, 0x1234567890ABCDEF) def test_endian_float(self): if sys.byteorder == "little": - self.failUnless(c_float.__ctype_le__ is c_float) - self.failUnless(c_float.__ctype_be__.__ctype_le__ is c_float) + self.assertTrue(c_float.__ctype_le__ is c_float) + self.assertTrue(c_float.__ctype_be__.__ctype_le__ is c_float) else: - self.failUnless(c_float.__ctype_be__ is c_float) - self.failUnless(c_float.__ctype_le__.__ctype_be__ is c_float) + self.assertTrue(c_float.__ctype_be__ is c_float) + self.assertTrue(c_float.__ctype_le__.__ctype_be__ is c_float) s = c_float(math.pi) - self.failUnlessEqual(bin(struct.pack("f", math.pi)), bin(s)) + self.assertEqual(bin(struct.pack("f", math.pi)), bin(s)) # Hm, what's the precision of a float compared to a double? - self.failUnlessAlmostEqual(s.value, math.pi, 6) + self.assertAlmostEqual(s.value, math.pi, 6) s = c_float.__ctype_le__(math.pi) - self.failUnlessAlmostEqual(s.value, math.pi, 6) - self.failUnlessEqual(bin(struct.pack("<f", math.pi)), bin(s)) + self.assertAlmostEqual(s.value, math.pi, 6) + self.assertEqual(bin(struct.pack("<f", math.pi)), bin(s)) s = c_float.__ctype_be__(math.pi) - self.failUnlessAlmostEqual(s.value, math.pi, 6) - self.failUnlessEqual(bin(struct.pack(">f", math.pi)), bin(s)) + self.assertAlmostEqual(s.value, math.pi, 6) + self.assertEqual(bin(struct.pack(">f", math.pi)), bin(s)) def test_endian_double(self): if sys.byteorder == "little": - self.failUnless(c_double.__ctype_le__ is c_double) - self.failUnless(c_double.__ctype_be__.__ctype_le__ is c_double) + self.assertTrue(c_double.__ctype_le__ is c_double) + self.assertTrue(c_double.__ctype_be__.__ctype_le__ is c_double) else: - self.failUnless(c_double.__ctype_be__ is c_double) - self.failUnless(c_double.__ctype_le__.__ctype_be__ is c_double) + self.assertTrue(c_double.__ctype_be__ is c_double) + self.assertTrue(c_double.__ctype_le__.__ctype_be__ is c_double) s = c_double(math.pi) - self.failUnlessEqual(s.value, math.pi) - self.failUnlessEqual(bin(struct.pack("d", math.pi)), bin(s)) + self.assertEqual(s.value, math.pi) + self.assertEqual(bin(struct.pack("d", math.pi)), bin(s)) s = c_double.__ctype_le__(math.pi) - self.failUnlessEqual(s.value, math.pi) - self.failUnlessEqual(bin(struct.pack("<d", math.pi)), bin(s)) + self.assertEqual(s.value, math.pi) + self.assertEqual(bin(struct.pack("<d", math.pi)), bin(s)) s = c_double.__ctype_be__(math.pi) - self.failUnlessEqual(s.value, math.pi) - self.failUnlessEqual(bin(struct.pack(">d", math.pi)), bin(s)) + self.assertEqual(s.value, math.pi) + self.assertEqual(bin(struct.pack(">d", math.pi)), bin(s)) def test_endian_other(self): - self.failUnless(c_byte.__ctype_le__ is c_byte) - self.failUnless(c_byte.__ctype_be__ is c_byte) + self.assertTrue(c_byte.__ctype_le__ is c_byte) + self.assertTrue(c_byte.__ctype_be__ is c_byte) - self.failUnless(c_ubyte.__ctype_le__ is c_ubyte) - self.failUnless(c_ubyte.__ctype_be__ is c_ubyte) + self.assertTrue(c_ubyte.__ctype_le__ is c_ubyte) + self.assertTrue(c_ubyte.__ctype_be__ is c_ubyte) - self.failUnless(c_char.__ctype_le__ is c_char) - self.failUnless(c_char.__ctype_be__ is c_char) + self.assertTrue(c_char.__ctype_le__ is c_char) + self.assertTrue(c_char.__ctype_be__ is c_char) def test_struct_fields_1(self): if sys.byteorder == "little": @@ -219,7 +219,7 @@ class Test(unittest.TestCase): s1 = S(0x12, 0x1234, 0x12345678, 3.14) s2 = struct.pack(fmt, 0x12, 0x1234, 0x12345678, 3.14) - self.failUnlessEqual(bin(s1), bin(s2)) + self.assertEqual(bin(s1), bin(s2)) def test_unaligned_nonnative_struct_fields(self): if sys.byteorder == "little": @@ -247,7 +247,7 @@ class Test(unittest.TestCase): s1.i = 0x12345678 s1.d = 3.14 s2 = struct.pack(fmt, 0x12, 0x1234, 0x12345678, 3.14) - self.failUnlessEqual(bin(s1), bin(s2)) + self.assertEqual(bin(s1), bin(s2)) def test_unaligned_native_struct_fields(self): if sys.byteorder == "little": @@ -274,7 +274,7 @@ class Test(unittest.TestCase): s1.i = 0x12345678 s1.d = 3.14 s2 = struct.pack(fmt, 0x12, 0x1234, 0x12345678, 3.14) - self.failUnlessEqual(bin(s1), bin(s2)) + self.assertEqual(bin(s1), bin(s2)) if __name__ == "__main__": unittest.main() diff --git a/Lib/ctypes/test/test_callbacks.py b/Lib/ctypes/test/test_callbacks.py index e3e4be8..b9e6628 100644 --- a/Lib/ctypes/test/test_callbacks.py +++ b/Lib/ctypes/test/test_callbacks.py @@ -17,18 +17,18 @@ class Callbacks(unittest.TestCase): PROTO = self.functype.im_func(typ, typ) result = PROTO(self.callback)(arg) if typ == c_float: - self.failUnlessAlmostEqual(result, arg, places=5) + self.assertAlmostEqual(result, arg, places=5) else: - self.failUnlessEqual(self.got_args, (arg,)) - self.failUnlessEqual(result, arg) + self.assertEqual(self.got_args, (arg,)) + self.assertEqual(result, arg) PROTO = self.functype.im_func(typ, c_byte, typ) result = PROTO(self.callback)(-3, arg) if typ == c_float: - self.failUnlessAlmostEqual(result, arg, places=5) + self.assertAlmostEqual(result, arg, places=5) else: - self.failUnlessEqual(self.got_args, (-3, arg)) - self.failUnlessEqual(result, arg) + self.assertEqual(self.got_args, (-3, arg)) + self.assertEqual(result, arg) ################ @@ -103,7 +103,7 @@ class Callbacks(unittest.TestCase): # ...but this call doesn't leak any more. Where is the refcount? self.check_type(py_object, o) after = grc(o) - self.failUnlessEqual((after, o), (before, o)) + self.assertEqual((after, o), (before, o)) def test_unsupported_restype_1(self): # Only "fundamental" result types are supported for callback @@ -148,7 +148,7 @@ class SampleCallbacksTestCase(unittest.TestCase): result = integrate(0.0, 1.0, CALLBACK(func), 10) diff = abs(result - 1./3.) - self.failUnless(diff < 0.01, "%s not less than 0.01" % diff) + self.assertTrue(diff < 0.01, "%s not less than 0.01" % diff) ################################################################ diff --git a/Lib/ctypes/test/test_cast.py b/Lib/ctypes/test/test_cast.py index 22c6475..906fffc 100644 --- a/Lib/ctypes/test/test_cast.py +++ b/Lib/ctypes/test/test_cast.py @@ -9,15 +9,15 @@ class Test(unittest.TestCase): # casting an array to a pointer works. ptr = cast(array, POINTER(c_int)) - self.failUnlessEqual([ptr[i] for i in range(3)], [42, 17, 2]) + self.assertEqual([ptr[i] for i in range(3)], [42, 17, 2]) if 2*sizeof(c_short) == sizeof(c_int): ptr = cast(array, POINTER(c_short)) if sys.byteorder == "little": - self.failUnlessEqual([ptr[i] for i in range(6)], + self.assertEqual([ptr[i] for i in range(6)], [42, 0, 17, 0, 2, 0]) else: - self.failUnlessEqual([ptr[i] for i in range(6)], + self.assertEqual([ptr[i] for i in range(6)], [0, 42, 0, 17, 0, 2]) def test_address2pointer(self): @@ -25,54 +25,54 @@ class Test(unittest.TestCase): address = addressof(array) ptr = cast(c_void_p(address), POINTER(c_int)) - self.failUnlessEqual([ptr[i] for i in range(3)], [42, 17, 2]) + self.assertEqual([ptr[i] for i in range(3)], [42, 17, 2]) ptr = cast(address, POINTER(c_int)) - self.failUnlessEqual([ptr[i] for i in range(3)], [42, 17, 2]) + self.assertEqual([ptr[i] for i in range(3)], [42, 17, 2]) def test_p2a_objects(self): array = (c_char_p * 5)() - self.failUnlessEqual(array._objects, None) + self.assertEqual(array._objects, None) array[0] = "foo bar" - self.failUnlessEqual(array._objects, {'0': "foo bar"}) + self.assertEqual(array._objects, {'0': "foo bar"}) p = cast(array, POINTER(c_char_p)) # array and p share a common _objects attribute - self.failUnless(p._objects is array._objects) - self.failUnlessEqual(array._objects, {'0': "foo bar", id(array): array}) + self.assertTrue(p._objects is array._objects) + self.assertEqual(array._objects, {'0': "foo bar", id(array): array}) p[0] = "spam spam" - self.failUnlessEqual(p._objects, {'0': "spam spam", id(array): array}) - self.failUnless(array._objects is p._objects) + self.assertEqual(p._objects, {'0': "spam spam", id(array): array}) + self.assertTrue(array._objects is p._objects) p[1] = "foo bar" - self.failUnlessEqual(p._objects, {'1': 'foo bar', '0': "spam spam", id(array): array}) - self.failUnless(array._objects is p._objects) + self.assertEqual(p._objects, {'1': 'foo bar', '0': "spam spam", id(array): array}) + self.assertTrue(array._objects is p._objects) def test_other(self): p = cast((c_int * 4)(1, 2, 3, 4), POINTER(c_int)) - self.failUnlessEqual(p[:4], [1,2, 3, 4]) - self.failUnlessEqual(p[:4:], [1, 2, 3, 4]) - self.failUnlessEqual(p[3:-1:-1], [4, 3, 2, 1]) - self.failUnlessEqual(p[:4:3], [1, 4]) + self.assertEqual(p[:4], [1,2, 3, 4]) + self.assertEqual(p[:4:], [1, 2, 3, 4]) + self.assertEqual(p[3:-1:-1], [4, 3, 2, 1]) + self.assertEqual(p[:4:3], [1, 4]) c_int() - self.failUnlessEqual(p[:4], [1, 2, 3, 4]) - self.failUnlessEqual(p[:4:], [1, 2, 3, 4]) - self.failUnlessEqual(p[3:-1:-1], [4, 3, 2, 1]) - self.failUnlessEqual(p[:4:3], [1, 4]) + self.assertEqual(p[:4], [1, 2, 3, 4]) + self.assertEqual(p[:4:], [1, 2, 3, 4]) + self.assertEqual(p[3:-1:-1], [4, 3, 2, 1]) + self.assertEqual(p[:4:3], [1, 4]) p[2] = 96 - self.failUnlessEqual(p[:4], [1, 2, 96, 4]) - self.failUnlessEqual(p[:4:], [1, 2, 96, 4]) - self.failUnlessEqual(p[3:-1:-1], [4, 96, 2, 1]) - self.failUnlessEqual(p[:4:3], [1, 4]) + self.assertEqual(p[:4], [1, 2, 96, 4]) + self.assertEqual(p[:4:], [1, 2, 96, 4]) + self.assertEqual(p[3:-1:-1], [4, 96, 2, 1]) + self.assertEqual(p[:4:3], [1, 4]) c_int() - self.failUnlessEqual(p[:4], [1, 2, 96, 4]) - self.failUnlessEqual(p[:4:], [1, 2, 96, 4]) - self.failUnlessEqual(p[3:-1:-1], [4, 96, 2, 1]) - self.failUnlessEqual(p[:4:3], [1, 4]) + self.assertEqual(p[:4], [1, 2, 96, 4]) + self.assertEqual(p[:4:], [1, 2, 96, 4]) + self.assertEqual(p[3:-1:-1], [4, 96, 2, 1]) + self.assertEqual(p[:4:3], [1, 4]) def test_char_p(self): # This didn't work: bad argument to internal function s = c_char_p("hiho") - self.failUnlessEqual(cast(cast(s, c_void_p), c_char_p).value, + self.assertEqual(cast(cast(s, c_void_p), c_char_p).value, "hiho") try: @@ -82,7 +82,7 @@ class Test(unittest.TestCase): else: def test_wchar_p(self): s = c_wchar_p("hiho") - self.failUnlessEqual(cast(cast(s, c_void_p), c_wchar_p).value, + self.assertEqual(cast(cast(s, c_void_p), c_wchar_p).value, "hiho") if __name__ == "__main__": diff --git a/Lib/ctypes/test/test_cfuncs.py b/Lib/ctypes/test/test_cfuncs.py index 8f97fc4..493cbe9 100644 --- a/Lib/ctypes/test/test_cfuncs.py +++ b/Lib/ctypes/test/test_cfuncs.py @@ -17,176 +17,176 @@ class CFunctions(unittest.TestCase): def test_byte(self): self._dll.tf_b.restype = c_byte self._dll.tf_b.argtypes = (c_byte,) - self.failUnlessEqual(self._dll.tf_b(-126), -42) - self.failUnlessEqual(self.S(), -126) + self.assertEqual(self._dll.tf_b(-126), -42) + self.assertEqual(self.S(), -126) def test_byte_plus(self): self._dll.tf_bb.restype = c_byte self._dll.tf_bb.argtypes = (c_byte, c_byte) - self.failUnlessEqual(self._dll.tf_bb(0, -126), -42) - self.failUnlessEqual(self.S(), -126) + self.assertEqual(self._dll.tf_bb(0, -126), -42) + self.assertEqual(self.S(), -126) def test_ubyte(self): self._dll.tf_B.restype = c_ubyte self._dll.tf_B.argtypes = (c_ubyte,) - self.failUnlessEqual(self._dll.tf_B(255), 85) - self.failUnlessEqual(self.U(), 255) + self.assertEqual(self._dll.tf_B(255), 85) + self.assertEqual(self.U(), 255) def test_ubyte_plus(self): self._dll.tf_bB.restype = c_ubyte self._dll.tf_bB.argtypes = (c_byte, c_ubyte) - self.failUnlessEqual(self._dll.tf_bB(0, 255), 85) - self.failUnlessEqual(self.U(), 255) + self.assertEqual(self._dll.tf_bB(0, 255), 85) + self.assertEqual(self.U(), 255) def test_short(self): self._dll.tf_h.restype = c_short self._dll.tf_h.argtypes = (c_short,) - self.failUnlessEqual(self._dll.tf_h(-32766), -10922) - self.failUnlessEqual(self.S(), -32766) + self.assertEqual(self._dll.tf_h(-32766), -10922) + self.assertEqual(self.S(), -32766) def test_short_plus(self): self._dll.tf_bh.restype = c_short self._dll.tf_bh.argtypes = (c_byte, c_short) - self.failUnlessEqual(self._dll.tf_bh(0, -32766), -10922) - self.failUnlessEqual(self.S(), -32766) + self.assertEqual(self._dll.tf_bh(0, -32766), -10922) + self.assertEqual(self.S(), -32766) def test_ushort(self): self._dll.tf_H.restype = c_ushort self._dll.tf_H.argtypes = (c_ushort,) - self.failUnlessEqual(self._dll.tf_H(65535), 21845) - self.failUnlessEqual(self.U(), 65535) + self.assertEqual(self._dll.tf_H(65535), 21845) + self.assertEqual(self.U(), 65535) def test_ushort_plus(self): self._dll.tf_bH.restype = c_ushort self._dll.tf_bH.argtypes = (c_byte, c_ushort) - self.failUnlessEqual(self._dll.tf_bH(0, 65535), 21845) - self.failUnlessEqual(self.U(), 65535) + self.assertEqual(self._dll.tf_bH(0, 65535), 21845) + self.assertEqual(self.U(), 65535) def test_int(self): self._dll.tf_i.restype = c_int self._dll.tf_i.argtypes = (c_int,) - self.failUnlessEqual(self._dll.tf_i(-2147483646), -715827882) - self.failUnlessEqual(self.S(), -2147483646) + self.assertEqual(self._dll.tf_i(-2147483646), -715827882) + self.assertEqual(self.S(), -2147483646) def test_int_plus(self): self._dll.tf_bi.restype = c_int self._dll.tf_bi.argtypes = (c_byte, c_int) - self.failUnlessEqual(self._dll.tf_bi(0, -2147483646), -715827882) - self.failUnlessEqual(self.S(), -2147483646) + self.assertEqual(self._dll.tf_bi(0, -2147483646), -715827882) + self.assertEqual(self.S(), -2147483646) def test_uint(self): self._dll.tf_I.restype = c_uint self._dll.tf_I.argtypes = (c_uint,) - self.failUnlessEqual(self._dll.tf_I(4294967295), 1431655765) - self.failUnlessEqual(self.U(), 4294967295) + self.assertEqual(self._dll.tf_I(4294967295), 1431655765) + self.assertEqual(self.U(), 4294967295) def test_uint_plus(self): self._dll.tf_bI.restype = c_uint self._dll.tf_bI.argtypes = (c_byte, c_uint) - self.failUnlessEqual(self._dll.tf_bI(0, 4294967295), 1431655765) - self.failUnlessEqual(self.U(), 4294967295) + self.assertEqual(self._dll.tf_bI(0, 4294967295), 1431655765) + self.assertEqual(self.U(), 4294967295) def test_long(self): self._dll.tf_l.restype = c_long self._dll.tf_l.argtypes = (c_long,) - self.failUnlessEqual(self._dll.tf_l(-2147483646), -715827882) - self.failUnlessEqual(self.S(), -2147483646) + self.assertEqual(self._dll.tf_l(-2147483646), -715827882) + self.assertEqual(self.S(), -2147483646) def test_long_plus(self): self._dll.tf_bl.restype = c_long self._dll.tf_bl.argtypes = (c_byte, c_long) - self.failUnlessEqual(self._dll.tf_bl(0, -2147483646), -715827882) - self.failUnlessEqual(self.S(), -2147483646) + self.assertEqual(self._dll.tf_bl(0, -2147483646), -715827882) + self.assertEqual(self.S(), -2147483646) def test_ulong(self): self._dll.tf_L.restype = c_ulong self._dll.tf_L.argtypes = (c_ulong,) - self.failUnlessEqual(self._dll.tf_L(4294967295), 1431655765) - self.failUnlessEqual(self.U(), 4294967295) + self.assertEqual(self._dll.tf_L(4294967295), 1431655765) + self.assertEqual(self.U(), 4294967295) def test_ulong_plus(self): self._dll.tf_bL.restype = c_ulong self._dll.tf_bL.argtypes = (c_char, c_ulong) - self.failUnlessEqual(self._dll.tf_bL(' ', 4294967295), 1431655765) - self.failUnlessEqual(self.U(), 4294967295) + self.assertEqual(self._dll.tf_bL(' ', 4294967295), 1431655765) + self.assertEqual(self.U(), 4294967295) def test_longlong(self): self._dll.tf_q.restype = c_longlong self._dll.tf_q.argtypes = (c_longlong, ) - self.failUnlessEqual(self._dll.tf_q(-9223372036854775806), -3074457345618258602) - self.failUnlessEqual(self.S(), -9223372036854775806) + self.assertEqual(self._dll.tf_q(-9223372036854775806), -3074457345618258602) + self.assertEqual(self.S(), -9223372036854775806) def test_longlong_plus(self): self._dll.tf_bq.restype = c_longlong self._dll.tf_bq.argtypes = (c_byte, c_longlong) - self.failUnlessEqual(self._dll.tf_bq(0, -9223372036854775806), -3074457345618258602) - self.failUnlessEqual(self.S(), -9223372036854775806) + self.assertEqual(self._dll.tf_bq(0, -9223372036854775806), -3074457345618258602) + self.assertEqual(self.S(), -9223372036854775806) def test_ulonglong(self): self._dll.tf_Q.restype = c_ulonglong self._dll.tf_Q.argtypes = (c_ulonglong, ) - self.failUnlessEqual(self._dll.tf_Q(18446744073709551615), 6148914691236517205) - self.failUnlessEqual(self.U(), 18446744073709551615) + self.assertEqual(self._dll.tf_Q(18446744073709551615), 6148914691236517205) + self.assertEqual(self.U(), 18446744073709551615) def test_ulonglong_plus(self): self._dll.tf_bQ.restype = c_ulonglong self._dll.tf_bQ.argtypes = (c_byte, c_ulonglong) - self.failUnlessEqual(self._dll.tf_bQ(0, 18446744073709551615), 6148914691236517205) - self.failUnlessEqual(self.U(), 18446744073709551615) + self.assertEqual(self._dll.tf_bQ(0, 18446744073709551615), 6148914691236517205) + self.assertEqual(self.U(), 18446744073709551615) def test_float(self): self._dll.tf_f.restype = c_float self._dll.tf_f.argtypes = (c_float,) - self.failUnlessEqual(self._dll.tf_f(-42.), -14.) - self.failUnlessEqual(self.S(), -42) + self.assertEqual(self._dll.tf_f(-42.), -14.) + self.assertEqual(self.S(), -42) def test_float_plus(self): self._dll.tf_bf.restype = c_float self._dll.tf_bf.argtypes = (c_byte, c_float) - self.failUnlessEqual(self._dll.tf_bf(0, -42.), -14.) - self.failUnlessEqual(self.S(), -42) + self.assertEqual(self._dll.tf_bf(0, -42.), -14.) + self.assertEqual(self.S(), -42) def test_double(self): self._dll.tf_d.restype = c_double self._dll.tf_d.argtypes = (c_double,) - self.failUnlessEqual(self._dll.tf_d(42.), 14.) - self.failUnlessEqual(self.S(), 42) + self.assertEqual(self._dll.tf_d(42.), 14.) + self.assertEqual(self.S(), 42) def test_double_plus(self): self._dll.tf_bd.restype = c_double self._dll.tf_bd.argtypes = (c_byte, c_double) - self.failUnlessEqual(self._dll.tf_bd(0, 42.), 14.) - self.failUnlessEqual(self.S(), 42) + self.assertEqual(self._dll.tf_bd(0, 42.), 14.) + self.assertEqual(self.S(), 42) def test_longdouble(self): self._dll.tf_D.restype = c_longdouble self._dll.tf_D.argtypes = (c_longdouble,) - self.failUnlessEqual(self._dll.tf_D(42.), 14.) - self.failUnlessEqual(self.S(), 42) + self.assertEqual(self._dll.tf_D(42.), 14.) + self.assertEqual(self.S(), 42) def test_longdouble_plus(self): self._dll.tf_bD.restype = c_longdouble self._dll.tf_bD.argtypes = (c_byte, c_longdouble) - self.failUnlessEqual(self._dll.tf_bD(0, 42.), 14.) - self.failUnlessEqual(self.S(), 42) + self.assertEqual(self._dll.tf_bD(0, 42.), 14.) + self.assertEqual(self.S(), 42) def test_callwithresult(self): def process_result(result): return result * 2 self._dll.tf_i.restype = process_result self._dll.tf_i.argtypes = (c_int,) - self.failUnlessEqual(self._dll.tf_i(42), 28) - self.failUnlessEqual(self.S(), 42) - self.failUnlessEqual(self._dll.tf_i(-42), -28) - self.failUnlessEqual(self.S(), -42) + self.assertEqual(self._dll.tf_i(42), 28) + self.assertEqual(self.S(), 42) + self.assertEqual(self._dll.tf_i(-42), -28) + self.assertEqual(self.S(), -42) def test_void(self): self._dll.tv_i.restype = None self._dll.tv_i.argtypes = (c_int,) - self.failUnlessEqual(self._dll.tv_i(42), None) - self.failUnlessEqual(self.S(), 42) - self.failUnlessEqual(self._dll.tv_i(-42), None) - self.failUnlessEqual(self.S(), -42) + self.assertEqual(self._dll.tv_i(42), None) + self.assertEqual(self.S(), 42) + self.assertEqual(self._dll.tv_i(-42), None) + self.assertEqual(self.S(), -42) # The following repeates the above tests with stdcall functions (where # they are available) diff --git a/Lib/ctypes/test/test_checkretval.py b/Lib/ctypes/test/test_checkretval.py index d15bd2e..01ccc57 100644 --- a/Lib/ctypes/test/test_checkretval.py +++ b/Lib/ctypes/test/test_checkretval.py @@ -14,16 +14,16 @@ class Test(unittest.TestCase): import _ctypes_test dll = CDLL(_ctypes_test.__file__) - self.failUnlessEqual(42, dll._testfunc_p_p(42)) + self.assertEqual(42, dll._testfunc_p_p(42)) dll._testfunc_p_p.restype = CHECKED - self.failUnlessEqual("42", dll._testfunc_p_p(42)) + self.assertEqual("42", dll._testfunc_p_p(42)) dll._testfunc_p_p.restype = None - self.failUnlessEqual(None, dll._testfunc_p_p(42)) + self.assertEqual(None, dll._testfunc_p_p(42)) del dll._testfunc_p_p.restype - self.failUnlessEqual(42, dll._testfunc_p_p(42)) + self.assertEqual(42, dll._testfunc_p_p(42)) try: oledll @@ -31,7 +31,7 @@ class Test(unittest.TestCase): pass else: def test_oledll(self): - self.failUnlessRaises(WindowsError, + self.assertRaises(WindowsError, oledll.oleaut32.CreateTypeLib2, 0, None, None) diff --git a/Lib/ctypes/test/test_errno.py b/Lib/ctypes/test/test_errno.py index b80656b..0254c3b 100644 --- a/Lib/ctypes/test/test_errno.py +++ b/Lib/ctypes/test/test_errno.py @@ -15,11 +15,11 @@ class Test(unittest.TestCase): libc_open.argtypes = c_char_p, c_int - self.failUnlessEqual(libc_open("", 0), -1) - self.failUnlessEqual(get_errno(), errno.ENOENT) + self.assertEqual(libc_open("", 0), -1) + self.assertEqual(get_errno(), errno.ENOENT) - self.failUnlessEqual(set_errno(32), errno.ENOENT) - self.failUnlessEqual(get_errno(), 32) + self.assertEqual(set_errno(32), errno.ENOENT) + self.assertEqual(get_errno(), 32) def _worker(): @@ -31,14 +31,14 @@ class Test(unittest.TestCase): else: libc_open = libc.open libc_open.argtypes = c_char_p, c_int - self.failUnlessEqual(libc_open("", 0), -1) - self.failUnlessEqual(get_errno(), 0) + self.assertEqual(libc_open("", 0), -1) + self.assertEqual(get_errno(), 0) t = threading.Thread(target=_worker) t.start() t.join() - self.failUnlessEqual(get_errno(), 32) + self.assertEqual(get_errno(), 32) set_errno(0) if os.name == "nt": @@ -48,11 +48,11 @@ class Test(unittest.TestCase): GetModuleHandle = dll.GetModuleHandleA GetModuleHandle.argtypes = [c_wchar_p] - self.failUnlessEqual(0, GetModuleHandle("foo")) - self.failUnlessEqual(get_last_error(), 126) + self.assertEqual(0, GetModuleHandle("foo")) + self.assertEqual(get_last_error(), 126) - self.failUnlessEqual(set_last_error(32), 126) - self.failUnlessEqual(get_last_error(), 32) + self.assertEqual(set_last_error(32), 126) + self.assertEqual(get_last_error(), 32) def _worker(): set_last_error(0) @@ -62,13 +62,13 @@ class Test(unittest.TestCase): GetModuleHandle.argtypes = [c_wchar_p] GetModuleHandle("bar") - self.failUnlessEqual(get_last_error(), 0) + self.assertEqual(get_last_error(), 0) t = threading.Thread(target=_worker) t.start() t.join() - self.failUnlessEqual(get_last_error(), 32) + self.assertEqual(get_last_error(), 32) set_last_error(0) diff --git a/Lib/ctypes/test/test_find.py b/Lib/ctypes/test/test_find.py index ed1297d..77e789f 100644 --- a/Lib/ctypes/test/test_find.py +++ b/Lib/ctypes/test/test_find.py @@ -76,7 +76,7 @@ class Test_OpenGL_libs(unittest.TestCase): ## sqrt = libm.sqrt ## sqrt.argtypes = (c_double,) ## sqrt.restype = c_double -## self.failUnlessEqual(sqrt(2), math.sqrt(2)) +## self.assertEqual(sqrt(2), math.sqrt(2)) if __name__ == "__main__": unittest.main() diff --git a/Lib/ctypes/test/test_frombuffer.py b/Lib/ctypes/test/test_frombuffer.py index 4285e40..624fb70 100644 --- a/Lib/ctypes/test/test_frombuffer.py +++ b/Lib/ctypes/test/test_frombuffer.py @@ -16,14 +16,14 @@ class Test(unittest.TestCase): y = X.from_buffer(a) self.assertEqual(y.c_int, a[0]) - self.failIf(y.init_called) + self.assertFalse(y.init_called) self.assertEqual(x[:], a.tolist()) a[0], a[-1] = 200, -200 self.assertEqual(x[:], a.tolist()) - self.assert_(a in x._objects.values()) + self.assertTrue(a in x._objects.values()) self.assertRaises(ValueError, c_int.from_buffer, a, -1) @@ -49,7 +49,7 @@ class Test(unittest.TestCase): y = X.from_buffer_copy(a) self.assertEqual(y.c_int, a[0]) - self.failIf(y.init_called) + self.assertFalse(y.init_called) self.assertEqual(x[:], range(16)) diff --git a/Lib/ctypes/test/test_funcptr.py b/Lib/ctypes/test/test_funcptr.py index 7ea873f..99af5ed 100644 --- a/Lib/ctypes/test/test_funcptr.py +++ b/Lib/ctypes/test/test_funcptr.py @@ -18,10 +18,10 @@ class CFuncPtrTestCase(unittest.TestCase): return len(args) x = X(func) - self.failUnlessEqual(x.restype, c_int) - self.failUnlessEqual(x.argtypes, (c_int, c_int)) - self.failUnlessEqual(sizeof(x), sizeof(c_voidp)) - self.failUnlessEqual(sizeof(X), sizeof(c_voidp)) + self.assertEqual(x.restype, c_int) + self.assertEqual(x.argtypes, (c_int, c_int)) + self.assertEqual(sizeof(x), sizeof(c_voidp)) + self.assertEqual(sizeof(X), sizeof(c_voidp)) def test_first(self): StdCallback = WINFUNCTYPE(c_int, c_int, c_int) @@ -33,12 +33,12 @@ class CFuncPtrTestCase(unittest.TestCase): s = StdCallback(func) c = CdeclCallback(func) - self.failUnlessEqual(s(1, 2), 3) - self.failUnlessEqual(c(1, 2), 3) + self.assertEqual(s(1, 2), 3) + self.assertEqual(c(1, 2), 3) # The following no longer raises a TypeError - it is now # possible, as in C, to call cdecl functions with more parameters. #self.assertRaises(TypeError, c, 1, 2, 3) - self.failUnlessEqual(c(1, 2, 3, 4, 5, 6), 3) + self.assertEqual(c(1, 2, 3, 4, 5, 6), 3) if not WINFUNCTYPE is CFUNCTYPE and os.name != "ce": self.assertRaises(TypeError, s, 1, 2, 3) @@ -75,9 +75,9 @@ class CFuncPtrTestCase(unittest.TestCase): ## "lpfnWndProc", WNDPROC_2(wndproc)) # instead: - self.failUnless(WNDPROC is WNDPROC_2) + self.assertTrue(WNDPROC is WNDPROC_2) # 'wndclass.lpfnWndProc' leaks 94 references. Why? - self.failUnlessEqual(wndclass.lpfnWndProc(1, 2, 3, 4), 10) + self.assertEqual(wndclass.lpfnWndProc(1, 2, 3, 4), 10) f = wndclass.lpfnWndProc @@ -85,7 +85,7 @@ class CFuncPtrTestCase(unittest.TestCase): del wndclass del wndproc - self.failUnlessEqual(f(10, 11, 12, 13), 46) + self.assertEqual(f(10, 11, 12, 13), 46) def test_dllfunctions(self): @@ -97,8 +97,8 @@ class CFuncPtrTestCase(unittest.TestCase): strchr = lib.my_strchr strchr.restype = c_char_p strchr.argtypes = (c_char_p, c_char) - self.failUnlessEqual(strchr("abcdefghi", "b"), "bcdefghi") - self.failUnlessEqual(strchr("abcdefghi", "x"), None) + self.assertEqual(strchr("abcdefghi", "b"), "bcdefghi") + self.assertEqual(strchr("abcdefghi", "x"), None) strtok = lib.my_strtok @@ -118,10 +118,10 @@ class CFuncPtrTestCase(unittest.TestCase): ## b.value = s ## b = c_string(s) - self.failUnlessEqual(strtok(b, "\n"), "a") - self.failUnlessEqual(strtok(None, "\n"), "b") - self.failUnlessEqual(strtok(None, "\n"), "c") - self.failUnlessEqual(strtok(None, "\n"), None) + self.assertEqual(strtok(b, "\n"), "a") + self.assertEqual(strtok(None, "\n"), "b") + self.assertEqual(strtok(None, "\n"), "c") + self.assertEqual(strtok(None, "\n"), None) if __name__ == '__main__': unittest.main() diff --git a/Lib/ctypes/test/test_functions.py b/Lib/ctypes/test/test_functions.py index 93d895b..4534815 100644 --- a/Lib/ctypes/test/test_functions.py +++ b/Lib/ctypes/test/test_functions.py @@ -71,8 +71,8 @@ class FunctionTestCase(unittest.TestCase): f = dll._testfunc_i_bhilfd f.argtypes = [c_byte, c_wchar, c_int, c_long, c_float, c_double] result = f(1, u"x", 3, 4, 5.0, 6.0) - self.failUnlessEqual(result, 139) - self.failUnlessEqual(type(result), int) + self.assertEqual(result, 139) + self.assertEqual(type(result), int) def test_wchar_result(self): try: @@ -83,38 +83,38 @@ class FunctionTestCase(unittest.TestCase): f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] f.restype = c_wchar result = f(0, 0, 0, 0, 0, 0) - self.failUnlessEqual(result, u'\x00') + self.assertEqual(result, u'\x00') def test_voidresult(self): f = dll._testfunc_v f.restype = None f.argtypes = [c_int, c_int, POINTER(c_int)] result = c_int() - self.failUnlessEqual(None, f(1, 2, byref(result))) - self.failUnlessEqual(result.value, 3) + self.assertEqual(None, f(1, 2, byref(result))) + self.assertEqual(result.value, 3) def test_intresult(self): f = dll._testfunc_i_bhilfd f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] f.restype = c_int result = f(1, 2, 3, 4, 5.0, 6.0) - self.failUnlessEqual(result, 21) - self.failUnlessEqual(type(result), int) + self.assertEqual(result, 21) + self.assertEqual(type(result), int) result = f(-1, -2, -3, -4, -5.0, -6.0) - self.failUnlessEqual(result, -21) - self.failUnlessEqual(type(result), int) + self.assertEqual(result, -21) + self.assertEqual(type(result), int) # If we declare the function to return a short, # is the high part split off? f.restype = c_short result = f(1, 2, 3, 4, 5.0, 6.0) - self.failUnlessEqual(result, 21) - self.failUnlessEqual(type(result), int) + self.assertEqual(result, 21) + self.assertEqual(type(result), int) result = f(1, 2, 3, 0x10004, 5.0, 6.0) - self.failUnlessEqual(result, 21) - self.failUnlessEqual(type(result), int) + self.assertEqual(result, 21) + self.assertEqual(type(result), int) # You cannot assing character format codes as restype any longer self.assertRaises(TypeError, setattr, f, "restype", "i") @@ -124,36 +124,36 @@ class FunctionTestCase(unittest.TestCase): f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] f.restype = c_float result = f(1, 2, 3, 4, 5.0, 6.0) - self.failUnlessEqual(result, 21) - self.failUnlessEqual(type(result), float) + self.assertEqual(result, 21) + self.assertEqual(type(result), float) result = f(-1, -2, -3, -4, -5.0, -6.0) - self.failUnlessEqual(result, -21) - self.failUnlessEqual(type(result), float) + self.assertEqual(result, -21) + self.assertEqual(type(result), float) def test_doubleresult(self): f = dll._testfunc_d_bhilfd f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] f.restype = c_double result = f(1, 2, 3, 4, 5.0, 6.0) - self.failUnlessEqual(result, 21) - self.failUnlessEqual(type(result), float) + self.assertEqual(result, 21) + self.assertEqual(type(result), float) result = f(-1, -2, -3, -4, -5.0, -6.0) - self.failUnlessEqual(result, -21) - self.failUnlessEqual(type(result), float) + self.assertEqual(result, -21) + self.assertEqual(type(result), float) def test_longdoubleresult(self): f = dll._testfunc_D_bhilfD f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_longdouble] f.restype = c_longdouble result = f(1, 2, 3, 4, 5.0, 6.0) - self.failUnlessEqual(result, 21) - self.failUnlessEqual(type(result), float) + self.assertEqual(result, 21) + self.assertEqual(type(result), float) result = f(-1, -2, -3, -4, -5.0, -6.0) - self.failUnlessEqual(result, -21) - self.failUnlessEqual(type(result), float) + self.assertEqual(result, -21) + self.assertEqual(type(result), float) def test_longlongresult(self): try: @@ -164,23 +164,23 @@ class FunctionTestCase(unittest.TestCase): f.restype = c_longlong f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] result = f(1, 2, 3, 4, 5.0, 6.0) - self.failUnlessEqual(result, 21) + self.assertEqual(result, 21) f = dll._testfunc_q_bhilfdq f.restype = c_longlong f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double, c_longlong] result = f(1, 2, 3, 4, 5.0, 6.0, 21) - self.failUnlessEqual(result, 42) + self.assertEqual(result, 42) def test_stringresult(self): f = dll._testfunc_p_p f.argtypes = None f.restype = c_char_p result = f("123") - self.failUnlessEqual(result, "123") + self.assertEqual(result, "123") result = f(None) - self.failUnlessEqual(result, None) + self.assertEqual(result, None) def test_pointers(self): f = dll._testfunc_p_p @@ -193,29 +193,29 @@ class FunctionTestCase(unittest.TestCase): v = c_int(42) - self.failUnlessEqual(pointer(v).contents.value, 42) + self.assertEqual(pointer(v).contents.value, 42) result = f(pointer(v)) - self.failUnlessEqual(type(result), POINTER(c_int)) - self.failUnlessEqual(result.contents.value, 42) + self.assertEqual(type(result), POINTER(c_int)) + self.assertEqual(result.contents.value, 42) # This on works... result = f(pointer(v)) - self.failUnlessEqual(result.contents.value, v.value) + self.assertEqual(result.contents.value, v.value) p = pointer(c_int(99)) result = f(p) - self.failUnlessEqual(result.contents.value, 99) + self.assertEqual(result.contents.value, 99) arg = byref(v) result = f(arg) - self.failIfEqual(result.contents, v.value) + self.assertNotEqual(result.contents, v.value) self.assertRaises(ArgumentError, f, byref(c_short(22))) # It is dangerous, however, because you don't control the lifetime # of the pointer: result = f(byref(c_int(99))) - self.failIfEqual(result.contents, 99) + self.assertNotEqual(result.contents, 99) def test_errors(self): f = dll._testfunc_p_p @@ -242,7 +242,7 @@ class FunctionTestCase(unittest.TestCase): cb = CallBack(callback) f(2**18, cb) - self.failUnlessEqual(args, expected) + self.assertEqual(args, expected) ################################################################ @@ -259,13 +259,13 @@ class FunctionTestCase(unittest.TestCase): cb = MyCallback(callback) result = f(-10, cb) - self.failUnlessEqual(result, -18) + self.assertEqual(result, -18) # test with prototype f.argtypes = [c_int, MyCallback] cb = MyCallback(callback) result = f(-10, cb) - self.failUnlessEqual(result, -18) + self.assertEqual(result, -18) AnotherCallback = WINFUNCTYPE(c_int, c_int, c_int, c_int, c_int) @@ -288,12 +288,12 @@ class FunctionTestCase(unittest.TestCase): def callback(value): #print "called back with", value - self.failUnlessEqual(type(value), int) + self.assertEqual(type(value), int) return value cb = MyCallback(callback) result = f(-10, cb) - self.failUnlessEqual(result, -18) + self.assertEqual(result, -18) def test_longlong_callbacks(self): @@ -305,12 +305,12 @@ class FunctionTestCase(unittest.TestCase): f.argtypes = [c_longlong, MyCallback] def callback(value): - self.failUnless(isinstance(value, (int, long))) + self.assertTrue(isinstance(value, (int, long))) return value & 0x7FFFFFFF cb = MyCallback(callback) - self.failUnlessEqual(13577625587, f(1000000000000, cb)) + self.assertEqual(13577625587, f(1000000000000, cb)) def test_errors(self): self.assertRaises(AttributeError, getattr, dll, "_xxx_yyy") @@ -325,7 +325,7 @@ class FunctionTestCase(unittest.TestCase): result = dll._testfunc_byval(ptin, byref(ptout)) got = result, ptout.x, ptout.y expected = 3, 1, 2 - self.failUnlessEqual(got, expected) + self.assertEqual(got, expected) # with prototype ptin = POINT(101, 102) @@ -335,7 +335,7 @@ class FunctionTestCase(unittest.TestCase): result = dll._testfunc_byval(ptin, byref(ptout)) got = result, ptout.x, ptout.y expected = 203, 101, 102 - self.failUnlessEqual(got, expected) + self.assertEqual(got, expected) def test_struct_return_2H(self): class S2H(Structure): @@ -345,7 +345,7 @@ class FunctionTestCase(unittest.TestCase): dll.ret_2h_func.argtypes = [S2H] inp = S2H(99, 88) s2h = dll.ret_2h_func(inp) - self.failUnlessEqual((s2h.x, s2h.y), (99*2, 88*3)) + self.assertEqual((s2h.x, s2h.y), (99*2, 88*3)) if sys.platform == "win32": def test_struct_return_2H_stdcall(self): @@ -356,7 +356,7 @@ class FunctionTestCase(unittest.TestCase): windll.s_ret_2h_func.restype = S2H windll.s_ret_2h_func.argtypes = [S2H] s2h = windll.s_ret_2h_func(S2H(99, 88)) - self.failUnlessEqual((s2h.x, s2h.y), (99*2, 88*3)) + self.assertEqual((s2h.x, s2h.y), (99*2, 88*3)) def test_struct_return_8H(self): class S8I(Structure): @@ -372,7 +372,7 @@ class FunctionTestCase(unittest.TestCase): dll.ret_8i_func.argtypes = [S8I] inp = S8I(9, 8, 7, 6, 5, 4, 3, 2) s8i = dll.ret_8i_func(inp) - self.failUnlessEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h), + self.assertEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h), (9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9)) if sys.platform == "win32": @@ -390,7 +390,7 @@ class FunctionTestCase(unittest.TestCase): windll.s_ret_8i_func.argtypes = [S8I] inp = S8I(9, 8, 7, 6, 5, 4, 3, 2) s8i = windll.s_ret_8i_func(inp) - self.failUnlessEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h), + self.assertEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h), (9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9)) def test_sf1651235(self): @@ -401,7 +401,7 @@ class FunctionTestCase(unittest.TestCase): return 0 callback = proto(callback) - self.failUnlessRaises(ArgumentError, lambda: callback((1, 2, 3, 4), POINT())) + self.assertRaises(ArgumentError, lambda: callback((1, 2, 3, 4), POINT())) if __name__ == '__main__': unittest.main() diff --git a/Lib/ctypes/test/test_incomplete.py b/Lib/ctypes/test/test_incomplete.py index af9f504..1e03e9f 100644 --- a/Lib/ctypes/test/test_incomplete.py +++ b/Lib/ctypes/test/test_incomplete.py @@ -30,7 +30,7 @@ class MyTestCase(unittest.TestCase): for i in range(8): result.append(p.name) p = p.next[0] - self.failUnlessEqual(result, ["foo", "bar"] * 4) + self.assertEqual(result, ["foo", "bar"] * 4) # to not leak references, we must clean _pointer_type_cache from ctypes import _pointer_type_cache diff --git a/Lib/ctypes/test/test_init.py b/Lib/ctypes/test/test_init.py index 3d9dc92..953a145 100644 --- a/Lib/ctypes/test/test_init.py +++ b/Lib/ctypes/test/test_init.py @@ -24,17 +24,17 @@ class InitTest(unittest.TestCase): # make sure the only accessing a nested structure # doesn't call the structure's __new__ and __init__ y = Y() - self.failUnlessEqual((y.x.a, y.x.b), (0, 0)) - self.failUnlessEqual(y.x.new_was_called, False) + self.assertEqual((y.x.a, y.x.b), (0, 0)) + self.assertEqual(y.x.new_was_called, False) # But explicitely creating an X structure calls __new__ and __init__, of course. x = X() - self.failUnlessEqual((x.a, x.b), (9, 12)) - self.failUnlessEqual(x.new_was_called, True) + self.assertEqual((x.a, x.b), (9, 12)) + self.assertEqual(x.new_was_called, True) y.x = x - self.failUnlessEqual((y.x.a, y.x.b), (9, 12)) - self.failUnlessEqual(y.x.new_was_called, False) + self.assertEqual((y.x.a, y.x.b), (9, 12)) + self.assertEqual(y.x.new_was_called, False) if __name__ == "__main__": unittest.main() diff --git a/Lib/ctypes/test/test_internals.py b/Lib/ctypes/test/test_internals.py index 04b2040..070da46 100644 --- a/Lib/ctypes/test/test_internals.py +++ b/Lib/ctypes/test/test_internals.py @@ -18,22 +18,22 @@ What about pointers? """ class ObjectsTestCase(unittest.TestCase): - def failUnlessSame(self, a, b): - self.failUnlessEqual(id(a), id(b)) + def assertTrueSame(self, a, b): + self.assertEqual(id(a), id(b)) def test_ints(self): i = 42000123 - self.failUnlessEqual(3, grc(i)) + self.assertEqual(3, grc(i)) ci = c_int(i) - self.failUnlessEqual(3, grc(i)) - self.failUnlessEqual(ci._objects, None) + self.assertEqual(3, grc(i)) + self.assertEqual(ci._objects, None) def test_c_char_p(self): s = "Hello, World" - self.failUnlessEqual(3, grc(s)) + self.assertEqual(3, grc(s)) cs = c_char_p(s) - self.failUnlessEqual(4, grc(s)) - self.failUnlessSame(cs._objects, s) + self.assertEqual(4, grc(s)) + self.assertTrueSame(cs._objects, s) def test_simple_struct(self): class X(Structure): @@ -42,10 +42,10 @@ class ObjectsTestCase(unittest.TestCase): a = 421234 b = 421235 x = X() - self.failUnlessEqual(x._objects, None) + self.assertEqual(x._objects, None) x.a = a x.b = b - self.failUnlessEqual(x._objects, None) + self.assertEqual(x._objects, None) def test_embedded_structs(self): class X(Structure): @@ -55,13 +55,13 @@ class ObjectsTestCase(unittest.TestCase): _fields_ = [("x", X), ("y", X)] y = Y() - self.failUnlessEqual(y._objects, None) + self.assertEqual(y._objects, None) x1, x2 = X(), X() y.x, y.y = x1, x2 - self.failUnlessEqual(y._objects, {"0": {}, "1": {}}) + self.assertEqual(y._objects, {"0": {}, "1": {}}) x1.a, x2.b = 42, 93 - self.failUnlessEqual(y._objects, {"0": {}, "1": {}}) + self.assertEqual(y._objects, {"0": {}, "1": {}}) def test_xxx(self): class X(Structure): @@ -76,11 +76,11 @@ class ObjectsTestCase(unittest.TestCase): x = X() x.a = s1 x.b = s2 - self.failUnlessEqual(x._objects, {"0": s1, "1": s2}) + self.assertEqual(x._objects, {"0": s1, "1": s2}) y = Y() y.x = x - self.failUnlessEqual(y._objects, {"0": {"0": s1, "1": s2}}) + self.assertEqual(y._objects, {"0": {"0": s1, "1": s2}}) ## x = y.x ## del y ## print x._b_base_._objects @@ -91,7 +91,7 @@ class ObjectsTestCase(unittest.TestCase): A = c_int*4 a = A(11, 22, 33, 44) - self.failUnlessEqual(a._objects, None) + self.assertEqual(a._objects, None) x = X() x.data = a diff --git a/Lib/ctypes/test/test_keeprefs.py b/Lib/ctypes/test/test_keeprefs.py index 80b6ca2..0955e76 100644 --- a/Lib/ctypes/test/test_keeprefs.py +++ b/Lib/ctypes/test/test_keeprefs.py @@ -91,7 +91,7 @@ class PointerTestCase(unittest.TestCase): def test_p_cint(self): i = c_int(42) x = pointer(i) - self.failUnlessEqual(x._objects, {'1': i}) + self.assertEqual(x._objects, {'1': i}) class DeletePointerTestCase(unittest.TestCase): def X_test(self): diff --git a/Lib/ctypes/test/test_libc.py b/Lib/ctypes/test/test_libc.py index 8d59f90..3dc463f 100644 --- a/Lib/ctypes/test/test_libc.py +++ b/Lib/ctypes/test/test_libc.py @@ -9,9 +9,9 @@ class LibTest(unittest.TestCase): def test_sqrt(self): lib.my_sqrt.argtypes = c_double, lib.my_sqrt.restype = c_double - self.failUnlessEqual(lib.my_sqrt(4.0), 2.0) + self.assertEqual(lib.my_sqrt(4.0), 2.0) import math - self.failUnlessEqual(lib.my_sqrt(2.0), math.sqrt(2.0)) + self.assertEqual(lib.my_sqrt(2.0), math.sqrt(2.0)) def test_qsort(self): comparefunc = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_char)) @@ -23,7 +23,7 @@ class LibTest(unittest.TestCase): chars = create_string_buffer("spam, spam, and spam") lib.my_qsort(chars, len(chars)-1, sizeof(c_char), comparefunc(sort)) - self.failUnlessEqual(chars.raw, " ,,aaaadmmmnpppsss\x00") + self.assertEqual(chars.raw, " ,,aaaadmmmnpppsss\x00") if __name__ == "__main__": unittest.main() diff --git a/Lib/ctypes/test/test_loading.py b/Lib/ctypes/test/test_loading.py index 712b650..26683d8 100644 --- a/Lib/ctypes/test/test_loading.py +++ b/Lib/ctypes/test/test_loading.py @@ -43,7 +43,7 @@ class LoaderTest(unittest.TestCase): if os.name in ("nt", "ce"): def test_load_library(self): - self.failIf(libc_name is None) + self.assertFalse(libc_name is None) if is_resource_enabled("printing"): print find_library("kernel32") print find_library("user32") @@ -70,9 +70,9 @@ class LoaderTest(unittest.TestCase): a_name = addressof(func_name) f_ord_addr = c_void_p.from_address(a_ord).value f_name_addr = c_void_p.from_address(a_name).value - self.failUnlessEqual(hex(f_ord_addr), hex(f_name_addr)) + self.assertEqual(hex(f_ord_addr), hex(f_name_addr)) - self.failUnlessRaises(AttributeError, dll.__getitem__, 1234) + self.assertRaises(AttributeError, dll.__getitem__, 1234) if os.name == "nt": def test_1703286_A(self): @@ -94,13 +94,13 @@ class LoaderTest(unittest.TestCase): advapi32 = windll.advapi32 # Calling CloseEventLog with a NULL argument should fail, # but the call should not segfault or so. - self.failUnlessEqual(0, advapi32.CloseEventLog(None)) + self.assertEqual(0, advapi32.CloseEventLog(None)) windll.kernel32.GetProcAddress.argtypes = c_void_p, c_char_p windll.kernel32.GetProcAddress.restype = c_void_p proc = windll.kernel32.GetProcAddress(advapi32._handle, "CloseEventLog") - self.failUnless(proc) + self.assertTrue(proc) # This is the real test: call the function via 'call_function' - self.failUnlessEqual(0, call_function(proc, (None,))) + self.assertEqual(0, call_function(proc, (None,))) if __name__ == "__main__": unittest.main() diff --git a/Lib/ctypes/test/test_macholib.py b/Lib/ctypes/test/test_macholib.py index f2ee035..eda846d 100644 --- a/Lib/ctypes/test/test_macholib.py +++ b/Lib/ctypes/test/test_macholib.py @@ -48,14 +48,14 @@ class MachOTest(unittest.TestCase): if sys.platform == "darwin": def test_find(self): - self.failUnlessEqual(find_lib('pthread'), + self.assertEqual(find_lib('pthread'), '/usr/lib/libSystem.B.dylib') result = find_lib('z') - self.failUnless(result.startswith('/usr/lib/libz.1')) - self.failUnless(result.endswith('.dylib')) + self.assertTrue(result.startswith('/usr/lib/libz.1')) + self.assertTrue(result.endswith('.dylib')) - self.failUnlessEqual(find_lib('IOKit'), + self.assertEqual(find_lib('IOKit'), '/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit') if __name__ == "__main__": diff --git a/Lib/ctypes/test/test_memfunctions.py b/Lib/ctypes/test/test_memfunctions.py index cb9099d..d072603 100644 --- a/Lib/ctypes/test/test_memfunctions.py +++ b/Lib/ctypes/test/test_memfunctions.py @@ -19,45 +19,45 @@ class MemFunctionsTest(unittest.TestCase): a = create_string_buffer(1000000) p = "Hello, World" result = memmove(a, p, len(p)) - self.failUnlessEqual(a.value, "Hello, World") + self.assertEqual(a.value, "Hello, World") - self.failUnlessEqual(string_at(result), "Hello, World") - self.failUnlessEqual(string_at(result, 5), "Hello") - self.failUnlessEqual(string_at(result, 16), "Hello, World\0\0\0\0") - self.failUnlessEqual(string_at(result, 0), "") + self.assertEqual(string_at(result), "Hello, World") + self.assertEqual(string_at(result, 5), "Hello") + self.assertEqual(string_at(result, 16), "Hello, World\0\0\0\0") + self.assertEqual(string_at(result, 0), "") def test_memset(self): a = create_string_buffer(1000000) result = memset(a, ord('x'), 16) - self.failUnlessEqual(a.value, "xxxxxxxxxxxxxxxx") + self.assertEqual(a.value, "xxxxxxxxxxxxxxxx") - self.failUnlessEqual(string_at(result), "xxxxxxxxxxxxxxxx") - self.failUnlessEqual(string_at(a), "xxxxxxxxxxxxxxxx") - self.failUnlessEqual(string_at(a, 20), "xxxxxxxxxxxxxxxx\0\0\0\0") + self.assertEqual(string_at(result), "xxxxxxxxxxxxxxxx") + self.assertEqual(string_at(a), "xxxxxxxxxxxxxxxx") + self.assertEqual(string_at(a, 20), "xxxxxxxxxxxxxxxx\0\0\0\0") def test_cast(self): a = (c_ubyte * 32)(*map(ord, "abcdef")) - self.failUnlessEqual(cast(a, c_char_p).value, "abcdef") - self.failUnlessEqual(cast(a, POINTER(c_byte))[:7], + self.assertEqual(cast(a, c_char_p).value, "abcdef") + self.assertEqual(cast(a, POINTER(c_byte))[:7], [97, 98, 99, 100, 101, 102, 0]) - self.failUnlessEqual(cast(a, POINTER(c_byte))[:7:], + self.assertEqual(cast(a, POINTER(c_byte))[:7:], [97, 98, 99, 100, 101, 102, 0]) - self.failUnlessEqual(cast(a, POINTER(c_byte))[6:-1:-1], + self.assertEqual(cast(a, POINTER(c_byte))[6:-1:-1], [0, 102, 101, 100, 99, 98, 97]) - self.failUnlessEqual(cast(a, POINTER(c_byte))[:7:2], + self.assertEqual(cast(a, POINTER(c_byte))[:7:2], [97, 99, 101, 0]) - self.failUnlessEqual(cast(a, POINTER(c_byte))[:7:7], + self.assertEqual(cast(a, POINTER(c_byte))[:7:7], [97]) def test_string_at(self): s = string_at("foo bar") # XXX The following may be wrong, depending on how Python # manages string instances - self.failUnlessEqual(2, sys.getrefcount(s)) - self.failUnless(s, "foo bar") + self.assertEqual(2, sys.getrefcount(s)) + self.assertTrue(s, "foo bar") - self.failUnlessEqual(string_at("foo bar", 8), "foo bar\0") - self.failUnlessEqual(string_at("foo bar", 3), "foo") + self.assertEqual(string_at("foo bar", 8), "foo bar\0") + self.assertEqual(string_at("foo bar", 3), "foo") try: create_unicode_buffer @@ -68,12 +68,12 @@ class MemFunctionsTest(unittest.TestCase): p = create_unicode_buffer("Hello, World") a = create_unicode_buffer(1000000) result = memmove(a, p, len(p) * sizeof(c_wchar)) - self.failUnlessEqual(a.value, "Hello, World") + self.assertEqual(a.value, "Hello, World") - self.failUnlessEqual(wstring_at(a), "Hello, World") - self.failUnlessEqual(wstring_at(a, 5), "Hello") - self.failUnlessEqual(wstring_at(a, 16), "Hello, World\0\0\0\0") - self.failUnlessEqual(wstring_at(a, 0), "") + self.assertEqual(wstring_at(a), "Hello, World") + self.assertEqual(wstring_at(a, 5), "Hello") + self.assertEqual(wstring_at(a, 16), "Hello, World\0\0\0\0") + self.assertEqual(wstring_at(a, 0), "") if __name__ == "__main__": unittest.main() diff --git a/Lib/ctypes/test/test_numbers.py b/Lib/ctypes/test/test_numbers.py index dfd84ee..b5185bf 100644 --- a/Lib/ctypes/test/test_numbers.py +++ b/Lib/ctypes/test/test_numbers.py @@ -55,25 +55,25 @@ class NumberTestCase(unittest.TestCase): def test_default_init(self): # default values are set to zero for t in signed_types + unsigned_types + float_types: - self.failUnlessEqual(t().value, 0) + self.assertEqual(t().value, 0) def test_unsigned_values(self): # the value given to the constructor is available # as the 'value' attribute for t, (l, h) in zip(unsigned_types, unsigned_ranges): - self.failUnlessEqual(t(l).value, l) - self.failUnlessEqual(t(h).value, h) + self.assertEqual(t(l).value, l) + self.assertEqual(t(h).value, h) def test_signed_values(self): # see above for t, (l, h) in zip(signed_types, signed_ranges): - self.failUnlessEqual(t(l).value, l) - self.failUnlessEqual(t(h).value, h) + self.assertEqual(t(l).value, l) + self.assertEqual(t(h).value, h) def test_bool_values(self): from operator import truth for t, v in zip(bool_types, bool_values): - self.failUnlessEqual(t(v).value, truth(v)) + self.assertEqual(t(v).value, truth(v)) def test_typeerror(self): # Only numbers are allowed in the contructor, @@ -93,13 +93,13 @@ class NumberTestCase(unittest.TestCase): # the from_param class method attribute always # returns PyCArgObject instances for t in signed_types + unsigned_types + float_types: - self.failUnlessEqual(ArgType, type(t.from_param(0))) + self.assertEqual(ArgType, type(t.from_param(0))) def test_byref(self): # calling byref returns also a PyCArgObject instance for t in signed_types + unsigned_types + float_types + bool_types: parm = byref(t()) - self.failUnlessEqual(ArgType, type(parm)) + self.assertEqual(ArgType, type(parm)) def test_floats(self): @@ -110,10 +110,10 @@ class NumberTestCase(unittest.TestCase): return 2.0 f = FloatLike() for t in float_types: - self.failUnlessEqual(t(2.0).value, 2.0) - self.failUnlessEqual(t(2).value, 2.0) - self.failUnlessEqual(t(2L).value, 2.0) - self.failUnlessEqual(t(f).value, 2.0) + self.assertEqual(t(2.0).value, 2.0) + self.assertEqual(t(2).value, 2.0) + self.assertEqual(t(2L).value, 2.0) + self.assertEqual(t(f).value, 2.0) def test_integers(self): class FloatLike(object): @@ -129,7 +129,7 @@ class NumberTestCase(unittest.TestCase): for t in signed_types + unsigned_types: self.assertRaises(TypeError, t, 3.14) self.assertRaises(TypeError, t, f) - self.failUnlessEqual(t(i).value, 2) + self.assertEqual(t(i).value, 2) def test_sizes(self): for t in signed_types + unsigned_types + float_types + bool_types: @@ -138,9 +138,9 @@ class NumberTestCase(unittest.TestCase): except struct.error: continue # sizeof of the type... - self.failUnlessEqual(sizeof(t), size) + self.assertEqual(sizeof(t), size) # and sizeof of an instance - self.failUnlessEqual(sizeof(t()), size) + self.assertEqual(sizeof(t()), size) def test_alignments(self): for t in signed_types + unsigned_types + float_types: @@ -148,10 +148,10 @@ class NumberTestCase(unittest.TestCase): align = struct.calcsize("c%c" % code) - struct.calcsize(code) # alignment of the type... - self.failUnlessEqual((code, alignment(t)), + self.assertEqual((code, alignment(t)), (code, align)) # and alignment of an instance - self.failUnlessEqual((code, alignment(t())), + self.assertEqual((code, alignment(t())), (code, align)) def test_int_from_address(self): @@ -167,12 +167,12 @@ class NumberTestCase(unittest.TestCase): # v now is an integer at an 'external' memory location v = t.from_address(a.buffer_info()[0]) - self.failUnlessEqual(v.value, a[0]) - self.failUnlessEqual(type(v), t) + self.assertEqual(v.value, a[0]) + self.assertEqual(type(v), t) # changing the value at the memory location changes v's value also a[0] = 42 - self.failUnlessEqual(v.value, a[0]) + self.assertEqual(v.value, a[0]) def test_float_from_address(self): @@ -180,11 +180,11 @@ class NumberTestCase(unittest.TestCase): for t in float_types: a = array(t._type_, [3.14]) v = t.from_address(a.buffer_info()[0]) - self.failUnlessEqual(v.value, a[0]) - self.failUnless(type(v) is t) + self.assertEqual(v.value, a[0]) + self.assertTrue(type(v) is t) a[0] = 2.3456e17 - self.failUnlessEqual(v.value, a[0]) - self.failUnless(type(v) is t) + self.assertEqual(v.value, a[0]) + self.assertTrue(type(v) is t) def test_char_from_address(self): from ctypes import c_char @@ -192,11 +192,11 @@ class NumberTestCase(unittest.TestCase): a = array('c', 'x') v = c_char.from_address(a.buffer_info()[0]) - self.failUnlessEqual(v.value, a[0]) - self.failUnless(type(v) is c_char) + self.assertEqual(v.value, a[0]) + self.assertTrue(type(v) is c_char) a[0] = '?' - self.failUnlessEqual(v.value, a[0]) + self.assertEqual(v.value, a[0]) # array does not support c_bool / 't' # def test_bool_from_address(self): @@ -204,11 +204,11 @@ class NumberTestCase(unittest.TestCase): # from array import array # a = array(c_bool._type_, [True]) # v = t.from_address(a.buffer_info()[0]) - # self.failUnlessEqual(v.value, a[0]) - # self.failUnlessEqual(type(v) is t) + # self.assertEqual(v.value, a[0]) + # self.assertEqual(type(v) is t) # a[0] = False - # self.failUnlessEqual(v.value, a[0]) - # self.failUnlessEqual(type(v) is t) + # self.assertEqual(v.value, a[0]) + # self.assertEqual(type(v) is t) def test_init(self): # c_int() can be initialized from Python's int, and c_int. diff --git a/Lib/ctypes/test/test_parameters.py b/Lib/ctypes/test/test_parameters.py index 1b7f0dc..69db14f 100644 --- a/Lib/ctypes/test/test_parameters.py +++ b/Lib/ctypes/test/test_parameters.py @@ -33,8 +33,8 @@ class SimpleTypesTestCase(unittest.TestCase): return value * 4 from_param = classmethod(from_param) - self.failUnlessEqual(CVOIDP.from_param("abc"), "abcabc") - self.failUnlessEqual(CCHARP.from_param("abc"), "abcabcabcabc") + self.assertEqual(CVOIDP.from_param("abc"), "abcabc") + self.assertEqual(CCHARP.from_param("abc"), "abcabcabcabc") try: from ctypes import c_wchar_p @@ -46,7 +46,7 @@ class SimpleTypesTestCase(unittest.TestCase): return value * 3 from_param = classmethod(from_param) - self.failUnlessEqual(CWCHARP.from_param("abc"), "abcabcabc") + self.assertEqual(CWCHARP.from_param("abc"), "abcabcabc") # XXX Replace by c_char_p tests def test_cstrings(self): @@ -55,10 +55,10 @@ class SimpleTypesTestCase(unittest.TestCase): # c_char_p.from_param on a Python String packs the string # into a cparam object s = "123" - self.failUnless(c_char_p.from_param(s)._obj is s) + self.assertTrue(c_char_p.from_param(s)._obj is s) # new in 0.9.1: convert (encode) unicode to ascii - self.failUnlessEqual(c_char_p.from_param(u"123")._obj, "123") + self.assertEqual(c_char_p.from_param(u"123")._obj, "123") self.assertRaises(UnicodeEncodeError, c_char_p.from_param, u"123\377") self.assertRaises(TypeError, c_char_p.from_param, 42) @@ -66,7 +66,7 @@ class SimpleTypesTestCase(unittest.TestCase): # calling c_char_p.from_param with a c_char_p instance # returns the argument itself: a = c_char_p("123") - self.failUnless(c_char_p.from_param(a) is a) + self.assertTrue(c_char_p.from_param(a) is a) def test_cw_strings(self): from ctypes import byref @@ -77,15 +77,15 @@ class SimpleTypesTestCase(unittest.TestCase): return s = u"123" if sys.platform == "win32": - self.failUnless(c_wchar_p.from_param(s)._obj is s) + self.assertTrue(c_wchar_p.from_param(s)._obj is s) self.assertRaises(TypeError, c_wchar_p.from_param, 42) # new in 0.9.1: convert (decode) ascii to unicode - self.failUnlessEqual(c_wchar_p.from_param("123")._obj, u"123") + self.assertEqual(c_wchar_p.from_param("123")._obj, u"123") self.assertRaises(UnicodeDecodeError, c_wchar_p.from_param, "123\377") pa = c_wchar_p.from_param(c_wchar_p(u"123")) - self.failUnlessEqual(type(pa), c_wchar_p) + self.assertEqual(type(pa), c_wchar_p) def test_int_pointers(self): from ctypes import c_short, c_uint, c_int, c_long, POINTER, pointer @@ -94,10 +94,10 @@ class SimpleTypesTestCase(unittest.TestCase): ## p = pointer(c_int(42)) ## x = LPINT.from_param(p) x = LPINT.from_param(pointer(c_int(42))) - self.failUnlessEqual(x.contents.value, 42) - self.failUnlessEqual(LPINT(c_int(42)).contents.value, 42) + self.assertEqual(x.contents.value, 42) + self.assertEqual(LPINT(c_int(42)).contents.value, 42) - self.failUnlessEqual(LPINT.from_param(None), 0) + self.assertEqual(LPINT.from_param(None), 0) if c_int != c_long: self.assertRaises(TypeError, LPINT.from_param, pointer(c_long(42))) @@ -133,8 +133,8 @@ class SimpleTypesTestCase(unittest.TestCase): from ctypes import c_short, c_uint, c_int, c_long, POINTER INTARRAY = c_int * 3 ia = INTARRAY() - self.failUnlessEqual(len(ia), 3) - self.failUnlessEqual([ia[i] for i in range(3)], [0, 0, 0]) + self.assertEqual(len(ia), 3) + self.assertEqual([ia[i] for i in range(3)], [0, 0, 0]) # Pointers are only compatible with arrays containing items of # the same type! @@ -161,8 +161,8 @@ class SimpleTypesTestCase(unittest.TestCase): return None func.argtypes = (Adapter(),) - self.failUnlessEqual(func(None), None) - self.failUnlessEqual(func(object()), None) + self.assertEqual(func(None), None) + self.assertEqual(func(object()), None) class Adapter(object): def from_param(cls, obj): @@ -171,7 +171,7 @@ class SimpleTypesTestCase(unittest.TestCase): func.argtypes = (Adapter(),) # don't know how to convert parameter 1 self.assertRaises(ArgumentError, func, object()) - self.failUnlessEqual(func(c_void_p(42)), 42) + self.assertEqual(func(c_void_p(42)), 42) class Adapter(object): def from_param(cls, obj): diff --git a/Lib/ctypes/test/test_pep3118.py b/Lib/ctypes/test/test_pep3118.py index 4ff2c3e..a015b74 100644 --- a/Lib/ctypes/test/test_pep3118.py +++ b/Lib/ctypes/test/test_pep3118.py @@ -45,20 +45,20 @@ class Test(unittest.TestCase): ob = tp() v = memoryview(ob) try: - self.failUnlessEqual(normalize(v.format), normalize(fmt)) - self.failUnlessEqual(v.size, sizeof(ob)) - self.failUnlessEqual(v.itemsize, sizeof(itemtp)) - self.failUnlessEqual(v.shape, shape) + self.assertEqual(normalize(v.format), normalize(fmt)) + self.assertEqual(v.size, sizeof(ob)) + self.assertEqual(v.itemsize, sizeof(itemtp)) + self.assertEqual(v.shape, shape) # ctypes object always have a non-strided memory block - self.failUnlessEqual(v.strides, None) + self.assertEqual(v.strides, None) # they are always read/write - self.failIf(v.readonly) + self.assertFalse(v.readonly) if v.shape: n = 1 for dim in v.shape: n = n * dim - self.failUnlessEqual(v.itemsize * n, v.size) + self.assertEqual(v.itemsize * n, v.size) except: # so that we can see the failing type print(tp) @@ -69,20 +69,20 @@ class Test(unittest.TestCase): ob = tp() v = memoryview(ob) try: - self.failUnlessEqual(v.format, fmt) - self.failUnlessEqual(v.size, sizeof(ob)) - self.failUnlessEqual(v.itemsize, sizeof(itemtp)) - self.failUnlessEqual(v.shape, shape) + self.assertEqual(v.format, fmt) + self.assertEqual(v.size, sizeof(ob)) + self.assertEqual(v.itemsize, sizeof(itemtp)) + self.assertEqual(v.shape, shape) # ctypes object always have a non-strided memory block - self.failUnlessEqual(v.strides, None) + self.assertEqual(v.strides, None) # they are always read/write - self.failIf(v.readonly) + self.assertFalse(v.readonly) if v.shape: n = 1 for dim in v.shape: n = n * dim - self.failUnlessEqual(v.itemsize * n, v.size) + self.assertEqual(v.itemsize * n, v.size) except: # so that we can see the failing type print(tp) diff --git a/Lib/ctypes/test/test_pickling.py b/Lib/ctypes/test/test_pickling.py index 28868f4..dee2060 100644 --- a/Lib/ctypes/test/test_pickling.py +++ b/Lib/ctypes/test/test_pickling.py @@ -27,8 +27,8 @@ class PickleTest(unittest.TestCase): c_double(3.14), ]: dst = self.loads(self.dumps(src)) - self.failUnlessEqual(src.__dict__, dst.__dict__) - self.failUnlessEqual(buffer(src)[:], + self.assertEqual(src.__dict__, dst.__dict__) + self.assertEqual(buffer(src)[:], buffer(dst)[:]) def test_struct(self): @@ -36,17 +36,17 @@ class PickleTest(unittest.TestCase): x = X() x.a = 42 - self.failUnlessEqual(X.init_called, 1) + self.assertEqual(X.init_called, 1) y = self.loads(self.dumps(x)) # loads must NOT call __init__ - self.failUnlessEqual(X.init_called, 1) + self.assertEqual(X.init_called, 1) # ctypes instances are identical when the instance __dict__ # and the memory buffer are identical - self.failUnlessEqual(y.__dict__, x.__dict__) - self.failUnlessEqual(buffer(y)[:], + self.assertEqual(y.__dict__, x.__dict__) + self.assertEqual(buffer(y)[:], buffer(x)[:]) def test_unpickable(self): diff --git a/Lib/ctypes/test/test_pointers.py b/Lib/ctypes/test/test_pointers.py index 076cd8b..92b8ce6 100644 --- a/Lib/ctypes/test/test_pointers.py +++ b/Lib/ctypes/test/test_pointers.py @@ -17,7 +17,7 @@ class PointersTestCase(unittest.TestCase): POINTER(c_ulong)(c_ulong(22)) # Pointer can't set contents: has no _type_ - self.failUnlessRaises(TypeError, A, c_ulong(33)) + self.assertRaises(TypeError, A, c_ulong(33)) def test_pass_pointers(self): dll = CDLL(_ctypes_test.__file__) @@ -27,12 +27,12 @@ class PointersTestCase(unittest.TestCase): i = c_int(12345678) ## func.argtypes = (POINTER(c_int),) address = func(byref(i)) - self.failUnlessEqual(c_int.from_address(address).value, 12345678) + self.assertEqual(c_int.from_address(address).value, 12345678) func.restype = POINTER(c_int) res = func(pointer(i)) - self.failUnlessEqual(res.contents.value, 12345678) - self.failUnlessEqual(res[0], 12345678) + self.assertEqual(res.contents.value, 12345678) + self.assertEqual(res[0], 12345678) def test_change_pointers(self): dll = CDLL(_ctypes_test.__file__) @@ -43,18 +43,18 @@ class PointersTestCase(unittest.TestCase): func.argtypes = (POINTER(c_int),) res = func(pointer(i)) - self.failUnlessEqual(res[0], 87654) - self.failUnlessEqual(res.contents.value, 87654) + self.assertEqual(res[0], 87654) + self.assertEqual(res.contents.value, 87654) # C code: *res = 54345 res[0] = 54345 - self.failUnlessEqual(i.value, 54345) + self.assertEqual(i.value, 54345) # C code: # int x = 12321; # res = &x res.contents = c_int(12321) - self.failUnlessEqual(i.value, 54345) + self.assertEqual(i.value, 54345) def test_callbacks_with_pointers(self): # a function type receiving a pointer @@ -78,7 +78,7 @@ class PointersTestCase(unittest.TestCase): ## i = c_int(42) ## callback(byref(i)) -## self.failUnless(i.value == 84) +## self.assertTrue(i.value == 84) doit(callback) ## print self.result @@ -91,11 +91,11 @@ class PointersTestCase(unittest.TestCase): i = ct(42) p = pointer(i) ## print type(p.contents), ct - self.failUnless(type(p.contents) is ct) + self.assertTrue(type(p.contents) is ct) # p.contents is the same as p[0] ## print p.contents -## self.failUnless(p.contents == 42) -## self.failUnless(p[0] == 42) +## self.assertTrue(p.contents == 42) +## self.assertTrue(p[0] == 42) self.assertRaises(TypeError, delitem, p, 0) @@ -117,9 +117,9 @@ class PointersTestCase(unittest.TestCase): pt = pointer(Table(1, 2, 3)) - self.failUnlessEqual(pt.contents.a, 1) - self.failUnlessEqual(pt.contents.b, 2) - self.failUnlessEqual(pt.contents.c, 3) + self.assertEqual(pt.contents.a, 1) + self.assertEqual(pt.contents.b, 2) + self.assertEqual(pt.contents.c, 3) pt.contents.c = 33 @@ -130,8 +130,8 @@ class PointersTestCase(unittest.TestCase): p = pointer(c_int(42)) # Although a pointer can be indexed, it ha no length self.assertRaises(TypeError, len, p) - self.failUnlessEqual(p[0], 42) - self.failUnlessEqual(p.contents.value, 42) + self.assertEqual(p[0], 42) + self.assertEqual(p.contents.value, 42) def test_charpp(self): """Test that a character pointer-to-pointer is correctly passed""" @@ -156,20 +156,20 @@ class PointersTestCase(unittest.TestCase): pp = pointer(p) q = pointer(y) pp[0] = q # <== - self.failUnlessEqual(p[0], 6) + self.assertEqual(p[0], 6) def test_c_void_p(self): # http://sourceforge.net/tracker/?func=detail&aid=1518190&group_id=5470&atid=105470 if sizeof(c_void_p) == 4: - self.failUnlessEqual(c_void_p(0xFFFFFFFFL).value, + self.assertEqual(c_void_p(0xFFFFFFFFL).value, c_void_p(-1).value) - self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFFL).value, + self.assertEqual(c_void_p(0xFFFFFFFFFFFFFFFFL).value, c_void_p(-1).value) elif sizeof(c_void_p) == 8: - self.failUnlessEqual(c_void_p(0xFFFFFFFFL).value, + self.assertEqual(c_void_p(0xFFFFFFFFL).value, 0xFFFFFFFFL) - self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFFL).value, + self.assertEqual(c_void_p(0xFFFFFFFFFFFFFFFFL).value, c_void_p(-1).value) - self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFFFFFFFFFFL).value, + self.assertEqual(c_void_p(0xFFFFFFFFFFFFFFFFFFFFFFFFL).value, c_void_p(-1).value) self.assertRaises(TypeError, c_void_p, 3.14) # make sure floats are NOT accepted @@ -177,16 +177,16 @@ class PointersTestCase(unittest.TestCase): def test_pointers_bool(self): # NULL pointers have a boolean False value, non-NULL pointers True. - self.failUnlessEqual(bool(POINTER(c_int)()), False) - self.failUnlessEqual(bool(pointer(c_int())), True) + self.assertEqual(bool(POINTER(c_int)()), False) + self.assertEqual(bool(pointer(c_int())), True) - self.failUnlessEqual(bool(CFUNCTYPE(None)(0)), False) - self.failUnlessEqual(bool(CFUNCTYPE(None)(42)), True) + self.assertEqual(bool(CFUNCTYPE(None)(0)), False) + self.assertEqual(bool(CFUNCTYPE(None)(42)), True) # COM methods are boolean True: if sys.platform == "win32": mth = WINFUNCTYPE(None)(42, "name", (), None) - self.failUnlessEqual(bool(mth), True) + self.assertEqual(bool(mth), True) if __name__ == '__main__': unittest.main() diff --git a/Lib/ctypes/test/test_prototypes.py b/Lib/ctypes/test/test_prototypes.py index 33deae3..09ba655 100644 --- a/Lib/ctypes/test/test_prototypes.py +++ b/Lib/ctypes/test/test_prototypes.py @@ -58,23 +58,23 @@ class CharPointersTestCase(unittest.TestCase): try: func() except TypeError, details: - self.failUnlessEqual(str(details), "required argument 'input' missing") + self.assertEqual(str(details), "required argument 'input' missing") else: self.fail("TypeError not raised") - self.failUnlessEqual(func(None), None) - self.failUnlessEqual(func(input=None), None) + self.assertEqual(func(None), None) + self.assertEqual(func(input=None), None) def test_int_pointer_arg(self): func = testdll._testfunc_p_p func.restype = c_long - self.failUnlessEqual(0, func(0)) + self.assertEqual(0, func(0)) ci = c_int(0) func.argtypes = POINTER(c_int), - self.failUnlessEqual(positive_address(addressof(ci)), + self.assertEqual(positive_address(addressof(ci)), positive_address(func(byref(ci)))) func.argtypes = c_char_p, @@ -91,45 +91,45 @@ class CharPointersTestCase(unittest.TestCase): func.restype = c_char_p func.argtypes = POINTER(c_char), - self.failUnlessEqual(None, func(None)) - self.failUnlessEqual("123", func("123")) - self.failUnlessEqual(None, func(c_char_p(None))) - self.failUnlessEqual("123", func(c_char_p("123"))) + self.assertEqual(None, func(None)) + self.assertEqual("123", func("123")) + self.assertEqual(None, func(c_char_p(None))) + self.assertEqual("123", func(c_char_p("123"))) - self.failUnlessEqual("123", func(c_buffer("123"))) + self.assertEqual("123", func(c_buffer("123"))) ca = c_char("a") - self.failUnlessEqual("a", func(pointer(ca))[0]) - self.failUnlessEqual("a", func(byref(ca))[0]) + self.assertEqual("a", func(pointer(ca))[0]) + self.assertEqual("a", func(byref(ca))[0]) def test_c_char_p_arg(self): func = testdll._testfunc_p_p func.restype = c_char_p func.argtypes = c_char_p, - self.failUnlessEqual(None, func(None)) - self.failUnlessEqual("123", func("123")) - self.failUnlessEqual(None, func(c_char_p(None))) - self.failUnlessEqual("123", func(c_char_p("123"))) + self.assertEqual(None, func(None)) + self.assertEqual("123", func("123")) + self.assertEqual(None, func(c_char_p(None))) + self.assertEqual("123", func(c_char_p("123"))) - self.failUnlessEqual("123", func(c_buffer("123"))) + self.assertEqual("123", func(c_buffer("123"))) ca = c_char("a") - self.failUnlessEqual("a", func(pointer(ca))[0]) - self.failUnlessEqual("a", func(byref(ca))[0]) + self.assertEqual("a", func(pointer(ca))[0]) + self.assertEqual("a", func(byref(ca))[0]) def test_c_void_p_arg(self): func = testdll._testfunc_p_p func.restype = c_char_p func.argtypes = c_void_p, - self.failUnlessEqual(None, func(None)) - self.failUnlessEqual("123", func("123")) - self.failUnlessEqual("123", func(c_char_p("123"))) - self.failUnlessEqual(None, func(c_char_p(None))) + self.assertEqual(None, func(None)) + self.assertEqual("123", func("123")) + self.assertEqual("123", func(c_char_p("123"))) + self.assertEqual(None, func(c_char_p(None))) - self.failUnlessEqual("123", func(c_buffer("123"))) + self.assertEqual("123", func(c_buffer("123"))) ca = c_char("a") - self.failUnlessEqual("a", func(pointer(ca))[0]) - self.failUnlessEqual("a", func(byref(ca))[0]) + self.assertEqual("a", func(pointer(ca))[0]) + self.assertEqual("a", func(byref(ca))[0]) func(byref(c_int())) func(pointer(c_int())) @@ -140,8 +140,8 @@ class CharPointersTestCase(unittest.TestCase): except NameError: pass else: - self.failUnlessEqual(None, func(c_wchar_p(None))) - self.failUnlessEqual(u"123", func(c_wchar_p(u"123"))) + self.assertEqual(None, func(c_wchar_p(None))) + self.assertEqual(u"123", func(c_wchar_p(u"123"))) def test_instance(self): func = testdll._testfunc_p_p @@ -151,10 +151,10 @@ class CharPointersTestCase(unittest.TestCase): _as_parameter_ = None func.argtypes = c_void_p, - self.failUnlessEqual(None, func(X())) + self.assertEqual(None, func(X())) func.argtypes = None - self.failUnlessEqual(None, func(X())) + self.assertEqual(None, func(X())) try: c_wchar @@ -174,15 +174,15 @@ else: func.restype = c_wchar_p func.argtypes = POINTER(c_wchar), - self.failUnlessEqual(None, func(None)) - self.failUnlessEqual(u"123", func(u"123")) - self.failUnlessEqual(None, func(c_wchar_p(None))) - self.failUnlessEqual(u"123", func(c_wchar_p(u"123"))) + self.assertEqual(None, func(None)) + self.assertEqual(u"123", func(u"123")) + self.assertEqual(None, func(c_wchar_p(None))) + self.assertEqual(u"123", func(c_wchar_p(u"123"))) - self.failUnlessEqual(u"123", func(c_wbuffer(u"123"))) + self.assertEqual(u"123", func(c_wbuffer(u"123"))) ca = c_wchar("a") - self.failUnlessEqual(u"a", func(pointer(ca))[0]) - self.failUnlessEqual(u"a", func(byref(ca))[0]) + self.assertEqual(u"a", func(pointer(ca))[0]) + self.assertEqual(u"a", func(byref(ca))[0]) def test_c_wchar_p_arg(self): func = testdll._testfunc_p_p @@ -191,16 +191,16 @@ else: c_wchar_p.from_param(u"123") - self.failUnlessEqual(None, func(None)) - self.failUnlessEqual("123", func(u"123")) - self.failUnlessEqual(None, func(c_wchar_p(None))) - self.failUnlessEqual("123", func(c_wchar_p("123"))) + self.assertEqual(None, func(None)) + self.assertEqual("123", func(u"123")) + self.assertEqual(None, func(c_wchar_p(None))) + self.assertEqual("123", func(c_wchar_p("123"))) # XXX Currently, these raise TypeErrors, although they shouldn't: - self.failUnlessEqual("123", func(c_wbuffer("123"))) + self.assertEqual("123", func(c_wbuffer("123"))) ca = c_wchar("a") - self.failUnlessEqual("a", func(pointer(ca))[0]) - self.failUnlessEqual("a", func(byref(ca))[0]) + self.assertEqual("a", func(pointer(ca))[0]) + self.assertEqual("a", func(byref(ca))[0]) class ArrayTest(unittest.TestCase): def test(self): diff --git a/Lib/ctypes/test/test_python_api.py b/Lib/ctypes/test/test_python_api.py index 265ee55..698170f 100644 --- a/Lib/ctypes/test/test_python_api.py +++ b/Lib/ctypes/test/test_python_api.py @@ -23,7 +23,7 @@ class PythonAPITestCase(unittest.TestCase): PyString_FromStringAndSize.restype = py_object PyString_FromStringAndSize.argtypes = c_char_p, c_py_ssize_t - self.failUnlessEqual(PyString_FromStringAndSize("abcdefghi", 3), "abc") + self.assertEqual(PyString_FromStringAndSize("abcdefghi", 3), "abc") def test_PyString_FromString(self): pythonapi.PyString_FromString.restype = py_object @@ -32,10 +32,10 @@ class PythonAPITestCase(unittest.TestCase): s = "abc" refcnt = grc(s) pyob = pythonapi.PyString_FromString(s) - self.failUnlessEqual(grc(s), refcnt) - self.failUnlessEqual(s, pyob) + self.assertEqual(grc(s), refcnt) + self.assertEqual(s, pyob) del pyob - self.failUnlessEqual(grc(s), refcnt) + self.assertEqual(grc(s), refcnt) if is_resource_enabled("refcount"): # This test is unreliable, because it is possible that code in @@ -44,28 +44,28 @@ class PythonAPITestCase(unittest.TestCase): def test_PyInt_Long(self): ref42 = grc(42) pythonapi.PyInt_FromLong.restype = py_object - self.failUnlessEqual(pythonapi.PyInt_FromLong(42), 42) + self.assertEqual(pythonapi.PyInt_FromLong(42), 42) - self.failUnlessEqual(grc(42), ref42) + self.assertEqual(grc(42), ref42) pythonapi.PyInt_AsLong.argtypes = (py_object,) pythonapi.PyInt_AsLong.restype = c_long res = pythonapi.PyInt_AsLong(42) - self.failUnlessEqual(grc(res), ref42 + 1) + self.assertEqual(grc(res), ref42 + 1) del res - self.failUnlessEqual(grc(42), ref42) + self.assertEqual(grc(42), ref42) def test_PyObj_FromPtr(self): s = "abc def ghi jkl" ref = grc(s) # id(python-object) is the address pyobj = PyObj_FromPtr(id(s)) - self.failUnless(s is pyobj) + self.assertTrue(s is pyobj) - self.failUnlessEqual(grc(s), ref + 1) + self.assertEqual(grc(s), ref + 1) del pyobj - self.failUnlessEqual(grc(s), ref) + self.assertEqual(grc(s), ref) def test_PyOS_snprintf(self): PyOS_snprintf = pythonapi.PyOS_snprintf @@ -73,18 +73,18 @@ class PythonAPITestCase(unittest.TestCase): buf = c_buffer(256) PyOS_snprintf(buf, sizeof(buf), "Hello from %s", "ctypes") - self.failUnlessEqual(buf.value, "Hello from ctypes") + self.assertEqual(buf.value, "Hello from ctypes") PyOS_snprintf(buf, sizeof(buf), "Hello from %s", "ctypes", 1, 2, 3) - self.failUnlessEqual(buf.value, "Hello from ctypes") + self.assertEqual(buf.value, "Hello from ctypes") # not enough arguments - self.failUnlessRaises(TypeError, PyOS_snprintf, buf) + self.assertRaises(TypeError, PyOS_snprintf, buf) def test_pyobject_repr(self): - self.failUnlessEqual(repr(py_object()), "py_object(<NULL>)") - self.failUnlessEqual(repr(py_object(42)), "py_object(42)") - self.failUnlessEqual(repr(py_object(object)), "py_object(%r)" % object) + self.assertEqual(repr(py_object()), "py_object(<NULL>)") + self.assertEqual(repr(py_object(42)), "py_object(42)") + self.assertEqual(repr(py_object(object)), "py_object(%r)" % object) if __name__ == "__main__": unittest.main() diff --git a/Lib/ctypes/test/test_random_things.py b/Lib/ctypes/test/test_random_things.py index 183b1d6..ddb597d 100644 --- a/Lib/ctypes/test/test_random_things.py +++ b/Lib/ctypes/test/test_random_things.py @@ -20,7 +20,7 @@ if sys.platform == "win32": hdll = windll.kernel32.LoadLibraryA("kernel32") funcaddr = windll.kernel32.GetProcAddress(hdll, "GetModuleHandleA") - self.failUnlessEqual(call_function(funcaddr, (None,)), + self.assertEqual(call_function(funcaddr, (None,)), windll.kernel32.GetModuleHandleA(None)) class CallbackTracbackTestCase(unittest.TestCase): @@ -49,25 +49,25 @@ class CallbackTracbackTestCase(unittest.TestCase): def test_ValueError(self): cb = CFUNCTYPE(c_int, c_int)(callback_func) out = self.capture_stderr(cb, 42) - self.failUnlessEqual(out.splitlines()[-1], + self.assertEqual(out.splitlines()[-1], "ValueError: 42") def test_IntegerDivisionError(self): cb = CFUNCTYPE(c_int, c_int)(callback_func) out = self.capture_stderr(cb, 0) - self.failUnlessEqual(out.splitlines()[-1][:19], + self.assertEqual(out.splitlines()[-1][:19], "ZeroDivisionError: ") def test_FloatDivisionError(self): cb = CFUNCTYPE(c_int, c_double)(callback_func) out = self.capture_stderr(cb, 0.0) - self.failUnlessEqual(out.splitlines()[-1][:19], + self.assertEqual(out.splitlines()[-1][:19], "ZeroDivisionError: ") def test_TypeErrorDivisionError(self): cb = CFUNCTYPE(c_int, c_char_p)(callback_func) out = self.capture_stderr(cb, "spam") - self.failUnlessEqual(out.splitlines()[-1], + self.assertEqual(out.splitlines()[-1], "TypeError: " "unsupported operand type(s) for /: 'int' and 'str'") diff --git a/Lib/ctypes/test/test_refcounts.py b/Lib/ctypes/test/test_refcounts.py index 448f292..35a81aa 100644 --- a/Lib/ctypes/test/test_refcounts.py +++ b/Lib/ctypes/test/test_refcounts.py @@ -21,17 +21,17 @@ class RefcountTestCase(unittest.TestCase): #print "called back with", value return value - self.failUnlessEqual(grc(callback), 2) + self.assertEqual(grc(callback), 2) cb = MyCallback(callback) - self.failUnless(grc(callback) > 2) + self.assertTrue(grc(callback) > 2) result = f(-10, cb) - self.failUnlessEqual(result, -18) + self.assertEqual(result, -18) cb = None gc.collect() - self.failUnlessEqual(grc(callback), 2) + self.assertEqual(grc(callback), 2) def test_refcount(self): @@ -39,19 +39,19 @@ class RefcountTestCase(unittest.TestCase): def func(*args): pass # this is the standard refcount for func - self.failUnlessEqual(grc(func), 2) + self.assertEqual(grc(func), 2) # the CFuncPtr instance holds atr least one refcount on func: f = OtherCallback(func) - self.failUnless(grc(func) > 2) + self.assertTrue(grc(func) > 2) # and may release it again del f - self.failUnless(grc(func) >= 2) + self.assertTrue(grc(func) >= 2) # but now it must be gone gc.collect() - self.failUnless(grc(func) == 2) + self.assertTrue(grc(func) == 2) class X(ctypes.Structure): _fields_ = [("a", OtherCallback)] @@ -59,27 +59,27 @@ class RefcountTestCase(unittest.TestCase): x.a = OtherCallback(func) # the CFuncPtr instance holds atr least one refcount on func: - self.failUnless(grc(func) > 2) + self.assertTrue(grc(func) > 2) # and may release it again del x - self.failUnless(grc(func) >= 2) + self.assertTrue(grc(func) >= 2) # and now it must be gone again gc.collect() - self.failUnlessEqual(grc(func), 2) + self.assertEqual(grc(func), 2) f = OtherCallback(func) # the CFuncPtr instance holds atr least one refcount on func: - self.failUnless(grc(func) > 2) + self.assertTrue(grc(func) > 2) # create a cycle f.cycle = f del f gc.collect() - self.failUnlessEqual(grc(func), 2) + self.assertEqual(grc(func), 2) class AnotherLeak(unittest.TestCase): def test_callback(self): @@ -92,7 +92,7 @@ class AnotherLeak(unittest.TestCase): a = sys.getrefcount(ctypes.c_int) f(1, 2) - self.failUnlessEqual(sys.getrefcount(ctypes.c_int), a) + self.assertEqual(sys.getrefcount(ctypes.c_int), a) if __name__ == '__main__': unittest.main() diff --git a/Lib/ctypes/test/test_repr.py b/Lib/ctypes/test/test_repr.py index 9fef21f..99cc556 100644 --- a/Lib/ctypes/test/test_repr.py +++ b/Lib/ctypes/test/test_repr.py @@ -18,12 +18,12 @@ class ReprTest(unittest.TestCase): def test_numbers(self): for typ in subclasses: base = typ.__bases__[0] - self.failUnless(repr(base(42)).startswith(base.__name__)) - self.failUnlessEqual("<X object at", repr(typ(42))[:12]) + self.assertTrue(repr(base(42)).startswith(base.__name__)) + self.assertEqual("<X object at", repr(typ(42))[:12]) def test_char(self): - self.failUnlessEqual("c_char('x')", repr(c_char('x'))) - self.failUnlessEqual("<X object at", repr(X('x'))[:12]) + self.assertEqual("c_char('x')", repr(c_char('x'))) + self.assertEqual("<X object at", repr(X('x'))[:12]) if __name__ == "__main__": unittest.main() diff --git a/Lib/ctypes/test/test_returnfuncptrs.py b/Lib/ctypes/test/test_returnfuncptrs.py index 88dccf2..f766189 100644 --- a/Lib/ctypes/test/test_returnfuncptrs.py +++ b/Lib/ctypes/test/test_returnfuncptrs.py @@ -12,8 +12,8 @@ class ReturnFuncPtrTestCase(unittest.TestCase): get_strchr = dll.get_strchr get_strchr.restype = CFUNCTYPE(c_char_p, c_char_p, c_char) strchr = get_strchr() - self.failUnlessEqual(strchr("abcdef", "b"), "bcdef") - self.failUnlessEqual(strchr("abcdef", "x"), None) + self.assertEqual(strchr("abcdef", "b"), "bcdef") + self.assertEqual(strchr("abcdef", "x"), None) self.assertRaises(ArgumentError, strchr, "abcdef", 3) self.assertRaises(TypeError, strchr, "abcdef") @@ -26,8 +26,8 @@ class ReturnFuncPtrTestCase(unittest.TestCase): # _CFuncPtr instances are now callable with an integer argument # which denotes a function address: strchr = CFUNCTYPE(c_char_p, c_char_p, c_char)(addr) - self.failUnless(strchr("abcdef", "b"), "bcdef") - self.failUnlessEqual(strchr("abcdef", "x"), None) + self.assertTrue(strchr("abcdef", "b"), "bcdef") + self.assertEqual(strchr("abcdef", "x"), None) self.assertRaises(ArgumentError, strchr, "abcdef", 3) self.assertRaises(TypeError, strchr, "abcdef") diff --git a/Lib/ctypes/test/test_simplesubclasses.py b/Lib/ctypes/test/test_simplesubclasses.py index 5671cce..1b73fb3 100644 --- a/Lib/ctypes/test/test_simplesubclasses.py +++ b/Lib/ctypes/test/test_simplesubclasses.py @@ -12,8 +12,8 @@ class MyInt(c_int): class Test(unittest.TestCase): def test_compare(self): - self.failUnlessEqual(MyInt(3), MyInt(3)) - self.failIfEqual(MyInt(42), MyInt(43)) + self.assertEqual(MyInt(3), MyInt(3)) + self.assertNotEqual(MyInt(42), MyInt(43)) def test_ignore_retval(self): # Test if the return value of a callback is ignored @@ -23,7 +23,7 @@ class Test(unittest.TestCase): return (1, "abc", None) cb = proto(func) - self.failUnlessEqual(None, cb()) + self.assertEqual(None, cb()) def test_int_callback(self): @@ -34,24 +34,24 @@ class Test(unittest.TestCase): cb = CFUNCTYPE(None, MyInt)(func) - self.failUnlessEqual(None, cb(42)) - self.failUnlessEqual(type(args[-1]), MyInt) + self.assertEqual(None, cb(42)) + self.assertEqual(type(args[-1]), MyInt) cb = CFUNCTYPE(c_int, c_int)(func) - self.failUnlessEqual(42, cb(42)) - self.failUnlessEqual(type(args[-1]), int) + self.assertEqual(42, cb(42)) + self.assertEqual(type(args[-1]), int) def test_int_struct(self): class X(Structure): _fields_ = [("x", MyInt)] - self.failUnlessEqual(X().x, MyInt()) + self.assertEqual(X().x, MyInt()) s = X() s.x = MyInt(42) - self.failUnlessEqual(s.x, MyInt(42)) + self.assertEqual(s.x, MyInt(42)) if __name__ == "__main__": unittest.main() diff --git a/Lib/ctypes/test/test_sizes.py b/Lib/ctypes/test/test_sizes.py index 208c00e..0509cbb 100644 --- a/Lib/ctypes/test/test_sizes.py +++ b/Lib/ctypes/test/test_sizes.py @@ -5,23 +5,23 @@ from ctypes import * class SizesTestCase(unittest.TestCase): def test_8(self): - self.failUnlessEqual(1, sizeof(c_int8)) - self.failUnlessEqual(1, sizeof(c_uint8)) + self.assertEqual(1, sizeof(c_int8)) + self.assertEqual(1, sizeof(c_uint8)) def test_16(self): - self.failUnlessEqual(2, sizeof(c_int16)) - self.failUnlessEqual(2, sizeof(c_uint16)) + self.assertEqual(2, sizeof(c_int16)) + self.assertEqual(2, sizeof(c_uint16)) def test_32(self): - self.failUnlessEqual(4, sizeof(c_int32)) - self.failUnlessEqual(4, sizeof(c_uint32)) + self.assertEqual(4, sizeof(c_int32)) + self.assertEqual(4, sizeof(c_uint32)) def test_64(self): - self.failUnlessEqual(8, sizeof(c_int64)) - self.failUnlessEqual(8, sizeof(c_uint64)) + self.assertEqual(8, sizeof(c_int64)) + self.assertEqual(8, sizeof(c_uint64)) def test_size_t(self): - self.failUnlessEqual(sizeof(c_void_p), sizeof(c_size_t)) + self.assertEqual(sizeof(c_void_p), sizeof(c_size_t)) if __name__ == "__main__": unittest.main() diff --git a/Lib/ctypes/test/test_slicing.py b/Lib/ctypes/test/test_slicing.py index 25bd801..a5632ec 100644 --- a/Lib/ctypes/test/test_slicing.py +++ b/Lib/ctypes/test/test_slicing.py @@ -7,43 +7,43 @@ class SlicesTestCase(unittest.TestCase): def test_getslice_cint(self): a = (c_int * 100)(*xrange(1100, 1200)) b = range(1100, 1200) - self.failUnlessEqual(a[0:2], b[0:2]) - self.failUnlessEqual(a[0:2:], b[0:2:]) - self.failUnlessEqual(len(a), len(b)) - self.failUnlessEqual(a[5:7], b[5:7]) - self.failUnlessEqual(a[5:7:], b[5:7:]) - self.failUnlessEqual(a[-1], b[-1]) - self.failUnlessEqual(a[:], b[:]) - self.failUnlessEqual(a[::], b[::]) - self.failUnlessEqual(a[10::-1], b[10::-1]) - self.failUnlessEqual(a[30:20:-1], b[30:20:-1]) - self.failUnlessEqual(a[:12:6], b[:12:6]) - self.failUnlessEqual(a[2:6:4], b[2:6:4]) + self.assertEqual(a[0:2], b[0:2]) + self.assertEqual(a[0:2:], b[0:2:]) + self.assertEqual(len(a), len(b)) + self.assertEqual(a[5:7], b[5:7]) + self.assertEqual(a[5:7:], b[5:7:]) + self.assertEqual(a[-1], b[-1]) + self.assertEqual(a[:], b[:]) + self.assertEqual(a[::], b[::]) + self.assertEqual(a[10::-1], b[10::-1]) + self.assertEqual(a[30:20:-1], b[30:20:-1]) + self.assertEqual(a[:12:6], b[:12:6]) + self.assertEqual(a[2:6:4], b[2:6:4]) a[0:5] = range(5, 10) - self.failUnlessEqual(a[0:5], range(5, 10)) - self.failUnlessEqual(a[0:5:], range(5, 10)) - self.failUnlessEqual(a[4::-1], range(9, 4, -1)) + self.assertEqual(a[0:5], range(5, 10)) + self.assertEqual(a[0:5:], range(5, 10)) + self.assertEqual(a[4::-1], range(9, 4, -1)) def test_setslice_cint(self): a = (c_int * 100)(*xrange(1100, 1200)) b = range(1100, 1200) a[32:47] = range(32, 47) - self.failUnlessEqual(a[32:47], range(32, 47)) + self.assertEqual(a[32:47], range(32, 47)) a[32:47] = range(132, 147) - self.failUnlessEqual(a[32:47:], range(132, 147)) + self.assertEqual(a[32:47:], range(132, 147)) a[46:31:-1] = range(232, 247) - self.failUnlessEqual(a[32:47:1], range(246, 231, -1)) + self.assertEqual(a[32:47:1], range(246, 231, -1)) a[32:47] = range(1132, 1147) - self.failUnlessEqual(a[:], b) + self.assertEqual(a[:], b) a[32:47:7] = range(3) b[32:47:7] = range(3) - self.failUnlessEqual(a[:], b) + self.assertEqual(a[:], b) a[33::-3] = range(12) b[33::-3] = range(12) - self.failUnlessEqual(a[:], b) + self.assertEqual(a[:], b) from operator import setslice, setitem @@ -69,12 +69,12 @@ class SlicesTestCase(unittest.TestCase): dll.my_strdup.restype = POINTER(c_char) dll.my_free.restype = None res = dll.my_strdup(s) - self.failUnlessEqual(res[:len(s)], s) - self.failUnlessEqual(res[:3], s[:3]) - self.failUnlessEqual(res[:len(s):], s) - self.failUnlessEqual(res[len(s)-1:-1:-1], s[::-1]) - self.failUnlessEqual(res[len(s)-1:5:-7], s[:5:-7]) - self.failUnlessEqual(res[0:-1:-1], s[0::-1]) + self.assertEqual(res[:len(s)], s) + self.assertEqual(res[:3], s[:3]) + self.assertEqual(res[:len(s):], s) + self.assertEqual(res[len(s)-1:-1:-1], s[::-1]) + self.assertEqual(res[len(s)-1:5:-7], s[:5:-7]) + self.assertEqual(res[0:-1:-1], s[0::-1]) import operator self.assertRaises(ValueError, operator.getitem, @@ -94,8 +94,8 @@ class SlicesTestCase(unittest.TestCase): dll.my_strdup.restype = POINTER(c_byte) res = dll.my_strdup(s) - self.failUnlessEqual(res[:len(s)], range(ord("a"), ord("z")+1)) - self.failUnlessEqual(res[:len(s):], range(ord("a"), ord("z")+1)) + self.assertEqual(res[:len(s)], range(ord("a"), ord("z")+1)) + self.assertEqual(res[:len(s):], range(ord("a"), ord("z")+1)) dll.my_free(res) def test_char_ptr_with_free(self): @@ -115,7 +115,7 @@ class SlicesTestCase(unittest.TestCase): dll.my_strdup.errcheck = errcheck try: res = dll.my_strdup(s) - self.failUnlessEqual(res, s) + self.assertEqual(res, s) finally: del dll.my_strdup.errcheck @@ -124,11 +124,11 @@ class SlicesTestCase(unittest.TestCase): s = "abcdefghijklmnopqrstuvwxyz\0" p = (c_char * 27)(*s) - self.failUnlessEqual(p[:], s) - self.failUnlessEqual(p[::], s) - self.failUnlessEqual(p[::-1], s[::-1]) - self.failUnlessEqual(p[5::-2], s[5::-2]) - self.failUnlessEqual(p[2:5:-3], s[2:5:-3]) + self.assertEqual(p[:], s) + self.assertEqual(p[::], s) + self.assertEqual(p[::-1], s[::-1]) + self.assertEqual(p[5::-2], s[5::-2]) + self.assertEqual(p[2:5:-3], s[2:5:-3]) try: @@ -144,10 +144,10 @@ class SlicesTestCase(unittest.TestCase): dll.my_wcsdup.argtypes = POINTER(c_wchar), dll.my_free.restype = None res = dll.my_wcsdup(s) - self.failUnlessEqual(res[:len(s)], s) - self.failUnlessEqual(res[:len(s):], s) - self.failUnlessEqual(res[len(s)-1:-1:-1], s[::-1]) - self.failUnlessEqual(res[len(s)-1:5:-7], s[:5:-7]) + self.assertEqual(res[:len(s)], s) + self.assertEqual(res[:len(s):], s) + self.assertEqual(res[len(s)-1:-1:-1], s[::-1]) + self.assertEqual(res[len(s)-1:5:-7], s[:5:-7]) import operator self.assertRaises(TypeError, operator.setslice, @@ -166,10 +166,10 @@ class SlicesTestCase(unittest.TestCase): return res = dll.my_wcsdup(s) tmpl = range(ord("a"), ord("z")+1) - self.failUnlessEqual(res[:len(s)-1], tmpl) - self.failUnlessEqual(res[:len(s)-1:], tmpl) - self.failUnlessEqual(res[len(s)-2:-1:-1], tmpl[::-1]) - self.failUnlessEqual(res[len(s)-2:5:-7], tmpl[:5:-7]) + self.assertEqual(res[:len(s)-1], tmpl) + self.assertEqual(res[:len(s)-1:], tmpl) + self.assertEqual(res[len(s)-2:-1:-1], tmpl[::-1]) + self.assertEqual(res[len(s)-2:5:-7], tmpl[:5:-7]) dll.my_free(res) ################################################################ diff --git a/Lib/ctypes/test/test_stringptr.py b/Lib/ctypes/test/test_stringptr.py index 6ee6ae0..abed58b 100644 --- a/Lib/ctypes/test/test_stringptr.py +++ b/Lib/ctypes/test/test_stringptr.py @@ -16,14 +16,14 @@ class StringPtrTestCase(unittest.TestCase): self.assertRaises(ValueError, getattr, x.str, "contents") b = c_buffer("Hello, World") from sys import getrefcount as grc - self.failUnlessEqual(grc(b), 2) + self.assertEqual(grc(b), 2) x.str = b - self.failUnlessEqual(grc(b), 3) + self.assertEqual(grc(b), 3) # POINTER(c_char) and Python string is NOT compatible # POINTER(c_char) and c_buffer() is compatible for i in range(len(b)): - self.failUnlessEqual(b[i], x.str[i]) + self.assertEqual(b[i], x.str[i]) self.assertRaises(TypeError, setattr, x, "str", "Hello, World") @@ -34,11 +34,11 @@ class StringPtrTestCase(unittest.TestCase): # c_char_p and Python string is compatible # c_char_p and c_buffer is NOT compatible - self.failUnlessEqual(x.str, None) + self.assertEqual(x.str, None) x.str = "Hello, World" - self.failUnlessEqual(x.str, "Hello, World") + self.assertEqual(x.str, "Hello, World") b = c_buffer("Hello, World") - self.failUnlessRaises(TypeError, setattr, x, "str", b) + self.assertRaises(TypeError, setattr, x, "str", b) def test_functions(self): @@ -48,15 +48,15 @@ class StringPtrTestCase(unittest.TestCase): # c_char_p and Python string is compatible # c_char_p and c_buffer are now compatible strchr.argtypes = c_char_p, c_char - self.failUnlessEqual(strchr("abcdef", "c"), "cdef") - self.failUnlessEqual(strchr(c_buffer("abcdef"), "c"), "cdef") + self.assertEqual(strchr("abcdef", "c"), "cdef") + self.assertEqual(strchr(c_buffer("abcdef"), "c"), "cdef") # POINTER(c_char) and Python string is NOT compatible # POINTER(c_char) and c_buffer() is compatible strchr.argtypes = POINTER(c_char), c_char buf = c_buffer("abcdef") - self.failUnlessEqual(strchr(buf, "c"), "cdef") - self.failUnlessEqual(strchr("abcdef", "c"), "cdef") + self.assertEqual(strchr(buf, "c"), "cdef") + self.assertEqual(strchr("abcdef", "c"), "cdef") # XXX These calls are dangerous, because the first argument # to strchr is no longer valid after the function returns! @@ -66,7 +66,7 @@ class StringPtrTestCase(unittest.TestCase): buf = c_buffer("abcdef") r = strchr(buf, "c") x = r[0], r[1], r[2], r[3], r[4] - self.failUnlessEqual(x, ("c", "d", "e", "f", "\000")) + self.assertEqual(x, ("c", "d", "e", "f", "\000")) del buf # x1 will NOT be the same as x, usually: x1 = r[0], r[1], r[2], r[3], r[4] diff --git a/Lib/ctypes/test/test_strings.py b/Lib/ctypes/test/test_strings.py index 72248e1..bc803db 100644 --- a/Lib/ctypes/test/test_strings.py +++ b/Lib/ctypes/test/test_strings.py @@ -6,20 +6,20 @@ class StringArrayTestCase(unittest.TestCase): BUF = c_char * 4 buf = BUF("a", "b", "c") - self.failUnlessEqual(buf.value, "abc") - self.failUnlessEqual(buf.raw, "abc\000") + self.assertEqual(buf.value, "abc") + self.assertEqual(buf.raw, "abc\000") buf.value = "ABCD" - self.failUnlessEqual(buf.value, "ABCD") - self.failUnlessEqual(buf.raw, "ABCD") + self.assertEqual(buf.value, "ABCD") + self.assertEqual(buf.raw, "ABCD") buf.value = "x" - self.failUnlessEqual(buf.value, "x") - self.failUnlessEqual(buf.raw, "x\000CD") + self.assertEqual(buf.value, "x") + self.assertEqual(buf.raw, "x\000CD") buf[1] = "Z" - self.failUnlessEqual(buf.value, "xZCD") - self.failUnlessEqual(buf.raw, "xZCD") + self.assertEqual(buf.value, "xZCD") + self.assertEqual(buf.raw, "xZCD") self.assertRaises(ValueError, setattr, buf, "value", "aaaaaaaa") self.assertRaises(TypeError, setattr, buf, "value", 42) @@ -28,9 +28,9 @@ class StringArrayTestCase(unittest.TestCase): buf = c_buffer(32) buf.value = "Hello, World" - self.failUnlessEqual(buf.value, "Hello, World") + self.assertEqual(buf.value, "Hello, World") - self.failUnlessRaises(TypeError, setattr, buf, "value", buffer("Hello, World")) + self.assertRaises(TypeError, setattr, buf, "value", buffer("Hello, World")) self.assertRaises(TypeError, setattr, buf, "value", buffer("abc")) self.assertRaises(ValueError, setattr, buf, "raw", buffer("x" * 100)) @@ -38,7 +38,7 @@ class StringArrayTestCase(unittest.TestCase): buf = c_buffer(32) buf.raw = buffer("Hello, World") - self.failUnlessEqual(buf.value, "Hello, World") + self.assertEqual(buf.value, "Hello, World") self.assertRaises(TypeError, setattr, buf, "value", buffer("abc")) self.assertRaises(ValueError, setattr, buf, "raw", buffer("x" * 100)) @@ -63,16 +63,16 @@ else: BUF = c_wchar * 4 buf = BUF(u"a", u"b", u"c") - self.failUnlessEqual(buf.value, u"abc") + self.assertEqual(buf.value, u"abc") buf.value = u"ABCD" - self.failUnlessEqual(buf.value, u"ABCD") + self.assertEqual(buf.value, u"ABCD") buf.value = u"x" - self.failUnlessEqual(buf.value, u"x") + self.assertEqual(buf.value, u"x") buf[1] = u"Z" - self.failUnlessEqual(buf.value, u"xZCD") + self.assertEqual(buf.value, u"xZCD") class StringTestCase(unittest.TestCase): def XX_test_basic_strings(self): @@ -80,24 +80,24 @@ class StringTestCase(unittest.TestCase): # Cannot call len on a c_string any longer self.assertRaises(TypeError, len, cs) - self.failUnlessEqual(sizeof(cs), 7) + self.assertEqual(sizeof(cs), 7) # The value property is the string up to the first terminating NUL. - self.failUnlessEqual(cs.value, "abcdef") - self.failUnlessEqual(c_string("abc\000def").value, "abc") + self.assertEqual(cs.value, "abcdef") + self.assertEqual(c_string("abc\000def").value, "abc") # The raw property is the total buffer contents: - self.failUnlessEqual(cs.raw, "abcdef\000") - self.failUnlessEqual(c_string("abc\000def").raw, "abc\000def\000") + self.assertEqual(cs.raw, "abcdef\000") + self.assertEqual(c_string("abc\000def").raw, "abc\000def\000") # We can change the value: cs.value = "ab" - self.failUnlessEqual(cs.value, "ab") - self.failUnlessEqual(cs.raw, "ab\000\000\000\000\000") + self.assertEqual(cs.value, "ab") + self.assertEqual(cs.raw, "ab\000\000\000\000\000") cs.raw = "XY" - self.failUnlessEqual(cs.value, "XY") - self.failUnlessEqual(cs.raw, "XY\000\000\000\000\000") + self.assertEqual(cs.value, "XY") + self.assertEqual(cs.raw, "XY\000\000\000\000\000") self.assertRaises(TypeError, c_string, u"123") @@ -108,24 +108,24 @@ class StringTestCase(unittest.TestCase): # New in releases later than 0.4.0: # c_string(number) returns an empty string of size number - self.failUnless(len(c_string(32).raw) == 32) + self.assertTrue(len(c_string(32).raw) == 32) self.assertRaises(ValueError, c_string, -1) self.assertRaises(ValueError, c_string, 0) # These tests fail, because it is no longer initialized -## self.failUnless(c_string(2).value == "") -## self.failUnless(c_string(2).raw == "\000\000") - self.failUnless(c_string(2).raw[-1] == "\000") - self.failUnless(len(c_string(2).raw) == 2) +## self.assertTrue(c_string(2).value == "") +## self.assertTrue(c_string(2).raw == "\000\000") + self.assertTrue(c_string(2).raw[-1] == "\000") + self.assertTrue(len(c_string(2).raw) == 2) def XX_test_initialized_strings(self): - self.failUnless(c_string("ab", 4).raw[:2] == "ab") - self.failUnless(c_string("ab", 4).raw[:2:] == "ab") - self.failUnless(c_string("ab", 4).raw[:2:-1] == "ba") - self.failUnless(c_string("ab", 4).raw[:2:2] == "a") - self.failUnless(c_string("ab", 4).raw[-1] == "\000") - self.failUnless(c_string("ab", 2).raw == "a\000") + self.assertTrue(c_string("ab", 4).raw[:2] == "ab") + self.assertTrue(c_string("ab", 4).raw[:2:] == "ab") + self.assertTrue(c_string("ab", 4).raw[:2:-1] == "ba") + self.assertTrue(c_string("ab", 4).raw[:2:2] == "a") + self.assertTrue(c_string("ab", 4).raw[-1] == "\000") + self.assertTrue(c_string("ab", 2).raw == "a\000") def XX_test_toolong(self): cs = c_string("abcdef") @@ -156,22 +156,22 @@ else: # XXX This behaviour is about to change: # len returns the size of the internal buffer in bytes. # This includes the terminating NUL character. - self.failUnless(sizeof(cs) == 14) + self.assertTrue(sizeof(cs) == 14) # The value property is the string up to the first terminating NUL. - self.failUnless(cs.value == u"abcdef") - self.failUnless(c_wstring(u"abc\000def").value == u"abc") + self.assertTrue(cs.value == u"abcdef") + self.assertTrue(c_wstring(u"abc\000def").value == u"abc") - self.failUnless(c_wstring(u"abc\000def").value == u"abc") + self.assertTrue(c_wstring(u"abc\000def").value == u"abc") # The raw property is the total buffer contents: - self.failUnless(cs.raw == u"abcdef\000") - self.failUnless(c_wstring(u"abc\000def").raw == u"abc\000def\000") + self.assertTrue(cs.raw == u"abcdef\000") + self.assertTrue(c_wstring(u"abc\000def").raw == u"abc\000def\000") # We can change the value: cs.value = u"ab" - self.failUnless(cs.value == u"ab") - self.failUnless(cs.raw == u"ab\000\000\000\000\000") + self.assertTrue(cs.value == u"ab") + self.assertTrue(cs.raw == u"ab\000\000\000\000\000") self.assertRaises(TypeError, c_wstring, "123") self.assertRaises(ValueError, c_wstring, 0) diff --git a/Lib/ctypes/test/test_struct_fields.py b/Lib/ctypes/test/test_struct_fields.py index ef5fb50..22eb3b0 100644 --- a/Lib/ctypes/test/test_struct_fields.py +++ b/Lib/ctypes/test/test_struct_fields.py @@ -15,7 +15,7 @@ class StructFieldsTestCase(unittest.TestCase): def test_1_A(self): class X(Structure): pass - self.failUnlessEqual(sizeof(X), 0) # not finalized + self.assertEqual(sizeof(X), 0) # not finalized X._fields_ = [] # finalized self.assertRaises(AttributeError, setattr, X, "_fields_", []) diff --git a/Lib/ctypes/test/test_structures.py b/Lib/ctypes/test/test_structures.py index 0c5a347..168c3cd 100644 --- a/Lib/ctypes/test/test_structures.py +++ b/Lib/ctypes/test/test_structures.py @@ -13,33 +13,33 @@ class SubclassesTest(unittest.TestCase): class Z(X): pass - self.failUnlessEqual(sizeof(X), sizeof(c_int)) - self.failUnlessEqual(sizeof(Y), sizeof(c_int)*2) - self.failUnlessEqual(sizeof(Z), sizeof(c_int)) - self.failUnlessEqual(X._fields_, [("a", c_int)]) - self.failUnlessEqual(Y._fields_, [("b", c_int)]) - self.failUnlessEqual(Z._fields_, [("a", c_int)]) + self.assertEqual(sizeof(X), sizeof(c_int)) + self.assertEqual(sizeof(Y), sizeof(c_int)*2) + self.assertEqual(sizeof(Z), sizeof(c_int)) + self.assertEqual(X._fields_, [("a", c_int)]) + self.assertEqual(Y._fields_, [("b", c_int)]) + self.assertEqual(Z._fields_, [("a", c_int)]) def test_subclass_delayed(self): class X(Structure): pass - self.failUnlessEqual(sizeof(X), 0) + self.assertEqual(sizeof(X), 0) X._fields_ = [("a", c_int)] class Y(X): pass - self.failUnlessEqual(sizeof(Y), sizeof(X)) + self.assertEqual(sizeof(Y), sizeof(X)) Y._fields_ = [("b", c_int)] class Z(X): pass - self.failUnlessEqual(sizeof(X), sizeof(c_int)) - self.failUnlessEqual(sizeof(Y), sizeof(c_int)*2) - self.failUnlessEqual(sizeof(Z), sizeof(c_int)) - self.failUnlessEqual(X._fields_, [("a", c_int)]) - self.failUnlessEqual(Y._fields_, [("b", c_int)]) - self.failUnlessEqual(Z._fields_, [("a", c_int)]) + self.assertEqual(sizeof(X), sizeof(c_int)) + self.assertEqual(sizeof(Y), sizeof(c_int)*2) + self.assertEqual(sizeof(Z), sizeof(c_int)) + self.assertEqual(X._fields_, [("a", c_int)]) + self.assertEqual(Y._fields_, [("b", c_int)]) + self.assertEqual(Z._fields_, [("a", c_int)]) class StructureTestCase(unittest.TestCase): formats = {"c": c_char, @@ -62,7 +62,7 @@ class StructureTestCase(unittest.TestCase): class X(Structure): _fields_ = [("x", c_char), ("y", tp)] - self.failUnlessEqual((sizeof(X), code), + self.assertEqual((sizeof(X), code), (calcsize("c%c0%c" % (code, code)), code)) def test_unions(self): @@ -70,39 +70,39 @@ class StructureTestCase(unittest.TestCase): class X(Union): _fields_ = [("x", c_char), ("y", tp)] - self.failUnlessEqual((sizeof(X), code), + self.assertEqual((sizeof(X), code), (calcsize("%c" % (code)), code)) def test_struct_alignment(self): class X(Structure): _fields_ = [("x", c_char * 3)] - self.failUnlessEqual(alignment(X), calcsize("s")) - self.failUnlessEqual(sizeof(X), calcsize("3s")) + self.assertEqual(alignment(X), calcsize("s")) + self.assertEqual(sizeof(X), calcsize("3s")) class Y(Structure): _fields_ = [("x", c_char * 3), ("y", c_int)] - self.failUnlessEqual(alignment(Y), calcsize("i")) - self.failUnlessEqual(sizeof(Y), calcsize("3si")) + self.assertEqual(alignment(Y), calcsize("i")) + self.assertEqual(sizeof(Y), calcsize("3si")) class SI(Structure): _fields_ = [("a", X), ("b", Y)] - self.failUnlessEqual(alignment(SI), max(alignment(Y), alignment(X))) - self.failUnlessEqual(sizeof(SI), calcsize("3s0i 3si 0i")) + self.assertEqual(alignment(SI), max(alignment(Y), alignment(X))) + self.assertEqual(sizeof(SI), calcsize("3s0i 3si 0i")) class IS(Structure): _fields_ = [("b", Y), ("a", X)] - self.failUnlessEqual(alignment(SI), max(alignment(X), alignment(Y))) - self.failUnlessEqual(sizeof(IS), calcsize("3si 3s 0i")) + self.assertEqual(alignment(SI), max(alignment(X), alignment(Y))) + self.assertEqual(sizeof(IS), calcsize("3si 3s 0i")) class XX(Structure): _fields_ = [("a", X), ("b", X)] - self.failUnlessEqual(alignment(XX), alignment(X)) - self.failUnlessEqual(sizeof(XX), calcsize("3s 3s 0s")) + self.assertEqual(alignment(XX), alignment(X)) + self.assertEqual(sizeof(XX), calcsize("3s 3s 0s")) def test_emtpy(self): # I had problems with these @@ -115,15 +115,15 @@ class StructureTestCase(unittest.TestCase): _fields_ = [] # Is this really the correct alignment, or should it be 0? - self.failUnless(alignment(X) == alignment(Y) == 1) - self.failUnless(sizeof(X) == sizeof(Y) == 0) + self.assertTrue(alignment(X) == alignment(Y) == 1) + self.assertTrue(sizeof(X) == sizeof(Y) == 0) class XX(Structure): _fields_ = [("a", X), ("b", X)] - self.failUnlessEqual(alignment(XX), 1) - self.failUnlessEqual(sizeof(XX), 0) + self.assertEqual(alignment(XX), 1) + self.assertEqual(sizeof(XX), 0) def test_fields(self): # test the offset and size attributes of Structure/Unoin fields. @@ -131,11 +131,11 @@ class StructureTestCase(unittest.TestCase): _fields_ = [("x", c_int), ("y", c_char)] - self.failUnlessEqual(X.x.offset, 0) - self.failUnlessEqual(X.x.size, sizeof(c_int)) + self.assertEqual(X.x.offset, 0) + self.assertEqual(X.x.size, sizeof(c_int)) - self.failUnlessEqual(X.y.offset, sizeof(c_int)) - self.failUnlessEqual(X.y.size, sizeof(c_char)) + self.assertEqual(X.y.offset, sizeof(c_int)) + self.assertEqual(X.y.size, sizeof(c_char)) # readonly self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92) @@ -145,11 +145,11 @@ class StructureTestCase(unittest.TestCase): _fields_ = [("x", c_int), ("y", c_char)] - self.failUnlessEqual(X.x.offset, 0) - self.failUnlessEqual(X.x.size, sizeof(c_int)) + self.assertEqual(X.x.offset, 0) + self.assertEqual(X.x.size, sizeof(c_int)) - self.failUnlessEqual(X.y.offset, 0) - self.failUnlessEqual(X.y.size, sizeof(c_char)) + self.assertEqual(X.y.offset, 0) + self.assertEqual(X.y.size, sizeof(c_char)) # readonly self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92) @@ -164,22 +164,22 @@ class StructureTestCase(unittest.TestCase): ("b", c_longlong)] _pack_ = 1 - self.failUnlessEqual(sizeof(X), 9) - self.failUnlessEqual(X.b.offset, 1) + self.assertEqual(sizeof(X), 9) + self.assertEqual(X.b.offset, 1) class X(Structure): _fields_ = [("a", c_byte), ("b", c_longlong)] _pack_ = 2 - self.failUnlessEqual(sizeof(X), 10) - self.failUnlessEqual(X.b.offset, 2) + self.assertEqual(sizeof(X), 10) + self.assertEqual(X.b.offset, 2) class X(Structure): _fields_ = [("a", c_byte), ("b", c_longlong)] _pack_ = 4 - self.failUnlessEqual(sizeof(X), 12) - self.failUnlessEqual(X.b.offset, 4) + self.assertEqual(sizeof(X), 12) + self.assertEqual(X.b.offset, 4) import struct longlong_size = struct.calcsize("q") @@ -190,8 +190,8 @@ class StructureTestCase(unittest.TestCase): ("b", c_longlong)] _pack_ = 8 - self.failUnlessEqual(sizeof(X), longlong_align + longlong_size) - self.failUnlessEqual(X.b.offset, min(8, longlong_align)) + self.assertEqual(sizeof(X), longlong_align + longlong_size) + self.assertEqual(X.b.offset, min(8, longlong_align)) d = {"_fields_": [("a", "b"), @@ -209,9 +209,9 @@ class StructureTestCase(unittest.TestCase): self.assertRaises(TypeError, Person, "Name", "HI") # short enough - self.failUnlessEqual(Person("12345", 5).name, "12345") + self.assertEqual(Person("12345", 5).name, "12345") # exact fit - self.failUnlessEqual(Person("123456", 5).name, "123456") + self.assertEqual(Person("123456", 5).name, "123456") # too long self.assertRaises(ValueError, Person, "1234567", 5) @@ -229,10 +229,10 @@ class StructureTestCase(unittest.TestCase): class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] pt = POINT(1, 2) - self.failUnlessEqual((pt.x, pt.y), (1, 2)) + self.assertEqual((pt.x, pt.y), (1, 2)) pt = POINT(y=2, x=1) - self.failUnlessEqual((pt.x, pt.y), (1, 2)) + self.assertEqual((pt.x, pt.y), (1, 2)) def test_invalid_field_types(self): class POINT(Structure): @@ -244,14 +244,14 @@ class StructureTestCase(unittest.TestCase): _fields_ = [("a", c_int * 4)] # can use tuple to initialize array (but not list!) - self.failUnlessEqual(SomeInts((1, 2)).a[:], [1, 2, 0, 0]) - self.failUnlessEqual(SomeInts((1, 2)).a[::], [1, 2, 0, 0]) - self.failUnlessEqual(SomeInts((1, 2)).a[::-1], [0, 0, 2, 1]) - self.failUnlessEqual(SomeInts((1, 2)).a[::2], [1, 0]) - self.failUnlessEqual(SomeInts((1, 2)).a[1:5:6], [2]) - self.failUnlessEqual(SomeInts((1, 2)).a[6:4:-1], []) - self.failUnlessEqual(SomeInts((1, 2, 3, 4)).a[:], [1, 2, 3, 4]) - self.failUnlessEqual(SomeInts((1, 2, 3, 4)).a[::], [1, 2, 3, 4]) + self.assertEqual(SomeInts((1, 2)).a[:], [1, 2, 0, 0]) + self.assertEqual(SomeInts((1, 2)).a[::], [1, 2, 0, 0]) + self.assertEqual(SomeInts((1, 2)).a[::-1], [0, 0, 2, 1]) + self.assertEqual(SomeInts((1, 2)).a[::2], [1, 0]) + self.assertEqual(SomeInts((1, 2)).a[1:5:6], [2]) + self.assertEqual(SomeInts((1, 2)).a[6:4:-1], []) + self.assertEqual(SomeInts((1, 2, 3, 4)).a[:], [1, 2, 3, 4]) + self.assertEqual(SomeInts((1, 2, 3, 4)).a[::], [1, 2, 3, 4]) # too long # XXX Should raise ValueError?, not RuntimeError self.assertRaises(RuntimeError, SomeInts, (1, 2, 3, 4, 5)) @@ -269,10 +269,10 @@ class StructureTestCase(unittest.TestCase): p = Person("Someone", ("1234", "5678"), 5) - self.failUnlessEqual(p.name, "Someone") - self.failUnlessEqual(p.phone.areacode, "1234") - self.failUnlessEqual(p.phone.number, "5678") - self.failUnlessEqual(p.age, 5) + self.assertEqual(p.name, "Someone") + self.assertEqual(p.phone.areacode, "1234") + self.assertEqual(p.phone.number, "5678") + self.assertEqual(p.age, 5) def test_structures_with_wchar(self): try: @@ -285,12 +285,12 @@ class StructureTestCase(unittest.TestCase): ("age", c_int)] p = PersonW(u"Someone") - self.failUnlessEqual(p.name, "Someone") + self.assertEqual(p.name, "Someone") - self.failUnlessEqual(PersonW(u"1234567890").name, u"1234567890") - self.failUnlessEqual(PersonW(u"12345678901").name, u"12345678901") + self.assertEqual(PersonW(u"1234567890").name, u"1234567890") + self.assertEqual(PersonW(u"12345678901").name, u"12345678901") # exact fit - self.failUnlessEqual(PersonW(u"123456789012").name, u"123456789012") + self.assertEqual(PersonW(u"123456789012").name, u"123456789012") #too long self.assertRaises(ValueError, PersonW, u"1234567890123") @@ -305,24 +305,24 @@ class StructureTestCase(unittest.TestCase): ("age", c_int)] cls, msg = self.get_except(Person, "Someone", (1, 2)) - self.failUnlessEqual(cls, RuntimeError) + self.assertEqual(cls, RuntimeError) # In Python 2.5, Exception is a new-style class, and the repr changed if issubclass(Exception, object): - self.failUnlessEqual(msg, + self.assertEqual(msg, "(Phone) <type 'exceptions.TypeError'>: " "expected string or Unicode object, int found") else: - self.failUnlessEqual(msg, + self.assertEqual(msg, "(Phone) exceptions.TypeError: " "expected string or Unicode object, int found") cls, msg = self.get_except(Person, "Someone", ("a", "b", "c")) - self.failUnlessEqual(cls, RuntimeError) + self.assertEqual(cls, RuntimeError) if issubclass(Exception, object): - self.failUnlessEqual(msg, + self.assertEqual(msg, "(Phone) <type 'exceptions.TypeError'>: too many initializers") else: - self.failUnlessEqual(msg, "(Phone) exceptions.TypeError: too many initializers") + self.assertEqual(msg, "(Phone) exceptions.TypeError: too many initializers") def get_except(self, func, *args): @@ -337,7 +337,7 @@ class StructureTestCase(unittest.TestCase): ## # same as 'class X(Structure): pass' ## # fails, since we need either a _fields_ or a _abstract_ attribute ## cls, msg = self.get_except(meta, "X", (Structure,), {}) -## self.failUnlessEqual((cls, msg), +## self.assertEqual((cls, msg), ## (AttributeError, "class must define a '_fields_' attribute")) def test_abstract_class(self): @@ -345,15 +345,15 @@ class StructureTestCase(unittest.TestCase): _abstract_ = "something" # try 'X()' cls, msg = self.get_except(eval, "X()", locals()) - self.failUnlessEqual((cls, msg), (TypeError, "abstract class")) + self.assertEqual((cls, msg), (TypeError, "abstract class")) def test_methods(self): ## class X(Structure): ## _fields_ = [] - self.failUnless("in_dll" in dir(type(Structure))) - self.failUnless("from_address" in dir(type(Structure))) - self.failUnless("in_dll" in dir(type(Structure))) + self.assertTrue("in_dll" in dir(type(Structure))) + self.assertTrue("from_address" in dir(type(Structure))) + self.assertTrue("in_dll" in dir(type(Structure))) class PointerMemberTestCase(unittest.TestCase): @@ -366,7 +366,7 @@ class PointerMemberTestCase(unittest.TestCase): # We can assign arrays of the correct type s.array = (c_int * 3)(1, 2, 3) items = [s.array[i] for i in range(3)] - self.failUnlessEqual(items, [1, 2, 3]) + self.assertEqual(items, [1, 2, 3]) # The following are bugs, but are included here because the unittests # also describe the current behaviour. @@ -377,14 +377,14 @@ class PointerMemberTestCase(unittest.TestCase): s.array[0] = 42 items = [s.array[i] for i in range(3)] - self.failUnlessEqual(items, [42, 2, 3]) + self.assertEqual(items, [42, 2, 3]) s.array[0] = 1 ## s.array[1] = 42 items = [s.array[i] for i in range(3)] - self.failUnlessEqual(items, [1, 2, 3]) + self.assertEqual(items, [1, 2, 3]) def test_none_to_pointer_fields(self): class S(Structure): @@ -394,7 +394,7 @@ class PointerMemberTestCase(unittest.TestCase): s = S() s.x = 12345678 s.p = None - self.failUnlessEqual(s.x, 12345678) + self.assertEqual(s.x, 12345678) class TestRecursiveStructure(unittest.TestCase): def test_contains_itself(self): @@ -404,7 +404,7 @@ class TestRecursiveStructure(unittest.TestCase): try: Recursive._fields_ = [("next", Recursive)] except AttributeError, details: - self.failUnless("Structure or union cannot contain itself" in + self.assertTrue("Structure or union cannot contain itself" in str(details)) else: self.fail("Structure or union cannot contain itself") @@ -421,7 +421,7 @@ class TestRecursiveStructure(unittest.TestCase): try: Second._fields_ = [("first", First)] except AttributeError, details: - self.failUnless("_fields_ is final" in + self.assertTrue("_fields_ is final" in str(details)) else: self.fail("AttributeError not raised") diff --git a/Lib/ctypes/test/test_unaligned_structures.py b/Lib/ctypes/test/test_unaligned_structures.py index 89343ba..bcacfc8 100644 --- a/Lib/ctypes/test/test_unaligned_structures.py +++ b/Lib/ctypes/test/test_unaligned_structures.py @@ -28,18 +28,18 @@ class TestStructures(unittest.TestCase): def test_native(self): for typ in structures: ## print typ.value - self.failUnlessEqual(typ.value.offset, 1) + self.assertEqual(typ.value.offset, 1) o = typ() o.value = 4 - self.failUnlessEqual(o.value, 4) + self.assertEqual(o.value, 4) def test_swapped(self): for typ in byteswapped_structures: ## print >> sys.stderr, typ.value - self.failUnlessEqual(typ.value.offset, 1) + self.assertEqual(typ.value.offset, 1) o = typ() o.value = 4 - self.failUnlessEqual(o.value, 4) + self.assertEqual(o.value, 4) if __name__ == '__main__': unittest.main() diff --git a/Lib/ctypes/test/test_unicode.py b/Lib/ctypes/test/test_unicode.py index 88d0773..6557479 100644 --- a/Lib/ctypes/test/test_unicode.py +++ b/Lib/ctypes/test/test_unicode.py @@ -23,55 +23,55 @@ else: def test_ascii_strict(self): ctypes.set_conversion_mode("ascii", "strict") # no conversions take place with unicode arguments - self.failUnlessEqual(wcslen(u"abc"), 3) - self.failUnlessEqual(wcslen(u"ab\u2070"), 3) + self.assertEqual(wcslen(u"abc"), 3) + self.assertEqual(wcslen(u"ab\u2070"), 3) # string args are converted - self.failUnlessEqual(wcslen("abc"), 3) - self.failUnlessRaises(ctypes.ArgumentError, wcslen, "abä") + self.assertEqual(wcslen("abc"), 3) + self.assertRaises(ctypes.ArgumentError, wcslen, "abä") def test_ascii_replace(self): ctypes.set_conversion_mode("ascii", "replace") - self.failUnlessEqual(wcslen(u"abc"), 3) - self.failUnlessEqual(wcslen(u"ab\u2070"), 3) - self.failUnlessEqual(wcslen("abc"), 3) - self.failUnlessEqual(wcslen("abä"), 3) + self.assertEqual(wcslen(u"abc"), 3) + self.assertEqual(wcslen(u"ab\u2070"), 3) + self.assertEqual(wcslen("abc"), 3) + self.assertEqual(wcslen("abä"), 3) def test_ascii_ignore(self): ctypes.set_conversion_mode("ascii", "ignore") - self.failUnlessEqual(wcslen(u"abc"), 3) - self.failUnlessEqual(wcslen(u"ab\u2070"), 3) + self.assertEqual(wcslen(u"abc"), 3) + self.assertEqual(wcslen(u"ab\u2070"), 3) # ignore error mode skips non-ascii characters - self.failUnlessEqual(wcslen("abc"), 3) - self.failUnlessEqual(wcslen("äöüß"), 0) + self.assertEqual(wcslen("abc"), 3) + self.assertEqual(wcslen("äöüß"), 0) def test_latin1_strict(self): ctypes.set_conversion_mode("latin-1", "strict") - self.failUnlessEqual(wcslen(u"abc"), 3) - self.failUnlessEqual(wcslen(u"ab\u2070"), 3) - self.failUnlessEqual(wcslen("abc"), 3) - self.failUnlessEqual(wcslen("äöüß"), 4) + self.assertEqual(wcslen(u"abc"), 3) + self.assertEqual(wcslen(u"ab\u2070"), 3) + self.assertEqual(wcslen("abc"), 3) + self.assertEqual(wcslen("äöüß"), 4) def test_buffers(self): ctypes.set_conversion_mode("ascii", "strict") buf = ctypes.create_unicode_buffer("abc") - self.failUnlessEqual(len(buf), 3+1) + self.assertEqual(len(buf), 3+1) ctypes.set_conversion_mode("ascii", "replace") buf = ctypes.create_unicode_buffer("abäöü") - self.failUnlessEqual(buf[:], u"ab\uFFFD\uFFFD\uFFFD\0") - self.failUnlessEqual(buf[::], u"ab\uFFFD\uFFFD\uFFFD\0") - self.failUnlessEqual(buf[::-1], u"\0\uFFFD\uFFFD\uFFFDba") - self.failUnlessEqual(buf[::2], u"a\uFFFD\uFFFD") - self.failUnlessEqual(buf[6:5:-1], u"") + self.assertEqual(buf[:], u"ab\uFFFD\uFFFD\uFFFD\0") + self.assertEqual(buf[::], u"ab\uFFFD\uFFFD\uFFFD\0") + self.assertEqual(buf[::-1], u"\0\uFFFD\uFFFD\uFFFDba") + self.assertEqual(buf[::2], u"a\uFFFD\uFFFD") + self.assertEqual(buf[6:5:-1], u"") ctypes.set_conversion_mode("ascii", "ignore") buf = ctypes.create_unicode_buffer("abäöü") # is that correct? not sure. But with 'ignore', you get what you pay for.. - self.failUnlessEqual(buf[:], u"ab\0\0\0\0") - self.failUnlessEqual(buf[::], u"ab\0\0\0\0") - self.failUnlessEqual(buf[::-1], u"\0\0\0\0ba") - self.failUnlessEqual(buf[::2], u"a\0\0") - self.failUnlessEqual(buf[6:5:-1], u"") + self.assertEqual(buf[:], u"ab\0\0\0\0") + self.assertEqual(buf[::], u"ab\0\0\0\0") + self.assertEqual(buf[::-1], u"\0\0\0\0ba") + self.assertEqual(buf[::2], u"a\0\0") + self.assertEqual(buf[6:5:-1], u"") import _ctypes_test func = ctypes.CDLL(_ctypes_test.__file__)._testfunc_p_p @@ -89,41 +89,41 @@ else: def test_ascii_replace(self): ctypes.set_conversion_mode("ascii", "strict") - self.failUnlessEqual(func("abc"), "abc") - self.failUnlessEqual(func(u"abc"), "abc") + self.assertEqual(func("abc"), "abc") + self.assertEqual(func(u"abc"), "abc") self.assertRaises(ctypes.ArgumentError, func, u"abä") def test_ascii_ignore(self): ctypes.set_conversion_mode("ascii", "ignore") - self.failUnlessEqual(func("abc"), "abc") - self.failUnlessEqual(func(u"abc"), "abc") - self.failUnlessEqual(func(u"äöüß"), "") + self.assertEqual(func("abc"), "abc") + self.assertEqual(func(u"abc"), "abc") + self.assertEqual(func(u"äöüß"), "") def test_ascii_replace(self): ctypes.set_conversion_mode("ascii", "replace") - self.failUnlessEqual(func("abc"), "abc") - self.failUnlessEqual(func(u"abc"), "abc") - self.failUnlessEqual(func(u"äöüß"), "????") + self.assertEqual(func("abc"), "abc") + self.assertEqual(func(u"abc"), "abc") + self.assertEqual(func(u"äöüß"), "????") def test_buffers(self): ctypes.set_conversion_mode("ascii", "strict") buf = ctypes.create_string_buffer(u"abc") - self.failUnlessEqual(len(buf), 3+1) + self.assertEqual(len(buf), 3+1) ctypes.set_conversion_mode("ascii", "replace") buf = ctypes.create_string_buffer(u"abäöü") - self.failUnlessEqual(buf[:], "ab???\0") - self.failUnlessEqual(buf[::], "ab???\0") - self.failUnlessEqual(buf[::-1], "\0???ba") - self.failUnlessEqual(buf[::2], "a??") - self.failUnlessEqual(buf[6:5:-1], "") + self.assertEqual(buf[:], "ab???\0") + self.assertEqual(buf[::], "ab???\0") + self.assertEqual(buf[::-1], "\0???ba") + self.assertEqual(buf[::2], "a??") + self.assertEqual(buf[6:5:-1], "") ctypes.set_conversion_mode("ascii", "ignore") buf = ctypes.create_string_buffer(u"abäöü") # is that correct? not sure. But with 'ignore', you get what you pay for.. - self.failUnlessEqual(buf[:], "ab\0\0\0\0") - self.failUnlessEqual(buf[::], "ab\0\0\0\0") - self.failUnlessEqual(buf[::-1], "\0\0\0\0ba") + self.assertEqual(buf[:], "ab\0\0\0\0") + self.assertEqual(buf[::], "ab\0\0\0\0") + self.assertEqual(buf[::-1], "\0\0\0\0ba") if __name__ == '__main__': unittest.main() diff --git a/Lib/ctypes/test/test_values.py b/Lib/ctypes/test/test_values.py index 7ba3e21..4cbfd4b 100644 --- a/Lib/ctypes/test/test_values.py +++ b/Lib/ctypes/test/test_values.py @@ -13,9 +13,9 @@ class ValuesTestCase(unittest.TestCase): ctdll = CDLL(_ctypes_test.__file__) an_integer = c_int.in_dll(ctdll, "an_integer") x = an_integer.value - self.failUnlessEqual(x, ctdll.get_an_integer()) + self.assertEqual(x, ctdll.get_an_integer()) an_integer.value *= 2 - self.failUnlessEqual(x*2, ctdll.get_an_integer()) + self.assertEqual(x*2, ctdll.get_an_integer()) def test_undefined(self): ctdll = CDLL(_ctypes_test.__file__) @@ -34,11 +34,11 @@ class ValuesTestCase(unittest.TestCase): # docstrings are also removed in the latter case. opt = c_int.in_dll(pydll, "Py_OptimizeFlag").value if __debug__: - self.failUnlessEqual(opt, 0) + self.assertEqual(opt, 0) elif ValuesTestCase.__doc__ is not None: - self.failUnlessEqual(opt, 1) + self.assertEqual(opt, 1) else: - self.failUnlessEqual(opt, 2) + self.assertEqual(opt, 2) def test_frozentable(self): # Python exports a PyImport_FrozenModules symbol. This is a @@ -70,7 +70,7 @@ class ValuesTestCase(unittest.TestCase): expected = [("__hello__", 104), ("__phello__", -104), ("__phello__.spam", 104)] else: expected = [("__hello__", 100), ("__phello__", -100), ("__phello__.spam", 100)] - self.failUnlessEqual(items, expected) + self.assertEqual(items, expected) from ctypes import _pointer_type_cache del _pointer_type_cache[struct_frozen] diff --git a/Lib/ctypes/test/test_varsize_struct.py b/Lib/ctypes/test/test_varsize_struct.py index 06d2323..f409500 100644 --- a/Lib/ctypes/test/test_varsize_struct.py +++ b/Lib/ctypes/test/test_varsize_struct.py @@ -7,44 +7,44 @@ class VarSizeTest(unittest.TestCase): _fields_ = [("item", c_int), ("array", c_int * 1)] - self.failUnlessEqual(sizeof(X), sizeof(c_int) * 2) + self.assertEqual(sizeof(X), sizeof(c_int) * 2) x = X() x.item = 42 x.array[0] = 100 - self.failUnlessEqual(sizeof(x), sizeof(c_int) * 2) + self.assertEqual(sizeof(x), sizeof(c_int) * 2) # make room for one additional item new_size = sizeof(X) + sizeof(c_int) * 1 resize(x, new_size) - self.failUnlessEqual(sizeof(x), new_size) - self.failUnlessEqual((x.item, x.array[0]), (42, 100)) + self.assertEqual(sizeof(x), new_size) + self.assertEqual((x.item, x.array[0]), (42, 100)) # make room for 10 additional items new_size = sizeof(X) + sizeof(c_int) * 9 resize(x, new_size) - self.failUnlessEqual(sizeof(x), new_size) - self.failUnlessEqual((x.item, x.array[0]), (42, 100)) + self.assertEqual(sizeof(x), new_size) + self.assertEqual((x.item, x.array[0]), (42, 100)) # make room for one additional item new_size = sizeof(X) + sizeof(c_int) * 1 resize(x, new_size) - self.failUnlessEqual(sizeof(x), new_size) - self.failUnlessEqual((x.item, x.array[0]), (42, 100)) + self.assertEqual(sizeof(x), new_size) + self.assertEqual((x.item, x.array[0]), (42, 100)) def test_array_invalid_length(self): # cannot create arrays with non-positive size - self.failUnlessRaises(ValueError, lambda: c_int * -1) - self.failUnlessRaises(ValueError, lambda: c_int * -3) + self.assertRaises(ValueError, lambda: c_int * -1) + self.assertRaises(ValueError, lambda: c_int * -3) def test_zerosized_array(self): array = (c_int * 0)() # accessing elements of zero-sized arrays raise IndexError - self.failUnlessRaises(IndexError, array.__setitem__, 0, None) - self.failUnlessRaises(IndexError, array.__getitem__, 0) - self.failUnlessRaises(IndexError, array.__setitem__, 1, None) - self.failUnlessRaises(IndexError, array.__getitem__, 1) - self.failUnlessRaises(IndexError, array.__setitem__, -1, None) - self.failUnlessRaises(IndexError, array.__getitem__, -1) + self.assertRaises(IndexError, array.__setitem__, 0, None) + self.assertRaises(IndexError, array.__getitem__, 0) + self.assertRaises(IndexError, array.__setitem__, 1, None) + self.assertRaises(IndexError, array.__getitem__, 1) + self.assertRaises(IndexError, array.__setitem__, -1, None) + self.assertRaises(IndexError, array.__getitem__, -1) if __name__ == "__main__": unittest.main() diff --git a/Lib/ctypes/test/test_win32.py b/Lib/ctypes/test/test_win32.py index 5067b60..5dedd9f 100644 --- a/Lib/ctypes/test/test_win32.py +++ b/Lib/ctypes/test/test_win32.py @@ -18,7 +18,7 @@ if sys.platform == "win32" and sizeof(c_void_p) == sizeof(c_int): self.assertRaises(ValueError, IsWindow) # This one should succeeed... - self.failUnlessEqual(0, IsWindow(0)) + self.assertEqual(0, IsWindow(0)) # ValueError: Procedure probably called with too many arguments (8 bytes in excess) self.assertRaises(ValueError, IsWindow, 0, 0, 0) @@ -49,13 +49,13 @@ if sys.platform == "win32": class TestWintypes(unittest.TestCase): def test_HWND(self): from ctypes import wintypes - self.failUnlessEqual(sizeof(wintypes.HWND), sizeof(c_void_p)) + self.assertEqual(sizeof(wintypes.HWND), sizeof(c_void_p)) def test_PARAM(self): from ctypes import wintypes - self.failUnlessEqual(sizeof(wintypes.WPARAM), + self.assertEqual(sizeof(wintypes.WPARAM), sizeof(c_void_p)) - self.failUnlessEqual(sizeof(wintypes.LPARAM), + self.assertEqual(sizeof(wintypes.LPARAM), sizeof(c_void_p)) def test_COMError(self): @@ -84,7 +84,7 @@ class Structures(unittest.TestCase): pt = POINT(10, 10) rect = RECT(0, 0, 20, 20) - self.failUnlessEqual(1, dll.PointInRect(byref(rect), pt)) + self.assertEqual(1, dll.PointInRect(byref(rect), pt)) if __name__ == '__main__': unittest.main() diff --git a/Lib/distutils/tests/test_archive_util.py b/Lib/distutils/tests/test_archive_util.py index 29cd271..91bc4e3 100644 --- a/Lib/distutils/tests/test_archive_util.py +++ b/Lib/distutils/tests/test_archive_util.py @@ -47,7 +47,7 @@ class ArchiveUtilTestCase(support.TempdirManager, # check if the compressed tarball was created tarball = base_name + '.tar.gz' - self.assert_(os.path.exists(tarball)) + self.assertTrue(os.path.exists(tarball)) # trying an uncompressed one base_name = os.path.join(tmpdir2, 'archive') @@ -58,7 +58,7 @@ class ArchiveUtilTestCase(support.TempdirManager, finally: os.chdir(old_dir) tarball = base_name + '.tar' - self.assert_(os.path.exists(tarball)) + self.assertTrue(os.path.exists(tarball)) def _tarinfo(self, path): tar = tarfile.open(path) @@ -96,7 +96,7 @@ class ArchiveUtilTestCase(support.TempdirManager, # check if the compressed tarball was created tarball = base_name + '.tar.gz' - self.assert_(os.path.exists(tarball)) + self.assertTrue(os.path.exists(tarball)) # now create another tarball using `tar` tarball2 = os.path.join(tmpdir, 'archive2.tar.gz') @@ -110,7 +110,7 @@ class ArchiveUtilTestCase(support.TempdirManager, finally: os.chdir(old_dir) - self.assert_(os.path.exists(tarball2)) + self.assertTrue(os.path.exists(tarball2)) # let's compare both tarballs self.assertEquals(self._tarinfo(tarball), self._tarinfo(tarball2)) @@ -123,7 +123,7 @@ class ArchiveUtilTestCase(support.TempdirManager, finally: os.chdir(old_dir) tarball = base_name + '.tar' - self.assert_(os.path.exists(tarball)) + self.assertTrue(os.path.exists(tarball)) # now for a dry_run base_name = os.path.join(tmpdir2, 'archive') @@ -134,7 +134,7 @@ class ArchiveUtilTestCase(support.TempdirManager, finally: os.chdir(old_dir) tarball = base_name + '.tar' - self.assert_(os.path.exists(tarball)) + self.assertTrue(os.path.exists(tarball)) @unittest.skipUnless(find_executable('compress'), 'The compress program is required') @@ -151,7 +151,7 @@ class ArchiveUtilTestCase(support.TempdirManager, finally: os.chdir(old_dir) tarball = base_name + '.tar.Z' - self.assert_(os.path.exists(tarball)) + self.assertTrue(os.path.exists(tarball)) self.assertEquals(len(w.warnings), 1) # same test with dry_run @@ -165,7 +165,7 @@ class ArchiveUtilTestCase(support.TempdirManager, dry_run=True) finally: os.chdir(old_dir) - self.assert_(not os.path.exists(tarball)) + self.assertTrue(not os.path.exists(tarball)) self.assertEquals(len(w.warnings), 1) @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run') diff --git a/Lib/distutils/tests/test_bdist_rpm.py b/Lib/distutils/tests/test_bdist_rpm.py index 2d84007..c271567 100644 --- a/Lib/distutils/tests/test_bdist_rpm.py +++ b/Lib/distutils/tests/test_bdist_rpm.py @@ -74,7 +74,7 @@ class BuildRpmTestCase(support.TempdirManager, cmd.run() dist_created = os.listdir(os.path.join(pkg_dir, 'dist')) - self.assert_('foo-0.1-1.noarch.rpm' in dist_created) + self.assertTrue('foo-0.1-1.noarch.rpm' in dist_created) def test_no_optimize_flag(self): @@ -114,7 +114,7 @@ class BuildRpmTestCase(support.TempdirManager, cmd.run() dist_created = os.listdir(os.path.join(pkg_dir, 'dist')) - self.assert_('foo-0.1-1.noarch.rpm' in dist_created) + self.assertTrue('foo-0.1-1.noarch.rpm' in dist_created) os.remove(os.path.join(pkg_dir, 'dist', 'foo-0.1-1.noarch.rpm')) def test_suite(): diff --git a/Lib/distutils/tests/test_bdist_wininst.py b/Lib/distutils/tests/test_bdist_wininst.py index f2cb4fd..9b1ba6d 100644 --- a/Lib/distutils/tests/test_bdist_wininst.py +++ b/Lib/distutils/tests/test_bdist_wininst.py @@ -21,7 +21,7 @@ class BuildWinInstTestCase(support.TempdirManager, # and make sure it finds it and returns its content # no matter what platform we have exe_file = cmd.get_exe_bytes() - self.assert_(len(exe_file) > 10) + self.assertTrue(len(exe_file) > 10) def test_suite(): return unittest.makeSuite(BuildWinInstTestCase) diff --git a/Lib/distutils/tests/test_build_clib.py b/Lib/distutils/tests/test_build_clib.py index 47d85cd..536cd67 100644 --- a/Lib/distutils/tests/test_build_clib.py +++ b/Lib/distutils/tests/test_build_clib.py @@ -135,7 +135,7 @@ class BuildCLibTestCase(support.TempdirManager, cmd.run() # let's check the result - self.assert_('libfoo.a' in os.listdir(build_temp)) + self.assertTrue('libfoo.a' in os.listdir(build_temp)) def test_suite(): return unittest.makeSuite(BuildCLibTestCase) diff --git a/Lib/distutils/tests/test_build_ext.py b/Lib/distutils/tests/test_build_ext.py index 5f28b79..467e90d 100644 --- a/Lib/distutils/tests/test_build_ext.py +++ b/Lib/distutils/tests/test_build_ext.py @@ -73,15 +73,15 @@ class BuildExtTestCase(support.TempdirManager, import xx for attr in ('error', 'foo', 'new', 'roj'): - self.assert_(hasattr(xx, attr)) + self.assertTrue(hasattr(xx, attr)) self.assertEquals(xx.foo(2, 5), 7) self.assertEquals(xx.foo(13,15), 28) self.assertEquals(xx.new().demo(), None) doc = 'This is a template module just for instruction.' self.assertEquals(xx.__doc__, doc) - self.assert_(isinstance(xx.Null(), xx.Null)) - self.assert_(isinstance(xx.Str(), xx.Str)) + self.assertTrue(isinstance(xx.Null(), xx.Null)) + self.assertTrue(isinstance(xx.Str(), xx.Str)) def tearDown(self): # Get everything back to normal @@ -114,7 +114,7 @@ class BuildExtTestCase(support.TempdirManager, _config_vars['Py_ENABLE_SHARED'] = old_var # make sure we get some library dirs under solaris - self.assert_(len(cmd.library_dirs) > 0) + self.assertTrue(len(cmd.library_dirs) > 0) def test_user_site(self): # site.USER_SITE was introduced in 2.6 @@ -128,7 +128,7 @@ class BuildExtTestCase(support.TempdirManager, # making sure the user option is there options = [name for name, short, lable in cmd.user_options] - self.assert_('user' in options) + self.assertTrue('user' in options) # setting a value cmd.user = 1 @@ -144,9 +144,9 @@ class BuildExtTestCase(support.TempdirManager, # see if include_dirs and library_dirs # were set - self.assert_(lib in cmd.library_dirs) - self.assert_(lib in cmd.rpath) - self.assert_(incl in cmd.include_dirs) + self.assertTrue(lib in cmd.library_dirs) + self.assertTrue(lib in cmd.rpath) + self.assertTrue(incl in cmd.include_dirs) def test_optional_extension(self): @@ -175,10 +175,10 @@ class BuildExtTestCase(support.TempdirManager, from distutils import sysconfig py_include = sysconfig.get_python_inc() - self.assert_(py_include in cmd.include_dirs) + self.assertTrue(py_include in cmd.include_dirs) plat_py_include = sysconfig.get_python_inc(plat_specific=1) - self.assert_(plat_py_include in cmd.include_dirs) + self.assertTrue(plat_py_include in cmd.include_dirs) # make sure cmd.libraries is turned into a list # if it's a string @@ -192,7 +192,7 @@ class BuildExtTestCase(support.TempdirManager, cmd = build_ext(dist) cmd.library_dirs = 'my_lib_dir' cmd.finalize_options() - self.assert_('my_lib_dir' in cmd.library_dirs) + self.assertTrue('my_lib_dir' in cmd.library_dirs) # make sure rpath is turned into a list # if it's a list of os.pathsep's paths @@ -257,13 +257,13 @@ class BuildExtTestCase(support.TempdirManager, 'some': 'bar'})] cmd.check_extensions_list(exts) ext = exts[0] - self.assert_(isinstance(ext, Extension)) + self.assertTrue(isinstance(ext, Extension)) # check_extensions_list adds in ext the values passed # when they are in ('include_dirs', 'library_dirs', 'libraries' # 'extra_objects', 'extra_compile_args', 'extra_link_args') self.assertEquals(ext.libraries, 'foo') - self.assert_(not hasattr(ext, 'some')) + self.assertTrue(not hasattr(ext, 'some')) # 'macros' element of build info dict must be 1- or 2-tuple exts = [('foo.bar', {'sources': [''], 'libraries': 'foo', @@ -321,7 +321,7 @@ class BuildExtTestCase(support.TempdirManager, so_file = cmd.get_outputs()[0] finally: os.chdir(old_wd) - self.assert_(os.path.exists(so_file)) + self.assertTrue(os.path.exists(so_file)) self.assertEquals(os.path.splitext(so_file)[-1], sysconfig.get_config_var('SO')) so_dir = os.path.dirname(so_file) @@ -330,7 +330,7 @@ class BuildExtTestCase(support.TempdirManager, cmd.inplace = 0 cmd.run() so_file = cmd.get_outputs()[0] - self.assert_(os.path.exists(so_file)) + self.assertTrue(os.path.exists(so_file)) self.assertEquals(os.path.splitext(so_file)[-1], sysconfig.get_config_var('SO')) so_dir = os.path.dirname(so_file) diff --git a/Lib/distutils/tests/test_build_py.py b/Lib/distutils/tests/test_build_py.py index 54a4ed8..c815d81 100644 --- a/Lib/distutils/tests/test_build_py.py +++ b/Lib/distutils/tests/test_build_py.py @@ -52,9 +52,9 @@ class BuildPyTestCase(support.TempdirManager, self.assertEqual(len(cmd.get_outputs()), 3) pkgdest = os.path.join(destination, "pkg") files = os.listdir(pkgdest) - self.assert_("__init__.py" in files) - self.assert_("__init__.pyc" in files) - self.assert_("README.txt" in files) + self.assertTrue("__init__.py" in files) + self.assertTrue("__init__.pyc" in files) + self.assertTrue("README.txt" in files) def test_empty_package_dir (self): # See SF 1668596/1720897. diff --git a/Lib/distutils/tests/test_build_scripts.py b/Lib/distutils/tests/test_build_scripts.py index b55eb58..b1d2d07 100644 --- a/Lib/distutils/tests/test_build_scripts.py +++ b/Lib/distutils/tests/test_build_scripts.py @@ -16,12 +16,12 @@ class BuildScriptsTestCase(support.TempdirManager, def test_default_settings(self): cmd = self.get_build_scripts_cmd("/foo/bar", []) - self.assert_(not cmd.force) - self.assert_(cmd.build_dir is None) + self.assertTrue(not cmd.force) + self.assertTrue(cmd.build_dir is None) cmd.finalize_options() - self.assert_(cmd.force) + self.assertTrue(cmd.force) self.assertEqual(cmd.build_dir, "/foo/bar") def test_build(self): @@ -37,7 +37,7 @@ class BuildScriptsTestCase(support.TempdirManager, built = os.listdir(target) for name in expected: - self.assert_(name in built) + self.assertTrue(name in built) def get_build_scripts_cmd(self, target, scripts): import sys @@ -100,7 +100,7 @@ class BuildScriptsTestCase(support.TempdirManager, built = os.listdir(target) for name in expected: - self.assert_(name in built) + self.assertTrue(name in built) def test_suite(): return unittest.makeSuite(BuildScriptsTestCase) diff --git a/Lib/distutils/tests/test_clean.py b/Lib/distutils/tests/test_clean.py index 3026032..dbc4ee2 100755 --- a/Lib/distutils/tests/test_clean.py +++ b/Lib/distutils/tests/test_clean.py @@ -35,7 +35,7 @@ class cleanTestCase(support.TempdirManager, # make sure the files where removed for name, path in dirs: - self.assert_(not os.path.exists(path), + self.assertTrue(not os.path.exists(path), '%s was not removed' % path) # let's run the command again (should spit warnings but suceed) diff --git a/Lib/distutils/tests/test_cmd.py b/Lib/distutils/tests/test_cmd.py index 8f2b36f..d6438b5 100644 --- a/Lib/distutils/tests/test_cmd.py +++ b/Lib/distutils/tests/test_cmd.py @@ -70,7 +70,7 @@ class CommandTestCase(unittest.TestCase): cmd.option2 = None cmd.ensure_string('option2', 'xxx') - self.assert_(hasattr(cmd, 'option2')) + self.assertTrue(hasattr(cmd, 'option2')) cmd.option3 = 1 self.assertRaises(DistutilsOptionError, cmd.ensure_string, 'option3') diff --git a/Lib/distutils/tests/test_config.py b/Lib/distutils/tests/test_config.py index fd778d1..6947275 100644 --- a/Lib/distutils/tests/test_config.py +++ b/Lib/distutils/tests/test_config.py @@ -105,9 +105,9 @@ class PyPIRCCommandTestCase(support.TempdirManager, def test_server_empty_registration(self): cmd = self._cmd(self.dist) rc = cmd._get_rc_file() - self.assert_(not os.path.exists(rc)) + self.assertTrue(not os.path.exists(rc)) cmd._store_pypirc('tarek', 'xxx') - self.assert_(os.path.exists(rc)) + self.assertTrue(os.path.exists(rc)) content = open(rc).read() self.assertEquals(content, WANTED) diff --git a/Lib/distutils/tests/test_config_cmd.py b/Lib/distutils/tests/test_config_cmd.py index bacf13a..ef2e7bc 100644 --- a/Lib/distutils/tests/test_config_cmd.py +++ b/Lib/distutils/tests/test_config_cmd.py @@ -73,14 +73,14 @@ class ConfigTestCase(support.LoggingSilencer, self.write_file(f2, 'xxx') for f in (f1, f2): - self.assert_(os.path.exists(f)) + self.assertTrue(os.path.exists(f)) pkg_dir, dist = self.create_dist() cmd = config(dist) cmd._clean(f1, f2) for f in (f1, f2): - self.assert_(not os.path.exists(f)) + self.assertTrue(not os.path.exists(f)) def test_suite(): return unittest.makeSuite(ConfigTestCase) diff --git a/Lib/distutils/tests/test_dist.py b/Lib/distutils/tests/test_dist.py index 7ccdd53..07f392c 100644 --- a/Lib/distutils/tests/test_dist.py +++ b/Lib/distutils/tests/test_dist.py @@ -73,7 +73,7 @@ class DistributionTestCase(support.TempdirManager, self.assertEqual(d.get_command_packages(), ["distutils.command", "foo.bar", "distutils.tests"]) cmd = d.get_command_obj("test_dist") - self.assert_(isinstance(cmd, test_dist)) + self.assertTrue(isinstance(cmd, test_dist)) self.assertEqual(cmd.sample_option, "sometext") def test_command_packages_configfile(self): @@ -204,10 +204,10 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard, "version": "1.0"} dist = Distribution(attrs) meta = self.format_metadata(dist) - self.assert_("Metadata-Version: 1.0" in meta) - self.assert_("provides:" not in meta.lower()) - self.assert_("requires:" not in meta.lower()) - self.assert_("obsoletes:" not in meta.lower()) + self.assertTrue("Metadata-Version: 1.0" in meta) + self.assertTrue("provides:" not in meta.lower()) + self.assertTrue("requires:" not in meta.lower()) + self.assertTrue("obsoletes:" not in meta.lower()) def test_provides(self): attrs = {"name": "package", @@ -219,9 +219,9 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard, self.assertEqual(dist.get_provides(), ["package", "package.sub"]) meta = self.format_metadata(dist) - self.assert_("Metadata-Version: 1.1" in meta) - self.assert_("requires:" not in meta.lower()) - self.assert_("obsoletes:" not in meta.lower()) + self.assertTrue("Metadata-Version: 1.1" in meta) + self.assertTrue("requires:" not in meta.lower()) + self.assertTrue("obsoletes:" not in meta.lower()) def test_provides_illegal(self): self.assertRaises(ValueError, Distribution, @@ -239,11 +239,11 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard, self.assertEqual(dist.get_requires(), ["other", "another (==1.0)"]) meta = self.format_metadata(dist) - self.assert_("Metadata-Version: 1.1" in meta) - self.assert_("provides:" not in meta.lower()) - self.assert_("Requires: other" in meta) - self.assert_("Requires: another (==1.0)" in meta) - self.assert_("obsoletes:" not in meta.lower()) + self.assertTrue("Metadata-Version: 1.1" in meta) + self.assertTrue("provides:" not in meta.lower()) + self.assertTrue("Requires: other" in meta) + self.assertTrue("Requires: another (==1.0)" in meta) + self.assertTrue("obsoletes:" not in meta.lower()) def test_requires_illegal(self): self.assertRaises(ValueError, Distribution, @@ -261,11 +261,11 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard, self.assertEqual(dist.get_obsoletes(), ["other", "another (<1.0)"]) meta = self.format_metadata(dist) - self.assert_("Metadata-Version: 1.1" in meta) - self.assert_("provides:" not in meta.lower()) - self.assert_("requires:" not in meta.lower()) - self.assert_("Obsoletes: other" in meta) - self.assert_("Obsoletes: another (<1.0)" in meta) + self.assertTrue("Metadata-Version: 1.1" in meta) + self.assertTrue("provides:" not in meta.lower()) + self.assertTrue("requires:" not in meta.lower()) + self.assertTrue("Obsoletes: other" in meta) + self.assertTrue("Obsoletes: another (<1.0)" in meta) def test_obsoletes_illegal(self): self.assertRaises(ValueError, Distribution, @@ -299,14 +299,14 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard, if sys.platform in ('linux', 'darwin'): self.environ['HOME'] = temp_dir files = dist.find_config_files() - self.assert_(user_filename in files) + self.assertTrue(user_filename in files) # win32-style if sys.platform == 'win32': # home drive should be found self.environ['HOME'] = temp_dir files = dist.find_config_files() - self.assert_(user_filename in files, + self.assertTrue(user_filename in files, '%r not found in %r' % (user_filename, files)) finally: os.remove(user_filename) @@ -332,7 +332,7 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard, output = [line for line in s.getvalue().split('\n') if line.strip() != ''] - self.assert_(len(output) > 0) + self.assertTrue(len(output) > 0) def test_suite(): suite = unittest.TestSuite() diff --git a/Lib/distutils/tests/test_install.py b/Lib/distutils/tests/test_install.py index 8d7e972..d0ad5ce 100644 --- a/Lib/distutils/tests/test_install.py +++ b/Lib/distutils/tests/test_install.py @@ -88,7 +88,7 @@ class InstallTestCase(support.TempdirManager, def _test_user_site(self): for key in ('nt_user', 'unix_user', 'os2_home'): - self.assert_(key in INSTALL_SCHEMES) + self.assertTrue(key in INSTALL_SCHEMES) dist = Distribution({'name': 'xx'}) cmd = install(dist) @@ -96,24 +96,24 @@ class InstallTestCase(support.TempdirManager, # making sure the user option is there options = [name for name, short, lable in cmd.user_options] - self.assert_('user' in options) + self.assertTrue('user' in options) # setting a value cmd.user = 1 # user base and site shouldn't be created yet - self.assert_(not os.path.exists(self.user_base)) - self.assert_(not os.path.exists(self.user_site)) + self.assertTrue(not os.path.exists(self.user_base)) + self.assertTrue(not os.path.exists(self.user_site)) # let's run finalize cmd.ensure_finalized() # now they should - self.assert_(os.path.exists(self.user_base)) - self.assert_(os.path.exists(self.user_site)) + self.assertTrue(os.path.exists(self.user_base)) + self.assertTrue(os.path.exists(self.user_site)) - self.assert_('userbase' in cmd.config_vars) - self.assert_('usersite' in cmd.config_vars) + self.assertTrue('userbase' in cmd.config_vars) + self.assertTrue('usersite' in cmd.config_vars) def test_handle_extra_path(self): dist = Distribution({'name': 'xx', 'extra_path': 'path,dirs'}) diff --git a/Lib/distutils/tests/test_install_data.py b/Lib/distutils/tests/test_install_data.py index 73c4037..7072136 100644 --- a/Lib/distutils/tests/test_install_data.py +++ b/Lib/distutils/tests/test_install_data.py @@ -35,9 +35,9 @@ class InstallDataTestCase(support.TempdirManager, # let's check the result self.assertEquals(len(cmd.get_outputs()), 2) rtwo = os.path.split(two)[-1] - self.assert_(os.path.exists(os.path.join(inst2, rtwo))) + self.assertTrue(os.path.exists(os.path.join(inst2, rtwo))) rone = os.path.split(one)[-1] - self.assert_(os.path.exists(os.path.join(inst, rone))) + self.assertTrue(os.path.exists(os.path.join(inst, rone))) cmd.outfiles = [] # let's try with warn_dir one @@ -47,8 +47,8 @@ class InstallDataTestCase(support.TempdirManager, # let's check the result self.assertEquals(len(cmd.get_outputs()), 2) - self.assert_(os.path.exists(os.path.join(inst2, rtwo))) - self.assert_(os.path.exists(os.path.join(inst, rone))) + self.assertTrue(os.path.exists(os.path.join(inst2, rtwo))) + self.assertTrue(os.path.exists(os.path.join(inst, rone))) cmd.outfiles = [] # now using root and empty dir @@ -65,8 +65,8 @@ class InstallDataTestCase(support.TempdirManager, # let's check the result self.assertEquals(len(cmd.get_outputs()), 4) - self.assert_(os.path.exists(os.path.join(inst2, rtwo))) - self.assert_(os.path.exists(os.path.join(inst, rone))) + self.assertTrue(os.path.exists(os.path.join(inst2, rtwo))) + self.assertTrue(os.path.exists(os.path.join(inst, rone))) def test_suite(): return unittest.makeSuite(InstallDataTestCase) diff --git a/Lib/distutils/tests/test_install_lib.py b/Lib/distutils/tests/test_install_lib.py index d768166..793b95c 100644 --- a/Lib/distutils/tests/test_install_lib.py +++ b/Lib/distutils/tests/test_install_lib.py @@ -39,8 +39,8 @@ class InstallLibTestCase(support.TempdirManager, f = os.path.join(pkg_dir, 'foo.py') self.write_file(f, '# python file') cmd.byte_compile([f]) - self.assert_(os.path.exists(os.path.join(pkg_dir, 'foo.pyc'))) - self.assert_(os.path.exists(os.path.join(pkg_dir, 'foo.pyo'))) + self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'foo.pyc'))) + self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'foo.pyo'))) def test_get_outputs(self): pkg_dir, dist = self.create_dist() @@ -57,7 +57,7 @@ class InstallLibTestCase(support.TempdirManager, cmd.distribution.script_name = 'setup.py' # get_output should return 4 elements - self.assert_(len(cmd.get_outputs()) >= 2) + self.assertTrue(len(cmd.get_outputs()) >= 2) def test_get_inputs(self): pkg_dir, dist = self.create_dist() diff --git a/Lib/distutils/tests/test_install_scripts.py b/Lib/distutils/tests/test_install_scripts.py index fffa6ef..b7eb625 100644 --- a/Lib/distutils/tests/test_install_scripts.py +++ b/Lib/distutils/tests/test_install_scripts.py @@ -23,15 +23,15 @@ class InstallScriptsTestCase(support.TempdirManager, skip_build=1, ) cmd = install_scripts(dist) - self.assert_(not cmd.force) - self.assert_(not cmd.skip_build) - self.assert_(cmd.build_dir is None) - self.assert_(cmd.install_dir is None) + self.assertTrue(not cmd.force) + self.assertTrue(not cmd.skip_build) + self.assertTrue(cmd.build_dir is None) + self.assertTrue(cmd.install_dir is None) cmd.finalize_options() - self.assert_(cmd.force) - self.assert_(cmd.skip_build) + self.assertTrue(cmd.force) + self.assertTrue(cmd.skip_build) self.assertEqual(cmd.build_dir, "/foo/bar") self.assertEqual(cmd.install_dir, "/splat/funk") @@ -69,7 +69,7 @@ class InstallScriptsTestCase(support.TempdirManager, installed = os.listdir(target) for name in expected: - self.assert_(name in installed) + self.assertTrue(name in installed) def test_suite(): diff --git a/Lib/distutils/tests/test_msvc9compiler.py b/Lib/distutils/tests/test_msvc9compiler.py index 78ce3b7..21242a8 100644 --- a/Lib/distutils/tests/test_msvc9compiler.py +++ b/Lib/distutils/tests/test_msvc9compiler.py @@ -46,7 +46,7 @@ class msvc9compilerTestCase(unittest.TestCase): # windows registeries versions. path = r'Software\Microsoft\Notepad' v = Reg.get_value(path, u"lfitalic") - self.assert_(v in (0, 1)) + self.assertTrue(v in (0, 1)) import _winreg HKCU = _winreg.HKEY_CURRENT_USER @@ -54,7 +54,7 @@ class msvc9compilerTestCase(unittest.TestCase): self.assertEquals(keys, None) keys = Reg.read_keys(HKCU, r'Software\Microsoft') - self.assert_('Notepad' in keys) + self.assertTrue('Notepad' in keys) def test_suite(): return unittest.makeSuite(msvc9compilerTestCase) diff --git a/Lib/distutils/tests/test_register.py b/Lib/distutils/tests/test_register.py index 0c6bf66..ada77a0 100644 --- a/Lib/distutils/tests/test_register.py +++ b/Lib/distutils/tests/test_register.py @@ -96,7 +96,7 @@ class RegisterTestCase(PyPIRCCommandTestCase): cmd = self._get_cmd() # we shouldn't have a .pypirc file yet - self.assert_(not os.path.exists(self.rc)) + self.assertTrue(not os.path.exists(self.rc)) # patching raw_input and getpass.getpass # so register gets happy @@ -115,7 +115,7 @@ class RegisterTestCase(PyPIRCCommandTestCase): del register_module.raw_input # we should have a brand new .pypirc file - self.assert_(os.path.exists(self.rc)) + self.assertTrue(os.path.exists(self.rc)) # with the content similar to WANTED_PYPIRC content = open(self.rc).read() @@ -133,13 +133,13 @@ class RegisterTestCase(PyPIRCCommandTestCase): # let's see what the server received : we should # have 2 similar requests - self.assert_(self.conn.reqs, 2) + self.assertTrue(self.conn.reqs, 2) req1 = dict(self.conn.reqs[0].headers) req2 = dict(self.conn.reqs[1].headers) self.assertEquals(req1['Content-length'], '1374') self.assertEquals(req2['Content-length'], '1374') - self.assert_('xxx' in self.conn.reqs[1].data) + self.assertTrue('xxx' in self.conn.reqs[1].data) def test_password_not_in_file(self): @@ -165,11 +165,11 @@ class RegisterTestCase(PyPIRCCommandTestCase): del register_module.raw_input # we should have send a request - self.assert_(self.conn.reqs, 1) + self.assertTrue(self.conn.reqs, 1) req = self.conn.reqs[0] headers = dict(req.headers) self.assertEquals(headers['Content-length'], '608') - self.assert_('tarek' in req.data) + self.assertTrue('tarek' in req.data) def test_password_reset(self): # this test runs choice 3 @@ -183,11 +183,11 @@ class RegisterTestCase(PyPIRCCommandTestCase): del register_module.raw_input # we should have send a request - self.assert_(self.conn.reqs, 1) + self.assertTrue(self.conn.reqs, 1) req = self.conn.reqs[0] headers = dict(req.headers) self.assertEquals(headers['Content-length'], '290') - self.assert_('tarek' in req.data) + self.assertTrue('tarek' in req.data) def test_strict(self): # testing the script option diff --git a/Lib/distutils/tests/test_sysconfig.py b/Lib/distutils/tests/test_sysconfig.py index 8534881..edc8fd8 100644 --- a/Lib/distutils/tests/test_sysconfig.py +++ b/Lib/distutils/tests/test_sysconfig.py @@ -21,12 +21,12 @@ class SysconfigTestCase(support.EnvironGuard, def test_get_config_h_filename(self): config_h = sysconfig.get_config_h_filename() - self.assert_(os.path.isfile(config_h), config_h) + self.assertTrue(os.path.isfile(config_h), config_h) def test_get_python_lib(self): lib_dir = sysconfig.get_python_lib() # XXX doesn't work on Linux when Python was never installed before - #self.assert_(os.path.isdir(lib_dir), lib_dir) + #self.assertTrue(os.path.isdir(lib_dir), lib_dir) # test for pythonxx.lib? self.assertNotEqual(sysconfig.get_python_lib(), sysconfig.get_python_lib(prefix=TESTFN)) @@ -36,14 +36,14 @@ class SysconfigTestCase(support.EnvironGuard, # This is not much of a test. We make sure Python.h exists # in the directory returned by get_python_inc() but we don't know # it is the correct file. - self.assert_(os.path.isdir(inc_dir), inc_dir) + self.assertTrue(os.path.isdir(inc_dir), inc_dir) python_h = os.path.join(inc_dir, "Python.h") - self.assert_(os.path.isfile(python_h), python_h) + self.assertTrue(os.path.isfile(python_h), python_h) def test_get_config_vars(self): cvars = sysconfig.get_config_vars() - self.assert_(isinstance(cvars, dict)) - self.assert_(cvars) + self.assertTrue(isinstance(cvars, dict)) + self.assertTrue(cvars) def test_customize_compiler(self): diff --git a/Lib/distutils/tests/test_upload.py b/Lib/distutils/tests/test_upload.py index bbcd80d..0d95a09 100644 --- a/Lib/distutils/tests/test_upload.py +++ b/Lib/distutils/tests/test_upload.py @@ -96,11 +96,11 @@ class uploadTestCase(PyPIRCCommandTestCase): # what did we send ? headers = dict(self.last_open.req.headers) self.assertEquals(headers['Content-length'], '2086') - self.assert_(headers['Content-type'].startswith('multipart/form-data')) + self.assertTrue(headers['Content-type'].startswith('multipart/form-data')) self.assertEquals(self.last_open.req.get_method(), 'POST') self.assertEquals(self.last_open.req.get_full_url(), 'http://pypi.python.org/pypi') - self.assert_('xxx' in self.last_open.req.data) + self.assertTrue('xxx' in self.last_open.req.data) def test_suite(): return unittest.makeSuite(uploadTestCase) diff --git a/Lib/distutils/tests/test_util.py b/Lib/distutils/tests/test_util.py index cee7d52..c0acf5f 100644 --- a/Lib/distutils/tests/test_util.py +++ b/Lib/distutils/tests/test_util.py @@ -225,10 +225,10 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase): no = ('n', 'no', 'f', 'false', 'off', '0', 'Off', 'No', 'N') for y in yes: - self.assert_(strtobool(y)) + self.assertTrue(strtobool(y)) for n in no: - self.assert_(not strtobool(n)) + self.assertTrue(not strtobool(n)) def test_rfc822_escape(self): header = 'I am a\npoor\nlonesome\nheader\n' diff --git a/Lib/email/test/test_email.py b/Lib/email/test/test_email.py index f9cc6f0..50d3fb6 100644 --- a/Lib/email/test/test_email.py +++ b/Lib/email/test/test_email.py @@ -50,7 +50,7 @@ def openfile(filename, mode='r'): # Base test class class TestEmailBase(unittest.TestCase): def ndiffAssertEqual(self, first, second): - """Like failUnlessEqual except use ndiff for readable output.""" + """Like assertEqual except use ndiff for readable output.""" if first <> second: sfirst = str(first) ssecond = str(second) @@ -239,12 +239,12 @@ class TestMessageAPI(TestEmailBase): msg['From'] = 'Me' msg['to'] = 'You' # Check for case insensitivity - self.failUnless('from' in msg) - self.failUnless('From' in msg) - self.failUnless('FROM' in msg) - self.failUnless('to' in msg) - self.failUnless('To' in msg) - self.failUnless('TO' in msg) + self.assertTrue('from' in msg) + self.assertTrue('From' in msg) + self.assertTrue('FROM' in msg) + self.assertTrue('to' in msg) + self.assertTrue('To' in msg) + self.assertTrue('TO' in msg) def test_as_string(self): eq = self.assertEqual @@ -266,7 +266,7 @@ class TestMessageAPI(TestEmailBase): eq(text, msg.as_string()) fullrepr = str(msg) lines = fullrepr.split('\n') - self.failUnless(lines[0].startswith('From ')) + self.assertTrue(lines[0].startswith('From ')) eq(text, NL.join(lines[1:])) def test_bad_param(self): @@ -337,10 +337,10 @@ class TestMessageAPI(TestEmailBase): def test_has_key(self): msg = email.message_from_string('Header: exists') - self.failUnless(msg.has_key('header')) - self.failUnless(msg.has_key('Header')) - self.failUnless(msg.has_key('HEADER')) - self.failIf(msg.has_key('headeri')) + self.assertTrue(msg.has_key('header')) + self.assertTrue(msg.has_key('Header')) + self.assertTrue(msg.has_key('HEADER')) + self.assertFalse(msg.has_key('headeri')) def test_set_param(self): eq = self.assertEqual @@ -931,7 +931,7 @@ class TestMIMEAudio(unittest.TestCase): def test_add_header(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue self._au.add_header('Content-Disposition', 'attachment', filename='audiotest.au') eq(self._au['content-disposition'], @@ -974,7 +974,7 @@ class TestMIMEImage(unittest.TestCase): def test_add_header(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue self._im.add_header('Content-Disposition', 'attachment', filename='dingusfish.gif') eq(self._im['content-disposition'], @@ -1001,7 +1001,7 @@ class TestMIMEText(unittest.TestCase): def test_types(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue eq(self._msg.get_content_type(), 'text/plain') eq(self._msg.get_param('charset'), 'us-ascii') missing = [] @@ -1011,7 +1011,7 @@ class TestMIMEText(unittest.TestCase): def test_payload(self): self.assertEqual(self._msg.get_payload(), 'hello there') - self.failUnless(not self._msg.is_multipart()) + self.assertTrue(not self._msg.is_multipart()) def test_charset(self): eq = self.assertEqual @@ -1066,7 +1066,7 @@ This is the dingus fish. def test_hierarchy(self): # convenience eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue raises = self.assertRaises # tests m = self._msg @@ -1380,7 +1380,7 @@ Content-Type: text/plain -- XXXX-- ''') - self.failUnless(msg.is_multipart()) + self.assertTrue(msg.is_multipart()) eq(msg.get_boundary(), ' XXXX') eq(len(msg.get_payload()), 2) @@ -1410,7 +1410,7 @@ class TestNonConformant(TestEmailBase): eq(msg.get_content_subtype(), 'plain') def test_same_boundary_inner_outer(self): - unless = self.failUnless + unless = self.assertTrue msg = self._msgobj('msg_15.txt') # XXX We can probably eventually do better inner = msg.get_payload(0) @@ -1420,7 +1420,7 @@ class TestNonConformant(TestEmailBase): Errors.StartBoundaryNotFoundDefect)) def test_multipart_no_boundary(self): - unless = self.failUnless + unless = self.assertTrue msg = self._msgobj('msg_25.txt') unless(isinstance(msg.get_payload(), str)) self.assertEqual(len(msg.defects), 2) @@ -1478,7 +1478,7 @@ counter to RFC 2822, there's no separating newline here """) def test_lying_multipart(self): - unless = self.failUnless + unless = self.assertTrue msg = self._msgobj('msg_41.txt') unless(hasattr(msg, 'defects')) self.assertEqual(len(msg.defects), 2) @@ -1498,7 +1498,7 @@ counter to RFC 2822, there's no separating newline here # [*] This message is missing its start boundary bad = outer.get_payload(1).get_payload(0) self.assertEqual(len(bad.defects), 1) - self.failUnless(isinstance(bad.defects[0], + self.assertTrue(isinstance(bad.defects[0], Errors.StartBoundaryNotFoundDefect)) def test_first_line_is_continuation_header(self): @@ -1508,7 +1508,7 @@ counter to RFC 2822, there's no separating newline here eq(msg.keys(), []) eq(msg.get_payload(), 'Line 2\nLine 3') eq(len(msg.defects), 1) - self.failUnless(isinstance(msg.defects[0], + self.assertTrue(isinstance(msg.defects[0], Errors.FirstHeaderLineIsContinuationDefect)) eq(msg.defects[0].line, ' Line 1\n') @@ -1576,7 +1576,7 @@ class TestMIMEMessage(TestEmailBase): def test_valid_argument(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue subject = 'A sub-message' m = Message() m['Subject'] = subject @@ -1620,20 +1620,20 @@ Here is the body of the message. def test_parse_message_rfc822(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue msg = self._msgobj('msg_11.txt') eq(msg.get_content_type(), 'message/rfc822') payload = msg.get_payload() unless(isinstance(payload, list)) eq(len(payload), 1) submsg = payload[0] - self.failUnless(isinstance(submsg, Message)) + self.assertTrue(isinstance(submsg, Message)) eq(submsg['subject'], 'An enclosed message') eq(submsg.get_payload(), 'Here is the body of the message.\n') def test_dsn(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue # msg 16 is a Delivery Status Notification, see RFC 1894 msg = self._msgobj('msg_16.txt') eq(msg.get_content_type(), 'multipart/report') @@ -1983,7 +1983,7 @@ class TestIdempotent(TestEmailBase): def test_content_type(self): eq = self.assertEquals - unless = self.failUnless + unless = self.assertTrue # Get a message object and reset the seek pointer for other tests msg, text = self._msgobj('msg_05.txt') eq(msg.get_content_type(), 'multipart/report') @@ -2005,7 +2005,7 @@ class TestIdempotent(TestEmailBase): eq(msg2.get_payload(), 'Yadda yadda yadda\n') msg3 = msg.get_payload(2) eq(msg3.get_content_type(), 'message/rfc822') - self.failUnless(isinstance(msg3, Message)) + self.assertTrue(isinstance(msg3, Message)) payload = msg3.get_payload() unless(isinstance(payload, list)) eq(len(payload), 1) @@ -2015,7 +2015,7 @@ class TestIdempotent(TestEmailBase): def test_parser(self): eq = self.assertEquals - unless = self.failUnless + unless = self.assertTrue msg, text = self._msgobj('msg_06.txt') # Check some of the outer headers eq(msg.get_content_type(), 'message/rfc822') @@ -2025,9 +2025,9 @@ class TestIdempotent(TestEmailBase): unless(isinstance(payload, list)) eq(len(payload), 1) msg1 = payload[0] - self.failUnless(isinstance(msg1, Message)) + self.assertTrue(isinstance(msg1, Message)) eq(msg1.get_content_type(), 'text/plain') - self.failUnless(isinstance(msg1.get_payload(), str)) + self.assertTrue(isinstance(msg1.get_payload(), str)) eq(msg1.get_payload(), '\n') @@ -2064,7 +2064,7 @@ class TestMiscellaneous(TestEmailBase): fp.close() def test_message_from_string_with_class(self): - unless = self.failUnless + unless = self.assertTrue fp = openfile('msg_01.txt') try: text = fp.read() @@ -2087,7 +2087,7 @@ class TestMiscellaneous(TestEmailBase): unless(isinstance(subpart, MyMessage)) def test_message_from_file_with_class(self): - unless = self.failUnless + unless = self.assertTrue # Create a subclass class MyMessage(Message): pass @@ -2229,7 +2229,7 @@ Foo def test_charset_richcomparisons(self): eq = self.assertEqual - ne = self.failIfEqual + ne = self.assertNotEqual cset1 = Charset() cset2 = Charset() eq(cset1, 'us-ascii') @@ -2428,8 +2428,8 @@ class TestParsers(TestEmailBase): eq(msg['from'], 'ppp-request@zzz.org') eq(msg['to'], 'ppp@zzz.org') eq(msg.get_content_type(), 'multipart/mixed') - self.failIf(msg.is_multipart()) - self.failUnless(isinstance(msg.get_payload(), str)) + self.assertFalse(msg.is_multipart()) + self.assertTrue(isinstance(msg.get_payload(), str)) def test_whitespace_continuation(self): eq = self.assertEqual @@ -2648,15 +2648,15 @@ class TestQuopri(unittest.TestCase): def test_header_quopri_check(self): for c in self.hlit: - self.failIf(quopriMIME.header_quopri_check(c)) + self.assertFalse(quopriMIME.header_quopri_check(c)) for c in self.hnon: - self.failUnless(quopriMIME.header_quopri_check(c)) + self.assertTrue(quopriMIME.header_quopri_check(c)) def test_body_quopri_check(self): for c in self.blit: - self.failIf(quopriMIME.body_quopri_check(c)) + self.assertFalse(quopriMIME.body_quopri_check(c)) for c in self.bnon: - self.failUnless(quopriMIME.body_quopri_check(c)) + self.assertTrue(quopriMIME.body_quopri_check(c)) def test_header_quopri_len(self): eq = self.assertEqual @@ -2825,7 +2825,7 @@ class TestHeader(TestEmailBase): h = Header("I am the very model of a modern Major-General; I've information vegetable, animal, and mineral; I know the kings of England, and I quote the fights historical from Marathon to Waterloo, in order categorical; I'm very well acquainted, too, with matters mathematical; I understand equations, both the simple and quadratical; about binomial theorem I'm teeming with a lot o' news, with many cheerful facts about the square of the hypotenuse.", maxlinelen=76) for l in h.encode(splitchars=' ').split('\n '): - self.failUnless(len(l) <= 76) + self.assertTrue(len(l) <= 76) def test_multilingual(self): eq = self.ndiffAssertEqual @@ -3055,7 +3055,7 @@ Content-Type: text/html; NAME*0=file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOC ''' msg = email.message_from_string(m) param = msg.get_param('NAME') - self.failIf(isinstance(param, tuple)) + self.assertFalse(isinstance(param, tuple)) self.assertEqual( param, 'file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm') @@ -3208,7 +3208,7 @@ Content-Type: application/x-foo; name*0=\"Frank's\"; name*1=\" Document\" """ msg = email.message_from_string(m) param = msg.get_param('name') - self.failIf(isinstance(param, tuple)) + self.assertFalse(isinstance(param, tuple)) self.assertEqual(param, "Frank's Document") def test_rfc2231_tick_attack_extended(self): @@ -3232,7 +3232,7 @@ Content-Type: application/x-foo; """ msg = email.message_from_string(m) param = msg.get_param('name') - self.failIf(isinstance(param, tuple)) + self.assertFalse(isinstance(param, tuple)) self.assertEqual(param, "us-ascii'en-us'Frank's Document") def test_rfc2231_no_extended_values(self): diff --git a/Lib/email/test/test_email_renamed.py b/Lib/email/test/test_email_renamed.py index 61fe26e..928d251 100644 --- a/Lib/email/test/test_email_renamed.py +++ b/Lib/email/test/test_email_renamed.py @@ -51,7 +51,7 @@ def openfile(filename, mode='r'): # Base test class class TestEmailBase(unittest.TestCase): def ndiffAssertEqual(self, first, second): - """Like failUnlessEqual except use ndiff for readable output.""" + """Like assertEqual except use ndiff for readable output.""" if first <> second: sfirst = str(first) ssecond = str(second) @@ -227,12 +227,12 @@ class TestMessageAPI(TestEmailBase): msg['From'] = 'Me' msg['to'] = 'You' # Check for case insensitivity - self.failUnless('from' in msg) - self.failUnless('From' in msg) - self.failUnless('FROM' in msg) - self.failUnless('to' in msg) - self.failUnless('To' in msg) - self.failUnless('TO' in msg) + self.assertTrue('from' in msg) + self.assertTrue('From' in msg) + self.assertTrue('FROM' in msg) + self.assertTrue('to' in msg) + self.assertTrue('To' in msg) + self.assertTrue('TO' in msg) def test_as_string(self): eq = self.assertEqual @@ -254,7 +254,7 @@ class TestMessageAPI(TestEmailBase): self.ndiffAssertEqual(text, msg.as_string()) fullrepr = str(msg) lines = fullrepr.split('\n') - self.failUnless(lines[0].startswith('From ')) + self.assertTrue(lines[0].startswith('From ')) eq(text, NL.join(lines[1:])) def test_bad_param(self): @@ -325,10 +325,10 @@ class TestMessageAPI(TestEmailBase): def test_has_key(self): msg = email.message_from_string('Header: exists') - self.failUnless(msg.has_key('header')) - self.failUnless(msg.has_key('Header')) - self.failUnless(msg.has_key('HEADER')) - self.failIf(msg.has_key('headeri')) + self.assertTrue(msg.has_key('header')) + self.assertTrue(msg.has_key('Header')) + self.assertTrue(msg.has_key('HEADER')) + self.assertFalse(msg.has_key('headeri')) def test_set_param(self): eq = self.assertEqual @@ -912,7 +912,7 @@ class TestMIMEAudio(unittest.TestCase): def test_add_header(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue self._au.add_header('Content-Disposition', 'attachment', filename='audiotest.au') eq(self._au['content-disposition'], @@ -955,7 +955,7 @@ class TestMIMEImage(unittest.TestCase): def test_add_header(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue self._im.add_header('Content-Disposition', 'attachment', filename='dingusfish.gif') eq(self._im['content-disposition'], @@ -999,7 +999,7 @@ class TestMIMEText(unittest.TestCase): def test_types(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue eq(self._msg.get_content_type(), 'text/plain') eq(self._msg.get_param('charset'), 'us-ascii') missing = [] @@ -1009,7 +1009,7 @@ class TestMIMEText(unittest.TestCase): def test_payload(self): self.assertEqual(self._msg.get_payload(), 'hello there') - self.failUnless(not self._msg.is_multipart()) + self.assertTrue(not self._msg.is_multipart()) def test_charset(self): eq = self.assertEqual @@ -1064,7 +1064,7 @@ This is the dingus fish. def test_hierarchy(self): # convenience eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue raises = self.assertRaises # tests m = self._msg @@ -1378,7 +1378,7 @@ Content-Type: text/plain -- XXXX-- ''') - self.failUnless(msg.is_multipart()) + self.assertTrue(msg.is_multipart()) eq(msg.get_boundary(), ' XXXX') eq(len(msg.get_payload()), 2) @@ -1408,7 +1408,7 @@ class TestNonConformant(TestEmailBase): eq(msg.get_content_subtype(), 'plain') def test_same_boundary_inner_outer(self): - unless = self.failUnless + unless = self.assertTrue msg = self._msgobj('msg_15.txt') # XXX We can probably eventually do better inner = msg.get_payload(0) @@ -1418,7 +1418,7 @@ class TestNonConformant(TestEmailBase): errors.StartBoundaryNotFoundDefect)) def test_multipart_no_boundary(self): - unless = self.failUnless + unless = self.assertTrue msg = self._msgobj('msg_25.txt') unless(isinstance(msg.get_payload(), str)) self.assertEqual(len(msg.defects), 2) @@ -1476,7 +1476,7 @@ counter to RFC 2822, there's no separating newline here """) def test_lying_multipart(self): - unless = self.failUnless + unless = self.assertTrue msg = self._msgobj('msg_41.txt') unless(hasattr(msg, 'defects')) self.assertEqual(len(msg.defects), 2) @@ -1496,7 +1496,7 @@ counter to RFC 2822, there's no separating newline here # [*] This message is missing its start boundary bad = outer.get_payload(1).get_payload(0) self.assertEqual(len(bad.defects), 1) - self.failUnless(isinstance(bad.defects[0], + self.assertTrue(isinstance(bad.defects[0], errors.StartBoundaryNotFoundDefect)) def test_first_line_is_continuation_header(self): @@ -1506,7 +1506,7 @@ counter to RFC 2822, there's no separating newline here eq(msg.keys(), []) eq(msg.get_payload(), 'Line 2\nLine 3') eq(len(msg.defects), 1) - self.failUnless(isinstance(msg.defects[0], + self.assertTrue(isinstance(msg.defects[0], errors.FirstHeaderLineIsContinuationDefect)) eq(msg.defects[0].line, ' Line 1\n') @@ -1573,7 +1573,7 @@ class TestMIMEMessage(TestEmailBase): def test_valid_argument(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue subject = 'A sub-message' m = Message() m['Subject'] = subject @@ -1617,20 +1617,20 @@ Here is the body of the message. def test_parse_message_rfc822(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue msg = self._msgobj('msg_11.txt') eq(msg.get_content_type(), 'message/rfc822') payload = msg.get_payload() unless(isinstance(payload, list)) eq(len(payload), 1) submsg = payload[0] - self.failUnless(isinstance(submsg, Message)) + self.assertTrue(isinstance(submsg, Message)) eq(submsg['subject'], 'An enclosed message') eq(submsg.get_payload(), 'Here is the body of the message.\n') def test_dsn(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue # msg 16 is a Delivery Status Notification, see RFC 1894 msg = self._msgobj('msg_16.txt') eq(msg.get_content_type(), 'multipart/report') @@ -1977,7 +1977,7 @@ class TestIdempotent(TestEmailBase): def test_content_type(self): eq = self.assertEquals - unless = self.failUnless + unless = self.assertTrue # Get a message object and reset the seek pointer for other tests msg, text = self._msgobj('msg_05.txt') eq(msg.get_content_type(), 'multipart/report') @@ -1999,7 +1999,7 @@ class TestIdempotent(TestEmailBase): eq(msg2.get_payload(), 'Yadda yadda yadda\n') msg3 = msg.get_payload(2) eq(msg3.get_content_type(), 'message/rfc822') - self.failUnless(isinstance(msg3, Message)) + self.assertTrue(isinstance(msg3, Message)) payload = msg3.get_payload() unless(isinstance(payload, list)) eq(len(payload), 1) @@ -2009,7 +2009,7 @@ class TestIdempotent(TestEmailBase): def test_parser(self): eq = self.assertEquals - unless = self.failUnless + unless = self.assertTrue msg, text = self._msgobj('msg_06.txt') # Check some of the outer headers eq(msg.get_content_type(), 'message/rfc822') @@ -2019,9 +2019,9 @@ class TestIdempotent(TestEmailBase): unless(isinstance(payload, list)) eq(len(payload), 1) msg1 = payload[0] - self.failUnless(isinstance(msg1, Message)) + self.assertTrue(isinstance(msg1, Message)) eq(msg1.get_content_type(), 'text/plain') - self.failUnless(isinstance(msg1.get_payload(), str)) + self.assertTrue(isinstance(msg1.get_payload(), str)) eq(msg1.get_payload(), '\n') @@ -2058,7 +2058,7 @@ class TestMiscellaneous(TestEmailBase): fp.close() def test_message_from_string_with_class(self): - unless = self.failUnless + unless = self.assertTrue fp = openfile('msg_01.txt') try: text = fp.read() @@ -2081,7 +2081,7 @@ class TestMiscellaneous(TestEmailBase): unless(isinstance(subpart, MyMessage)) def test_message_from_file_with_class(self): - unless = self.failUnless + unless = self.assertTrue # Create a subclass class MyMessage(Message): pass @@ -2224,7 +2224,7 @@ Foo def test_charset_richcomparisons(self): eq = self.assertEqual - ne = self.failIfEqual + ne = self.assertNotEqual cset1 = Charset() cset2 = Charset() eq(cset1, 'us-ascii') @@ -2423,8 +2423,8 @@ class TestParsers(TestEmailBase): eq(msg['from'], 'ppp-request@zzz.org') eq(msg['to'], 'ppp@zzz.org') eq(msg.get_content_type(), 'multipart/mixed') - self.failIf(msg.is_multipart()) - self.failUnless(isinstance(msg.get_payload(), str)) + self.assertFalse(msg.is_multipart()) + self.assertTrue(isinstance(msg.get_payload(), str)) def test_whitespace_continuation(self): eq = self.assertEqual @@ -2643,15 +2643,15 @@ class TestQuopri(unittest.TestCase): def test_header_quopri_check(self): for c in self.hlit: - self.failIf(quoprimime.header_quopri_check(c)) + self.assertFalse(quoprimime.header_quopri_check(c)) for c in self.hnon: - self.failUnless(quoprimime.header_quopri_check(c)) + self.assertTrue(quoprimime.header_quopri_check(c)) def test_body_quopri_check(self): for c in self.blit: - self.failIf(quoprimime.body_quopri_check(c)) + self.assertFalse(quoprimime.body_quopri_check(c)) for c in self.bnon: - self.failUnless(quoprimime.body_quopri_check(c)) + self.assertTrue(quoprimime.body_quopri_check(c)) def test_header_quopri_len(self): eq = self.assertEqual @@ -2820,7 +2820,7 @@ class TestHeader(TestEmailBase): h = Header("I am the very model of a modern Major-General; I've information vegetable, animal, and mineral; I know the kings of England, and I quote the fights historical from Marathon to Waterloo, in order categorical; I'm very well acquainted, too, with matters mathematical; I understand equations, both the simple and quadratical; about binomial theorem I'm teeming with a lot o' news, with many cheerful facts about the square of the hypotenuse.", maxlinelen=76) for l in h.encode(splitchars=' ').split('\n '): - self.failUnless(len(l) <= 76) + self.assertTrue(len(l) <= 76) def test_multilingual(self): eq = self.ndiffAssertEqual @@ -3050,7 +3050,7 @@ Content-Type: text/html; NAME*0=file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOC ''' msg = email.message_from_string(m) param = msg.get_param('NAME') - self.failIf(isinstance(param, tuple)) + self.assertFalse(isinstance(param, tuple)) self.assertEqual( param, 'file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm') @@ -3203,7 +3203,7 @@ Content-Type: application/x-foo; name*0=\"Frank's\"; name*1=\" Document\" """ msg = email.message_from_string(m) param = msg.get_param('name') - self.failIf(isinstance(param, tuple)) + self.assertFalse(isinstance(param, tuple)) self.assertEqual(param, "Frank's Document") def test_rfc2231_tick_attack_extended(self): @@ -3227,7 +3227,7 @@ Content-Type: application/x-foo; """ msg = email.message_from_string(m) param = msg.get_param('name') - self.failIf(isinstance(param, tuple)) + self.assertFalse(isinstance(param, tuple)) self.assertEqual(param, "us-ascii'en-us'Frank's Document") def test_rfc2231_no_extended_values(self): diff --git a/Lib/json/tests/test_decode.py b/Lib/json/tests/test_decode.py index 7109527..ca8f7b3 100644 --- a/Lib/json/tests/test_decode.py +++ b/Lib/json/tests/test_decode.py @@ -8,12 +8,12 @@ from collections import OrderedDict class TestDecode(TestCase): def test_decimal(self): rval = json.loads('1.1', parse_float=decimal.Decimal) - self.assert_(isinstance(rval, decimal.Decimal)) + self.assertTrue(isinstance(rval, decimal.Decimal)) self.assertEquals(rval, decimal.Decimal('1.1')) def test_float(self): rval = json.loads('1', parse_int=float) - self.assert_(isinstance(rval, float)) + self.assertTrue(isinstance(rval, float)) self.assertEquals(rval, 1.0) def test_decoder_optimizations(self): diff --git a/Lib/json/tests/test_speedups.py b/Lib/json/tests/test_speedups.py index 8ff9a38..3a84ddf 100644 --- a/Lib/json/tests/test_speedups.py +++ b/Lib/json/tests/test_speedups.py @@ -7,9 +7,9 @@ from json import encoder class TestSpeedups(TestCase): def test_scanstring(self): self.assertEquals(decoder.scanstring.__module__, "_json") - self.assert_(decoder.scanstring is decoder.c_scanstring) + self.assertTrue(decoder.scanstring is decoder.c_scanstring) def test_encode_basestring_ascii(self): self.assertEquals(encoder.encode_basestring_ascii.__module__, "_json") - self.assert_(encoder.encode_basestring_ascii is + self.assertTrue(encoder.encode_basestring_ascii is encoder.c_encode_basestring_ascii) diff --git a/Lib/lib-tk/test/test_tkinter/test_text.py b/Lib/lib-tk/test/test_tkinter/test_text.py index 009b8de..e6c08be 100644 --- a/Lib/lib-tk/test/test_tkinter/test_text.py +++ b/Lib/lib-tk/test/test_tkinter/test_text.py @@ -19,18 +19,18 @@ class TextTest(unittest.TestCase): text = self.text # pattern and index are obligatory arguments. - self.failUnlessRaises(Tkinter.TclError, text.search, None, '1.0') - self.failUnlessRaises(Tkinter.TclError, text.search, 'a', None) - self.failUnlessRaises(Tkinter.TclError, text.search, None, None) + self.assertRaises(Tkinter.TclError, text.search, None, '1.0') + self.assertRaises(Tkinter.TclError, text.search, 'a', None) + self.assertRaises(Tkinter.TclError, text.search, None, None) # Invalid text index. - self.failUnlessRaises(Tkinter.TclError, text.search, '', 0) + self.assertRaises(Tkinter.TclError, text.search, '', 0) # Check if we are getting the indices as strings -- you are likely # to get Tcl_Obj under Tk 8.5 if Tkinter doesn't convert it. text.insert('1.0', 'hi-test') - self.failUnlessEqual(text.search('-test', '1.0', 'end'), '1.2') - self.failUnlessEqual(text.search('test', '1.0', 'end'), '1.3') + self.assertEqual(text.search('-test', '1.0', 'end'), '1.2') + self.assertEqual(text.search('test', '1.0', 'end'), '1.3') tests_gui = (TextTest, ) diff --git a/Lib/lib-tk/test/test_ttk/test_extensions.py b/Lib/lib-tk/test/test_ttk/test_extensions.py index 413d225..6e46cbc 100644 --- a/Lib/lib-tk/test/test_ttk/test_extensions.py +++ b/Lib/lib-tk/test/test_ttk/test_extensions.py @@ -22,16 +22,16 @@ class LabeledScaleTest(unittest.TestCase): x = ttk.LabeledScale() var = x._variable._name x.destroy() - self.failUnlessRaises(Tkinter.TclError, x.tk.globalgetvar, var) + self.assertRaises(Tkinter.TclError, x.tk.globalgetvar, var) # manually created variable myvar = Tkinter.DoubleVar() name = myvar._name x = ttk.LabeledScale(variable=myvar) x.destroy() - self.failUnlessEqual(x.tk.globalgetvar(name), myvar.get()) + self.assertEqual(x.tk.globalgetvar(name), myvar.get()) del myvar - self.failUnlessRaises(Tkinter.TclError, x.tk.globalgetvar, name) + self.assertRaises(Tkinter.TclError, x.tk.globalgetvar, name) # checking that the tracing callback is properly removed myvar = Tkinter.IntVar() @@ -45,17 +45,17 @@ class LabeledScaleTest(unittest.TestCase): # it tries calling instance attributes not yet defined. ttk.LabeledScale(variable=myvar) if hasattr(sys, 'last_type'): - self.failIf(sys.last_type == Tkinter.TclError) + self.assertFalse(sys.last_type == Tkinter.TclError) def test_initialization(self): # master passing x = ttk.LabeledScale() - self.failUnlessEqual(x.master, Tkinter._default_root) + self.assertEqual(x.master, Tkinter._default_root) x.destroy() master = Tkinter.Frame() x = ttk.LabeledScale(master) - self.failUnlessEqual(x.master, master) + self.assertEqual(x.master, master) x.destroy() # variable initialization/passing @@ -63,29 +63,29 @@ class LabeledScaleTest(unittest.TestCase): (-1, -1), (sys.maxint + 1, sys.maxint + 1)) for pair in passed_expected: x = ttk.LabeledScale(from_=pair[0]) - self.failUnlessEqual(x.value, pair[1]) + self.assertEqual(x.value, pair[1]) x.destroy() x = ttk.LabeledScale(from_='2.5') - self.failUnlessRaises(ValueError, x._variable.get) + self.assertRaises(ValueError, x._variable.get) x.destroy() x = ttk.LabeledScale(from_=None) - self.failUnlessRaises(ValueError, x._variable.get) + self.assertRaises(ValueError, x._variable.get) x.destroy() # variable should have its default value set to the from_ value myvar = Tkinter.DoubleVar(value=20) x = ttk.LabeledScale(variable=myvar) - self.failUnlessEqual(x.value, 0) + self.assertEqual(x.value, 0) x.destroy() # check that it is really using a DoubleVar x = ttk.LabeledScale(variable=myvar, from_=0.5) - self.failUnlessEqual(x.value, 0.5) - self.failUnlessEqual(x._variable._name, myvar._name) + self.assertEqual(x.value, 0.5) + self.assertEqual(x._variable._name, myvar._name) x.destroy() # widget positionment def check_positions(scale, scale_pos, label, label_pos): - self.failUnlessEqual(scale.pack_info()['side'], scale_pos) - self.failUnlessEqual(label.place_info()['anchor'], label_pos) + self.assertEqual(scale.pack_info()['side'], scale_pos) + self.assertEqual(label.place_info()['anchor'], label_pos) x = ttk.LabeledScale(compound='top') check_positions(x.scale, 'bottom', x.label, 'n') x.destroy() @@ -100,7 +100,7 @@ class LabeledScaleTest(unittest.TestCase): x.destroy() # extra, and invalid, kwargs - self.failUnlessRaises(Tkinter.TclError, ttk.LabeledScale, a='b') + self.assertRaises(Tkinter.TclError, ttk.LabeledScale, a='b') def test_horizontal_range(self): @@ -111,7 +111,7 @@ class LabeledScaleTest(unittest.TestCase): linfo_1 = lscale.label.place_info() prev_xcoord = lscale.scale.coords()[0] - self.failUnlessEqual(prev_xcoord, int(linfo_1['x'])) + self.assertEqual(prev_xcoord, int(linfo_1['x'])) # change range to: from -5 to 5. This should change the x coord of # the scale widget, since 0 is at the middle of the new # range. @@ -120,15 +120,15 @@ class LabeledScaleTest(unittest.TestCase): # at the same time this shouldn't affect test outcome lscale.update() curr_xcoord = lscale.scale.coords()[0] - self.failUnless(prev_xcoord != curr_xcoord) + self.assertTrue(prev_xcoord != curr_xcoord) # the label widget should have been repositioned too linfo_2 = lscale.label.place_info() - self.failUnlessEqual(lscale.label['text'], 0) - self.failUnlessEqual(curr_xcoord, int(linfo_2['x'])) + self.assertEqual(lscale.label['text'], 0) + self.assertEqual(curr_xcoord, int(linfo_2['x'])) # change the range back lscale.scale.configure(from_=0, to=10) - self.failUnless(prev_xcoord != curr_xcoord) - self.failUnlessEqual(prev_xcoord, int(linfo_1['x'])) + self.assertTrue(prev_xcoord != curr_xcoord) + self.assertEqual(prev_xcoord, int(linfo_1['x'])) lscale.destroy() @@ -145,16 +145,16 @@ class LabeledScaleTest(unittest.TestCase): # The following update is needed since the test doesn't use mainloop, # at the same time this shouldn't affect test outcome x.update() - self.failUnlessEqual(x.label['text'], newval) - self.failUnless(x.scale.coords()[0] > curr_xcoord) - self.failUnlessEqual(x.scale.coords()[0], + self.assertEqual(x.label['text'], newval) + self.assertTrue(x.scale.coords()[0] > curr_xcoord) + self.assertEqual(x.scale.coords()[0], int(x.label.place_info()['x'])) # value outside range x.value = x.scale['to'] + 1 # no changes shouldn't happen x.update() - self.failUnlessEqual(x.label['text'], newval) - self.failUnlessEqual(x.scale.coords()[0], + self.assertEqual(x.label['text'], newval) + self.assertEqual(x.scale.coords()[0], int(x.label.place_info()['x'])) x.destroy() @@ -172,7 +172,7 @@ class LabeledScaleTest(unittest.TestCase): x.value = 3 x.update() x.master.wm_geometry("%dx%d" % (width_new, height_new)) - self.failUnlessEqual(int(x.label.place_info()['x']), + self.assertEqual(int(x.label.place_info()['x']), x.scale.coords()[0]) # Reset geometry @@ -197,20 +197,20 @@ class OptionMenuTest(unittest.TestCase): name = var._name optmenu.update_idletasks() optmenu.destroy() - self.failUnlessEqual(optmenu.tk.globalgetvar(name), var.get()) + self.assertEqual(optmenu.tk.globalgetvar(name), var.get()) del var - self.failUnlessRaises(Tkinter.TclError, optmenu.tk.globalgetvar, name) + self.assertRaises(Tkinter.TclError, optmenu.tk.globalgetvar, name) def test_initialization(self): - self.failUnlessRaises(Tkinter.TclError, + self.assertRaises(Tkinter.TclError, ttk.OptionMenu, None, self.textvar, invalid='thing') optmenu = ttk.OptionMenu(None, self.textvar, 'b', 'a', 'b') - self.failUnlessEqual(optmenu._variable.get(), 'b') + self.assertEqual(optmenu._variable.get(), 'b') - self.failUnless(optmenu['menu']) - self.failUnless(optmenu['textvariable']) + self.assertTrue(optmenu['menu']) + self.assertTrue(optmenu['textvariable']) optmenu.destroy() @@ -222,10 +222,10 @@ class OptionMenuTest(unittest.TestCase): found_default = False for i in range(len(items)): value = optmenu['menu'].entrycget(i, 'value') - self.failUnlessEqual(value, items[i]) + self.assertEqual(value, items[i]) if value == default: found_default = True - self.failUnless(found_default) + self.assertTrue(found_default) optmenu.destroy() # default shouldn't be in menu if it is not part of values @@ -238,26 +238,26 @@ class OptionMenuTest(unittest.TestCase): if last == curr: # no more menu entries break - self.failIf(curr == default) + self.assertFalse(curr == default) i += 1 - self.failUnlessEqual(i, len(items)) + self.assertEqual(i, len(items)) # check that variable is updated correctly optmenu.pack() optmenu.wait_visibility() optmenu['menu'].invoke(0) - self.failUnlessEqual(optmenu._variable.get(), items[0]) + self.assertEqual(optmenu._variable.get(), items[0]) # changing to an invalid index shouldn't change the variable - self.failUnlessRaises(Tkinter.TclError, optmenu['menu'].invoke, -1) - self.failUnlessEqual(optmenu._variable.get(), items[0]) + self.assertRaises(Tkinter.TclError, optmenu['menu'].invoke, -1) + self.assertEqual(optmenu._variable.get(), items[0]) optmenu.destroy() # specifying a callback success = [] def cb_test(item): - self.failUnlessEqual(item, items[1]) + self.assertEqual(item, items[1]) success.append(True) optmenu = ttk.OptionMenu(None, self.textvar, 'a', command=cb_test, *items) diff --git a/Lib/lib-tk/test/test_ttk/test_functions.py b/Lib/lib-tk/test/test_ttk/test_functions.py index a1b0854..e516fa4 100644 --- a/Lib/lib-tk/test/test_ttk/test_functions.py +++ b/Lib/lib-tk/test/test_ttk/test_functions.py @@ -28,12 +28,12 @@ class InternalFunctionsTest(unittest.TestCase): def test_format_optdict(self): def check_against(fmt_opts, result): for i in range(0, len(fmt_opts), 2): - self.failUnlessEqual(result.pop(fmt_opts[i]), fmt_opts[i + 1]) + self.assertEqual(result.pop(fmt_opts[i]), fmt_opts[i + 1]) if result: self.fail("result still got elements: %s" % result) # passing an empty dict should return an empty object (tuple here) - self.failIf(ttk._format_optdict({})) + self.assertFalse(ttk._format_optdict({})) # check list formatting check_against( @@ -63,7 +63,7 @@ class InternalFunctionsTest(unittest.TestCase): # check if giving unicode keys is fine check_against(ttk._format_optdict(opts), {u'-αβγ': True, u'-á': False}) # opts should remain unchanged - self.failUnlessEqual(opts, orig_opts) + self.assertEqual(opts, orig_opts) # passing values with spaces inside a tuple/list check_against( @@ -73,113 +73,113 @@ class InternalFunctionsTest(unittest.TestCase): # ignore an option amount_opts = len(ttk._format_optdict(opts, ignore=(u'á'))) / 2 - self.failUnlessEqual(amount_opts, len(opts) - 1) + self.assertEqual(amount_opts, len(opts) - 1) # ignore non-existing options amount_opts = len(ttk._format_optdict(opts, ignore=(u'á', 'b'))) / 2 - self.failUnlessEqual(amount_opts, len(opts) - 1) + self.assertEqual(amount_opts, len(opts) - 1) # ignore every option - self.failIf(ttk._format_optdict(opts, ignore=opts.keys())) + self.assertFalse(ttk._format_optdict(opts, ignore=opts.keys())) def test_format_mapdict(self): opts = {'a': [('b', 'c', 'val'), ('d', 'otherval'), ('', 'single')]} result = ttk._format_mapdict(opts) - self.failUnlessEqual(len(result), len(opts.keys()) * 2) - self.failUnlessEqual(result, ('-a', '{b c} val d otherval {} single')) - self.failUnlessEqual(ttk._format_mapdict(opts, script=True), + self.assertEqual(len(result), len(opts.keys()) * 2) + self.assertEqual(result, ('-a', '{b c} val d otherval {} single')) + self.assertEqual(ttk._format_mapdict(opts, script=True), ('-a', '{{b c} val d otherval {} single}')) - self.failUnlessEqual(ttk._format_mapdict({2: []}), ('-2', '')) + self.assertEqual(ttk._format_mapdict({2: []}), ('-2', '')) opts = {u'üñÃćódè': [(u'á', u'vãl')]} result = ttk._format_mapdict(opts) - self.failUnlessEqual(result, (u'-üñÃćódè', u'á vãl')) + self.assertEqual(result, (u'-üñÃćódè', u'á vãl')) # empty states valid = {'opt': [('', u'', 'hi')]} - self.failUnlessEqual(ttk._format_mapdict(valid), ('-opt', '{ } hi')) + self.assertEqual(ttk._format_mapdict(valid), ('-opt', '{ } hi')) # when passing multiple states, they all must be strings invalid = {'opt': [(1, 2, 'valid val')]} - self.failUnlessRaises(TypeError, ttk._format_mapdict, invalid) + self.assertRaises(TypeError, ttk._format_mapdict, invalid) invalid = {'opt': [([1], '2', 'valid val')]} - self.failUnlessRaises(TypeError, ttk._format_mapdict, invalid) + self.assertRaises(TypeError, ttk._format_mapdict, invalid) # but when passing a single state, it can be anything valid = {'opt': [[1, 'value']]} - self.failUnlessEqual(ttk._format_mapdict(valid), ('-opt', '1 value')) + self.assertEqual(ttk._format_mapdict(valid), ('-opt', '1 value')) # special attention to single states which evalute to False for stateval in (None, 0, False, '', set()): # just some samples valid = {'opt': [(stateval, 'value')]} - self.failUnlessEqual(ttk._format_mapdict(valid), + self.assertEqual(ttk._format_mapdict(valid), ('-opt', '{} value')) # values must be iterable opts = {'a': None} - self.failUnlessRaises(TypeError, ttk._format_mapdict, opts) + self.assertRaises(TypeError, ttk._format_mapdict, opts) # items in the value must have size >= 2 - self.failUnlessRaises(IndexError, ttk._format_mapdict, + self.assertRaises(IndexError, ttk._format_mapdict, {'a': [('invalid', )]}) def test_format_elemcreate(self): - self.failUnless(ttk._format_elemcreate(None), (None, ())) + self.assertTrue(ttk._format_elemcreate(None), (None, ())) ## Testing type = image # image type expects at least an image name, so this should raise # IndexError since it tries to access the index 0 of an empty tuple - self.failUnlessRaises(IndexError, ttk._format_elemcreate, 'image') + self.assertRaises(IndexError, ttk._format_elemcreate, 'image') # don't format returned values as a tcl script # minimum acceptable for image type - self.failUnlessEqual(ttk._format_elemcreate('image', False, 'test'), + self.assertEqual(ttk._format_elemcreate('image', False, 'test'), ("test ", ())) # specifiyng a state spec - self.failUnlessEqual(ttk._format_elemcreate('image', False, 'test', + self.assertEqual(ttk._format_elemcreate('image', False, 'test', ('', 'a')), ("test {} a", ())) # state spec with multiple states - self.failUnlessEqual(ttk._format_elemcreate('image', False, 'test', + self.assertEqual(ttk._format_elemcreate('image', False, 'test', ('a', 'b', 'c')), ("test {a b} c", ())) # state spec and options - self.failUnlessEqual(ttk._format_elemcreate('image', False, 'test', + self.assertEqual(ttk._format_elemcreate('image', False, 'test', ('a', 'b'), a='x', b='y'), ("test a b", ("-a", "x", "-b", "y"))) # format returned values as a tcl script # state spec with multiple states and an option with a multivalue - self.failUnlessEqual(ttk._format_elemcreate('image', True, 'test', + self.assertEqual(ttk._format_elemcreate('image', True, 'test', ('a', 'b', 'c', 'd'), x=[2, 3]), ("{test {a b c} d}", "-x {2 3}")) ## Testing type = vsapi # vsapi type expects at least a class name and a part_id, so this # should raise an ValueError since it tries to get two elements from # an empty tuple - self.failUnlessRaises(ValueError, ttk._format_elemcreate, 'vsapi') + self.assertRaises(ValueError, ttk._format_elemcreate, 'vsapi') # don't format returned values as a tcl script # minimum acceptable for vsapi - self.failUnlessEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b'), + self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b'), ("a b ", ())) # now with a state spec with multiple states - self.failUnlessEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b', + self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b', ('a', 'b', 'c')), ("a b {a b} c", ())) # state spec and option - self.failUnlessEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b', + self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b', ('a', 'b'), opt='x'), ("a b a b", ("-opt", "x"))) # format returned values as a tcl script # state spec with a multivalue and an option - self.failUnlessEqual(ttk._format_elemcreate('vsapi', True, 'a', 'b', + self.assertEqual(ttk._format_elemcreate('vsapi', True, 'a', 'b', ('a', 'b', [1, 2]), opt='x'), ("{a b {a b} {1 2}}", "-opt x")) # Testing type = from # from type expects at least a type name - self.failUnlessRaises(IndexError, ttk._format_elemcreate, 'from') + self.assertRaises(IndexError, ttk._format_elemcreate, 'from') - self.failUnlessEqual(ttk._format_elemcreate('from', False, 'a'), + self.assertEqual(ttk._format_elemcreate('from', False, 'a'), ('a', ())) - self.failUnlessEqual(ttk._format_elemcreate('from', False, 'a', 'b'), + self.assertEqual(ttk._format_elemcreate('from', False, 'a', 'b'), ('a', ('b', ))) - self.failUnlessEqual(ttk._format_elemcreate('from', True, 'a', 'b'), + self.assertEqual(ttk._format_elemcreate('from', True, 'a', 'b'), ('{a}', 'b')) @@ -208,75 +208,75 @@ class InternalFunctionsTest(unittest.TestCase): spaces(2 * indent_size), spaces(indent_size), spaces())) # empty layout - self.failUnlessEqual(ttk._format_layoutlist([])[0], '') + self.assertEqual(ttk._format_layoutlist([])[0], '') # smallest (after an empty one) acceptable layout smallest = ttk._format_layoutlist([('a', None)], indent=0) - self.failUnlessEqual(smallest, + self.assertEqual(smallest, ttk._format_layoutlist([('a', '')], indent=0)) - self.failUnlessEqual(smallest[0], 'a') + self.assertEqual(smallest[0], 'a') # testing indentation levels - self.failUnlessEqual(sample(), sample_expected()) + self.assertEqual(sample(), sample_expected()) for i in range(4): - self.failUnlessEqual(sample(i), sample_expected(i)) - self.failUnlessEqual(sample(i, i), sample_expected(i, i)) + self.assertEqual(sample(i), sample_expected(i)) + self.assertEqual(sample(i, i), sample_expected(i, i)) # invalid layout format, different kind of exceptions will be # raised # plain wrong format - self.failUnlessRaises(ValueError, ttk._format_layoutlist, + self.assertRaises(ValueError, ttk._format_layoutlist, ['bad', 'format']) - self.failUnlessRaises(TypeError, ttk._format_layoutlist, None) + self.assertRaises(TypeError, ttk._format_layoutlist, None) # _format_layoutlist always expects the second item (in every item) # to act like a dict (except when the value evalutes to False). - self.failUnlessRaises(AttributeError, + self.assertRaises(AttributeError, ttk._format_layoutlist, [('a', 'b')]) # bad children formatting - self.failUnlessRaises(ValueError, ttk._format_layoutlist, + self.assertRaises(ValueError, ttk._format_layoutlist, [('name', {'children': {'a': None}})]) def test_script_from_settings(self): # empty options - self.failIf(ttk._script_from_settings({'name': + self.assertFalse(ttk._script_from_settings({'name': {'configure': None, 'map': None, 'element create': None}})) # empty layout - self.failUnlessEqual( + self.assertEqual( ttk._script_from_settings({'name': {'layout': None}}), "ttk::style layout name {\nnull\n}") configdict = {u'αβγ': True, u'á': False} - self.failUnless( + self.assertTrue( ttk._script_from_settings({'name': {'configure': configdict}})) mapdict = {u'üñÃćódè': [(u'á', u'vãl')]} - self.failUnless( + self.assertTrue( ttk._script_from_settings({'name': {'map': mapdict}})) # invalid image element - self.failUnlessRaises(IndexError, + self.assertRaises(IndexError, ttk._script_from_settings, {'name': {'element create': ['image']}}) # minimal valid image - self.failUnless(ttk._script_from_settings({'name': + self.assertTrue(ttk._script_from_settings({'name': {'element create': ['image', 'name']}})) image = {'thing': {'element create': ['image', 'name', ('state1', 'state2', 'val')]}} - self.failUnlessEqual(ttk._script_from_settings(image), + self.assertEqual(ttk._script_from_settings(image), "ttk::style element create thing image {name {state1 state2} val} ") image['thing']['element create'].append({'opt': 30}) - self.failUnlessEqual(ttk._script_from_settings(image), + self.assertEqual(ttk._script_from_settings(image), "ttk::style element create thing image {name {state1 state2} val} " "-opt 30") image['thing']['element create'][-1]['opt'] = [MockTclObj(3), MockTclObj('2m')] - self.failUnlessEqual(ttk._script_from_settings(image), + self.assertEqual(ttk._script_from_settings(image), "ttk::style element create thing image {name {state1 state2} val} " "-opt {3 2m}") @@ -284,28 +284,28 @@ class InternalFunctionsTest(unittest.TestCase): def test_dict_from_tcltuple(self): fakettuple = ('-a', '{1 2 3}', '-something', 'foo') - self.failUnlessEqual(ttk._dict_from_tcltuple(fakettuple, False), + self.assertEqual(ttk._dict_from_tcltuple(fakettuple, False), {'-a': '{1 2 3}', '-something': 'foo'}) - self.failUnlessEqual(ttk._dict_from_tcltuple(fakettuple), + self.assertEqual(ttk._dict_from_tcltuple(fakettuple), {'a': '{1 2 3}', 'something': 'foo'}) # passing a tuple with a single item should return an empty dict, # since it tries to break the tuple by pairs. - self.failIf(ttk._dict_from_tcltuple(('single', ))) + self.assertFalse(ttk._dict_from_tcltuple(('single', ))) sspec = MockStateSpec('a', 'b') - self.failUnlessEqual(ttk._dict_from_tcltuple(('-a', (sspec, 'val'))), + self.assertEqual(ttk._dict_from_tcltuple(('-a', (sspec, 'val'))), {'a': [('a', 'b', 'val')]}) - self.failUnlessEqual(ttk._dict_from_tcltuple((MockTclObj('-padding'), + self.assertEqual(ttk._dict_from_tcltuple((MockTclObj('-padding'), [MockTclObj('1'), 2, MockTclObj('3m')])), {'padding': [1, 2, '3m']}) def test_list_from_statespec(self): def test_it(sspec, value, res_value, states): - self.failUnlessEqual(ttk._list_from_statespec( + self.assertEqual(ttk._list_from_statespec( (sspec, value)), [states + (res_value, )]) states_even = tuple('state%d' % i for i in range(6)) @@ -322,19 +322,19 @@ class InternalFunctionsTest(unittest.TestCase): def test_list_from_layouttuple(self): # empty layout tuple - self.failIf(ttk._list_from_layouttuple(())) + self.assertFalse(ttk._list_from_layouttuple(())) # shortest layout tuple - self.failUnlessEqual(ttk._list_from_layouttuple(('name', )), + self.assertEqual(ttk._list_from_layouttuple(('name', )), [('name', {})]) # not so interesting ltuple sample_ltuple = ('name', '-option', 'value') - self.failUnlessEqual(ttk._list_from_layouttuple(sample_ltuple), + self.assertEqual(ttk._list_from_layouttuple(sample_ltuple), [('name', {'option': 'value'})]) # empty children - self.failUnlessEqual(ttk._list_from_layouttuple( + self.assertEqual(ttk._list_from_layouttuple( ('something', '-children', ())), [('something', {'children': []})] ) @@ -347,7 +347,7 @@ class InternalFunctionsTest(unittest.TestCase): ) ) ) - self.failUnlessEqual(ttk._list_from_layouttuple(ltuple), + self.assertEqual(ttk._list_from_layouttuple(ltuple), [('name', {'option': 'niceone', 'children': [('otherone', {'otheropt': 'othervalue', 'children': [('child', {})] @@ -356,13 +356,13 @@ class InternalFunctionsTest(unittest.TestCase): ) # bad tuples - self.failUnlessRaises(ValueError, ttk._list_from_layouttuple, + self.assertRaises(ValueError, ttk._list_from_layouttuple, ('name', 'no_minus')) - self.failUnlessRaises(ValueError, ttk._list_from_layouttuple, + self.assertRaises(ValueError, ttk._list_from_layouttuple, ('name', 'no_minus', 'value')) - self.failUnlessRaises(ValueError, ttk._list_from_layouttuple, + self.assertRaises(ValueError, ttk._list_from_layouttuple, ('something', '-children')) # no children - self.failUnlessRaises(ValueError, ttk._list_from_layouttuple, + self.assertRaises(ValueError, ttk._list_from_layouttuple, ('something', '-children', 'value')) # invalid children @@ -373,10 +373,10 @@ class InternalFunctionsTest(unittest.TestCase): return (opt, val) options = {'test': None} - self.failUnlessEqual(ttk._val_or_dict(options, func), "test val") + self.assertEqual(ttk._val_or_dict(options, func), "test val") options = {'test': 3} - self.failUnlessEqual(ttk._val_or_dict(options, func), options) + self.assertEqual(ttk._val_or_dict(options, func), options) def test_convert_stringval(self): @@ -385,10 +385,10 @@ class InternalFunctionsTest(unittest.TestCase): (None, 'None') ) for orig, expected in tests: - self.failUnlessEqual(ttk._convert_stringval(orig), expected) + self.assertEqual(ttk._convert_stringval(orig), expected) if sys.getdefaultencoding() == 'ascii': - self.failUnlessRaises(UnicodeDecodeError, + self.assertRaises(UnicodeDecodeError, ttk._convert_stringval, 'á') @@ -396,27 +396,27 @@ class TclObjsToPyTest(unittest.TestCase): def test_unicode(self): adict = {'opt': u'välúè'} - self.failUnlessEqual(ttk.tclobjs_to_py(adict), {'opt': u'välúè'}) + self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': u'välúè'}) adict['opt'] = MockTclObj(adict['opt']) - self.failUnlessEqual(ttk.tclobjs_to_py(adict), {'opt': u'välúè'}) + self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': u'välúè'}) def test_multivalues(self): adict = {'opt': [1, 2, 3, 4]} - self.failUnlessEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 2, 3, 4]}) + self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 2, 3, 4]}) adict['opt'] = [1, 'xm', 3] - self.failUnlessEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 'xm', 3]}) + self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 'xm', 3]}) adict['opt'] = (MockStateSpec('a', 'b'), u'válũè') - self.failUnlessEqual(ttk.tclobjs_to_py(adict), + self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [('a', 'b', u'válũè')]}) - self.failUnlessEqual(ttk.tclobjs_to_py({'x': ['y z']}), + self.assertEqual(ttk.tclobjs_to_py({'x': ['y z']}), {'x': ['y z']}) def test_nosplit(self): - self.failUnlessEqual(ttk.tclobjs_to_py({'text': 'some text'}), + self.assertEqual(ttk.tclobjs_to_py({'text': 'some text'}), {'text': 'some text'}) tests_nogui = (InternalFunctionsTest, TclObjsToPyTest) diff --git a/Lib/lib-tk/test/test_ttk/test_style.py b/Lib/lib-tk/test/test_ttk/test_style.py index ab3554d..630e075 100644 --- a/Lib/lib-tk/test/test_ttk/test_style.py +++ b/Lib/lib-tk/test/test_ttk/test_style.py @@ -16,17 +16,17 @@ class StyleTest(unittest.TestCase): def test_configure(self): style = self.style style.configure('TButton', background='yellow') - self.failUnlessEqual(style.configure('TButton', 'background'), + self.assertEqual(style.configure('TButton', 'background'), 'yellow') - self.failUnless(isinstance(style.configure('TButton'), dict)) + self.assertTrue(isinstance(style.configure('TButton'), dict)) def test_map(self): style = self.style style.map('TButton', background=[('active', 'background', 'blue')]) - self.failUnlessEqual(style.map('TButton', 'background'), + self.assertEqual(style.map('TButton', 'background'), [('active', 'background', 'blue')]) - self.failUnless(isinstance(style.map('TButton'), dict)) + self.assertTrue(isinstance(style.map('TButton'), dict)) def test_lookup(self): @@ -34,38 +34,38 @@ class StyleTest(unittest.TestCase): style.configure('TButton', background='yellow') style.map('TButton', background=[('active', 'background', 'blue')]) - self.failUnlessEqual(style.lookup('TButton', 'background'), 'yellow') - self.failUnlessEqual(style.lookup('TButton', 'background', + self.assertEqual(style.lookup('TButton', 'background'), 'yellow') + self.assertEqual(style.lookup('TButton', 'background', ['active', 'background']), 'blue') - self.failUnlessEqual(style.lookup('TButton', 'optionnotdefined', + self.assertEqual(style.lookup('TButton', 'optionnotdefined', default='iknewit'), 'iknewit') def test_layout(self): style = self.style - self.failUnlessRaises(Tkinter.TclError, style.layout, 'NotALayout') + self.assertRaises(Tkinter.TclError, style.layout, 'NotALayout') tv_style = style.layout('Treeview') # "erase" Treeview layout style.layout('Treeview', '') - self.failUnlessEqual(style.layout('Treeview'), + self.assertEqual(style.layout('Treeview'), [('null', {'sticky': 'nswe'})] ) # restore layout style.layout('Treeview', tv_style) - self.failUnlessEqual(style.layout('Treeview'), tv_style) + self.assertEqual(style.layout('Treeview'), tv_style) # should return a list - self.failUnless(isinstance(style.layout('TButton'), list)) + self.assertTrue(isinstance(style.layout('TButton'), list)) # correct layout, but "option" doesn't exist as option - self.failUnlessRaises(Tkinter.TclError, style.layout, 'Treeview', + self.assertRaises(Tkinter.TclError, style.layout, 'Treeview', [('name', {'option': 'inexistent'})]) def test_theme_use(self): - self.failUnlessRaises(Tkinter.TclError, self.style.theme_use, + self.assertRaises(Tkinter.TclError, self.style.theme_use, 'nonexistingname') curr_theme = self.style.theme_use() @@ -79,8 +79,8 @@ class StyleTest(unittest.TestCase): # just one theme available, can't go on with tests return - self.failIf(curr_theme == new_theme) - self.failIf(new_theme != self.style.theme_use()) + self.assertFalse(curr_theme == new_theme) + self.assertFalse(new_theme != self.style.theme_use()) self.style.theme_use(curr_theme) diff --git a/Lib/lib-tk/test/test_ttk/test_widgets.py b/Lib/lib-tk/test/test_ttk/test_widgets.py index 4f6f44d..6cf040c 100644 --- a/Lib/lib-tk/test/test_ttk/test_widgets.py +++ b/Lib/lib-tk/test/test_ttk/test_widgets.py @@ -24,48 +24,48 @@ class WidgetTest(unittest.TestCase): def test_identify(self): self.widget.update_idletasks() - self.failUnlessEqual(self.widget.identify(5, 5), "label") - self.failUnlessEqual(self.widget.identify(-1, -1), "") + self.assertEqual(self.widget.identify(5, 5), "label") + self.assertEqual(self.widget.identify(-1, -1), "") - self.failUnlessRaises(Tkinter.TclError, self.widget.identify, None, 5) - self.failUnlessRaises(Tkinter.TclError, self.widget.identify, 5, None) - self.failUnlessRaises(Tkinter.TclError, self.widget.identify, 5, '') + self.assertRaises(Tkinter.TclError, self.widget.identify, None, 5) + self.assertRaises(Tkinter.TclError, self.widget.identify, 5, None) + self.assertRaises(Tkinter.TclError, self.widget.identify, 5, '') def test_widget_state(self): # XXX not sure about the portability of all these tests - self.failUnlessEqual(self.widget.state(), ()) - self.failUnlessEqual(self.widget.instate(['!disabled']), True) + self.assertEqual(self.widget.state(), ()) + self.assertEqual(self.widget.instate(['!disabled']), True) # changing from !disabled to disabled - self.failUnlessEqual(self.widget.state(['disabled']), ('!disabled', )) + self.assertEqual(self.widget.state(['disabled']), ('!disabled', )) # no state change - self.failUnlessEqual(self.widget.state(['disabled']), ()) + self.assertEqual(self.widget.state(['disabled']), ()) # change back to !disable but also active - self.failUnlessEqual(self.widget.state(['!disabled', 'active']), + self.assertEqual(self.widget.state(['!disabled', 'active']), ('!active', 'disabled')) # no state changes, again - self.failUnlessEqual(self.widget.state(['!disabled', 'active']), ()) - self.failUnlessEqual(self.widget.state(['active', '!disabled']), ()) + self.assertEqual(self.widget.state(['!disabled', 'active']), ()) + self.assertEqual(self.widget.state(['active', '!disabled']), ()) def test_cb(arg1, **kw): return arg1, kw - self.failUnlessEqual(self.widget.instate(['!disabled'], + self.assertEqual(self.widget.instate(['!disabled'], test_cb, "hi", **{"msg": "there"}), ('hi', {'msg': 'there'})) # attempt to set invalid statespec currstate = self.widget.state() - self.failUnlessRaises(Tkinter.TclError, self.widget.instate, + self.assertRaises(Tkinter.TclError, self.widget.instate, ['badstate']) - self.failUnlessRaises(Tkinter.TclError, self.widget.instate, + self.assertRaises(Tkinter.TclError, self.widget.instate, ['disabled', 'badstate']) # verify that widget didn't change its state - self.failUnlessEqual(currstate, self.widget.state()) + self.assertEqual(currstate, self.widget.state()) # ensuring that passing None as state doesn't modify current state self.widget.state(['active', '!disabled']) - self.failUnlessEqual(self.widget.state(), ('active', )) + self.assertEqual(self.widget.state(), ('active', )) class ButtonTest(unittest.TestCase): @@ -74,7 +74,7 @@ class ButtonTest(unittest.TestCase): success = [] btn = ttk.Button(command=lambda: success.append(1)) btn.invoke() - self.failUnless(success) + self.assertTrue(success) class CheckbuttonTest(unittest.TestCase): @@ -88,21 +88,21 @@ class CheckbuttonTest(unittest.TestCase): cbtn = ttk.Checkbutton(command=cb_test) # the variable automatically created by ttk.Checkbutton is actually # undefined till we invoke the Checkbutton - self.failUnlessEqual(cbtn.state(), ('alternate', )) - self.failUnlessRaises(Tkinter.TclError, cbtn.tk.globalgetvar, + self.assertEqual(cbtn.state(), ('alternate', )) + self.assertRaises(Tkinter.TclError, cbtn.tk.globalgetvar, cbtn['variable']) res = cbtn.invoke() - self.failUnlessEqual(res, "cb test called") - self.failUnlessEqual(cbtn['onvalue'], + self.assertEqual(res, "cb test called") + self.assertEqual(cbtn['onvalue'], cbtn.tk.globalgetvar(cbtn['variable'])) - self.failUnless(success) + self.assertTrue(success) cbtn['command'] = '' res = cbtn.invoke() - self.failUnlessEqual(res, '') - self.failIf(len(success) > 1) - self.failUnlessEqual(cbtn['offvalue'], + self.assertEqual(res, '') + self.assertFalse(len(success) > 1) + self.assertEqual(cbtn['offvalue'], cbtn.tk.globalgetvar(cbtn['variable'])) @@ -138,7 +138,7 @@ class ComboboxTest(unittest.TestCase): self.combo.event_generate('<Return>') self.combo.update() - self.failUnless(success) + self.assertTrue(success) def test_postcommand(self): @@ -149,18 +149,18 @@ class ComboboxTest(unittest.TestCase): self.combo.wait_visibility() self._show_drop_down_listbox() - self.failUnless(success) + self.assertTrue(success) # testing postcommand removal self.combo['postcommand'] = '' self._show_drop_down_listbox() - self.failUnlessEqual(len(success), 1) + self.assertEqual(len(success), 1) def test_values(self): def check_get_current(getval, currval): - self.failUnlessEqual(self.combo.get(), getval) - self.failUnlessEqual(self.combo.current(), currval) + self.assertEqual(self.combo.get(), getval) + self.assertEqual(self.combo.current(), currval) check_get_current('', -1) @@ -182,17 +182,17 @@ class ComboboxTest(unittest.TestCase): # testing values with empty string set through configure self.combo.configure(values=[1, '', 2]) - self.failUnlessEqual(self.combo['values'], ('1', '', '2')) + self.assertEqual(self.combo['values'], ('1', '', '2')) # out of range - self.failUnlessRaises(Tkinter.TclError, self.combo.current, + self.assertRaises(Tkinter.TclError, self.combo.current, len(self.combo['values'])) # it expects an integer (or something that can be converted to int) - self.failUnlessRaises(Tkinter.TclError, self.combo.current, '') + self.assertRaises(Tkinter.TclError, self.combo.current, '') # testing creating combobox with empty string in values combo2 = ttk.Combobox(values=[1, 2, '']) - self.failUnlessEqual(combo2['values'], ('1', '2', '')) + self.assertEqual(combo2['values'], ('1', '2', '')) combo2.destroy() @@ -208,12 +208,12 @@ class EntryTest(unittest.TestCase): def test_bbox(self): - self.failUnlessEqual(len(self.entry.bbox(0)), 4) + self.assertEqual(len(self.entry.bbox(0)), 4) for item in self.entry.bbox(0): - self.failUnless(isinstance(item, int)) + self.assertTrue(isinstance(item, int)) - self.failUnlessRaises(Tkinter.TclError, self.entry.bbox, 'noindex') - self.failUnlessRaises(Tkinter.TclError, self.entry.bbox, None) + self.assertRaises(Tkinter.TclError, self.entry.bbox, 'noindex') + self.assertRaises(Tkinter.TclError, self.entry.bbox, None) def test_identify(self): @@ -221,12 +221,12 @@ class EntryTest(unittest.TestCase): self.entry.wait_visibility() self.entry.update_idletasks() - self.failUnlessEqual(self.entry.identify(5, 5), "textarea") - self.failUnlessEqual(self.entry.identify(-1, -1), "") + self.assertEqual(self.entry.identify(5, 5), "textarea") + self.assertEqual(self.entry.identify(-1, -1), "") - self.failUnlessRaises(Tkinter.TclError, self.entry.identify, None, 5) - self.failUnlessRaises(Tkinter.TclError, self.entry.identify, 5, None) - self.failUnlessRaises(Tkinter.TclError, self.entry.identify, 5, '') + self.assertRaises(Tkinter.TclError, self.entry.identify, None, 5) + self.assertRaises(Tkinter.TclError, self.entry.identify, 5, None) + self.assertRaises(Tkinter.TclError, self.entry.identify, 5, '') def test_validation_options(self): @@ -238,23 +238,23 @@ class EntryTest(unittest.TestCase): self.entry['invalidcommand'] = test_invalid self.entry.validate() - self.failUnless(success) + self.assertTrue(success) self.entry['invalidcommand'] = '' self.entry.validate() - self.failUnlessEqual(len(success), 1) + self.assertEqual(len(success), 1) self.entry['invalidcommand'] = test_invalid self.entry['validatecommand'] = lambda: True self.entry.validate() - self.failUnlessEqual(len(success), 1) + self.assertEqual(len(success), 1) self.entry['validatecommand'] = '' self.entry.validate() - self.failUnlessEqual(len(success), 1) + self.assertEqual(len(success), 1) self.entry['validatecommand'] = True - self.failUnlessRaises(Tkinter.TclError, self.entry.validate) + self.assertRaises(Tkinter.TclError, self.entry.validate) def test_validation(self): @@ -271,8 +271,8 @@ class EntryTest(unittest.TestCase): self.entry.insert('end', 1) self.entry.insert('end', 'a') - self.failUnlessEqual(validation, [False, True]) - self.failUnlessEqual(self.entry.get(), 'a') + self.assertEqual(validation, [False, True]) + self.assertEqual(self.entry.get(), 'a') def test_revalidation(self): @@ -285,19 +285,19 @@ class EntryTest(unittest.TestCase): self.entry['validatecommand'] = self.entry.register(validate), '%P' self.entry.insert('end', 'avocado') - self.failUnlessEqual(self.entry.validate(), True) - self.failUnlessEqual(self.entry.state(), ()) + self.assertEqual(self.entry.validate(), True) + self.assertEqual(self.entry.state(), ()) self.entry.delete(0, 'end') - self.failUnlessEqual(self.entry.get(), '') + self.assertEqual(self.entry.get(), '') self.entry.insert('end', 'a1b') - self.failUnlessEqual(self.entry.validate(), False) - self.failUnlessEqual(self.entry.state(), ('invalid', )) + self.assertEqual(self.entry.validate(), False) + self.assertEqual(self.entry.state(), ('invalid', )) self.entry.delete(1) - self.failUnlessEqual(self.entry.validate(), True) - self.failUnlessEqual(self.entry.state(), ()) + self.assertEqual(self.entry.validate(), True) + self.assertEqual(self.entry.state(), ()) class PanedwindowTest(unittest.TestCase): @@ -315,108 +315,108 @@ class PanedwindowTest(unittest.TestCase): # attempt to add a child that is not a direct child of the paned window label = ttk.Label(self.paned) child = ttk.Label(label) - self.failUnlessRaises(Tkinter.TclError, self.paned.add, child) + self.assertRaises(Tkinter.TclError, self.paned.add, child) label.destroy() child.destroy() # another attempt label = ttk.Label() child = ttk.Label(label) - self.failUnlessRaises(Tkinter.TclError, self.paned.add, child) + self.assertRaises(Tkinter.TclError, self.paned.add, child) child.destroy() label.destroy() good_child = ttk.Label() self.paned.add(good_child) # re-adding a child is not accepted - self.failUnlessRaises(Tkinter.TclError, self.paned.add, good_child) + self.assertRaises(Tkinter.TclError, self.paned.add, good_child) other_child = ttk.Label(self.paned) self.paned.add(other_child) - self.failUnlessEqual(self.paned.pane(0), self.paned.pane(1)) - self.failUnlessRaises(Tkinter.TclError, self.paned.pane, 2) + self.assertEqual(self.paned.pane(0), self.paned.pane(1)) + self.assertRaises(Tkinter.TclError, self.paned.pane, 2) good_child.destroy() other_child.destroy() - self.failUnlessRaises(Tkinter.TclError, self.paned.pane, 0) + self.assertRaises(Tkinter.TclError, self.paned.pane, 0) def test_forget(self): - self.failUnlessRaises(Tkinter.TclError, self.paned.forget, None) - self.failUnlessRaises(Tkinter.TclError, self.paned.forget, 0) + self.assertRaises(Tkinter.TclError, self.paned.forget, None) + self.assertRaises(Tkinter.TclError, self.paned.forget, 0) self.paned.add(ttk.Label()) self.paned.forget(0) - self.failUnlessRaises(Tkinter.TclError, self.paned.forget, 0) + self.assertRaises(Tkinter.TclError, self.paned.forget, 0) def test_insert(self): - self.failUnlessRaises(Tkinter.TclError, self.paned.insert, None, 0) - self.failUnlessRaises(Tkinter.TclError, self.paned.insert, 0, None) - self.failUnlessRaises(Tkinter.TclError, self.paned.insert, 0, 0) + self.assertRaises(Tkinter.TclError, self.paned.insert, None, 0) + self.assertRaises(Tkinter.TclError, self.paned.insert, 0, None) + self.assertRaises(Tkinter.TclError, self.paned.insert, 0, 0) child = ttk.Label() child2 = ttk.Label() child3 = ttk.Label() - self.failUnlessRaises(Tkinter.TclError, self.paned.insert, 0, child) + self.assertRaises(Tkinter.TclError, self.paned.insert, 0, child) self.paned.insert('end', child2) self.paned.insert(0, child) - self.failUnlessEqual(self.paned.panes(), (str(child), str(child2))) + self.assertEqual(self.paned.panes(), (str(child), str(child2))) self.paned.insert(0, child2) - self.failUnlessEqual(self.paned.panes(), (str(child2), str(child))) + self.assertEqual(self.paned.panes(), (str(child2), str(child))) self.paned.insert('end', child3) - self.failUnlessEqual(self.paned.panes(), + self.assertEqual(self.paned.panes(), (str(child2), str(child), str(child3))) # reinserting a child should move it to its current position panes = self.paned.panes() self.paned.insert('end', child3) - self.failUnlessEqual(panes, self.paned.panes()) + self.assertEqual(panes, self.paned.panes()) # moving child3 to child2 position should result in child2 ending up # in previous child position and child ending up in previous child3 # position self.paned.insert(child2, child3) - self.failUnlessEqual(self.paned.panes(), + self.assertEqual(self.paned.panes(), (str(child3), str(child2), str(child))) def test_pane(self): - self.failUnlessRaises(Tkinter.TclError, self.paned.pane, 0) + self.assertRaises(Tkinter.TclError, self.paned.pane, 0) child = ttk.Label() self.paned.add(child) - self.failUnless(isinstance(self.paned.pane(0), dict)) - self.failUnlessEqual(self.paned.pane(0, weight=None), 0) + self.assertTrue(isinstance(self.paned.pane(0), dict)) + self.assertEqual(self.paned.pane(0, weight=None), 0) # newer form for querying a single option - self.failUnlessEqual(self.paned.pane(0, 'weight'), 0) - self.failUnlessEqual(self.paned.pane(0), self.paned.pane(str(child))) + self.assertEqual(self.paned.pane(0, 'weight'), 0) + self.assertEqual(self.paned.pane(0), self.paned.pane(str(child))) - self.failUnlessRaises(Tkinter.TclError, self.paned.pane, 0, + self.assertRaises(Tkinter.TclError, self.paned.pane, 0, badoption='somevalue') def test_sashpos(self): - self.failUnlessRaises(Tkinter.TclError, self.paned.sashpos, None) - self.failUnlessRaises(Tkinter.TclError, self.paned.sashpos, '') - self.failUnlessRaises(Tkinter.TclError, self.paned.sashpos, 0) + self.assertRaises(Tkinter.TclError, self.paned.sashpos, None) + self.assertRaises(Tkinter.TclError, self.paned.sashpos, '') + self.assertRaises(Tkinter.TclError, self.paned.sashpos, 0) child = ttk.Label(self.paned, text='a') self.paned.add(child, weight=1) - self.failUnlessRaises(Tkinter.TclError, self.paned.sashpos, 0) + self.assertRaises(Tkinter.TclError, self.paned.sashpos, 0) child2 = ttk.Label(self.paned, text='b') self.paned.add(child2) - self.failUnlessRaises(Tkinter.TclError, self.paned.sashpos, 1) + self.assertRaises(Tkinter.TclError, self.paned.sashpos, 1) self.paned.pack(expand=True, fill='both') self.paned.wait_visibility() curr_pos = self.paned.sashpos(0) self.paned.sashpos(0, 1000) - self.failUnless(curr_pos != self.paned.sashpos(0)) - self.failUnless(isinstance(self.paned.sashpos(0), int)) + self.assertTrue(curr_pos != self.paned.sashpos(0)) + self.assertTrue(isinstance(self.paned.sashpos(0), int)) class RadiobuttonTest(unittest.TestCase): @@ -432,21 +432,21 @@ class RadiobuttonTest(unittest.TestCase): cbtn2 = ttk.Radiobutton(command=cb_test, variable=myvar, value=1) res = cbtn.invoke() - self.failUnlessEqual(res, "cb test called") - self.failUnlessEqual(cbtn['value'], myvar.get()) - self.failUnlessEqual(myvar.get(), + self.assertEqual(res, "cb test called") + self.assertEqual(cbtn['value'], myvar.get()) + self.assertEqual(myvar.get(), cbtn.tk.globalgetvar(cbtn['variable'])) - self.failUnless(success) + self.assertTrue(success) cbtn2['command'] = '' res = cbtn2.invoke() - self.failUnlessEqual(res, '') - self.failIf(len(success) > 1) - self.failUnlessEqual(cbtn2['value'], myvar.get()) - self.failUnlessEqual(myvar.get(), + self.assertEqual(res, '') + self.assertFalse(len(success) > 1) + self.assertEqual(cbtn2['value'], myvar.get()) + self.assertEqual(myvar.get(), cbtn.tk.globalgetvar(cbtn['variable'])) - self.failUnlessEqual(str(cbtn['variable']), str(cbtn2['variable'])) + self.assertEqual(str(cbtn['variable']), str(cbtn2['variable'])) @@ -472,27 +472,27 @@ class ScaleTest(unittest.TestCase): self.scale['from_'] = 10 self.scale['to'] = 3 - self.failIf(failure) + self.assertFalse(failure) failure = [1, 1, 1] self.scale.configure(from_=2, to=5) self.scale.configure(from_=0, to=-2) self.scale.configure(to=10) - self.failIf(failure) + self.assertFalse(failure) def test_get(self): scale_width = self.scale.winfo_width() - self.failUnlessEqual(self.scale.get(scale_width, 0), self.scale['to']) + self.assertEqual(self.scale.get(scale_width, 0), self.scale['to']) - self.failUnlessEqual(self.scale.get(0, 0), self.scale['from']) - self.failUnlessEqual(self.scale.get(), self.scale['value']) + self.assertEqual(self.scale.get(0, 0), self.scale['from']) + self.assertEqual(self.scale.get(), self.scale['value']) self.scale['value'] = 30 - self.failUnlessEqual(self.scale.get(), self.scale['value']) + self.assertEqual(self.scale.get(), self.scale['value']) - self.failUnlessRaises(Tkinter.TclError, self.scale.get, '', 0) - self.failUnlessRaises(Tkinter.TclError, self.scale.get, 0, '') + self.assertRaises(Tkinter.TclError, self.scale.get, '', 0) + self.assertRaises(Tkinter.TclError, self.scale.get, 0, '') def test_set(self): @@ -500,30 +500,30 @@ class ScaleTest(unittest.TestCase): max = self.scale['to'] new_max = max + 10 self.scale.set(new_max) - self.failUnlessEqual(self.scale.get(), max) + self.assertEqual(self.scale.get(), max) min = self.scale['from'] self.scale.set(min - 1) - self.failUnlessEqual(self.scale.get(), min) + self.assertEqual(self.scale.get(), min) # changing directly the variable doesn't impose this limitation tho var = Tkinter.DoubleVar() self.scale['variable'] = var var.set(max + 5) - self.failUnlessEqual(self.scale.get(), var.get()) - self.failUnlessEqual(self.scale.get(), max + 5) + self.assertEqual(self.scale.get(), var.get()) + self.assertEqual(self.scale.get(), max + 5) del var # the same happens with the value option self.scale['value'] = max + 10 - self.failUnlessEqual(self.scale.get(), max + 10) - self.failUnlessEqual(self.scale.get(), self.scale['value']) + self.assertEqual(self.scale.get(), max + 10) + self.assertEqual(self.scale.get(), self.scale['value']) # nevertheless, note that the max/min values we can get specifying # x, y coords are the ones according to the current range - self.failUnlessEqual(self.scale.get(0, 0), min) - self.failUnlessEqual(self.scale.get(self.scale.winfo_width(), 0), max) + self.assertEqual(self.scale.get(0, 0), min) + self.assertEqual(self.scale.get(self.scale.winfo_width(), 0), max) - self.failUnlessRaises(Tkinter.TclError, self.scale.set, None) + self.assertRaises(Tkinter.TclError, self.scale.set, None) class NotebookTest(unittest.TestCase): @@ -546,18 +546,18 @@ class NotebookTest(unittest.TestCase): def test_tab_identifiers(self): self.nb.forget(0) self.nb.hide(self.child2) - self.failUnlessRaises(Tkinter.TclError, self.nb.tab, self.child1) - self.failUnlessEqual(self.nb.index('end'), 1) + self.assertRaises(Tkinter.TclError, self.nb.tab, self.child1) + self.assertEqual(self.nb.index('end'), 1) self.nb.add(self.child2) - self.failUnlessEqual(self.nb.index('end'), 1) + self.assertEqual(self.nb.index('end'), 1) self.nb.select(self.child2) - self.failUnless(self.nb.tab('current')) + self.assertTrue(self.nb.tab('current')) self.nb.add(self.child1, text='a') self.nb.pack() self.nb.wait_visibility() - self.failUnlessEqual(self.nb.tab('@5,5'), self.nb.tab('current')) + self.assertEqual(self.nb.tab('@5,5'), self.nb.tab('current')) for i in range(5, 100, 5): if self.nb.tab('@%d, 5' % i, text=None) == 'a': @@ -567,17 +567,17 @@ class NotebookTest(unittest.TestCase): def test_add_and_hidden(self): - self.failUnlessRaises(Tkinter.TclError, self.nb.hide, -1) - self.failUnlessRaises(Tkinter.TclError, self.nb.hide, 'hi') - self.failUnlessRaises(Tkinter.TclError, self.nb.hide, None) - self.failUnlessRaises(Tkinter.TclError, self.nb.add, None) - self.failUnlessRaises(Tkinter.TclError, self.nb.add, ttk.Label(), + self.assertRaises(Tkinter.TclError, self.nb.hide, -1) + self.assertRaises(Tkinter.TclError, self.nb.hide, 'hi') + self.assertRaises(Tkinter.TclError, self.nb.hide, None) + self.assertRaises(Tkinter.TclError, self.nb.add, None) + self.assertRaises(Tkinter.TclError, self.nb.add, ttk.Label(), unknown='option') tabs = self.nb.tabs() self.nb.hide(self.child1) self.nb.add(self.child1) - self.failUnlessEqual(self.nb.tabs(), tabs) + self.assertEqual(self.nb.tabs(), tabs) child = ttk.Label() self.nb.add(child, text='c') @@ -588,70 +588,70 @@ class NotebookTest(unittest.TestCase): child2_index = self.nb.index(self.child2) self.nb.hide(self.child2) self.nb.add(self.child2) - self.failUnlessEqual(self.nb.tabs(), tabs) - self.failUnlessEqual(self.nb.index(self.child2), child2_index) - self.failUnless(str(self.child2) == self.nb.tabs()[child2_index]) + self.assertEqual(self.nb.tabs(), tabs) + self.assertEqual(self.nb.index(self.child2), child2_index) + self.assertTrue(str(self.child2) == self.nb.tabs()[child2_index]) # but the tab next to it (not hidden) is the one selected now - self.failUnlessEqual(self.nb.index('current'), curr + 1) + self.assertEqual(self.nb.index('current'), curr + 1) def test_forget(self): - self.failUnlessRaises(Tkinter.TclError, self.nb.forget, -1) - self.failUnlessRaises(Tkinter.TclError, self.nb.forget, 'hi') - self.failUnlessRaises(Tkinter.TclError, self.nb.forget, None) + self.assertRaises(Tkinter.TclError, self.nb.forget, -1) + self.assertRaises(Tkinter.TclError, self.nb.forget, 'hi') + self.assertRaises(Tkinter.TclError, self.nb.forget, None) tabs = self.nb.tabs() child1_index = self.nb.index(self.child1) self.nb.forget(self.child1) - self.failIf(str(self.child1) in self.nb.tabs()) - self.failUnlessEqual(len(tabs) - 1, len(self.nb.tabs())) + self.assertFalse(str(self.child1) in self.nb.tabs()) + self.assertEqual(len(tabs) - 1, len(self.nb.tabs())) self.nb.add(self.child1) - self.failUnlessEqual(self.nb.index(self.child1), 1) - self.failIf(child1_index == self.nb.index(self.child1)) + self.assertEqual(self.nb.index(self.child1), 1) + self.assertFalse(child1_index == self.nb.index(self.child1)) def test_index(self): - self.failUnlessRaises(Tkinter.TclError, self.nb.index, -1) - self.failUnlessRaises(Tkinter.TclError, self.nb.index, None) + self.assertRaises(Tkinter.TclError, self.nb.index, -1) + self.assertRaises(Tkinter.TclError, self.nb.index, None) - self.failUnless(isinstance(self.nb.index('end'), int)) - self.failUnlessEqual(self.nb.index(self.child1), 0) - self.failUnlessEqual(self.nb.index(self.child2), 1) - self.failUnlessEqual(self.nb.index('end'), 2) + self.assertTrue(isinstance(self.nb.index('end'), int)) + self.assertEqual(self.nb.index(self.child1), 0) + self.assertEqual(self.nb.index(self.child2), 1) + self.assertEqual(self.nb.index('end'), 2) def test_insert(self): # moving tabs tabs = self.nb.tabs() self.nb.insert(1, tabs[0]) - self.failUnlessEqual(self.nb.tabs(), (tabs[1], tabs[0])) + self.assertEqual(self.nb.tabs(), (tabs[1], tabs[0])) self.nb.insert(self.child1, self.child2) - self.failUnlessEqual(self.nb.tabs(), tabs) + self.assertEqual(self.nb.tabs(), tabs) self.nb.insert('end', self.child1) - self.failUnlessEqual(self.nb.tabs(), (tabs[1], tabs[0])) + self.assertEqual(self.nb.tabs(), (tabs[1], tabs[0])) self.nb.insert('end', 0) - self.failUnlessEqual(self.nb.tabs(), tabs) + self.assertEqual(self.nb.tabs(), tabs) # bad moves - self.failUnlessRaises(Tkinter.TclError, self.nb.insert, 2, tabs[0]) - self.failUnlessRaises(Tkinter.TclError, self.nb.insert, -1, tabs[0]) + self.assertRaises(Tkinter.TclError, self.nb.insert, 2, tabs[0]) + self.assertRaises(Tkinter.TclError, self.nb.insert, -1, tabs[0]) # new tab child3 = ttk.Label() self.nb.insert(1, child3) - self.failUnlessEqual(self.nb.tabs(), (tabs[0], str(child3), tabs[1])) + self.assertEqual(self.nb.tabs(), (tabs[0], str(child3), tabs[1])) self.nb.forget(child3) - self.failUnlessEqual(self.nb.tabs(), tabs) + self.assertEqual(self.nb.tabs(), tabs) self.nb.insert(self.child1, child3) - self.failUnlessEqual(self.nb.tabs(), (str(child3), ) + tabs) + self.assertEqual(self.nb.tabs(), (str(child3), ) + tabs) self.nb.forget(child3) - self.failUnlessRaises(Tkinter.TclError, self.nb.insert, 2, child3) - self.failUnlessRaises(Tkinter.TclError, self.nb.insert, -1, child3) + self.assertRaises(Tkinter.TclError, self.nb.insert, 2, child3) + self.assertRaises(Tkinter.TclError, self.nb.insert, -1, child3) # bad inserts - self.failUnlessRaises(Tkinter.TclError, self.nb.insert, 'end', None) - self.failUnlessRaises(Tkinter.TclError, self.nb.insert, None, 0) - self.failUnlessRaises(Tkinter.TclError, self.nb.insert, None, None) + self.assertRaises(Tkinter.TclError, self.nb.insert, 'end', None) + self.assertRaises(Tkinter.TclError, self.nb.insert, None, 0) + self.assertRaises(Tkinter.TclError, self.nb.insert, None, None) def test_select(self): @@ -665,36 +665,36 @@ class NotebookTest(unittest.TestCase): self.nb.bind('<<NotebookTabChanged>>', lambda evt: tab_changed.append(True)) - self.failUnlessEqual(self.nb.select(), str(self.child1)) + self.assertEqual(self.nb.select(), str(self.child1)) self.nb.select(self.child2) - self.failUnless(success) - self.failUnlessEqual(self.nb.select(), str(self.child2)) + self.assertTrue(success) + self.assertEqual(self.nb.select(), str(self.child2)) self.nb.update() - self.failUnless(tab_changed) + self.assertTrue(tab_changed) def test_tab(self): - self.failUnlessRaises(Tkinter.TclError, self.nb.tab, -1) - self.failUnlessRaises(Tkinter.TclError, self.nb.tab, 'notab') - self.failUnlessRaises(Tkinter.TclError, self.nb.tab, None) + self.assertRaises(Tkinter.TclError, self.nb.tab, -1) + self.assertRaises(Tkinter.TclError, self.nb.tab, 'notab') + self.assertRaises(Tkinter.TclError, self.nb.tab, None) - self.failUnless(isinstance(self.nb.tab(self.child1), dict)) - self.failUnlessEqual(self.nb.tab(self.child1, text=None), 'a') + self.assertTrue(isinstance(self.nb.tab(self.child1), dict)) + self.assertEqual(self.nb.tab(self.child1, text=None), 'a') # newer form for querying a single option - self.failUnlessEqual(self.nb.tab(self.child1, 'text'), 'a') + self.assertEqual(self.nb.tab(self.child1, 'text'), 'a') self.nb.tab(self.child1, text='abc') - self.failUnlessEqual(self.nb.tab(self.child1, text=None), 'abc') - self.failUnlessEqual(self.nb.tab(self.child1, 'text'), 'abc') + self.assertEqual(self.nb.tab(self.child1, text=None), 'abc') + self.assertEqual(self.nb.tab(self.child1, 'text'), 'abc') def test_tabs(self): - self.failUnlessEqual(len(self.nb.tabs()), 2) + self.assertEqual(len(self.nb.tabs()), 2) self.nb.forget(self.child1) self.nb.forget(self.child2) - self.failUnlessEqual(self.nb.tabs(), ()) + self.assertEqual(self.nb.tabs(), ()) def test_traversal(self): @@ -705,16 +705,16 @@ class NotebookTest(unittest.TestCase): support.simulate_mouse_click(self.nb, 5, 5) self.nb.event_generate('<Control-Tab>') - self.failUnlessEqual(self.nb.select(), str(self.child2)) + self.assertEqual(self.nb.select(), str(self.child2)) self.nb.event_generate('<Shift-Control-Tab>') - self.failUnlessEqual(self.nb.select(), str(self.child1)) + self.assertEqual(self.nb.select(), str(self.child1)) self.nb.event_generate('<Shift-Control-Tab>') - self.failUnlessEqual(self.nb.select(), str(self.child2)) + self.assertEqual(self.nb.select(), str(self.child2)) self.nb.tab(self.child1, text='a', underline=0) self.nb.enable_traversal() self.nb.event_generate('<Alt-a>') - self.failUnlessEqual(self.nb.select(), str(self.child1)) + self.assertEqual(self.nb.select(), str(self.child1)) class TreeviewTest(unittest.TestCase): @@ -730,17 +730,17 @@ class TreeviewTest(unittest.TestCase): def test_bbox(self): self.tv.pack() - self.failUnlessEqual(self.tv.bbox(''), '') + self.assertEqual(self.tv.bbox(''), '') self.tv.wait_visibility() self.tv.update() item_id = self.tv.insert('', 'end') children = self.tv.get_children() - self.failUnless(children) + self.assertTrue(children) bbox = self.tv.bbox(children[0]) - self.failUnlessEqual(len(bbox), 4) - self.failUnless(isinstance(bbox, tuple)) + self.assertEqual(len(bbox), 4) + self.assertTrue(isinstance(bbox, tuple)) for item in bbox: if not isinstance(item, int): self.fail("Invalid bounding box: %s" % bbox) @@ -751,86 +751,86 @@ class TreeviewTest(unittest.TestCase): self.tv.column('test', width=50) bbox_column0 = self.tv.bbox(children[0], 0) root_width = self.tv.column('#0', width=None) - self.failUnlessEqual(bbox_column0[0], bbox[0] + root_width) + self.assertEqual(bbox_column0[0], bbox[0] + root_width) # verify that bbox of a closed item is the empty string child1 = self.tv.insert(item_id, 'end') - self.failUnlessEqual(self.tv.bbox(child1), '') + self.assertEqual(self.tv.bbox(child1), '') def test_children(self): # no children yet, should get an empty tuple - self.failUnlessEqual(self.tv.get_children(), ()) + self.assertEqual(self.tv.get_children(), ()) item_id = self.tv.insert('', 'end') - self.failUnless(isinstance(self.tv.get_children(), tuple)) - self.failUnlessEqual(self.tv.get_children()[0], item_id) + self.assertTrue(isinstance(self.tv.get_children(), tuple)) + self.assertEqual(self.tv.get_children()[0], item_id) # add item_id and child3 as children of child2 child2 = self.tv.insert('', 'end') child3 = self.tv.insert('', 'end') self.tv.set_children(child2, item_id, child3) - self.failUnlessEqual(self.tv.get_children(child2), (item_id, child3)) + self.assertEqual(self.tv.get_children(child2), (item_id, child3)) # child3 has child2 as parent, thus trying to set child2 as a children # of child3 should result in an error - self.failUnlessRaises(Tkinter.TclError, + self.assertRaises(Tkinter.TclError, self.tv.set_children, child3, child2) # remove child2 children self.tv.set_children(child2) - self.failUnlessEqual(self.tv.get_children(child2), ()) + self.assertEqual(self.tv.get_children(child2), ()) # remove root's children self.tv.set_children('') - self.failUnlessEqual(self.tv.get_children(), ()) + self.assertEqual(self.tv.get_children(), ()) def test_column(self): # return a dict with all options/values - self.failUnless(isinstance(self.tv.column('#0'), dict)) + self.assertTrue(isinstance(self.tv.column('#0'), dict)) # return a single value of the given option - self.failUnless(isinstance(self.tv.column('#0', width=None), int)) + self.assertTrue(isinstance(self.tv.column('#0', width=None), int)) # set a new value for an option self.tv.column('#0', width=10) # testing new way to get option value - self.failUnlessEqual(self.tv.column('#0', 'width'), 10) - self.failUnlessEqual(self.tv.column('#0', width=None), 10) + self.assertEqual(self.tv.column('#0', 'width'), 10) + self.assertEqual(self.tv.column('#0', width=None), 10) # check read-only option - self.failUnlessRaises(Tkinter.TclError, self.tv.column, '#0', id='X') + self.assertRaises(Tkinter.TclError, self.tv.column, '#0', id='X') - self.failUnlessRaises(Tkinter.TclError, self.tv.column, 'invalid') + self.assertRaises(Tkinter.TclError, self.tv.column, 'invalid') invalid_kws = [ {'unknown_option': 'some value'}, {'stretch': 'wrong'}, {'anchor': 'wrong'}, {'width': 'wrong'}, {'minwidth': 'wrong'} ] for kw in invalid_kws: - self.failUnlessRaises(Tkinter.TclError, self.tv.column, '#0', + self.assertRaises(Tkinter.TclError, self.tv.column, '#0', **kw) def test_delete(self): - self.failUnlessRaises(Tkinter.TclError, self.tv.delete, '#0') + self.assertRaises(Tkinter.TclError, self.tv.delete, '#0') item_id = self.tv.insert('', 'end') item2 = self.tv.insert(item_id, 'end') - self.failUnlessEqual(self.tv.get_children(), (item_id, )) - self.failUnlessEqual(self.tv.get_children(item_id), (item2, )) + self.assertEqual(self.tv.get_children(), (item_id, )) + self.assertEqual(self.tv.get_children(item_id), (item2, )) self.tv.delete(item_id) - self.failIf(self.tv.get_children()) + self.assertFalse(self.tv.get_children()) # reattach should fail - self.failUnlessRaises(Tkinter.TclError, + self.assertRaises(Tkinter.TclError, self.tv.reattach, item_id, '', 'end') # test multiple item delete item1 = self.tv.insert('', 'end') item2 = self.tv.insert('', 'end') - self.failUnlessEqual(self.tv.get_children(), (item1, item2)) + self.assertEqual(self.tv.get_children(), (item1, item2)) self.tv.delete(item1, item2) - self.failIf(self.tv.get_children()) + self.assertFalse(self.tv.get_children()) def test_detach_reattach(self): @@ -840,81 +840,81 @@ class TreeviewTest(unittest.TestCase): # calling detach without items is valid, although it does nothing prev = self.tv.get_children() self.tv.detach() # this should do nothing - self.failUnlessEqual(prev, self.tv.get_children()) + self.assertEqual(prev, self.tv.get_children()) - self.failUnlessEqual(self.tv.get_children(), (item_id, )) - self.failUnlessEqual(self.tv.get_children(item_id), (item2, )) + self.assertEqual(self.tv.get_children(), (item_id, )) + self.assertEqual(self.tv.get_children(item_id), (item2, )) # detach item with children self.tv.detach(item_id) - self.failIf(self.tv.get_children()) + self.assertFalse(self.tv.get_children()) # reattach item with children self.tv.reattach(item_id, '', 'end') - self.failUnlessEqual(self.tv.get_children(), (item_id, )) - self.failUnlessEqual(self.tv.get_children(item_id), (item2, )) + self.assertEqual(self.tv.get_children(), (item_id, )) + self.assertEqual(self.tv.get_children(item_id), (item2, )) # move a children to the root self.tv.move(item2, '', 'end') - self.failUnlessEqual(self.tv.get_children(), (item_id, item2)) - self.failUnlessEqual(self.tv.get_children(item_id), ()) + self.assertEqual(self.tv.get_children(), (item_id, item2)) + self.assertEqual(self.tv.get_children(item_id), ()) # bad values - self.failUnlessRaises(Tkinter.TclError, + self.assertRaises(Tkinter.TclError, self.tv.reattach, 'nonexistent', '', 'end') - self.failUnlessRaises(Tkinter.TclError, + self.assertRaises(Tkinter.TclError, self.tv.detach, 'nonexistent') - self.failUnlessRaises(Tkinter.TclError, + self.assertRaises(Tkinter.TclError, self.tv.reattach, item2, 'otherparent', 'end') - self.failUnlessRaises(Tkinter.TclError, + self.assertRaises(Tkinter.TclError, self.tv.reattach, item2, '', 'invalid') # multiple detach self.tv.detach(item_id, item2) - self.failUnlessEqual(self.tv.get_children(), ()) - self.failUnlessEqual(self.tv.get_children(item_id), ()) + self.assertEqual(self.tv.get_children(), ()) + self.assertEqual(self.tv.get_children(item_id), ()) def test_exists(self): - self.failUnlessEqual(self.tv.exists('something'), False) - self.failUnlessEqual(self.tv.exists(''), True) - self.failUnlessEqual(self.tv.exists({}), False) + self.assertEqual(self.tv.exists('something'), False) + self.assertEqual(self.tv.exists(''), True) + self.assertEqual(self.tv.exists({}), False) # the following will make a tk.call equivalent to # tk.call(treeview, "exists") which should result in an error # in the tcl interpreter since tk requires an item. - self.failUnlessRaises(Tkinter.TclError, self.tv.exists, None) + self.assertRaises(Tkinter.TclError, self.tv.exists, None) def test_focus(self): # nothing is focused right now - self.failUnlessEqual(self.tv.focus(), '') + self.assertEqual(self.tv.focus(), '') item1 = self.tv.insert('', 'end') self.tv.focus(item1) - self.failUnlessEqual(self.tv.focus(), item1) + self.assertEqual(self.tv.focus(), item1) self.tv.delete(item1) - self.failUnlessEqual(self.tv.focus(), '') + self.assertEqual(self.tv.focus(), '') # try focusing inexistent item - self.failUnlessRaises(Tkinter.TclError, self.tv.focus, 'hi') + self.assertRaises(Tkinter.TclError, self.tv.focus, 'hi') def test_heading(self): # check a dict is returned - self.failUnless(isinstance(self.tv.heading('#0'), dict)) + self.assertTrue(isinstance(self.tv.heading('#0'), dict)) # check a value is returned self.tv.heading('#0', text='hi') - self.failUnlessEqual(self.tv.heading('#0', 'text'), 'hi') - self.failUnlessEqual(self.tv.heading('#0', text=None), 'hi') + self.assertEqual(self.tv.heading('#0', 'text'), 'hi') + self.assertEqual(self.tv.heading('#0', text=None), 'hi') # invalid option - self.failUnlessRaises(Tkinter.TclError, self.tv.heading, '#0', + self.assertRaises(Tkinter.TclError, self.tv.heading, '#0', background=None) # invalid value - self.failUnlessRaises(Tkinter.TclError, self.tv.heading, '#0', + self.assertRaises(Tkinter.TclError, self.tv.heading, '#0', anchor=1) @@ -940,7 +940,7 @@ class TreeviewTest(unittest.TestCase): success = [] commands = self.tv.master._tclCommands self.tv.heading('#0', command=str(self.tv.heading('#0', command=None))) - self.failUnlessEqual(commands, self.tv.master._tclCommands) + self.assertEqual(commands, self.tv.master._tclCommands) simulate_heading_click(5, 5) if not success: self.fail("The command associated to the treeview heading wasn't " @@ -954,92 +954,92 @@ class TreeviewTest(unittest.TestCase): def test_index(self): # item 'what' doesn't exist - self.failUnlessRaises(Tkinter.TclError, self.tv.index, 'what') + self.assertRaises(Tkinter.TclError, self.tv.index, 'what') - self.failUnlessEqual(self.tv.index(''), 0) + self.assertEqual(self.tv.index(''), 0) item1 = self.tv.insert('', 'end') item2 = self.tv.insert('', 'end') c1 = self.tv.insert(item1, 'end') c2 = self.tv.insert(item1, 'end') - self.failUnlessEqual(self.tv.index(item1), 0) - self.failUnlessEqual(self.tv.index(c1), 0) - self.failUnlessEqual(self.tv.index(c2), 1) - self.failUnlessEqual(self.tv.index(item2), 1) + self.assertEqual(self.tv.index(item1), 0) + self.assertEqual(self.tv.index(c1), 0) + self.assertEqual(self.tv.index(c2), 1) + self.assertEqual(self.tv.index(item2), 1) self.tv.move(item2, '', 0) - self.failUnlessEqual(self.tv.index(item2), 0) - self.failUnlessEqual(self.tv.index(item1), 1) + self.assertEqual(self.tv.index(item2), 0) + self.assertEqual(self.tv.index(item1), 1) # check that index still works even after its parent and siblings # have been detached self.tv.detach(item1) - self.failUnlessEqual(self.tv.index(c2), 1) + self.assertEqual(self.tv.index(c2), 1) self.tv.detach(c1) - self.failUnlessEqual(self.tv.index(c2), 0) + self.assertEqual(self.tv.index(c2), 0) # but it fails after item has been deleted self.tv.delete(item1) - self.failUnlessRaises(Tkinter.TclError, self.tv.index, c2) + self.assertRaises(Tkinter.TclError, self.tv.index, c2) def test_insert_item(self): # parent 'none' doesn't exist - self.failUnlessRaises(Tkinter.TclError, self.tv.insert, 'none', 'end') + self.assertRaises(Tkinter.TclError, self.tv.insert, 'none', 'end') # open values - self.failUnlessRaises(Tkinter.TclError, self.tv.insert, '', 'end', + self.assertRaises(Tkinter.TclError, self.tv.insert, '', 'end', open='') - self.failUnlessRaises(Tkinter.TclError, self.tv.insert, '', 'end', + self.assertRaises(Tkinter.TclError, self.tv.insert, '', 'end', open='please') - self.failIf(self.tv.delete(self.tv.insert('', 'end', open=True))) - self.failIf(self.tv.delete(self.tv.insert('', 'end', open=False))) + self.assertFalse(self.tv.delete(self.tv.insert('', 'end', open=True))) + self.assertFalse(self.tv.delete(self.tv.insert('', 'end', open=False))) # invalid index - self.failUnlessRaises(Tkinter.TclError, self.tv.insert, '', 'middle') + self.assertRaises(Tkinter.TclError, self.tv.insert, '', 'middle') # trying to duplicate item id is invalid itemid = self.tv.insert('', 'end', 'first-item') - self.failUnlessEqual(itemid, 'first-item') - self.failUnlessRaises(Tkinter.TclError, self.tv.insert, '', 'end', + self.assertEqual(itemid, 'first-item') + self.assertRaises(Tkinter.TclError, self.tv.insert, '', 'end', 'first-item') - self.failUnlessRaises(Tkinter.TclError, self.tv.insert, '', 'end', + self.assertRaises(Tkinter.TclError, self.tv.insert, '', 'end', MockTclObj('first-item')) # unicode values value = u'\xe1ba' item = self.tv.insert('', 'end', values=(value, )) - self.failUnlessEqual(self.tv.item(item, 'values'), (value, )) - self.failUnlessEqual(self.tv.item(item, values=None), (value, )) + self.assertEqual(self.tv.item(item, 'values'), (value, )) + self.assertEqual(self.tv.item(item, values=None), (value, )) self.tv.item(item, values=list(self.tv.item(item, values=None))) - self.failUnlessEqual(self.tv.item(item, values=None), (value, )) + self.assertEqual(self.tv.item(item, values=None), (value, )) - self.failUnless(isinstance(self.tv.item(item), dict)) + self.assertTrue(isinstance(self.tv.item(item), dict)) # erase item values self.tv.item(item, values='') - self.failIf(self.tv.item(item, values=None)) + self.assertFalse(self.tv.item(item, values=None)) # item tags item = self.tv.insert('', 'end', tags=[1, 2, value]) - self.failUnlessEqual(self.tv.item(item, tags=None), ('1', '2', value)) + self.assertEqual(self.tv.item(item, tags=None), ('1', '2', value)) self.tv.item(item, tags=[]) - self.failIf(self.tv.item(item, tags=None)) + self.assertFalse(self.tv.item(item, tags=None)) self.tv.item(item, tags=(1, 2)) - self.failUnlessEqual(self.tv.item(item, tags=None), ('1', '2')) + self.assertEqual(self.tv.item(item, tags=None), ('1', '2')) # values with spaces item = self.tv.insert('', 'end', values=('a b c', '%s %s' % (value, value))) - self.failUnlessEqual(self.tv.item(item, values=None), + self.assertEqual(self.tv.item(item, values=None), ('a b c', '%s %s' % (value, value))) # text - self.failUnlessEqual(self.tv.item( + self.assertEqual(self.tv.item( self.tv.insert('', 'end', text="Label here"), text=None), "Label here") - self.failUnlessEqual(self.tv.item( + self.assertEqual(self.tv.item( self.tv.insert('', 'end', text=value), text=None), value) @@ -1047,29 +1047,29 @@ class TreeviewTest(unittest.TestCase): def test_set(self): self.tv['columns'] = ['A', 'B'] item = self.tv.insert('', 'end', values=['a', 'b']) - self.failUnlessEqual(self.tv.set(item), {'A': 'a', 'B': 'b'}) + self.assertEqual(self.tv.set(item), {'A': 'a', 'B': 'b'}) self.tv.set(item, 'B', 'a') - self.failUnlessEqual(self.tv.item(item, values=None), ('a', 'a')) + self.assertEqual(self.tv.item(item, values=None), ('a', 'a')) self.tv['columns'] = ['B'] - self.failUnlessEqual(self.tv.set(item), {'B': 'a'}) + self.assertEqual(self.tv.set(item), {'B': 'a'}) self.tv.set(item, 'B', 'b') - self.failUnlessEqual(self.tv.set(item, column='B'), 'b') - self.failUnlessEqual(self.tv.item(item, values=None), ('b', 'a')) + self.assertEqual(self.tv.set(item, column='B'), 'b') + self.assertEqual(self.tv.item(item, values=None), ('b', 'a')) self.tv.set(item, 'B', 123) - self.failUnlessEqual(self.tv.set(item, 'B'), 123) - self.failUnlessEqual(self.tv.item(item, values=None), (123, 'a')) - self.failUnlessEqual(self.tv.set(item), {'B': 123}) + self.assertEqual(self.tv.set(item, 'B'), 123) + self.assertEqual(self.tv.item(item, values=None), (123, 'a')) + self.assertEqual(self.tv.set(item), {'B': 123}) # inexistent column - self.failUnlessRaises(Tkinter.TclError, self.tv.set, item, 'A') - self.failUnlessRaises(Tkinter.TclError, self.tv.set, item, 'A', 'b') + self.assertRaises(Tkinter.TclError, self.tv.set, item, 'A') + self.assertRaises(Tkinter.TclError, self.tv.set, item, 'A', 'b') # inexistent item - self.failUnlessRaises(Tkinter.TclError, self.tv.set, 'notme') + self.assertRaises(Tkinter.TclError, self.tv.set, 'notme') def test_tag_bind(self): @@ -1095,28 +1095,28 @@ class TreeviewTest(unittest.TestCase): pos_y.add(i) found.add(item_id) - self.failUnlessEqual(len(pos_y), 2) # item1 and item2 y pos + self.assertEqual(len(pos_y), 2) # item1 and item2 y pos for y in pos_y: support.simulate_mouse_click(self.tv, 0, y) # by now there should be 4 things in the events list, since each # item had a bind for two events that were simulated above - self.failUnlessEqual(len(events), 4) + self.assertEqual(len(events), 4) for evt in zip(events[::2], events[1::2]): - self.failUnlessEqual(evt, (1, 2)) + self.assertEqual(evt, (1, 2)) def test_tag_configure(self): # Just testing parameter passing for now - self.failUnlessRaises(TypeError, self.tv.tag_configure) - self.failUnlessRaises(Tkinter.TclError, self.tv.tag_configure, + self.assertRaises(TypeError, self.tv.tag_configure) + self.assertRaises(Tkinter.TclError, self.tv.tag_configure, 'test', sky='blue') self.tv.tag_configure('test', foreground='blue') - self.failUnlessEqual(self.tv.tag_configure('test', 'foreground'), + self.assertEqual(self.tv.tag_configure('test', 'foreground'), 'blue') - self.failUnlessEqual(self.tv.tag_configure('test', foreground=None), + self.assertEqual(self.tv.tag_configure('test', foreground=None), 'blue') - self.failUnless(isinstance(self.tv.tag_configure('test'), dict)) + self.assertTrue(isinstance(self.tv.tag_configure('test'), dict)) tests_gui = ( diff --git a/Lib/test/mapping_tests.py b/Lib/test/mapping_tests.py index c6857ab..7ec4bb1 100644 --- a/Lib/test/mapping_tests.py +++ b/Lib/test/mapping_tests.py @@ -50,17 +50,17 @@ class BasicTestMappingProtocol(unittest.TestCase): for key, value in self.reference.items(): self.assertEqual(d[key], value) knownkey = self.other.keys()[0] - self.failUnlessRaises(KeyError, lambda:d[knownkey]) + self.assertRaises(KeyError, lambda:d[knownkey]) #len self.assertEqual(len(p), 0) self.assertEqual(len(d), len(self.reference)) #has_key for k in self.reference: - self.assert_(d.has_key(k)) - self.assert_(k in d) + self.assertTrue(d.has_key(k)) + self.assertTrue(k in d) for k in self.other: - self.failIf(d.has_key(k)) - self.failIf(k in d) + self.assertFalse(d.has_key(k)) + self.assertFalse(k in d) #cmp self.assertEqual(cmp(p,p), 0) self.assertEqual(cmp(d,d), 0) @@ -71,10 +71,10 @@ class BasicTestMappingProtocol(unittest.TestCase): if not d: self.fail("Full mapping must compare to True") # keys(), items(), iterkeys() ... def check_iterandlist(iter, lst, ref): - self.assert_(hasattr(iter, 'next')) - self.assert_(hasattr(iter, '__iter__')) + self.assertTrue(hasattr(iter, 'next')) + self.assertTrue(hasattr(iter, '__iter__')) x = list(iter) - self.assert_(set(x)==set(lst)==set(ref)) + self.assertTrue(set(x)==set(lst)==set(ref)) check_iterandlist(d.iterkeys(), d.keys(), self.reference.keys()) check_iterandlist(iter(d), d.keys(), self.reference.keys()) check_iterandlist(d.itervalues(), d.values(), self.reference.values()) @@ -84,7 +84,7 @@ class BasicTestMappingProtocol(unittest.TestCase): knownkey, knownvalue = self.other.iteritems().next() self.assertEqual(d.get(key, knownvalue), value) self.assertEqual(d.get(knownkey, knownvalue), knownvalue) - self.failIf(knownkey in d) + self.assertFalse(knownkey in d) def test_write(self): # Test for write operations on mapping @@ -95,7 +95,7 @@ class BasicTestMappingProtocol(unittest.TestCase): self.assertEqual(p[key], value) for key in self.reference.keys(): del p[key] - self.failUnlessRaises(KeyError, lambda:p[key]) + self.assertRaises(KeyError, lambda:p[key]) p = self._empty_mapping() #update p.update(self.reference) @@ -114,16 +114,16 @@ class BasicTestMappingProtocol(unittest.TestCase): self.assertEqual(d[knownkey], knownvalue) #pop self.assertEqual(d.pop(knownkey), knownvalue) - self.failIf(knownkey in d) + self.assertFalse(knownkey in d) self.assertRaises(KeyError, d.pop, knownkey) default = 909 d[knownkey] = knownvalue self.assertEqual(d.pop(knownkey, default), knownvalue) - self.failIf(knownkey in d) + self.assertFalse(knownkey in d) self.assertEqual(d.pop(knownkey, default), default) #popitem key, value = d.popitem() - self.failIf(key in d) + self.assertFalse(key in d) self.assertEqual(value, self.reference[key]) p=self._empty_mapping() self.assertRaises(KeyError, p.popitem) @@ -132,17 +132,17 @@ class BasicTestMappingProtocol(unittest.TestCase): self.assertEqual(self._empty_mapping(), self._empty_mapping()) def test_bool(self): - self.assert_(not self._empty_mapping()) - self.assert_(self.reference) - self.assert_(bool(self._empty_mapping()) is False) - self.assert_(bool(self.reference) is True) + self.assertTrue(not self._empty_mapping()) + self.assertTrue(self.reference) + self.assertTrue(bool(self._empty_mapping()) is False) + self.assertTrue(bool(self.reference) is True) def test_keys(self): d = self._empty_mapping() self.assertEqual(d.keys(), []) d = self.reference - self.assert_(self.inmapping.keys()[0] in d.keys()) - self.assert_(self.other.keys()[0] not in d.keys()) + self.assertTrue(self.inmapping.keys()[0] in d.keys()) + self.assertTrue(self.other.keys()[0] not in d.keys()) self.assertRaises(TypeError, d.keys, None) def test_values(self): @@ -268,10 +268,10 @@ class BasicTestMappingProtocol(unittest.TestCase): def test_get(self): d = self._empty_mapping() - self.assert_(d.get(self.other.keys()[0]) is None) + self.assertTrue(d.get(self.other.keys()[0]) is None) self.assertEqual(d.get(self.other.keys()[0], 3), 3) d = self.reference - self.assert_(d.get(self.other.keys()[0]) is None) + self.assertTrue(d.get(self.other.keys()[0]) is None) self.assertEqual(d.get(self.other.keys()[0], 3), 3) self.assertEqual(d.get(self.inmapping.keys()[0]), self.inmapping.values()[0]) self.assertEqual(d.get(self.inmapping.keys()[0], 3), self.inmapping.values()[0]) @@ -302,15 +302,15 @@ class BasicTestMappingProtocol(unittest.TestCase): class TestMappingProtocol(BasicTestMappingProtocol): def test_constructor(self): BasicTestMappingProtocol.test_constructor(self) - self.assert_(self._empty_mapping() is not self._empty_mapping()) + self.assertTrue(self._empty_mapping() is not self._empty_mapping()) self.assertEqual(self.type2test(x=1, y=2), {"x": 1, "y": 2}) def test_bool(self): BasicTestMappingProtocol.test_bool(self) - self.assert_(not self._empty_mapping()) - self.assert_(self._full_mapping({"x": "y"})) - self.assert_(bool(self._empty_mapping()) is False) - self.assert_(bool(self._full_mapping({"x": "y"})) is True) + self.assertTrue(not self._empty_mapping()) + self.assertTrue(self._full_mapping({"x": "y"})) + self.assertTrue(bool(self._empty_mapping()) is False) + self.assertTrue(bool(self._full_mapping({"x": "y"})) is True) def test_keys(self): BasicTestMappingProtocol.test_keys(self) @@ -318,9 +318,9 @@ class TestMappingProtocol(BasicTestMappingProtocol): self.assertEqual(d.keys(), []) d = self._full_mapping({'a': 1, 'b': 2}) k = d.keys() - self.assert_('a' in k) - self.assert_('b' in k) - self.assert_('c' not in k) + self.assertTrue('a' in k) + self.assertTrue('b' in k) + self.assertTrue('c' not in k) def test_values(self): BasicTestMappingProtocol.test_values(self) @@ -335,7 +335,7 @@ class TestMappingProtocol(BasicTestMappingProtocol): def test_has_key(self): d = self._empty_mapping() - self.assert_(not d.has_key('a')) + self.assertTrue(not d.has_key('a')) d = self._full_mapping({'a': 1, 'b': 2}) k = d.keys() k.sort() @@ -345,12 +345,12 @@ class TestMappingProtocol(BasicTestMappingProtocol): def test_contains(self): d = self._empty_mapping() - self.assert_(not ('a' in d)) - self.assert_('a' not in d) + self.assertTrue(not ('a' in d)) + self.assertTrue('a' not in d) d = self._full_mapping({'a': 1, 'b': 2}) - self.assert_('a' in d) - self.assert_('b' in d) - self.assert_('c' not in d) + self.assertTrue('a' in d) + self.assertTrue('b' in d) + self.assertTrue('c' not in d) self.assertRaises(TypeError, d.__contains__) @@ -429,7 +429,7 @@ class TestMappingProtocol(BasicTestMappingProtocol): def test_fromkeys(self): self.assertEqual(self.type2test.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) d = self._empty_mapping() - self.assert_(not(d.fromkeys('abc') is d)) + self.assertTrue(not(d.fromkeys('abc') is d)) self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0}) self.assertEqual(d.fromkeys([]), {}) @@ -440,17 +440,17 @@ class TestMappingProtocol(BasicTestMappingProtocol): class dictlike(self.type2test): pass self.assertEqual(dictlike.fromkeys('a'), {'a':None}) self.assertEqual(dictlike().fromkeys('a'), {'a':None}) - self.assert_(dictlike.fromkeys('a').__class__ is dictlike) - self.assert_(dictlike().fromkeys('a').__class__ is dictlike) + self.assertTrue(dictlike.fromkeys('a').__class__ is dictlike) + self.assertTrue(dictlike().fromkeys('a').__class__ is dictlike) # FIXME: the following won't work with UserDict, because it's an old style class - # self.assert_(type(dictlike.fromkeys('a')) is dictlike) + # self.assertTrue(type(dictlike.fromkeys('a')) is dictlike) class mydict(self.type2test): def __new__(cls): return UserDict.UserDict() ud = mydict.fromkeys('ab') self.assertEqual(ud, {'a':None, 'b':None}) # FIXME: the following won't work with UserDict, because it's an old style class - # self.assert_(isinstance(ud, UserDict.UserDict)) + # self.assertTrue(isinstance(ud, UserDict.UserDict)) self.assertRaises(TypeError, dict.fromkeys) class Exc(Exception): pass @@ -480,16 +480,16 @@ class TestMappingProtocol(BasicTestMappingProtocol): self.assertEqual(d.copy(), {1:1, 2:2, 3:3}) d = self._empty_mapping() self.assertEqual(d.copy(), d) - self.assert_(isinstance(d.copy(), d.__class__)) + self.assertTrue(isinstance(d.copy(), d.__class__)) self.assertRaises(TypeError, d.copy, None) def test_get(self): BasicTestMappingProtocol.test_get(self) d = self._empty_mapping() - self.assert_(d.get('c') is None) + self.assertTrue(d.get('c') is None) self.assertEqual(d.get('c', 3), 3) d = self._full_mapping({'a' : 1, 'b' : 2}) - self.assert_(d.get('c') is None) + self.assertTrue(d.get('c') is None) self.assertEqual(d.get('c', 3), 3) self.assertEqual(d.get('a'), 1) self.assertEqual(d.get('a', 3), 1) @@ -497,9 +497,9 @@ class TestMappingProtocol(BasicTestMappingProtocol): def test_setdefault(self): BasicTestMappingProtocol.test_setdefault(self) d = self._empty_mapping() - self.assert_(d.setdefault('key0') is None) + self.assertTrue(d.setdefault('key0') is None) d.setdefault('key0', []) - self.assert_(d.setdefault('key0') is None) + self.assertTrue(d.setdefault('key0') is None) d.setdefault('key', []).append(3) self.assertEqual(d['key'][0], 3) d.setdefault('key', []).append(4) @@ -525,9 +525,9 @@ class TestMappingProtocol(BasicTestMappingProtocol): self.assertEqual(va, int(ka)) kb, vb = tb = b.popitem() self.assertEqual(vb, int(kb)) - self.assert_(not(copymode < 0 and ta != tb)) - self.assert_(not a) - self.assert_(not b) + self.assertTrue(not(copymode < 0 and ta != tb)) + self.assertTrue(not a) + self.assertTrue(not b) def test_pop(self): BasicTestMappingProtocol.test_pop(self) @@ -585,7 +585,7 @@ class TestHashMappingProtocol(TestMappingProtocol): return UserDict.UserDict() ud = mydict.fromkeys('ab') self.assertEqual(ud, {'a':None, 'b':None}) - self.assert_(isinstance(ud, UserDict.UserDict)) + self.assertTrue(isinstance(ud, UserDict.UserDict)) def test_pop(self): TestMappingProtocol.test_pop(self) @@ -636,8 +636,8 @@ class TestHashMappingProtocol(TestMappingProtocol): self.assertRaises(Exc, repr, d) def test_le(self): - self.assert_(not (self._empty_mapping() < self._empty_mapping())) - self.assert_(not (self._full_mapping({1: 2}) < self._full_mapping({1L: 2L}))) + self.assertTrue(not (self._empty_mapping() < self._empty_mapping())) + self.assertTrue(not (self._full_mapping({1: 2}) < self._full_mapping({1L: 2L}))) class Exc(Exception): pass diff --git a/Lib/test/pickletester.py b/Lib/test/pickletester.py index ce49fdd..7306aa8 100644 --- a/Lib/test/pickletester.py +++ b/Lib/test/pickletester.py @@ -461,7 +461,7 @@ class AbstractPickleTests(unittest.TestCase): s = self.dumps(l, proto) x = self.loads(s) self.assertEqual(len(x), 1) - self.assert_(x is x[0]) + self.assertTrue(x is x[0]) def test_recursive_tuple(self): t = ([],) @@ -471,7 +471,7 @@ class AbstractPickleTests(unittest.TestCase): x = self.loads(s) self.assertEqual(len(x), 1) self.assertEqual(len(x[0]), 1) - self.assert_(x is x[0][0]) + self.assertTrue(x is x[0][0]) def test_recursive_dict(self): d = {} @@ -480,7 +480,7 @@ class AbstractPickleTests(unittest.TestCase): s = self.dumps(d, proto) x = self.loads(s) self.assertEqual(x.keys(), [1]) - self.assert_(x[1] is x) + self.assertTrue(x[1] is x) def test_recursive_inst(self): i = C() @@ -489,7 +489,7 @@ class AbstractPickleTests(unittest.TestCase): s = self.dumps(i, 2) x = self.loads(s) self.assertEqual(dir(x), dir(i)) - self.assert_(x.attr is x) + self.assertTrue(x.attr is x) def test_recursive_multi(self): l = [] @@ -503,7 +503,7 @@ class AbstractPickleTests(unittest.TestCase): self.assertEqual(len(x), 1) self.assertEqual(dir(x[0]), dir(i)) self.assertEqual(x[0].attr.keys(), [1]) - self.assert_(x[0].attr[1] is x) + self.assertTrue(x[0].attr[1] is x) def test_garyp(self): self.assertRaises(self.error, self.loads, 'garyp') @@ -644,7 +644,7 @@ class AbstractPickleTests(unittest.TestCase): try: self.loads(badpickle) except ValueError, detail: - self.failUnless(str(detail).startswith( + self.assertTrue(str(detail).startswith( "unsupported pickle protocol")) else: self.fail("expected bad protocol number to raise ValueError") @@ -716,7 +716,7 @@ class AbstractPickleTests(unittest.TestCase): for x in None, False, True: s = self.dumps(x, proto) y = self.loads(s) - self.assert_(x is y, (proto, x, s, y)) + self.assertTrue(x is y, (proto, x, s, y)) expected = expected_opcode[proto, x] self.assertEqual(opcode_in_pickle(expected, s), True) @@ -766,8 +766,8 @@ class AbstractPickleTests(unittest.TestCase): # Dump using protocol 1 for comparison. s1 = self.dumps(x, 1) - self.assert_(__name__ in s1) - self.assert_("MyList" in s1) + self.assertTrue(__name__ in s1) + self.assertTrue("MyList" in s1) self.assertEqual(opcode_in_pickle(opcode, s1), False) y = self.loads(s1) @@ -776,8 +776,8 @@ class AbstractPickleTests(unittest.TestCase): # Dump using protocol 2 for test. s2 = self.dumps(x, 2) - self.assert_(__name__ not in s2) - self.assert_("MyList" not in s2) + self.assertTrue(__name__ not in s2) + self.assertTrue("MyList" not in s2) self.assertEqual(opcode_in_pickle(opcode, s2), True) y = self.loads(s2) @@ -821,7 +821,7 @@ class AbstractPickleTests(unittest.TestCase): if proto == 0: self.assertEqual(num_appends, 0) else: - self.failUnless(num_appends >= 2) + self.assertTrue(num_appends >= 2) def test_dict_chunking(self): n = 10 # too small to chunk @@ -843,7 +843,7 @@ class AbstractPickleTests(unittest.TestCase): if proto == 0: self.assertEqual(num_setitems, 0) else: - self.failUnless(num_setitems >= 2) + self.assertTrue(num_setitems >= 2) def test_simple_newobj(self): x = object.__new__(SimpleNewObj) # avoid __init__ diff --git a/Lib/test/test_StringIO.py b/Lib/test/test_StringIO.py index 58cbec0..f5a177e 100644 --- a/Lib/test/test_StringIO.py +++ b/Lib/test/test_StringIO.py @@ -85,7 +85,7 @@ class TestGenericStringIO(unittest.TestCase): def test_iterator(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue eq(iter(self._fp), self._fp) # Does this object support the iteration protocol? unless(hasattr(self._fp, '__iter__')) diff --git a/Lib/test/test___all__.py b/Lib/test/test___all__.py index 0a8c5d6..623ce96 100644 --- a/Lib/test/test___all__.py +++ b/Lib/test/test___all__.py @@ -18,7 +18,7 @@ class AllTest(unittest.TestCase): # Silent fail here seems the best route since some modules # may not be available in all environments. return - self.failUnless(hasattr(sys.modules[modname], "__all__"), + self.assertTrue(hasattr(sys.modules[modname], "__all__"), "%s has no __all__ attribute" % modname) names = {} exec "from %s import *" % modname in names diff --git a/Lib/test/test___future__.py b/Lib/test/test___future__.py index 50a2c74..a8c7c2e 100644 --- a/Lib/test/test___future__.py +++ b/Lib/test/test___future__.py @@ -15,7 +15,7 @@ class FutureTest(unittest.TestCase): for name in dir(__future__): obj = getattr(__future__, name, None) if obj is not None and isinstance(obj, __future__._Feature): - self.assert_( + self.assertTrue( name in given_feature_names, "%r should have been in all_feature_names" % name ) @@ -30,7 +30,7 @@ class FutureTest(unittest.TestCase): optional = value.getOptionalRelease() mandatory = value.getMandatoryRelease() - a = self.assert_ + a = self.assertTrue e = self.assertEqual def check(t, name): a(isinstance(t, tuple), "%s isn't tuple" % name) diff --git a/Lib/test/test_abc.py b/Lib/test/test_abc.py index 3e0955f..718d903 100644 --- a/Lib/test/test_abc.py +++ b/Lib/test/test_abc.py @@ -44,23 +44,23 @@ class TestABC(unittest.TestCase): def bar(self): pass # concrete self.assertEqual(C.__abstractmethods__, set(["foo"])) self.assertRaises(TypeError, C) # because foo is abstract - self.assert_(isabstract(C)) + self.assertTrue(isabstract(C)) class D(C): def bar(self): pass # concrete override of concrete self.assertEqual(D.__abstractmethods__, set(["foo"])) self.assertRaises(TypeError, D) # because foo is still abstract - self.assert_(isabstract(D)) + self.assertTrue(isabstract(D)) class E(D): def foo(self): pass self.assertEqual(E.__abstractmethods__, set()) E() # now foo is concrete, too - self.failIf(isabstract(E)) + self.assertFalse(isabstract(E)) class F(E): @abstractthing def bar(self): pass # abstract override of concrete self.assertEqual(F.__abstractmethods__, set(["bar"])) self.assertRaises(TypeError, F) # because bar is abstract now - self.assert_(isabstract(F)) + self.assertTrue(isabstract(F)) def test_subclass_oldstyle_class(self): class A: @@ -152,41 +152,41 @@ class TestABC(unittest.TestCase): def test_registration_transitiveness(self): class A: __metaclass__ = abc.ABCMeta - self.failUnless(issubclass(A, A)) - self.failUnless(issubclass(A, (A,))) + self.assertTrue(issubclass(A, A)) + self.assertTrue(issubclass(A, (A,))) class B: __metaclass__ = abc.ABCMeta - self.failIf(issubclass(A, B)) - self.failIf(issubclass(A, (B,))) - self.failIf(issubclass(B, A)) - self.failIf(issubclass(B, (A,))) + self.assertFalse(issubclass(A, B)) + self.assertFalse(issubclass(A, (B,))) + self.assertFalse(issubclass(B, A)) + self.assertFalse(issubclass(B, (A,))) class C: __metaclass__ = abc.ABCMeta A.register(B) class B1(B): pass - self.failUnless(issubclass(B1, A)) - self.failUnless(issubclass(B1, (A,))) + self.assertTrue(issubclass(B1, A)) + self.assertTrue(issubclass(B1, (A,))) class C1(C): pass B1.register(C1) - self.failIf(issubclass(C, B)) - self.failIf(issubclass(C, (B,))) - self.failIf(issubclass(C, B1)) - self.failIf(issubclass(C, (B1,))) - self.failUnless(issubclass(C1, A)) - self.failUnless(issubclass(C1, (A,))) - self.failUnless(issubclass(C1, B)) - self.failUnless(issubclass(C1, (B,))) - self.failUnless(issubclass(C1, B1)) - self.failUnless(issubclass(C1, (B1,))) + self.assertFalse(issubclass(C, B)) + self.assertFalse(issubclass(C, (B,))) + self.assertFalse(issubclass(C, B1)) + self.assertFalse(issubclass(C, (B1,))) + self.assertTrue(issubclass(C1, A)) + self.assertTrue(issubclass(C1, (A,))) + self.assertTrue(issubclass(C1, B)) + self.assertTrue(issubclass(C1, (B,))) + self.assertTrue(issubclass(C1, B1)) + self.assertTrue(issubclass(C1, (B1,))) C1.register(int) class MyInt(int): pass - self.failUnless(issubclass(MyInt, A)) - self.failUnless(issubclass(MyInt, (A,))) - self.failUnless(isinstance(42, A)) - self.failUnless(isinstance(42, (A,))) + self.assertTrue(issubclass(MyInt, A)) + self.assertTrue(issubclass(MyInt, (A,))) + self.assertTrue(isinstance(42, A)) + self.assertTrue(isinstance(42, (A,))) def test_all_new_methods_are_called(self): class A: diff --git a/Lib/test/test_abstract_numbers.py b/Lib/test/test_abstract_numbers.py index 034fb52..8f1fdd7 100644 --- a/Lib/test/test_abstract_numbers.py +++ b/Lib/test/test_abstract_numbers.py @@ -9,8 +9,8 @@ from test import test_support class TestNumbers(unittest.TestCase): def test_int(self): - self.failUnless(issubclass(int, Integral)) - self.failUnless(issubclass(int, Complex)) + self.assertTrue(issubclass(int, Integral)) + self.assertTrue(issubclass(int, Complex)) self.assertEqual(7, int(7).real) self.assertEqual(0, int(7).imag) @@ -19,8 +19,8 @@ class TestNumbers(unittest.TestCase): self.assertEqual(1, int(7).denominator) def test_long(self): - self.failUnless(issubclass(long, Integral)) - self.failUnless(issubclass(long, Complex)) + self.assertTrue(issubclass(long, Integral)) + self.assertTrue(issubclass(long, Complex)) self.assertEqual(7, long(7).real) self.assertEqual(0, long(7).imag) @@ -29,16 +29,16 @@ class TestNumbers(unittest.TestCase): self.assertEqual(1, long(7).denominator) def test_float(self): - self.failIf(issubclass(float, Rational)) - self.failUnless(issubclass(float, Real)) + self.assertFalse(issubclass(float, Rational)) + self.assertTrue(issubclass(float, Real)) self.assertEqual(7.3, float(7.3).real) self.assertEqual(0, float(7.3).imag) self.assertEqual(7.3, float(7.3).conjugate()) def test_complex(self): - self.failIf(issubclass(complex, Real)) - self.failUnless(issubclass(complex, Complex)) + self.assertFalse(issubclass(complex, Real)) + self.assertTrue(issubclass(complex, Complex)) c1, c2 = complex(3, 2), complex(4,1) # XXX: This is not ideal, but see the comment in math_trunc(). diff --git a/Lib/test/test_array.py b/Lib/test/test_array.py index 2c4c2fd..6433935 100755 --- a/Lib/test/test_array.py +++ b/Lib/test/test_array.py @@ -48,7 +48,7 @@ class BaseTest(unittest.TestCase): def test_constructor(self): a = array.array(self.typecode) self.assertEqual(a.typecode, self.typecode) - self.assert_(a.itemsize>=self.minitemsize) + self.assertTrue(a.itemsize>=self.minitemsize) self.assertRaises(TypeError, array.array, self.typecode, None) def test_len(self): @@ -63,10 +63,10 @@ class BaseTest(unittest.TestCase): a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.buffer_info, 42) bi = a.buffer_info() - self.assert_(isinstance(bi, tuple)) + self.assertTrue(isinstance(bi, tuple)) self.assertEqual(len(bi), 2) - self.assert_(isinstance(bi[0], (int, long))) - self.assert_(isinstance(bi[1], int)) + self.assertTrue(isinstance(bi[0], (int, long))) + self.assertTrue(isinstance(bi[1], int)) self.assertEqual(bi[1], len(a)) def test_byteswap(self): @@ -222,39 +222,39 @@ class BaseTest(unittest.TestCase): def test_cmp(self): a = array.array(self.typecode, self.example) - self.assert_((a == 42) is False) - self.assert_((a != 42) is True) + self.assertTrue((a == 42) is False) + self.assertTrue((a != 42) is True) - self.assert_((a == a) is True) - self.assert_((a != a) is False) - self.assert_((a < a) is False) - self.assert_((a <= a) is True) - self.assert_((a > a) is False) - self.assert_((a >= a) is True) + self.assertTrue((a == a) is True) + self.assertTrue((a != a) is False) + self.assertTrue((a < a) is False) + self.assertTrue((a <= a) is True) + self.assertTrue((a > a) is False) + self.assertTrue((a >= a) is True) al = array.array(self.typecode, self.smallerexample) ab = array.array(self.typecode, self.biggerexample) - self.assert_((a == 2*a) is False) - self.assert_((a != 2*a) is True) - self.assert_((a < 2*a) is True) - self.assert_((a <= 2*a) is True) - self.assert_((a > 2*a) is False) - self.assert_((a >= 2*a) is False) - - self.assert_((a == al) is False) - self.assert_((a != al) is True) - self.assert_((a < al) is False) - self.assert_((a <= al) is False) - self.assert_((a > al) is True) - self.assert_((a >= al) is True) - - self.assert_((a == ab) is False) - self.assert_((a != ab) is True) - self.assert_((a < ab) is True) - self.assert_((a <= ab) is True) - self.assert_((a > ab) is False) - self.assert_((a >= ab) is False) + self.assertTrue((a == 2*a) is False) + self.assertTrue((a != 2*a) is True) + self.assertTrue((a < 2*a) is True) + self.assertTrue((a <= 2*a) is True) + self.assertTrue((a > 2*a) is False) + self.assertTrue((a >= 2*a) is False) + + self.assertTrue((a == al) is False) + self.assertTrue((a != al) is True) + self.assertTrue((a < al) is False) + self.assertTrue((a <= al) is False) + self.assertTrue((a > al) is True) + self.assertTrue((a >= al) is True) + + self.assertTrue((a == ab) is False) + self.assertTrue((a != ab) is True) + self.assertTrue((a < ab) is True) + self.assertTrue((a <= ab) is True) + self.assertTrue((a > ab) is False) + self.assertTrue((a >= ab) is False) def test_add(self): a = array.array(self.typecode, self.example) \ @@ -273,7 +273,7 @@ class BaseTest(unittest.TestCase): a = array.array(self.typecode, self.example[::-1]) b = a a += array.array(self.typecode, 2*self.example) - self.assert_(a is b) + self.assertTrue(a is b) self.assertEqual( a, array.array(self.typecode, self.example[::-1]+2*self.example) @@ -316,22 +316,22 @@ class BaseTest(unittest.TestCase): b = a a *= 5 - self.assert_(a is b) + self.assertTrue(a is b) self.assertEqual( a, array.array(self.typecode, 5*self.example) ) a *= 0 - self.assert_(a is b) + self.assertTrue(a is b) self.assertEqual(a, array.array(self.typecode)) a *= 1000 - self.assert_(a is b) + self.assertTrue(a is b) self.assertEqual(a, array.array(self.typecode)) a *= -1 - self.assert_(a is b) + self.assertTrue(a is b) self.assertEqual(a, array.array(self.typecode)) a = array.array(self.typecode, self.example) diff --git a/Lib/test/test_ast.py b/Lib/test/test_ast.py index 89850f6..4e311e4 100644 --- a/Lib/test/test_ast.py +++ b/Lib/test/test_ast.py @@ -122,20 +122,20 @@ eval_tests = [ class AST_Tests(unittest.TestCase): - def _assert_order(self, ast_node, parent_pos): + def _assertTrueorder(self, ast_node, parent_pos): if not isinstance(ast_node, ast.AST) or ast_node._fields is None: return if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)): node_pos = (ast_node.lineno, ast_node.col_offset) - self.assert_(node_pos >= parent_pos) + self.assertTrue(node_pos >= parent_pos) parent_pos = (ast_node.lineno, ast_node.col_offset) for name in ast_node._fields: value = getattr(ast_node, name) if isinstance(value, list): for child in value: - self._assert_order(child, parent_pos) + self._assertTrueorder(child, parent_pos) elif value is not None: - self._assert_order(value, parent_pos) + self._assertTrueorder(value, parent_pos) def test_snippets(self): for input, output, kind in ((exec_tests, exec_results, "exec"), @@ -144,7 +144,7 @@ class AST_Tests(unittest.TestCase): for i, o in itertools.izip(input, output): ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST) self.assertEquals(to_tuple(ast_tree), o) - self._assert_order(ast_tree, (0, 0)) + self._assertTrueorder(ast_tree, (0, 0)) def test_slice(self): slc = ast.parse("x[::]").body[0].value.slice diff --git a/Lib/test/test_augassign.py b/Lib/test/test_augassign.py index dbf71bc..24aa2b7 100644 --- a/Lib/test/test_augassign.py +++ b/Lib/test/test_augassign.py @@ -71,7 +71,7 @@ class AugAssignTest(unittest.TestCase): y[1:2] += [1] self.assertEquals(x, [1, 2, 1, 2, 3]) - self.assert_(x is y) + self.assertTrue(x is y) def testCustomMethods1(self): @@ -96,23 +96,23 @@ class AugAssignTest(unittest.TestCase): y = x x += 10 - self.assert_(isinstance(x, aug_test)) - self.assert_(y is not x) + self.assertTrue(isinstance(x, aug_test)) + self.assertTrue(y is not x) self.assertEquals(x.val, 11) x = aug_test2(2) y = x x += 10 - self.assert_(y is x) + self.assertTrue(y is x) self.assertEquals(x.val, 12) x = aug_test3(3) y = x x += 10 - self.assert_(isinstance(x, aug_test3)) - self.assert_(y is not x) + self.assertTrue(isinstance(x, aug_test3)) + self.assertTrue(y is not x) self.assertEquals(x.val, 13) diff --git a/Lib/test/test_bigmem.py b/Lib/test/test_bigmem.py index 360bcb2..cb1b2f5 100644 --- a/Lib/test/test_bigmem.py +++ b/Lib/test/test_bigmem.py @@ -130,18 +130,18 @@ class StrTest(unittest.TestCase): except MemoryError: pass # acceptable on 32-bit else: - self.failUnless(s == eval(r)) + self.assertTrue(s == eval(r)) @bigmemtest(minsize=_2G, memuse=2) def test_endswith(self, size): SUBSTR = ' abc def ghi' s = '-' * size + SUBSTR - self.failUnless(s.endswith(SUBSTR)) - self.failUnless(s.endswith(s)) + self.assertTrue(s.endswith(SUBSTR)) + self.assertTrue(s.endswith(s)) s2 = '...' + s - self.failUnless(s2.endswith(s)) - self.failIf(s.endswith('a' + SUBSTR)) - self.failIf(SUBSTR.endswith(s)) + self.assertTrue(s2.endswith(s)) + self.assertFalse(s.endswith('a' + SUBSTR)) + self.assertFalse(SUBSTR.endswith(s)) @bigmemtest(minsize=_2G + 10, memuse=2) def test_expandtabs(self, size): @@ -191,62 +191,62 @@ class StrTest(unittest.TestCase): def test_isalnum(self, size): SUBSTR = '123456' s = 'a' * size + SUBSTR - self.failUnless(s.isalnum()) + self.assertTrue(s.isalnum()) s += '.' - self.failIf(s.isalnum()) + self.assertFalse(s.isalnum()) @bigmemtest(minsize=_2G, memuse=2) def test_isalpha(self, size): SUBSTR = 'zzzzzzz' s = 'a' * size + SUBSTR - self.failUnless(s.isalpha()) + self.assertTrue(s.isalpha()) s += '.' - self.failIf(s.isalpha()) + self.assertFalse(s.isalpha()) @bigmemtest(minsize=_2G, memuse=2) def test_isdigit(self, size): SUBSTR = '123456' s = '9' * size + SUBSTR - self.failUnless(s.isdigit()) + self.assertTrue(s.isdigit()) s += 'z' - self.failIf(s.isdigit()) + self.assertFalse(s.isdigit()) @bigmemtest(minsize=_2G, memuse=2) def test_islower(self, size): chars = ''.join([ chr(c) for c in range(255) if not chr(c).isupper() ]) repeats = size // len(chars) + 2 s = chars * repeats - self.failUnless(s.islower()) + self.assertTrue(s.islower()) s += 'A' - self.failIf(s.islower()) + self.assertFalse(s.islower()) @bigmemtest(minsize=_2G, memuse=2) def test_isspace(self, size): whitespace = ' \f\n\r\t\v' repeats = size // len(whitespace) + 2 s = whitespace * repeats - self.failUnless(s.isspace()) + self.assertTrue(s.isspace()) s += 'j' - self.failIf(s.isspace()) + self.assertFalse(s.isspace()) @bigmemtest(minsize=_2G, memuse=2) def test_istitle(self, size): SUBSTR = '123456' s = ''.join(['A', 'a' * size, SUBSTR]) - self.failUnless(s.istitle()) + self.assertTrue(s.istitle()) s += 'A' - self.failUnless(s.istitle()) + self.assertTrue(s.istitle()) s += 'aA' - self.failIf(s.istitle()) + self.assertFalse(s.istitle()) @bigmemtest(minsize=_2G, memuse=2) def test_isupper(self, size): chars = ''.join([ chr(c) for c in range(255) if not chr(c).islower() ]) repeats = size // len(chars) + 2 s = chars * repeats - self.failUnless(s.isupper()) + self.assertTrue(s.isupper()) s += 'a' - self.failIf(s.isupper()) + self.assertFalse(s.isupper()) @bigmemtest(minsize=_2G, memuse=2) def test_join(self, size): @@ -254,14 +254,14 @@ class StrTest(unittest.TestCase): x = s.join(['aaaaa', 'bbbbb']) self.assertEquals(x.count('a'), 5) self.assertEquals(x.count('b'), 5) - self.failUnless(x.startswith('aaaaaA')) - self.failUnless(x.endswith('Abbbbb')) + self.assertTrue(x.startswith('aaaaaA')) + self.assertTrue(x.endswith('Abbbbb')) @bigmemtest(minsize=_2G + 10, memuse=1) def test_ljust(self, size): SUBSTR = ' abc def ghi' s = SUBSTR.ljust(size) - self.failUnless(s.startswith(SUBSTR + ' ')) + self.assertTrue(s.startswith(SUBSTR + ' ')) self.assertEquals(len(s), size) self.assertEquals(s.strip(), SUBSTR.strip()) @@ -282,7 +282,7 @@ class StrTest(unittest.TestCase): s = SUBSTR.ljust(size) self.assertEquals(len(s), size) stripped = s.lstrip() - self.failUnless(stripped is s) + self.assertTrue(stripped is s) @bigmemtest(minsize=_2G + 10, memuse=2) def test_replace(self, size): @@ -333,7 +333,7 @@ class StrTest(unittest.TestCase): def test_rjust(self, size): SUBSTR = ' abc def ghi' s = SUBSTR.ljust(size) - self.failUnless(s.startswith(SUBSTR + ' ')) + self.assertTrue(s.startswith(SUBSTR + ' ')) self.assertEquals(len(s), size) self.assertEquals(s.strip(), SUBSTR.strip()) @@ -347,7 +347,7 @@ class StrTest(unittest.TestCase): s = SUBSTR.rjust(size) self.assertEquals(len(s), size) stripped = s.rstrip() - self.failUnless(stripped is s) + self.assertTrue(stripped is s) # The test takes about size bytes to build a string, and then about # sqrt(size) substrings of sqrt(size) in size and a list to @@ -399,9 +399,9 @@ class StrTest(unittest.TestCase): def test_startswith(self, size): SUBSTR = ' abc def ghi' s = '-' * size + SUBSTR - self.failUnless(s.startswith(s)) - self.failUnless(s.startswith('-' * size)) - self.failIf(s.startswith(SUBSTR)) + self.assertTrue(s.startswith(s)) + self.assertTrue(s.startswith('-' * size)) + self.assertFalse(s.startswith(SUBSTR)) @bigmemtest(minsize=_2G, memuse=1) def test_strip(self, size): @@ -430,8 +430,8 @@ class StrTest(unittest.TestCase): SUBSTR = 'SpaaHAaaAaham' s = SUBSTR * (size // len(SUBSTR) + 2) s = s.title() - self.failUnless(s.startswith((SUBSTR * 3).title())) - self.failUnless(s.endswith(SUBSTR.lower() * 3)) + self.assertTrue(s.startswith((SUBSTR * 3).title())) + self.assertTrue(s.endswith(SUBSTR.lower() * 3)) @bigmemtest(minsize=_2G, memuse=2) def test_translate(self, size): @@ -459,8 +459,8 @@ class StrTest(unittest.TestCase): def test_zfill(self, size): SUBSTR = '-568324723598234' s = SUBSTR.zfill(size) - self.failUnless(s.endswith('0' + SUBSTR[1:])) - self.failUnless(s.startswith('-0')) + self.assertTrue(s.endswith('0' + SUBSTR[1:])) + self.assertTrue(s.startswith('-0')) self.assertEquals(len(s), size) self.assertEquals(s.count('0'), size - len(SUBSTR)) @@ -468,12 +468,12 @@ class StrTest(unittest.TestCase): def test_format(self, size): s = '-' * size sf = '%s' % (s,) - self.failUnless(s == sf) + self.assertTrue(s == sf) del sf sf = '..%s..' % (s,) self.assertEquals(len(sf), len(s) + 4) - self.failUnless(sf.startswith('..-')) - self.failUnless(sf.endswith('-..')) + self.assertTrue(sf.startswith('..-')) + self.assertTrue(sf.endswith('-..')) del s, sf size //= 2 @@ -519,7 +519,7 @@ class StrTest(unittest.TestCase): @bigmemtest(minsize=2**32 / 5, memuse=6+2) def test_unicode_repr(self, size): s = u"\uAAAA" * size - self.failUnless(len(repr(s)) > size) + self.assertTrue(len(repr(s)) > size) # This test is meaningful even with size < 2G, as long as the # doubled string is > 2G (but it tests more if both are > 2G :) @@ -580,24 +580,24 @@ class StrTest(unittest.TestCase): edge = '-' * (size // 2) s = ''.join([edge, SUBSTR, edge]) del edge - self.failUnless(SUBSTR in s) - self.failIf(SUBSTR * 2 in s) - self.failUnless('-' in s) - self.failIf('a' in s) + self.assertTrue(SUBSTR in s) + self.assertFalse(SUBSTR * 2 in s) + self.assertTrue('-' in s) + self.assertFalse('a' in s) s += 'a' - self.failUnless('a' in s) + self.assertTrue('a' in s) @bigmemtest(minsize=_2G + 10, memuse=2) def test_compare(self, size): s1 = '-' * size s2 = '-' * size - self.failUnless(s1 == s2) + self.assertTrue(s1 == s2) del s2 s2 = s1 + 'a' - self.failIf(s1 == s2) + self.assertFalse(s1 == s2) del s2 s2 = '.' * size - self.failIf(s1 == s2) + self.assertFalse(s1 == s2) @bigmemtest(minsize=_2G + 10, memuse=1) def test_hash(self, size): @@ -611,7 +611,7 @@ class StrTest(unittest.TestCase): h1 = hash(s) del s s = '\x00' * (size + 1) - self.failIf(h1 == hash(s)) + self.assertFalse(h1 == hash(s)) class TupleTest(unittest.TestCase): @@ -628,13 +628,13 @@ class TupleTest(unittest.TestCase): def test_compare(self, size): t1 = (u'',) * size t2 = (u'',) * size - self.failUnless(t1 == t2) + self.assertTrue(t1 == t2) del t2 t2 = (u'',) * (size + 1) - self.failIf(t1 == t2) + self.assertFalse(t1 == t2) del t2 t2 = (1,) * size - self.failIf(t1 == t2) + self.assertFalse(t1 == t2) # Test concatenating into a single tuple of more than 2G in length, # and concatenating a tuple of more than 2G in length separately, so @@ -659,9 +659,9 @@ class TupleTest(unittest.TestCase): def test_contains(self, size): t = (1, 2, 3, 4, 5) * size self.assertEquals(len(t), size * 5) - self.failUnless(5 in t) - self.failIf((1, 2, 3, 4, 5) in t) - self.failIf(0 in t) + self.assertTrue(5 in t) + self.assertFalse((1, 2, 3, 4, 5) in t) + self.assertFalse(0 in t) @bigmemtest(minsize=_2G + 10, memuse=8) def test_hash(self, size): @@ -669,7 +669,7 @@ class TupleTest(unittest.TestCase): h1 = hash(t1) del t1 t2 = (0,) * (size + 1) - self.failIf(h1 == hash(t2)) + self.assertFalse(h1 == hash(t2)) @bigmemtest(minsize=_2G + 10, memuse=8) def test_index_and_slice(self, size): @@ -762,13 +762,13 @@ class ListTest(unittest.TestCase): def test_compare(self, size): l1 = [u''] * size l2 = [u''] * size - self.failUnless(l1 == l2) + self.assertTrue(l1 == l2) del l2 l2 = [u''] * (size + 1) - self.failIf(l1 == l2) + self.assertFalse(l1 == l2) del l2 l2 = [2] * size - self.failIf(l1 == l2) + self.assertFalse(l1 == l2) # Test concatenating into a single list of more than 2G in length, # and concatenating a list of more than 2G in length separately, so @@ -793,8 +793,8 @@ class ListTest(unittest.TestCase): l = [sys.stdout] * size l += l self.assertEquals(len(l), size * 2) - self.failUnless(l[0] is l[-1]) - self.failUnless(l[size - 1] is l[size + 1]) + self.assertTrue(l[0] is l[-1]) + self.assertTrue(l[size - 1] is l[size + 1]) @bigmemtest(minsize=_2G // 2 + 2, memuse=24) def test_inplace_concat_small(self, size): @@ -808,14 +808,14 @@ class ListTest(unittest.TestCase): def test_contains(self, size): l = [1, 2, 3, 4, 5] * size self.assertEquals(len(l), size * 5) - self.failUnless(5 in l) - self.failIf([1, 2, 3, 4, 5] in l) - self.failIf(0 in l) + self.assertTrue(5 in l) + self.assertFalse([1, 2, 3, 4, 5] in l) + self.assertFalse(0 in l) @bigmemtest(minsize=_2G + 10, memuse=8) def test_hash(self, size): l = [0] * size - self.failUnlessRaises(TypeError, hash, l) + self.assertRaises(TypeError, hash, l) @bigmemtest(minsize=_2G + 10, memuse=8) def test_index_and_slice(self, size): @@ -875,7 +875,7 @@ class ListTest(unittest.TestCase): # Like test_concat, split in two. def basic_test_repeat(self, size): l = [] * size - self.failIf(l) + self.assertFalse(l) l = [''] * size self.assertEquals(len(l), size) l = l * 2 @@ -893,13 +893,13 @@ class ListTest(unittest.TestCase): l = [''] l *= size self.assertEquals(len(l), size) - self.failUnless(l[0] is l[-1]) + self.assertTrue(l[0] is l[-1]) del l l = [''] * size l *= 2 self.assertEquals(len(l), size * 2) - self.failUnless(l[size - 1] is l[-1]) + self.assertTrue(l[size - 1] is l[-1]) @bigmemtest(minsize=_2G // 2 + 2, memuse=16) def test_inplace_repeat_small(self, size): @@ -933,8 +933,8 @@ class ListTest(unittest.TestCase): l = [object()] * size l.append(object()) self.assertEquals(len(l), size+1) - self.failUnless(l[-3] is l[-2]) - self.failIf(l[-2] is l[-1]) + self.assertTrue(l[-3] is l[-2]) + self.assertFalse(l[-2] is l[-1]) @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) def test_count(self, size): @@ -946,8 +946,8 @@ class ListTest(unittest.TestCase): l = [file] * size l.extend(l) self.assertEquals(len(l), size * 2) - self.failUnless(l[0] is l[-1]) - self.failUnless(l[size - 1] is l[size + 1]) + self.assertTrue(l[0] is l[-1]) + self.assertTrue(l[size - 1] is l[size + 1]) @bigmemtest(minsize=_2G // 2 + 2, memuse=16) def test_extend_small(self, size): diff --git a/Lib/test/test_binascii.py b/Lib/test/test_binascii.py index ea8be31..c531c65 100755 --- a/Lib/test/test_binascii.py +++ b/Lib/test/test_binascii.py @@ -14,8 +14,8 @@ class BinASCIITest(unittest.TestCase): def test_exceptions(self): # Check module exceptions - self.assert_(issubclass(binascii.Error, Exception)) - self.assert_(issubclass(binascii.Incomplete, Exception)) + self.assertTrue(issubclass(binascii.Error, Exception)) + self.assertTrue(issubclass(binascii.Incomplete, Exception)) def test_functions(self): # Check presence of all functions @@ -26,10 +26,10 @@ class BinASCIITest(unittest.TestCase): prefixes.extend(["crc_", "rlecode_", "rledecode_"]) for prefix in prefixes: name = prefix + suffix - self.assert_(callable(getattr(binascii, name))) + self.assertTrue(callable(getattr(binascii, name))) self.assertRaises(TypeError, getattr(binascii, name)) for name in ("hexlify", "unhexlify"): - self.assert_(callable(getattr(binascii, name))) + self.assertTrue(callable(getattr(binascii, name))) self.assertRaises(TypeError, getattr(binascii, name)) def test_base64valid(self): diff --git a/Lib/test/test_binop.py b/Lib/test/test_binop.py index b3d9a62..8ae8f42 100644 --- a/Lib/test/test_binop.py +++ b/Lib/test/test_binop.py @@ -220,10 +220,10 @@ class RatTestCase(unittest.TestCase): self.assertEqual(gcd(-10, -2), -2) for i in range(1, 20): for j in range(1, 20): - self.assert_(gcd(i, j) > 0) - self.assert_(gcd(-i, j) < 0) - self.assert_(gcd(i, -j) > 0) - self.assert_(gcd(-i, -j) < 0) + self.assertTrue(gcd(i, j) > 0) + self.assertTrue(gcd(-i, j) < 0) + self.assertTrue(gcd(i, -j) > 0) + self.assertTrue(gcd(-i, -j) < 0) def test_constructor(self): a = Rat(10, 15) diff --git a/Lib/test/test_bisect.py b/Lib/test/test_bisect.py index 66bae48..934ba8c 100644 --- a/Lib/test/test_bisect.py +++ b/Lib/test/test_bisect.py @@ -130,14 +130,14 @@ class TestBisect(unittest.TestCase): elem = randrange(-1, n+1) ip = self.module.bisect_left(data, elem) if ip < len(data): - self.failUnless(elem <= data[ip]) + self.assertTrue(elem <= data[ip]) if ip > 0: - self.failUnless(data[ip-1] < elem) + self.assertTrue(data[ip-1] < elem) ip = self.module.bisect_right(data, elem) if ip < len(data): - self.failUnless(elem < data[ip]) + self.assertTrue(elem < data[ip]) if ip > 0: - self.failUnless(data[ip-1] <= elem) + self.assertTrue(data[ip-1] <= elem) def test_optionalSlicing(self): for func, data, elem, expected in self.precomputedCases: @@ -146,15 +146,15 @@ class TestBisect(unittest.TestCase): for hi in xrange(3,8): hi = min(len(data), hi) ip = func(data, elem, lo, hi) - self.failUnless(lo <= ip <= hi) + self.assertTrue(lo <= ip <= hi) if func is self.module.bisect_left and ip < hi: - self.failUnless(elem <= data[ip]) + self.assertTrue(elem <= data[ip]) if func is self.module.bisect_left and ip > lo: - self.failUnless(data[ip-1] < elem) + self.assertTrue(data[ip-1] < elem) if func is self.module.bisect_right and ip < hi: - self.failUnless(elem < data[ip]) + self.assertTrue(elem < data[ip]) if func is self.module.bisect_right and ip > lo: - self.failUnless(data[ip-1] <= elem) + self.assertTrue(data[ip-1] <= elem) self.assertEqual(ip, max(lo, min(hi, expected))) def test_backcompatibility(self): diff --git a/Lib/test/test_bool.py b/Lib/test/test_bool.py index 33185a0..2a9ef5d 100644 --- a/Lib/test/test_bool.py +++ b/Lib/test/test_bool.py @@ -8,10 +8,10 @@ import os class BoolTest(unittest.TestCase): def assertIs(self, a, b): - self.assert_(a is b) + self.assertTrue(a is b) def assertIsNot(self, a, b): - self.assert_(a is not b) + self.assertTrue(a is not b) def test_subclass(self): try: @@ -233,15 +233,15 @@ class BoolTest(unittest.TestCase): def test_boolean(self): self.assertEqual(True & 1, 1) - self.assert_(not isinstance(True & 1, bool)) + self.assertTrue(not isinstance(True & 1, bool)) self.assertIs(True & True, True) self.assertEqual(True | 1, 1) - self.assert_(not isinstance(True | 1, bool)) + self.assertTrue(not isinstance(True | 1, bool)) self.assertIs(True | True, True) self.assertEqual(True ^ 1, 0) - self.assert_(not isinstance(True ^ 1, bool)) + self.assertTrue(not isinstance(True ^ 1, bool)) self.assertIs(True ^ True, False) def test_fileclosed(self): diff --git a/Lib/test/test_bsddb.py b/Lib/test/test_bsddb.py index 56dade4..a4af0f3 100755 --- a/Lib/test/test_bsddb.py +++ b/Lib/test/test_bsddb.py @@ -43,8 +43,8 @@ class TestBSDDB(unittest.TestCase): def test_change(self): self.f['r'] = 'discovered' self.assertEqual(self.f['r'], 'discovered') - self.assert_('r' in self.f.keys()) - self.assert_('discovered' in self.f.values()) + self.assertTrue('r' in self.f.keys()) + self.assertTrue('discovered' in self.f.values()) def test_close_and_reopen(self): if self.fname is None: @@ -176,7 +176,7 @@ class TestBSDDB(unittest.TestCase): def test_first_while_deleting(self): # Test for bug 1725856 - self.assert_(len(self.d) >= 2, "test requires >=2 items") + self.assertTrue(len(self.d) >= 2, "test requires >=2 items") for _ in self.d: key = self.f.first()[0] del self.f[key] @@ -184,7 +184,7 @@ class TestBSDDB(unittest.TestCase): def test_last_while_deleting(self): # Test for bug 1725856's evil twin - self.assert_(len(self.d) >= 2, "test requires >=2 items") + self.assertTrue(len(self.d) >= 2, "test requires >=2 items") for _ in self.d: key = self.f.last()[0] del self.f[key] @@ -195,13 +195,13 @@ class TestBSDDB(unittest.TestCase): def test_contains(self): for k in self.d: - self.assert_(k in self.f) - self.assert_('not here' not in self.f) + self.assertTrue(k in self.f) + self.assertTrue('not here' not in self.f) def test_has_key(self): for k in self.d: - self.assert_(self.f.has_key(k)) - self.assert_(not self.f.has_key('not here')) + self.assertTrue(self.f.has_key(k)) + self.assertTrue(not self.f.has_key('not here')) def test_clear(self): self.f.clear() @@ -253,11 +253,11 @@ class TestBSDDB(unittest.TestCase): if debug: print "K" # test the legacy cursor interface mixed with writes - self.assert_(self.f.first()[0] in self.d) + self.assertTrue(self.f.first()[0] in self.d) k = self.f.next()[0] - self.assert_(k in self.d) + self.assertTrue(k in self.d) self.f[k] = "be gone with ye deadlocks" - self.assert_(self.f[k], "be gone with ye deadlocks") + self.assertTrue(self.f[k], "be gone with ye deadlocks") def test_for_cursor_memleak(self): # do the bsddb._DBWithCursor iterator internals leak cursors? @@ -275,21 +275,21 @@ class TestBSDDB(unittest.TestCase): self.assertEqual(nc1, nc2) self.assertEqual(nc1, nc4) - self.assert_(nc3 == nc1+1) + self.assertTrue(nc3 == nc1+1) def test_popitem(self): k, v = self.f.popitem() - self.assert_(k in self.d) - self.assert_(v in self.d.values()) - self.assert_(k not in self.f) + self.assertTrue(k in self.d) + self.assertTrue(v in self.d.values()) + self.assertTrue(k not in self.f) self.assertEqual(len(self.d)-1, len(self.f)) def test_pop(self): k = 'w' v = self.f.pop(k) self.assertEqual(v, self.d[k]) - self.assert_(k not in self.f) - self.assert_(v not in self.f.values()) + self.assertTrue(k not in self.f) + self.assertTrue(v not in self.f.values()) self.assertEqual(len(self.d)-1, len(self.f)) def test_get(self): diff --git a/Lib/test/test_bufio.py b/Lib/test/test_bufio.py index 48cc0f3..108b1e1 100644 --- a/Lib/test/test_bufio.py +++ b/Lib/test/test_bufio.py @@ -34,7 +34,7 @@ class BufferSizeTest(unittest.TestCase): line = f.readline() self.assertEqual(line, s) line = f.readline() - self.assert_(not line) # Must be at EOF + self.assertTrue(not line) # Must be at EOF f.close() finally: support.unlink(support.TESTFN) diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index 19ce9ec..80e1b81 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -122,7 +122,7 @@ class BuiltinTest(unittest.TestCase): def test_neg(self): x = -sys.maxint-1 - self.assert_(isinstance(x, int)) + self.assertTrue(isinstance(x, int)) self.assertEqual(-x, sys.maxint+1) def test_apply(self): @@ -152,19 +152,19 @@ class BuiltinTest(unittest.TestCase): self.assertRaises(TypeError, apply, id, (42,), 42) def test_callable(self): - self.assert_(callable(len)) + self.assertTrue(callable(len)) def f(): pass - self.assert_(callable(f)) + self.assertTrue(callable(f)) class C: def meth(self): pass - self.assert_(callable(C)) + self.assertTrue(callable(C)) x = C() - self.assert_(callable(x.meth)) - self.assert_(not callable(x)) + self.assertTrue(callable(x.meth)) + self.assertTrue(not callable(x)) class D(C): def __call__(self): pass y = D() - self.assert_(callable(y)) + self.assertTrue(callable(y)) y() def test_chr(self): @@ -193,9 +193,9 @@ class BuiltinTest(unittest.TestCase): self.assertRaises(TypeError, cmp) def test_coerce(self): - self.assert_(not fcmp(coerce(1, 1.1), (1.0, 1.1))) + self.assertTrue(not fcmp(coerce(1, 1.1), (1.0, 1.1))) self.assertEqual(coerce(1, 1L), (1L, 1L)) - self.assert_(not fcmp(coerce(1L, 1.1), (1.0, 1.1))) + self.assertTrue(not fcmp(coerce(1L, 1.1), (1.0, 1.1))) self.assertRaises(TypeError, coerce) class BadNumber: def __coerce__(self, other): @@ -234,11 +234,11 @@ class BuiltinTest(unittest.TestCase): # dir() - local scope local_var = 1 - self.assert_('local_var' in dir()) + self.assertTrue('local_var' in dir()) # dir(module) import sys - self.assert_('exit' in dir(sys)) + self.assertTrue('exit' in dir(sys)) # dir(module_with_invalid__dict__) import types @@ -248,8 +248,8 @@ class BuiltinTest(unittest.TestCase): self.assertRaises(TypeError, dir, f) # dir(type) - self.assert_("strip" in dir(str)) - self.assert_("__mro__" not in dir(str)) + self.assertTrue("strip" in dir(str)) + self.assertTrue("__mro__" not in dir(str)) # dir(obj) class Foo(object): @@ -258,13 +258,13 @@ class BuiltinTest(unittest.TestCase): self.y = 8 self.z = 9 f = Foo() - self.assert_("y" in dir(f)) + self.assertTrue("y" in dir(f)) # dir(obj_no__dict__) class Foo(object): __slots__ = [] f = Foo() - self.assert_("__repr__" in dir(f)) + self.assertTrue("__repr__" in dir(f)) # dir(obj_no__class__with__dict__) # (an ugly trick to cause getattr(f, "__class__") to fail) @@ -273,15 +273,15 @@ class BuiltinTest(unittest.TestCase): def __init__(self): self.bar = "wow" f = Foo() - self.assert_("__repr__" not in dir(f)) - self.assert_("bar" in dir(f)) + self.assertTrue("__repr__" not in dir(f)) + self.assertTrue("bar" in dir(f)) # dir(obj_using __dir__) class Foo(object): def __dir__(self): return ["kan", "ga", "roo"] f = Foo() - self.assert_(dir(f) == ["ga", "kan", "roo"]) + self.assertTrue(dir(f) == ["ga", "kan", "roo"]) # dir(obj__dir__not_list) class Foo(object): @@ -309,10 +309,10 @@ class BuiltinTest(unittest.TestCase): self.assertEqual(divmod(-sys.maxint-1, -1), (sys.maxint+1, 0)) - self.assert_(not fcmp(divmod(3.25, 1.0), (3.0, 0.25))) - self.assert_(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75))) - self.assert_(not fcmp(divmod(3.25, -1.0), (-4.0, -0.75))) - self.assert_(not fcmp(divmod(-3.25, -1.0), (3.0, -0.25))) + self.assertTrue(not fcmp(divmod(3.25, 1.0), (3.0, 0.25))) + self.assertTrue(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75))) + self.assertTrue(not fcmp(divmod(3.25, -1.0), (-4.0, -0.75))) + self.assertTrue(not fcmp(divmod(-3.25, -1.0), (3.0, -0.25))) self.assertRaises(TypeError, divmod) @@ -571,11 +571,11 @@ class BuiltinTest(unittest.TestCase): for func in funcs: outp = filter(func, cls(inp)) self.assertEqual(outp, exp) - self.assert_(not isinstance(outp, cls)) + self.assertTrue(not isinstance(outp, cls)) def test_getattr(self): import sys - self.assert_(getattr(sys, 'stdout') is sys.stdout) + self.assertTrue(getattr(sys, 'stdout') is sys.stdout) self.assertRaises(TypeError, getattr, sys, 1) self.assertRaises(TypeError, getattr, sys, 1, "foo") self.assertRaises(TypeError, getattr) @@ -584,7 +584,7 @@ class BuiltinTest(unittest.TestCase): def test_hasattr(self): import sys - self.assert_(hasattr(sys, 'stdout')) + self.assertTrue(hasattr(sys, 'stdout')) self.assertRaises(TypeError, hasattr, sys, 1) self.assertRaises(TypeError, hasattr) if have_unicode: @@ -647,9 +647,9 @@ class BuiltinTest(unittest.TestCase): def test_intern(self): self.assertRaises(TypeError, intern) s = "never interned before" - self.assert_(intern(s) is s) + self.assertTrue(intern(s) is s) s2 = s.swapcase().swapcase() - self.assert_(intern(s2) is s) + self.assertTrue(intern(s2) is s) # Subclasses of string can't be interned, because they # provide too much opportunity for insane things to happen. @@ -690,11 +690,11 @@ class BuiltinTest(unittest.TestCase): c = C() d = D() e = E() - self.assert_(isinstance(c, C)) - self.assert_(isinstance(d, C)) - self.assert_(not isinstance(e, C)) - self.assert_(not isinstance(c, D)) - self.assert_(not isinstance('foo', E)) + self.assertTrue(isinstance(c, C)) + self.assertTrue(isinstance(d, C)) + self.assertTrue(not isinstance(e, C)) + self.assertTrue(not isinstance(c, D)) + self.assertTrue(not isinstance('foo', E)) self.assertRaises(TypeError, isinstance, E, 'foo') self.assertRaises(TypeError, isinstance) @@ -708,9 +708,9 @@ class BuiltinTest(unittest.TestCase): c = C() d = D() e = E() - self.assert_(issubclass(D, C)) - self.assert_(issubclass(C, C)) - self.assert_(not issubclass(C, D)) + self.assertTrue(issubclass(D, C)) + self.assertTrue(issubclass(C, C)) + self.assertTrue(not issubclass(C, D)) self.assertRaises(TypeError, issubclass, 'foo', E) self.assertRaises(TypeError, issubclass, E, 'foo') self.assertRaises(TypeError, issubclass) @@ -1042,18 +1042,18 @@ class BuiltinTest(unittest.TestCase): self.assertEqual(range(a+4, a, -2), [a+4, a+2]) seq = range(a, b, c) - self.assert_(a in seq) - self.assert_(b not in seq) + self.assertTrue(a in seq) + self.assertTrue(b not in seq) self.assertEqual(len(seq), 2) seq = range(b, a, -c) - self.assert_(b in seq) - self.assert_(a not in seq) + self.assertTrue(b in seq) + self.assertTrue(a not in seq) self.assertEqual(len(seq), 2) seq = range(-a, -b, -c) - self.assert_(-a in seq) - self.assert_(-b not in seq) + self.assertTrue(-a in seq) + self.assertTrue(-b not in seq) self.assertEqual(len(seq), 2) self.assertRaises(TypeError, range) @@ -1452,7 +1452,7 @@ class BuiltinTest(unittest.TestCase): # tests for object.__format__ really belong elsewhere, but # there's no good place to put them x = object().__format__('') - self.assert_(x.startswith('<object object at')) + self.assertTrue(x.startswith('<object object at')) # first argument to object.__format__ must be string self.assertRaises(TypeError, object().__format__, 3) diff --git a/Lib/test/test_bytes.py b/Lib/test/test_bytes.py index 09b497b..ee4804f 100644 --- a/Lib/test/test_bytes.py +++ b/Lib/test/test_bytes.py @@ -102,22 +102,22 @@ class BaseBytesTest(unittest.TestCase): b3 = self.type2test([1, 3]) self.assertEqual(b1, b2) - self.failUnless(b2 != b3) - self.failUnless(b1 <= b2) - self.failUnless(b1 <= b3) - self.failUnless(b1 < b3) - self.failUnless(b1 >= b2) - self.failUnless(b3 >= b2) - self.failUnless(b3 > b2) - - self.failIf(b1 != b2) - self.failIf(b2 == b3) - self.failIf(b1 > b2) - self.failIf(b1 > b3) - self.failIf(b1 >= b3) - self.failIf(b1 < b2) - self.failIf(b3 < b2) - self.failIf(b3 <= b2) + self.assertTrue(b2 != b3) + self.assertTrue(b1 <= b2) + self.assertTrue(b1 <= b3) + self.assertTrue(b1 < b3) + self.assertTrue(b1 >= b2) + self.assertTrue(b3 >= b2) + self.assertTrue(b3 > b2) + + self.assertFalse(b1 != b2) + self.assertFalse(b2 == b3) + self.assertFalse(b1 > b2) + self.assertFalse(b1 > b3) + self.assertFalse(b1 >= b3) + self.assertFalse(b1 < b2) + self.assertFalse(b3 < b2) + self.assertFalse(b3 <= b2) def test_compare_to_str(self): warnings.simplefilter('ignore', BytesWarning) @@ -220,27 +220,27 @@ class BaseBytesTest(unittest.TestCase): def test_contains(self): b = self.type2test(b"abc") - self.failUnless(ord('a') in b) - self.failUnless(int(ord('a')) in b) - self.failIf(200 in b) - self.failIf(200 in b) + self.assertTrue(ord('a') in b) + self.assertTrue(int(ord('a')) in b) + self.assertFalse(200 in b) + self.assertFalse(200 in b) self.assertRaises(ValueError, lambda: 300 in b) self.assertRaises(ValueError, lambda: -1 in b) self.assertRaises(TypeError, lambda: None in b) self.assertRaises(TypeError, lambda: float(ord('a')) in b) self.assertRaises(TypeError, lambda: u"a" in b) for f in bytes, bytearray: - self.failUnless(f(b"") in b) - self.failUnless(f(b"a") in b) - self.failUnless(f(b"b") in b) - self.failUnless(f(b"c") in b) - self.failUnless(f(b"ab") in b) - self.failUnless(f(b"bc") in b) - self.failUnless(f(b"abc") in b) - self.failIf(f(b"ac") in b) - self.failIf(f(b"d") in b) - self.failIf(f(b"dab") in b) - self.failIf(f(b"abd") in b) + self.assertTrue(f(b"") in b) + self.assertTrue(f(b"a") in b) + self.assertTrue(f(b"b") in b) + self.assertTrue(f(b"c") in b) + self.assertTrue(f(b"ab") in b) + self.assertTrue(f(b"bc") in b) + self.assertTrue(f(b"abc") in b) + self.assertFalse(f(b"ac") in b) + self.assertFalse(f(b"d") in b) + self.assertFalse(f(b"dab") in b) + self.assertFalse(f(b"abd") in b) def test_fromhex(self): self.assertRaises(TypeError, self.type2test.fromhex) @@ -600,7 +600,7 @@ class ByteArrayTest(BaseBytesTest): b += b"def" self.assertEqual(b, b"abcdef") self.assertEqual(b, b1) - self.failUnless(b is b1) + self.assertTrue(b is b1) b += b"xyz" self.assertEqual(b, b"abcdefxyz") try: @@ -616,7 +616,7 @@ class ByteArrayTest(BaseBytesTest): b *= 3 self.assertEqual(b, b"abcabcabc") self.assertEqual(b, b1) - self.failUnless(b is b1) + self.assertTrue(b is b1) def test_irepeat_1char(self): b = bytearray(b"x") @@ -624,17 +624,17 @@ class ByteArrayTest(BaseBytesTest): b *= 100 self.assertEqual(b, b"x"*100) self.assertEqual(b, b1) - self.failUnless(b is b1) + self.assertTrue(b is b1) def test_alloc(self): b = bytearray() alloc = b.__alloc__() - self.assert_(alloc >= 0) + self.assertTrue(alloc >= 0) seq = [alloc] for i in range(100): b += b"x" alloc = b.__alloc__() - self.assert_(alloc >= len(b)) + self.assertTrue(alloc >= len(b)) if alloc not in seq: seq.append(alloc) @@ -734,7 +734,7 @@ class ByteArrayTest(BaseBytesTest): a, b, c = bytearray(b"x").partition(b"y") self.assertEqual(b, b"") self.assertEqual(c, b"") - self.assert_(b is not c) + self.assertTrue(b is not c) b += b"!" self.assertEqual(c, b"") a, b, c = bytearray(b"x").partition(b"y") @@ -744,7 +744,7 @@ class ByteArrayTest(BaseBytesTest): b, c, a = bytearray(b"x").rpartition(b"y") self.assertEqual(b, b"") self.assertEqual(c, b"") - self.assert_(b is not c) + self.assertTrue(b is not c) b += b"!" self.assertEqual(c, b"") c, b, a = bytearray(b"x").rpartition(b"y") @@ -836,10 +836,10 @@ class AssortedBytesTest(unittest.TestCase): self.assertEqual(bytes(b"abc") <= b"ab", False) def test_doc(self): - self.failUnless(bytearray.__doc__ != None) - self.failUnless(bytearray.__doc__.startswith("bytearray("), bytearray.__doc__) - self.failUnless(bytes.__doc__ != None) - self.failUnless(bytes.__doc__.startswith("bytes("), bytes.__doc__) + self.assertTrue(bytearray.__doc__ != None) + self.assertTrue(bytearray.__doc__.startswith("bytearray("), bytearray.__doc__) + self.assertTrue(bytes.__doc__ != None) + self.assertTrue(bytes.__doc__.startswith("bytes("), bytes.__doc__) def test_from_bytearray(self): sample = bytes(b"Hello world\n\x80\x81\xfe\xff") @@ -958,20 +958,20 @@ class ByteArraySubclass(bytearray): class ByteArraySubclassTest(unittest.TestCase): def test_basic(self): - self.assert_(issubclass(ByteArraySubclass, bytearray)) - self.assert_(isinstance(ByteArraySubclass(), bytearray)) + self.assertTrue(issubclass(ByteArraySubclass, bytearray)) + self.assertTrue(isinstance(ByteArraySubclass(), bytearray)) a, b = b"abcd", b"efgh" _a, _b = ByteArraySubclass(a), ByteArraySubclass(b) # test comparison operators with subclass instances - self.assert_(_a == _a) - self.assert_(_a != _b) - self.assert_(_a < _b) - self.assert_(_a <= _b) - self.assert_(_b >= _a) - self.assert_(_b > _a) - self.assert_(_a is not a) + self.assertTrue(_a == _a) + self.assertTrue(_a != _b) + self.assertTrue(_a < _b) + self.assertTrue(_a <= _b) + self.assertTrue(_b >= _a) + self.assertTrue(_b > _a) + self.assertTrue(_a is not a) # test concat of subclass instances self.assertEqual(a + b, _a + _b) @@ -979,7 +979,7 @@ class ByteArraySubclassTest(unittest.TestCase): self.assertEqual(a + b, _a + b) # test repeat - self.assert_(a*5 == _a*5) + self.assertTrue(a*5 == _a*5) def test_join(self): # Make sure join returns a NEW object for single item sequences @@ -987,12 +987,12 @@ class ByteArraySubclassTest(unittest.TestCase): # Make sure that it is of the appropriate type. s1 = ByteArraySubclass(b"abcd") s2 = bytearray().join([s1]) - self.assert_(s1 is not s2) - self.assert_(type(s2) is bytearray, type(s2)) + self.assertTrue(s1 is not s2) + self.assertTrue(type(s2) is bytearray, type(s2)) # Test reverse, calling join on subclass s3 = s1.join([b"abcd"]) - self.assert_(type(s3) is bytearray) + self.assertTrue(type(s3) is bytearray) def test_pickle(self): a = ByteArraySubclass(b"abcd") diff --git a/Lib/test/test_capi.py b/Lib/test/test_capi.py index 87fe13c..4dc3104 100644 --- a/Lib/test/test_capi.py +++ b/Lib/test/test_capi.py @@ -41,7 +41,7 @@ class TestPendingCalls(unittest.TestCase): if context and not context.event.is_set(): continue count += 1 - self.failUnless(count < 10000, + self.assertTrue(count < 10000, "timeout waiting for %i callbacks, got %i"%(n, len(l))) if False and test_support.verbose: print "(%i)"%(len(l),) diff --git a/Lib/test/test_cfgparser.py b/Lib/test/test_cfgparser.py index a0d8051..b99ddc1 100644 --- a/Lib/test/test_cfgparser.py +++ b/Lib/test/test_cfgparser.py @@ -81,16 +81,16 @@ class TestCaseBase(unittest.TestCase): eq(cf.get('Spaces', 'key with spaces'), 'value') eq(cf.get('Spaces', 'another with spaces'), 'splat!') - self.failIf('__name__' in cf.options("Foo Bar"), + self.assertFalse('__name__' in cf.options("Foo Bar"), '__name__ "option" should not be exposed by the API!') # Make sure the right things happen for remove_option(); # added to include check for SourceForge bug #123324: - self.failUnless(cf.remove_option('Foo Bar', 'foo'), + self.assertTrue(cf.remove_option('Foo Bar', 'foo'), "remove_option() failed to report existence of option") - self.failIf(cf.has_option('Foo Bar', 'foo'), + self.assertFalse(cf.has_option('Foo Bar', 'foo'), "remove_option() failed to remove option") - self.failIf(cf.remove_option('Foo Bar', 'foo'), + self.assertFalse(cf.remove_option('Foo Bar', 'foo'), "remove_option() failed to report non-existence of option" " that was removed") @@ -112,10 +112,10 @@ class TestCaseBase(unittest.TestCase): eq(cf.options("a"), ["b"]) eq(cf.get("a", "b"), "value", "could not locate option, expecting case-insensitive option names") - self.failUnless(cf.has_option("a", "b")) + self.assertTrue(cf.has_option("a", "b")) cf.set("A", "A-B", "A-B value") for opt in ("a-b", "A-b", "a-B", "A-B"): - self.failUnless( + self.assertTrue( cf.has_option("A", opt), "has_option() returned false for option which should exist") eq(cf.options("A"), ["a-b"]) @@ -132,7 +132,7 @@ class TestCaseBase(unittest.TestCase): # SF bug #561822: cf = self.fromstring("[section]\nnekey=nevalue\n", defaults={"key":"value"}) - self.failUnless(cf.has_option("section", "Key")) + self.assertTrue(cf.has_option("section", "Key")) def test_default_case_sensitivity(self): @@ -168,7 +168,7 @@ class TestCaseBase(unittest.TestCase): cf = self.newconfig() self.assertEqual(cf.sections(), [], "new ConfigParser should have no defined sections") - self.failIf(cf.has_section("Foo"), + self.assertFalse(cf.has_section("Foo"), "new ConfigParser should have no acknowledged sections") self.assertRaises(ConfigParser.NoSectionError, cf.options, "Foo") @@ -207,8 +207,8 @@ class TestCaseBase(unittest.TestCase): "E5=FALSE AND MORE" ) for x in range(1, 5): - self.failUnless(cf.getboolean('BOOLTEST', 't%d' % x)) - self.failIf(cf.getboolean('BOOLTEST', 'f%d' % x)) + self.assertTrue(cf.getboolean('BOOLTEST', 't%d' % x)) + self.assertFalse(cf.getboolean('BOOLTEST', 'f%d' % x)) self.assertRaises(ValueError, cf.getboolean, 'BOOLTEST', 'e%d' % x) diff --git a/Lib/test/test_cgi.py b/Lib/test/test_cgi.py index 800f629..aa26bb6 100644 --- a/Lib/test/test_cgi.py +++ b/Lib/test/test_cgi.py @@ -151,10 +151,10 @@ class CgiTests(unittest.TestCase): # test individual fields for key in expect.keys(): expect_val = expect[key] - self.assert_(fcd.has_key(key)) + self.assertTrue(fcd.has_key(key)) self.assertEqual(norm(fcd[key]), norm(expect[key])) self.assertEqual(fcd.get(key, "default"), fcd[key]) - self.assert_(fs.has_key(key)) + self.assertTrue(fs.has_key(key)) if len(expect_val) > 1: single_value = 0 else: @@ -162,10 +162,10 @@ class CgiTests(unittest.TestCase): try: val = sd[key] except IndexError: - self.failIf(single_value) + self.assertFalse(single_value) self.assertEqual(fs.getvalue(key), expect_val) else: - self.assert_(single_value) + self.assertTrue(single_value) self.assertEqual(val, expect_val[0]) self.assertEqual(fs.getvalue(key), expect_val[0]) self.assertEqual(norm(sd.getlist(key)), norm(expect_val)) @@ -231,7 +231,7 @@ class CgiTests(unittest.TestCase): # if we're not chunking properly, readline is only called twice # (by read_binary); if we are chunking properly, it will be called 5 times # as long as the chunksize is 1 << 16. - self.assert_(f.numcalls > 2) + self.assertTrue(f.numcalls > 2) def test_fieldstorage_multipart(self): #Test basic FieldStorage multipart parsing diff --git a/Lib/test/test_cmath.py b/Lib/test/test_cmath.py index 528f307..20c17bd 100755 --- a/Lib/test/test_cmath.py +++ b/Lib/test/test_cmath.py @@ -416,7 +416,7 @@ class CMathTests(unittest.TestCase): # real or imaginary part NaN for z in complex_nans: - self.assert_(math.isnan(phase(z))) + self.assertTrue(math.isnan(phase(z))) def test_abs(self): # zeros @@ -429,18 +429,18 @@ class CMathTests(unittest.TestCase): # real or imaginary part NaN self.assertEqual(abs(complex(NAN, -INF)), INF) - self.assert_(math.isnan(abs(complex(NAN, -2.3)))) - self.assert_(math.isnan(abs(complex(NAN, -0.0)))) - self.assert_(math.isnan(abs(complex(NAN, 0.0)))) - self.assert_(math.isnan(abs(complex(NAN, 2.3)))) + self.assertTrue(math.isnan(abs(complex(NAN, -2.3)))) + self.assertTrue(math.isnan(abs(complex(NAN, -0.0)))) + self.assertTrue(math.isnan(abs(complex(NAN, 0.0)))) + self.assertTrue(math.isnan(abs(complex(NAN, 2.3)))) self.assertEqual(abs(complex(NAN, INF)), INF) self.assertEqual(abs(complex(-INF, NAN)), INF) - self.assert_(math.isnan(abs(complex(-2.3, NAN)))) - self.assert_(math.isnan(abs(complex(-0.0, NAN)))) - self.assert_(math.isnan(abs(complex(0.0, NAN)))) - self.assert_(math.isnan(abs(complex(2.3, NAN)))) + self.assertTrue(math.isnan(abs(complex(-2.3, NAN)))) + self.assertTrue(math.isnan(abs(complex(-0.0, NAN)))) + self.assertTrue(math.isnan(abs(complex(0.0, NAN)))) + self.assertTrue(math.isnan(abs(complex(2.3, NAN)))) self.assertEqual(abs(complex(INF, NAN)), INF) - self.assert_(math.isnan(abs(complex(NAN, NAN)))) + self.assertTrue(math.isnan(abs(complex(NAN, NAN)))) # result overflows if float.__getformat__("double").startswith("IEEE"): @@ -459,26 +459,26 @@ class CMathTests(unittest.TestCase): self.assertCEqual(rect(1, -pi/2), (0, -1.)) def test_isnan(self): - self.failIf(cmath.isnan(1)) - self.failIf(cmath.isnan(1j)) - self.failIf(cmath.isnan(INF)) - self.assert_(cmath.isnan(NAN)) - self.assert_(cmath.isnan(complex(NAN, 0))) - self.assert_(cmath.isnan(complex(0, NAN))) - self.assert_(cmath.isnan(complex(NAN, NAN))) - self.assert_(cmath.isnan(complex(NAN, INF))) - self.assert_(cmath.isnan(complex(INF, NAN))) + self.assertFalse(cmath.isnan(1)) + self.assertFalse(cmath.isnan(1j)) + self.assertFalse(cmath.isnan(INF)) + self.assertTrue(cmath.isnan(NAN)) + self.assertTrue(cmath.isnan(complex(NAN, 0))) + self.assertTrue(cmath.isnan(complex(0, NAN))) + self.assertTrue(cmath.isnan(complex(NAN, NAN))) + self.assertTrue(cmath.isnan(complex(NAN, INF))) + self.assertTrue(cmath.isnan(complex(INF, NAN))) def test_isinf(self): - self.failIf(cmath.isinf(1)) - self.failIf(cmath.isinf(1j)) - self.failIf(cmath.isinf(NAN)) - self.assert_(cmath.isinf(INF)) - self.assert_(cmath.isinf(complex(INF, 0))) - self.assert_(cmath.isinf(complex(0, INF))) - self.assert_(cmath.isinf(complex(INF, INF))) - self.assert_(cmath.isinf(complex(NAN, INF))) - self.assert_(cmath.isinf(complex(INF, NAN))) + self.assertFalse(cmath.isinf(1)) + self.assertFalse(cmath.isinf(1j)) + self.assertFalse(cmath.isinf(NAN)) + self.assertTrue(cmath.isinf(INF)) + self.assertTrue(cmath.isinf(complex(INF, 0))) + self.assertTrue(cmath.isinf(complex(0, INF))) + self.assertTrue(cmath.isinf(complex(INF, INF))) + self.assertTrue(cmath.isinf(complex(NAN, INF))) + self.assertTrue(cmath.isinf(complex(INF, NAN))) def test_main(): diff --git a/Lib/test/test_cmd_line_script.py b/Lib/test/test_cmd_line_script.py index 29c92fa..cefb9ae 100644 --- a/Lib/test/test_cmd_line_script.py +++ b/Lib/test/test_cmd_line_script.py @@ -154,9 +154,9 @@ class CmdLineTest(unittest.TestCase): print printed_file print printed_package print printed_argv0 - self.assert_(printed_file in data) - self.assert_(printed_package in data) - self.assert_(printed_argv0 in data) + self.assertTrue(printed_file in data) + self.assertTrue(printed_package in data) + self.assertTrue(printed_argv0 in data) def _check_import_error(self, script_name, expected_msg, *cmd_line_switches): @@ -166,7 +166,7 @@ class CmdLineTest(unittest.TestCase): print 'Output from test script %r:' % script_name print data print 'Expected output: %r' % expected_msg - self.assert_(expected_msg in data) + self.assertTrue(expected_msg in data) def test_basic_script(self): with temp_dir() as script_dir: diff --git a/Lib/test/test_codecs.py b/Lib/test/test_codecs.py index 5df6fe5..06cab1c 100644 --- a/Lib/test/test_codecs.py +++ b/Lib/test/test_codecs.py @@ -263,7 +263,7 @@ class UTF32Test(ReadTest): f.write(u"spam") d = s.getvalue() # check whether there is exactly one BOM in it - self.assert_(d == self.spamle or d == self.spambe) + self.assertTrue(d == self.spamle or d == self.spambe) # try to read it back s = StringIO.StringIO(d) f = reader(s) @@ -390,7 +390,7 @@ class UTF16Test(ReadTest): f.write(u"spam") d = s.getvalue() # check whether there is exactly one BOM in it - self.assert_(d == self.spamle or d == self.spambe) + self.assertTrue(d == self.spamle or d == self.spambe) # try to read it back s = StringIO.StringIO(d) f = reader(s) @@ -1129,14 +1129,14 @@ class Str2StrTest(unittest.TestCase): reader = codecs.getreader("base64_codec")(StringIO.StringIO(sin)) sout = reader.read() self.assertEqual(sout, "\x80") - self.assert_(isinstance(sout, str)) + self.assertTrue(isinstance(sout, str)) def test_readline(self): sin = "\x80".encode("base64_codec") reader = codecs.getreader("base64_codec")(StringIO.StringIO(sin)) sout = reader.readline() self.assertEqual(sout, "\x80") - self.assert_(isinstance(sout, str)) + self.assertTrue(isinstance(sout, str)) all_unicode_encodings = [ "ascii", diff --git a/Lib/test/test_codeop.py b/Lib/test/test_codeop.py index 5d06f2c..6900408 100644 --- a/Lib/test/test_codeop.py +++ b/Lib/test/test_codeop.py @@ -23,7 +23,7 @@ class CodeopTests(unittest.TestCase): '''succeed iff str is a valid piece of code''' if is_jython: code = compile_command(str, "<input>", symbol) - self.assert_(code) + self.assertTrue(code) if symbol == "single": d,r = {},{} saved_stdout = sys.stdout @@ -52,9 +52,9 @@ class CodeopTests(unittest.TestCase): compile_command(str,symbol=symbol) self.fail("No exception thrown for invalid code") except SyntaxError: - self.assert_(is_syntax) + self.assertTrue(is_syntax) except OverflowError: - self.assert_(not is_syntax) + self.assertTrue(not is_syntax) def test_valid(self): av = self.assertValid diff --git a/Lib/test/test_coercion.py b/Lib/test/test_coercion.py index a70f82d..67d19a6 100644 --- a/Lib/test/test_coercion.py +++ b/Lib/test/test_coercion.py @@ -307,14 +307,14 @@ class CoercionTest(unittest.TestCase): # ...but that this still works class WackyComparer(object): def __cmp__(slf, other): - self.assert_(other == 42, 'expected evil_coercer, got %r' % other) + self.assertTrue(other == 42, 'expected evil_coercer, got %r' % other) return 0 __hash__ = None # Invalid cmp makes this unhashable self.assertEquals(cmp(WackyComparer(), evil_coercer), 0) # ...and classic classes too, since that code path is a little different class ClassicWackyComparer: def __cmp__(slf, other): - self.assert_(other == 42, 'expected evil_coercer, got %r' % other) + self.assertTrue(other == 42, 'expected evil_coercer, got %r' % other) return 0 self.assertEquals(cmp(ClassicWackyComparer(), evil_coercer), 0) diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py index 1c49876..fb24d43 100644 --- a/Lib/test/test_collections.py +++ b/Lib/test/test_collections.py @@ -42,9 +42,9 @@ class TestNamedTuple(unittest.TestCase): namedtuple('_', 'a b c') # Test leading underscores in a typename nt = namedtuple('nt', u'the quick brown fox') # check unicode input - self.assert_("u'" not in repr(nt._fields)) + self.assertTrue("u'" not in repr(nt._fields)) nt = namedtuple('nt', (u'the', u'quick')) # check unicode input - self.assert_("u'" not in repr(nt._fields)) + self.assertTrue("u'" not in repr(nt._fields)) self.assertRaises(TypeError, Point._make, [11]) # catch too few args self.assertRaises(TypeError, Point._make, [11, 22, 33]) # catch too many args @@ -73,8 +73,8 @@ class TestNamedTuple(unittest.TestCase): self.assertRaises(TypeError, eval, 'Point(XXX=1, y=2)', locals()) # wrong keyword argument self.assertRaises(TypeError, eval, 'Point(x=1)', locals()) # missing keyword argument self.assertEqual(repr(p), 'Point(x=11, y=22)') - self.assert_('__dict__' not in dir(p)) # verify instance has no dict - self.assert_('__weakref__' not in dir(p)) + self.assertTrue('__dict__' not in dir(p)) # verify instance has no dict + self.assertTrue('__weakref__' not in dir(p)) self.assertEqual(p, Point._make([11, 22])) # test _make classmethod self.assertEqual(p._fields, ('x', 'y')) # test _fields attribute self.assertEqual(p._replace(x=1), (1, 22)) # test _replace method @@ -101,7 +101,7 @@ class TestNamedTuple(unittest.TestCase): Point = namedtuple('Point', 'x y') p = Point(11, 22) - self.assert_(isinstance(p, tuple)) + self.assertTrue(isinstance(p, tuple)) self.assertEqual(p, (11, 22)) # matches a real tuple self.assertEqual(tuple(p), (11, 22)) # coercable to a real tuple self.assertEqual(list(p), [11, 22]) # coercable to a list @@ -233,8 +233,8 @@ class TestOneTrickPonyABCs(ABCTestCase): # Check some non-hashables non_samples = [list(), set(), dict()] for x in non_samples: - self.failIf(isinstance(x, Hashable), repr(x)) - self.failIf(issubclass(type(x), Hashable), repr(type(x))) + self.assertFalse(isinstance(x, Hashable), repr(x)) + self.assertFalse(issubclass(type(x), Hashable), repr(type(x))) # Check some hashables samples = [None, int(), float(), complex(), @@ -243,8 +243,8 @@ class TestOneTrickPonyABCs(ABCTestCase): int, list, object, type, ] for x in samples: - self.failUnless(isinstance(x, Hashable), repr(x)) - self.failUnless(issubclass(type(x), Hashable), repr(type(x))) + self.assertTrue(isinstance(x, Hashable), repr(x)) + self.assertTrue(issubclass(type(x), Hashable), repr(type(x))) self.assertRaises(TypeError, Hashable) # Check direct subclassing class H(Hashable): @@ -252,15 +252,15 @@ class TestOneTrickPonyABCs(ABCTestCase): return super(H, self).__hash__() __eq__ = Hashable.__eq__ # Silence Py3k warning self.assertEqual(hash(H()), 0) - self.failIf(issubclass(int, H)) + self.assertFalse(issubclass(int, H)) self.validate_abstract_methods(Hashable, '__hash__') def test_Iterable(self): # Check some non-iterables non_samples = [None, 42, 3.14, 1j] for x in non_samples: - self.failIf(isinstance(x, Iterable), repr(x)) - self.failIf(issubclass(type(x), Iterable), repr(type(x))) + self.assertFalse(isinstance(x, Iterable), repr(x)) + self.assertFalse(issubclass(type(x), Iterable), repr(type(x))) # Check some iterables samples = [str(), tuple(), list(), set(), frozenset(), dict(), @@ -269,22 +269,22 @@ class TestOneTrickPonyABCs(ABCTestCase): (x for x in []), ] for x in samples: - self.failUnless(isinstance(x, Iterable), repr(x)) - self.failUnless(issubclass(type(x), Iterable), repr(type(x))) + self.assertTrue(isinstance(x, Iterable), repr(x)) + self.assertTrue(issubclass(type(x), Iterable), repr(type(x))) # Check direct subclassing class I(Iterable): def __iter__(self): return super(I, self).__iter__() self.assertEqual(list(I()), []) - self.failIf(issubclass(str, I)) + self.assertFalse(issubclass(str, I)) self.validate_abstract_methods(Iterable, '__iter__') def test_Iterator(self): non_samples = [None, 42, 3.14, 1j, "".encode('ascii'), "", (), [], {}, set()] for x in non_samples: - self.failIf(isinstance(x, Iterator), repr(x)) - self.failIf(issubclass(type(x), Iterator), repr(type(x))) + self.assertFalse(isinstance(x, Iterator), repr(x)) + self.assertFalse(issubclass(type(x), Iterator), repr(type(x))) samples = [iter(str()), iter(tuple()), iter(list()), iter(dict()), iter(set()), iter(frozenset()), @@ -294,8 +294,8 @@ class TestOneTrickPonyABCs(ABCTestCase): (x for x in []), ] for x in samples: - self.failUnless(isinstance(x, Iterator), repr(x)) - self.failUnless(issubclass(type(x), Iterator), repr(type(x))) + self.assertTrue(isinstance(x, Iterator), repr(x)) + self.assertTrue(issubclass(type(x), Iterator), repr(type(x))) self.validate_abstract_methods(Iterator, 'next') def test_Sized(self): @@ -304,15 +304,15 @@ class TestOneTrickPonyABCs(ABCTestCase): (x for x in []), ] for x in non_samples: - self.failIf(isinstance(x, Sized), repr(x)) - self.failIf(issubclass(type(x), Sized), repr(type(x))) + self.assertFalse(isinstance(x, Sized), repr(x)) + self.assertFalse(issubclass(type(x), Sized), repr(type(x))) samples = [str(), tuple(), list(), set(), frozenset(), dict(), dict().keys(), dict().items(), dict().values(), ] for x in samples: - self.failUnless(isinstance(x, Sized), repr(x)) - self.failUnless(issubclass(type(x), Sized), repr(type(x))) + self.assertTrue(isinstance(x, Sized), repr(x)) + self.assertTrue(issubclass(type(x), Sized), repr(type(x))) self.validate_abstract_methods(Sized, '__len__') def test_Container(self): @@ -321,15 +321,15 @@ class TestOneTrickPonyABCs(ABCTestCase): (x for x in []), ] for x in non_samples: - self.failIf(isinstance(x, Container), repr(x)) - self.failIf(issubclass(type(x), Container), repr(type(x))) + self.assertFalse(isinstance(x, Container), repr(x)) + self.assertFalse(issubclass(type(x), Container), repr(type(x))) samples = [str(), tuple(), list(), set(), frozenset(), dict(), dict().keys(), dict().items(), ] for x in samples: - self.failUnless(isinstance(x, Container), repr(x)) - self.failUnless(issubclass(type(x), Container), repr(type(x))) + self.assertTrue(isinstance(x, Container), repr(x)) + self.assertTrue(issubclass(type(x), Container), repr(type(x))) self.validate_abstract_methods(Container, '__contains__') def test_Callable(self): @@ -339,33 +339,33 @@ class TestOneTrickPonyABCs(ABCTestCase): (x for x in []), ] for x in non_samples: - self.failIf(isinstance(x, Callable), repr(x)) - self.failIf(issubclass(type(x), Callable), repr(type(x))) + self.assertFalse(isinstance(x, Callable), repr(x)) + self.assertFalse(issubclass(type(x), Callable), repr(type(x))) samples = [lambda: None, type, int, object, len, list.append, [].append, ] for x in samples: - self.failUnless(isinstance(x, Callable), repr(x)) - self.failUnless(issubclass(type(x), Callable), repr(type(x))) + self.assertTrue(isinstance(x, Callable), repr(x)) + self.assertTrue(issubclass(type(x), Callable), repr(type(x))) self.validate_abstract_methods(Callable, '__call__') def test_direct_subclassing(self): for B in Hashable, Iterable, Iterator, Sized, Container, Callable: class C(B): pass - self.failUnless(issubclass(C, B)) - self.failIf(issubclass(int, C)) + self.assertTrue(issubclass(C, B)) + self.assertFalse(issubclass(int, C)) def test_registration(self): for B in Hashable, Iterable, Iterator, Sized, Container, Callable: class C: __metaclass__ = type __hash__ = None # Make sure it isn't hashable by default - self.failIf(issubclass(C, B), B.__name__) + self.assertFalse(issubclass(C, B), B.__name__) B.register(C) - self.failUnless(issubclass(C, B)) + self.assertTrue(issubclass(C, B)) class WithSet(MutableSet): @@ -395,8 +395,8 @@ class TestCollectionABCs(ABCTestCase): def test_Set(self): for sample in [set, frozenset]: - self.failUnless(isinstance(sample(), Set)) - self.failUnless(issubclass(sample, Set)) + self.assertTrue(isinstance(sample(), Set)) + self.assertTrue(issubclass(sample, Set)) self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__') def test_hash_Set(self): @@ -412,13 +412,13 @@ class TestCollectionABCs(ABCTestCase): def __hash__(self): return self._hash() a, b = OneTwoThreeSet(), OneTwoThreeSet() - self.failUnless(hash(a) == hash(b)) + self.assertTrue(hash(a) == hash(b)) def test_MutableSet(self): - self.failUnless(isinstance(set(), MutableSet)) - self.failUnless(issubclass(set, MutableSet)) - self.failIf(isinstance(frozenset(), MutableSet)) - self.failIf(issubclass(frozenset, MutableSet)) + self.assertTrue(isinstance(set(), MutableSet)) + self.assertTrue(issubclass(set, MutableSet)) + self.assertFalse(isinstance(frozenset(), MutableSet)) + self.assertFalse(issubclass(frozenset, MutableSet)) self.validate_abstract_methods(MutableSet, '__contains__', '__iter__', '__len__', 'add', 'discard') @@ -457,37 +457,37 @@ class TestCollectionABCs(ABCTestCase): def test_Mapping(self): for sample in [dict]: - self.failUnless(isinstance(sample(), Mapping)) - self.failUnless(issubclass(sample, Mapping)) + self.assertTrue(isinstance(sample(), Mapping)) + self.assertTrue(issubclass(sample, Mapping)) self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__', '__getitem__') def test_MutableMapping(self): for sample in [dict]: - self.failUnless(isinstance(sample(), MutableMapping)) - self.failUnless(issubclass(sample, MutableMapping)) + self.assertTrue(isinstance(sample(), MutableMapping)) + self.assertTrue(issubclass(sample, MutableMapping)) self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__', '__len__', '__getitem__', '__setitem__', '__delitem__') def test_Sequence(self): for sample in [tuple, list, str]: - self.failUnless(isinstance(sample(), Sequence)) - self.failUnless(issubclass(sample, Sequence)) - self.failUnless(issubclass(basestring, Sequence)) - self.failUnless(isinstance(range(10), Sequence)) - self.failUnless(issubclass(xrange, Sequence)) - self.failUnless(issubclass(str, Sequence)) + self.assertTrue(isinstance(sample(), Sequence)) + self.assertTrue(issubclass(sample, Sequence)) + self.assertTrue(issubclass(basestring, Sequence)) + self.assertTrue(isinstance(range(10), Sequence)) + self.assertTrue(issubclass(xrange, Sequence)) + self.assertTrue(issubclass(str, Sequence)) self.validate_abstract_methods(Sequence, '__contains__', '__iter__', '__len__', '__getitem__') def test_MutableSequence(self): for sample in [tuple, str]: - self.failIf(isinstance(sample(), MutableSequence)) - self.failIf(issubclass(sample, MutableSequence)) + self.assertFalse(isinstance(sample(), MutableSequence)) + self.assertFalse(issubclass(sample, MutableSequence)) for sample in [list]: - self.failUnless(isinstance(sample(), MutableSequence)) - self.failUnless(issubclass(sample, MutableSequence)) - self.failIf(issubclass(basestring, MutableSequence)) + self.assertTrue(isinstance(sample(), MutableSequence)) + self.assertTrue(issubclass(sample, MutableSequence)) + self.assertFalse(issubclass(basestring, MutableSequence)) self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__', '__len__', '__getitem__', '__setitem__', '__delitem__', 'insert') @@ -497,10 +497,10 @@ class TestCounter(unittest.TestCase): c = Counter('abcaba') self.assertEqual(c, Counter({'a':3 , 'b': 2, 'c': 1})) self.assertEqual(c, Counter(a=3, b=2, c=1)) - self.assert_(isinstance(c, dict)) - self.assert_(isinstance(c, Mapping)) - self.assert_(issubclass(Counter, dict)) - self.assert_(issubclass(Counter, Mapping)) + self.assertTrue(isinstance(c, dict)) + self.assertTrue(isinstance(c, Mapping)) + self.assertTrue(issubclass(Counter, dict)) + self.assertTrue(issubclass(Counter, Mapping)) self.assertEqual(len(c), 3) self.assertEqual(sum(c.values()), 6) self.assertEqual(sorted(c.values()), [1, 2, 3]) @@ -578,7 +578,7 @@ class TestCounter(unittest.TestCase): Counter(words), ]): msg = (i, dup, words) - self.assert_(dup is not words) + self.assertTrue(dup is not words) self.assertEquals(dup, words) self.assertEquals(len(dup), len(words)) self.assertEquals(type(dup), type(words)) @@ -594,7 +594,7 @@ class TestCounter(unittest.TestCase): def test_invariant_for_the_in_operator(self): c = Counter(a=10, b=-2, c=0) for elem in c: - self.assert_(elem in c) + self.assertTrue(elem in c) def test_multiset_operations(self): # Verify that adding a zero counter will strip zeros and negatives @@ -619,7 +619,7 @@ class TestCounter(unittest.TestCase): self.assertEqual(numberop(p[x], q[x]), result[x], (counterop, x, p, q)) # verify that results exclude non-positive counts - self.assert_(x>0 for x in result.values()) + self.assertTrue(x>0 for x in result.values()) elements = 'abcdef' for i in range(100): @@ -693,7 +693,7 @@ class TestOrderedDict(unittest.TestCase): pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] od = OrderedDict(pairs) del od['a'] - self.assert_('a' not in od) + self.assertTrue('a' not in od) with self.assertRaises(KeyError): del od['a'] self.assertEqual(list(od.items()), pairs[:2] + pairs[3:]) @@ -776,7 +776,7 @@ class TestOrderedDict(unittest.TestCase): update_test, OrderedDict(od), ]): - self.assert_(dup is not od) + self.assertTrue(dup is not od) self.assertEquals(dup, od) self.assertEquals(list(dup.items()), list(od.items())) self.assertEquals(len(dup), len(od)) @@ -789,7 +789,7 @@ class TestOrderedDict(unittest.TestCase): od = OrderedDict(pairs) # yaml.dump(od) --> # '!!python/object/apply:__main__.OrderedDict\n- - [a, 1]\n - [b, 2]\n' - self.assert_(all(type(pair)==list for pair in od.__reduce__()[1])) + self.assertTrue(all(type(pair)==list for pair in od.__reduce__()[1])) def test_reduce_not_too_fat(self): # do not save instance dictionary if not needed diff --git a/Lib/test/test_commands.py b/Lib/test/test_commands.py index 36c2a63..fcfa616 100644 --- a/Lib/test/test_commands.py +++ b/Lib/test/test_commands.py @@ -57,7 +57,7 @@ class CommandTests(unittest.TestCase): /\. # and end with the name of the file. ''' - self.assert_(re.match(pat, getstatus("/."), re.VERBOSE)) + self.assertTrue(re.match(pat, getstatus("/."), re.VERBOSE)) def test_main(): diff --git a/Lib/test/test_compile.py b/Lib/test/test_compile.py index 6ffd64a..75c983a 100644 --- a/Lib/test/test_compile.py +++ b/Lib/test/test_compile.py @@ -424,10 +424,10 @@ if 1: import __mangled_mod import __package__.module - self.assert_("_A__mangled" in A.f.func_code.co_varnames) - self.assert_("__not_mangled__" in A.f.func_code.co_varnames) - self.assert_("_A__mangled_mod" in A.f.func_code.co_varnames) - self.assert_("__package__" in A.f.func_code.co_varnames) + self.assertTrue("_A__mangled" in A.f.func_code.co_varnames) + self.assertTrue("__not_mangled__" in A.f.func_code.co_varnames) + self.assertTrue("_A__mangled_mod" in A.f.func_code.co_varnames) + self.assertTrue("__package__" in A.f.func_code.co_varnames) def test_compile_ast(self): fname = __file__ @@ -450,7 +450,7 @@ if 1: for fname, code in sample_code: co1 = compile(code, '%s1' % fname, 'exec') ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST) - self.assert_(type(ast) == _ast.Module) + self.assertTrue(type(ast) == _ast.Module) co2 = compile(ast, '%s3' % fname, 'exec') self.assertEqual(co1, co2) # the code object's filename comes from the second compilation step diff --git a/Lib/test/test_compiler.py b/Lib/test/test_compiler.py index f1fef74..24930f8 100644 --- a/Lib/test/test_compiler.py +++ b/Lib/test/test_compiler.py @@ -87,7 +87,7 @@ class CompilerTest(unittest.TestCase): def testDocstrings(self): c = compiler.compile('"doc"', '<string>', 'exec') - self.assert_('__doc__' in c.co_names) + self.assertTrue('__doc__' in c.co_names) c = compiler.compile('def f():\n "doc"', '<string>', 'exec') g = {} exec c in g @@ -110,9 +110,9 @@ class CompilerTest(unittest.TestCase): def _check_lineno(self, node): if not node.__class__ in NOLINENO: - self.assert_(isinstance(node.lineno, int), + self.assertTrue(isinstance(node.lineno, int), "lineno=%s on %s" % (node.lineno, node.__class__)) - self.assert_(node.lineno > 0, + self.assertTrue(node.lineno > 0, "lineno=%s on %s" % (node.lineno, node.__class__)) for child in node.getChildNodes(): self.check_lineno(child) diff --git a/Lib/test/test_complex.py b/Lib/test/test_complex.py index 60c5252..f07a6b4 100644 --- a/Lib/test/test_complex.py +++ b/Lib/test/test_complex.py @@ -42,7 +42,7 @@ class ComplexTest(unittest.TestCase): if x == 0: return abs(y) < eps # check that relative difference < eps - self.assert_(abs((x-y)/y) < eps) + self.assertTrue(abs((x-y)/y) < eps) def assertFloatsAreIdentical(self, x, y): """assert that floats x and y are identical, in the sense that: @@ -73,7 +73,7 @@ class ComplexTest(unittest.TestCase): self.assertCloseAbs(x.imag, y.imag, eps) def assertIs(self, a, b): - self.assert_(a is b) + self.assertTrue(a is b) def check_div(self, x, y): """Compute complex z=x*y, and check that z/x==y and z/y==x.""" @@ -192,8 +192,8 @@ class ComplexTest(unittest.TestCase): def test_boolcontext(self): for i in xrange(100): - self.assert_(complex(random() + 1e-6, random() + 1e-6)) - self.assert_(not complex(0.0, 0.0)) + self.assertTrue(complex(random() + 1e-6, random() + 1e-6)) + self.assertTrue(not complex(0.0, 0.0)) def test_conjugate(self): self.assertClose(complex(5.3, 9.8).conjugate(), 5.3-9.8j) @@ -275,7 +275,7 @@ class ComplexTest(unittest.TestCase): self.assertEqual(split_zeros(complex(-0., 1.).real), split_zeros(-0.)) c = 3.14 + 1j - self.assert_(complex(c) is c) + self.assertTrue(complex(c) is c) del c self.assertRaises(TypeError, complex, "1", "1") diff --git a/Lib/test/test_contains.py b/Lib/test/test_contains.py index 0d54099..73e0685 100644 --- a/Lib/test/test_contains.py +++ b/Lib/test/test_contains.py @@ -20,57 +20,57 @@ class TestContains(unittest.TestCase): a = base_set(1) b = set(1) c = seq(1) - self.assert_(1 in b) - self.assert_(0 not in b) - self.assert_(1 in c) - self.assert_(0 not in c) + self.assertTrue(1 in b) + self.assertTrue(0 not in b) + self.assertTrue(1 in c) + self.assertTrue(0 not in c) self.assertRaises(TypeError, lambda: 1 in a) self.assertRaises(TypeError, lambda: 1 not in a) # test char in string - self.assert_('c' in 'abc') - self.assert_('d' not in 'abc') + self.assertTrue('c' in 'abc') + self.assertTrue('d' not in 'abc') - self.assert_('' in '') - self.assert_('' in 'abc') + self.assertTrue('' in '') + self.assertTrue('' in 'abc') self.assertRaises(TypeError, lambda: None in 'abc') if have_unicode: def test_char_in_unicode(self): - self.assert_('c' in unicode('abc')) - self.assert_('d' not in unicode('abc')) + self.assertTrue('c' in unicode('abc')) + self.assertTrue('d' not in unicode('abc')) - self.assert_('' in unicode('')) - self.assert_(unicode('') in '') - self.assert_(unicode('') in unicode('')) - self.assert_('' in unicode('abc')) - self.assert_(unicode('') in 'abc') - self.assert_(unicode('') in unicode('abc')) + self.assertTrue('' in unicode('')) + self.assertTrue(unicode('') in '') + self.assertTrue(unicode('') in unicode('')) + self.assertTrue('' in unicode('abc')) + self.assertTrue(unicode('') in 'abc') + self.assertTrue(unicode('') in unicode('abc')) self.assertRaises(TypeError, lambda: None in unicode('abc')) # test Unicode char in Unicode - self.assert_(unicode('c') in unicode('abc')) - self.assert_(unicode('d') not in unicode('abc')) + self.assertTrue(unicode('c') in unicode('abc')) + self.assertTrue(unicode('d') not in unicode('abc')) # test Unicode char in string - self.assert_(unicode('c') in 'abc') - self.assert_(unicode('d') not in 'abc') + self.assertTrue(unicode('c') in 'abc') + self.assertTrue(unicode('d') not in 'abc') def test_builtin_sequence_types(self): # a collection of tests on builtin sequence types a = range(10) for i in a: - self.assert_(i in a) - self.assert_(16 not in a) - self.assert_(a not in a) + self.assertTrue(i in a) + self.assertTrue(16 not in a) + self.assertTrue(a not in a) a = tuple(a) for i in a: - self.assert_(i in a) - self.assert_(16 not in a) - self.assert_(a not in a) + self.assertTrue(i in a) + self.assertTrue(16 not in a) + self.assertTrue(a not in a) class Deviant1: """Behaves strangely when compared @@ -86,7 +86,7 @@ class TestContains(unittest.TestCase): self.aList.remove(14) return 1 - self.assert_(Deviant1() not in Deviant1.aList) + self.assertTrue(Deviant1() not in Deviant1.aList) class Deviant2: """Behaves strangely when compared @@ -99,7 +99,7 @@ class TestContains(unittest.TestCase): raise RuntimeError, "gotcha" try: - self.assert_(Deviant2() not in a) + self.assertTrue(Deviant2() not in a) except TypeError: pass diff --git a/Lib/test/test_contextlib.py b/Lib/test/test_contextlib.py index 274af3d..80ba3e8 100644 --- a/Lib/test/test_contextlib.py +++ b/Lib/test/test_contextlib.py @@ -54,7 +54,7 @@ class ContextManagerTestCase(unittest.TestCase): ctx = whee() ctx.__enter__() # Calling __exit__ should not result in an exception - self.failIf(ctx.__exit__(TypeError, TypeError("foo"), None)) + self.assertFalse(ctx.__exit__(TypeError, TypeError("foo"), None)) def test_contextmanager_trap_yield_after_throw(self): @contextmanager @@ -261,17 +261,17 @@ class FileContextTestCase(unittest.TestCase): try: f = None with open(tfn, "w") as f: - self.failIf(f.closed) + self.assertFalse(f.closed) f.write("Booh\n") - self.failUnless(f.closed) + self.assertTrue(f.closed) f = None try: with open(tfn, "r") as f: - self.failIf(f.closed) + self.assertFalse(f.closed) self.assertEqual(f.read(), "Booh\n") 1/0 except ZeroDivisionError: - self.failUnless(f.closed) + self.assertTrue(f.closed) else: self.fail("Didn't raise ZeroDivisionError") finally: @@ -283,16 +283,16 @@ class FileContextTestCase(unittest.TestCase): class LockContextTestCase(unittest.TestCase): def boilerPlate(self, lock, locked): - self.failIf(locked()) + self.assertFalse(locked()) with lock: - self.failUnless(locked()) - self.failIf(locked()) + self.assertTrue(locked()) + self.assertFalse(locked()) try: with lock: - self.failUnless(locked()) + self.assertTrue(locked()) 1/0 except ZeroDivisionError: - self.failIf(locked()) + self.assertFalse(locked()) else: self.fail("Didn't raise ZeroDivisionError") diff --git a/Lib/test/test_cookielib.py b/Lib/test/test_cookielib.py index 93d62f7..e43d734 100644 --- a/Lib/test/test_cookielib.py +++ b/Lib/test/test_cookielib.py @@ -21,7 +21,7 @@ class DateTimeTests(TestCase): az = time2isoz() bz = time2isoz(500000) for text in (az, bz): - self.assert_(re.search(r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\dZ$", text), + self.assertTrue(re.search(r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\dZ$", text), "bad time2isoz format: %s %s" % (az, bz)) def test_http2time(self): @@ -74,7 +74,7 @@ class DateTimeTests(TestCase): t2 = http2time(s.lower()) t3 = http2time(s.upper()) - self.assert_(t == t2 == t3 == test_t, + self.assertTrue(t == t2 == t3 == test_t, "'%s' => %s, %s, %s (%s)" % (s, t, t2, t3, test_t)) def test_http2time_garbage(self): @@ -92,7 +92,7 @@ class DateTimeTests(TestCase): '01-01-1980 00:61:00', '01-01-1980 00:00:62', ]: - self.assert_(http2time(test) is None, + self.assertTrue(http2time(test) is None, "http2time(%s) is not None\n" "http2time(test) %s" % (test, http2time(test)) ) @@ -349,8 +349,8 @@ class CookieTests(TestCase): ]: request = urllib2.Request(url) r = pol.domain_return_ok(domain, request) - if ok: self.assert_(r) - else: self.assert_(not r) + if ok: self.assertTrue(r) + else: self.assertTrue(not r) def test_missing_value(self): from cookielib import MozillaCookieJar, lwp_cookie_str @@ -362,10 +362,10 @@ class CookieTests(TestCase): interact_netscape(c, "http://www.acme.com/", 'eggs') interact_netscape(c, "http://www.acme.com/", '"spam"; path=/foo/') cookie = c._cookies["www.acme.com"]["/"]["eggs"] - self.assert_(cookie.value is None) + self.assertTrue(cookie.value is None) self.assertEquals(cookie.name, "eggs") cookie = c._cookies["www.acme.com"]['/foo/']['"spam"'] - self.assert_(cookie.value is None) + self.assertTrue(cookie.value is None) self.assertEquals(cookie.name, '"spam"') self.assertEquals(lwp_cookie_str(cookie), ( r'"spam"; path="/foo/"; domain="www.acme.com"; ' @@ -409,7 +409,7 @@ class CookieTests(TestCase): try: cookie = c._cookies["www.example.com"]["/"]["ni"] except KeyError: - self.assert_(version is None) # didn't expect a stored cookie + self.assertTrue(version is None) # didn't expect a stored cookie else: self.assertEqual(cookie.version, version) # 2965 cookies are unaffected @@ -433,28 +433,28 @@ class CookieTests(TestCase): cookie = c._cookies[".acme.com"]["/"]["spam"] self.assertEquals(cookie.domain, ".acme.com") - self.assert_(cookie.domain_specified) + self.assertTrue(cookie.domain_specified) self.assertEquals(cookie.port, DEFAULT_HTTP_PORT) - self.assert_(not cookie.port_specified) + self.assertTrue(not cookie.port_specified) # case is preserved - self.assert_(cookie.has_nonstandard_attr("blArgh") and + self.assertTrue(cookie.has_nonstandard_attr("blArgh") and not cookie.has_nonstandard_attr("blargh")) cookie = c._cookies["www.acme.com"]["/"]["ni"] self.assertEquals(cookie.domain, "www.acme.com") - self.assert_(not cookie.domain_specified) + self.assertTrue(not cookie.domain_specified) self.assertEquals(cookie.port, "80,8080") - self.assert_(cookie.port_specified) + self.assertTrue(cookie.port_specified) cookie = c._cookies["www.acme.com"]["/"]["nini"] - self.assert_(cookie.port is None) - self.assert_(not cookie.port_specified) + self.assertTrue(cookie.port is None) + self.assertTrue(not cookie.port_specified) # invalid expires should not cause cookie to be dropped foo = c._cookies["www.acme.com"]["/"]["foo"] spam = c._cookies["www.acme.com"]["/"]["foo"] - self.assert_(foo.expires is None) - self.assert_(spam.expires is None) + self.assertTrue(foo.expires is None) + self.assertTrue(spam.expires is None) def test_ns_parser_special_names(self): # names such as 'expires' are not special in first name=value pair @@ -466,8 +466,8 @@ class CookieTests(TestCase): interact_netscape(c, "http://www.acme.com/", 'version=eggs; spam=eggs') cookies = c._cookies["www.acme.com"]["/"] - self.assert_('expires' in cookies) - self.assert_('version' in cookies) + self.assertTrue('expires' in cookies) + self.assertTrue('version' in cookies) def test_expires(self): from cookielib import time2netscape, CookieJar @@ -484,7 +484,7 @@ class CookieTests(TestCase): now) h = interact_netscape(c, "http://www.acme.com/") self.assertEquals(len(c), 1) - self.assert_('spam="bar"' in h and "foo" not in h) + self.assertTrue('spam="bar"' in h and "foo" not in h) # max-age takes precedence over expires, and zero max-age is request to # delete both new cookie and any old matching cookie @@ -505,7 +505,7 @@ class CookieTests(TestCase): self.assertEquals(len(c), 2) c.clear_session_cookies() self.assertEquals(len(c), 1) - self.assert_('spam="bar"' in h) + self.assertTrue('spam="bar"' in h) # XXX RFC 2965 expiry rules (some apply to V0 too) @@ -517,39 +517,39 @@ class CookieTests(TestCase): c = CookieJar(pol) interact_2965(c, "http://www.acme.com/", 'spam="bar"; Version="1"') - self.assert_("/" in c._cookies["www.acme.com"]) + self.assertTrue("/" in c._cookies["www.acme.com"]) c = CookieJar(pol) interact_2965(c, "http://www.acme.com/blah", 'eggs="bar"; Version="1"') - self.assert_("/" in c._cookies["www.acme.com"]) + self.assertTrue("/" in c._cookies["www.acme.com"]) c = CookieJar(pol) interact_2965(c, "http://www.acme.com/blah/rhubarb", 'eggs="bar"; Version="1"') - self.assert_("/blah/" in c._cookies["www.acme.com"]) + self.assertTrue("/blah/" in c._cookies["www.acme.com"]) c = CookieJar(pol) interact_2965(c, "http://www.acme.com/blah/rhubarb/", 'eggs="bar"; Version="1"') - self.assert_("/blah/rhubarb/" in c._cookies["www.acme.com"]) + self.assertTrue("/blah/rhubarb/" in c._cookies["www.acme.com"]) # Netscape c = CookieJar() interact_netscape(c, "http://www.acme.com/", 'spam="bar"') - self.assert_("/" in c._cookies["www.acme.com"]) + self.assertTrue("/" in c._cookies["www.acme.com"]) c = CookieJar() interact_netscape(c, "http://www.acme.com/blah", 'eggs="bar"') - self.assert_("/" in c._cookies["www.acme.com"]) + self.assertTrue("/" in c._cookies["www.acme.com"]) c = CookieJar() interact_netscape(c, "http://www.acme.com/blah/rhubarb", 'eggs="bar"') - self.assert_("/blah" in c._cookies["www.acme.com"]) + self.assertTrue("/blah" in c._cookies["www.acme.com"]) c = CookieJar() interact_netscape(c, "http://www.acme.com/blah/rhubarb/", 'eggs="bar"') - self.assert_("/blah/rhubarb" in c._cookies["www.acme.com"]) + self.assertTrue("/blah/rhubarb" in c._cookies["www.acme.com"]) def test_escape_path(self): from cookielib import escape_path @@ -627,14 +627,14 @@ class CookieTests(TestCase): def test_is_HDN(self): from cookielib import is_HDN - self.assert_(is_HDN("foo.bar.com")) - self.assert_(is_HDN("1foo2.3bar4.5com")) - self.assert_(not is_HDN("192.168.1.1")) - self.assert_(not is_HDN("")) - self.assert_(not is_HDN(".")) - self.assert_(not is_HDN(".foo.bar.com")) - self.assert_(not is_HDN("..foo")) - self.assert_(not is_HDN("foo.")) + self.assertTrue(is_HDN("foo.bar.com")) + self.assertTrue(is_HDN("1foo2.3bar4.5com")) + self.assertTrue(not is_HDN("192.168.1.1")) + self.assertTrue(not is_HDN("")) + self.assertTrue(not is_HDN(".")) + self.assertTrue(not is_HDN(".foo.bar.com")) + self.assertTrue(not is_HDN("..foo")) + self.assertTrue(not is_HDN("foo.")) def test_reach(self): from cookielib import reach @@ -649,40 +649,40 @@ class CookieTests(TestCase): def test_domain_match(self): from cookielib import domain_match, user_domain_match - self.assert_(domain_match("192.168.1.1", "192.168.1.1")) - self.assert_(not domain_match("192.168.1.1", ".168.1.1")) - self.assert_(domain_match("x.y.com", "x.Y.com")) - self.assert_(domain_match("x.y.com", ".Y.com")) - self.assert_(not domain_match("x.y.com", "Y.com")) - self.assert_(domain_match("a.b.c.com", ".c.com")) - self.assert_(not domain_match(".c.com", "a.b.c.com")) - self.assert_(domain_match("example.local", ".local")) - self.assert_(not domain_match("blah.blah", "")) - self.assert_(not domain_match("", ".rhubarb.rhubarb")) - self.assert_(domain_match("", "")) - - self.assert_(user_domain_match("acme.com", "acme.com")) - self.assert_(not user_domain_match("acme.com", ".acme.com")) - self.assert_(user_domain_match("rhubarb.acme.com", ".acme.com")) - self.assert_(user_domain_match("www.rhubarb.acme.com", ".acme.com")) - self.assert_(user_domain_match("x.y.com", "x.Y.com")) - self.assert_(user_domain_match("x.y.com", ".Y.com")) - self.assert_(not user_domain_match("x.y.com", "Y.com")) - self.assert_(user_domain_match("y.com", "Y.com")) - self.assert_(not user_domain_match(".y.com", "Y.com")) - self.assert_(user_domain_match(".y.com", ".Y.com")) - self.assert_(user_domain_match("x.y.com", ".com")) - self.assert_(not user_domain_match("x.y.com", "com")) - self.assert_(not user_domain_match("x.y.com", "m")) - self.assert_(not user_domain_match("x.y.com", ".m")) - self.assert_(not user_domain_match("x.y.com", "")) - self.assert_(not user_domain_match("x.y.com", ".")) - self.assert_(user_domain_match("192.168.1.1", "192.168.1.1")) + self.assertTrue(domain_match("192.168.1.1", "192.168.1.1")) + self.assertTrue(not domain_match("192.168.1.1", ".168.1.1")) + self.assertTrue(domain_match("x.y.com", "x.Y.com")) + self.assertTrue(domain_match("x.y.com", ".Y.com")) + self.assertTrue(not domain_match("x.y.com", "Y.com")) + self.assertTrue(domain_match("a.b.c.com", ".c.com")) + self.assertTrue(not domain_match(".c.com", "a.b.c.com")) + self.assertTrue(domain_match("example.local", ".local")) + self.assertTrue(not domain_match("blah.blah", "")) + self.assertTrue(not domain_match("", ".rhubarb.rhubarb")) + self.assertTrue(domain_match("", "")) + + self.assertTrue(user_domain_match("acme.com", "acme.com")) + self.assertTrue(not user_domain_match("acme.com", ".acme.com")) + self.assertTrue(user_domain_match("rhubarb.acme.com", ".acme.com")) + self.assertTrue(user_domain_match("www.rhubarb.acme.com", ".acme.com")) + self.assertTrue(user_domain_match("x.y.com", "x.Y.com")) + self.assertTrue(user_domain_match("x.y.com", ".Y.com")) + self.assertTrue(not user_domain_match("x.y.com", "Y.com")) + self.assertTrue(user_domain_match("y.com", "Y.com")) + self.assertTrue(not user_domain_match(".y.com", "Y.com")) + self.assertTrue(user_domain_match(".y.com", ".Y.com")) + self.assertTrue(user_domain_match("x.y.com", ".com")) + self.assertTrue(not user_domain_match("x.y.com", "com")) + self.assertTrue(not user_domain_match("x.y.com", "m")) + self.assertTrue(not user_domain_match("x.y.com", ".m")) + self.assertTrue(not user_domain_match("x.y.com", "")) + self.assertTrue(not user_domain_match("x.y.com", ".")) + self.assertTrue(user_domain_match("192.168.1.1", "192.168.1.1")) # not both HDNs, so must string-compare equal to match - self.assert_(not user_domain_match("192.168.1.1", ".168.1.1")) - self.assert_(not user_domain_match("192.168.1.1", ".")) + self.assertTrue(not user_domain_match("192.168.1.1", ".168.1.1")) + self.assertTrue(not user_domain_match("192.168.1.1", ".")) # empty string is a special case - self.assert_(not user_domain_match("192.168.1.1", "")) + self.assertTrue(not user_domain_match("192.168.1.1", "")) def test_wrong_domain(self): # Cookies whose effective request-host name does not domain-match the @@ -839,7 +839,7 @@ class CookieTests(TestCase): self.assertEquals(len(c), 2) # ... and check is doesn't get returned c.add_cookie_header(req) - self.assert_(not req.has_header("Cookie")) + self.assertTrue(not req.has_header("Cookie")) def test_domain_block(self): from cookielib import CookieJar, DefaultCookiePolicy @@ -866,7 +866,7 @@ class CookieTests(TestCase): self.assertEquals(len(c), 1) req = Request("http://www.roadrunner.net/") c.add_cookie_header(req) - self.assert_((req.has_header("Cookie") and + self.assertTrue((req.has_header("Cookie") and req.has_header("Cookie2"))) c.clear() @@ -882,7 +882,7 @@ class CookieTests(TestCase): self.assertEquals(len(c), 2) # ... and check is doesn't get returned c.add_cookie_header(req) - self.assert_(not req.has_header("Cookie")) + self.assertTrue(not req.has_header("Cookie")) def test_secure(self): from cookielib import CookieJar, DefaultCookiePolicy @@ -902,10 +902,10 @@ class CookieTests(TestCase): url = "http://www.acme.com/" int(c, url, "foo1=bar%s%s" % (vs, whitespace)) int(c, url, "foo2=bar%s; secure%s" % (vs, whitespace)) - self.assert_( + self.assertTrue( not c._cookies["www.acme.com"]["/"]["foo1"].secure, "non-secure cookie registered secure") - self.assert_( + self.assertTrue( c._cookies["www.acme.com"]["/"]["foo2"].secure, "secure cookie registered non-secure") @@ -926,7 +926,7 @@ class CookieTests(TestCase): req = Request(url) self.assertEquals(len(c), 1) c.add_cookie_header(req) - self.assert_(req.has_header("Cookie")) + self.assertTrue(req.has_header("Cookie")) def test_domain_mirror(self): from cookielib import CookieJar, DefaultCookiePolicy @@ -937,21 +937,21 @@ class CookieTests(TestCase): url = "http://foo.bar.com/" interact_2965(c, url, "spam=eggs; Version=1") h = interact_2965(c, url) - self.assert_("Domain" not in h, + self.assertTrue("Domain" not in h, "absent domain returned with domain present") c = CookieJar(pol) url = "http://foo.bar.com/" interact_2965(c, url, 'spam=eggs; Version=1; Domain=.bar.com') h = interact_2965(c, url) - self.assert_('$Domain=".bar.com"' in h, "domain not returned") + self.assertTrue('$Domain=".bar.com"' in h, "domain not returned") c = CookieJar(pol) url = "http://foo.bar.com/" # note missing initial dot in Domain interact_2965(c, url, 'spam=eggs; Version=1; Domain=bar.com') h = interact_2965(c, url) - self.assert_('$Domain="bar.com"' in h, "domain not returned") + self.assertTrue('$Domain="bar.com"' in h, "domain not returned") def test_path_mirror(self): from cookielib import CookieJar, DefaultCookiePolicy @@ -962,14 +962,14 @@ class CookieTests(TestCase): url = "http://foo.bar.com/" interact_2965(c, url, "spam=eggs; Version=1") h = interact_2965(c, url) - self.assert_("Path" not in h, + self.assertTrue("Path" not in h, "absent path returned with path present") c = CookieJar(pol) url = "http://foo.bar.com/" interact_2965(c, url, 'spam=eggs; Version=1; Path=/') h = interact_2965(c, url) - self.assert_('$Path="/"' in h, "path not returned") + self.assertTrue('$Path="/"' in h, "path not returned") def test_port_mirror(self): from cookielib import CookieJar, DefaultCookiePolicy @@ -980,28 +980,28 @@ class CookieTests(TestCase): url = "http://foo.bar.com/" interact_2965(c, url, "spam=eggs; Version=1") h = interact_2965(c, url) - self.assert_("Port" not in h, + self.assertTrue("Port" not in h, "absent port returned with port present") c = CookieJar(pol) url = "http://foo.bar.com/" interact_2965(c, url, "spam=eggs; Version=1; Port") h = interact_2965(c, url) - self.assert_(re.search("\$Port([^=]|$)", h), + self.assertTrue(re.search("\$Port([^=]|$)", h), "port with no value not returned with no value") c = CookieJar(pol) url = "http://foo.bar.com/" interact_2965(c, url, 'spam=eggs; Version=1; Port="80"') h = interact_2965(c, url) - self.assert_('$Port="80"' in h, + self.assertTrue('$Port="80"' in h, "port with single value not returned with single value") c = CookieJar(pol) url = "http://foo.bar.com/" interact_2965(c, url, 'spam=eggs; Version=1; Port="80,8080"') h = interact_2965(c, url) - self.assert_('$Port="80,8080"' in h, + self.assertTrue('$Port="80,8080"' in h, "port with multiple values not returned with multiple " "values") @@ -1014,7 +1014,7 @@ class CookieTests(TestCase): 'Comment="does anybody read these?"; ' 'CommentURL="http://foo.bar.net/comment.html"') h = interact_2965(c, url) - self.assert_( + self.assertTrue( "Comment" not in h, "Comment or CommentURL cookie-attributes returned to server") @@ -1045,7 +1045,7 @@ class CookieTests(TestCase): for i in range(4): i = 0 for c in cs: - self.assert_(isinstance(c, Cookie)) + self.assertTrue(isinstance(c, Cookie)) self.assertEquals(c.version, versions[i]) self.assertEquals(c.name, names[i]) self.assertEquals(c.domain, domains[i]) @@ -1102,7 +1102,7 @@ class CookieTests(TestCase): headers = ["Set-Cookie: c=foo; expires=Foo Bar 12 33:22:11 2000"] c = cookiejar_from_cookie_headers(headers) cookie = c._cookies["www.example.com"]["/"]["c"] - self.assert_(cookie.expires is None) + self.assertTrue(cookie.expires is None) class LWPCookieTests(TestCase): @@ -1179,7 +1179,7 @@ class LWPCookieTests(TestCase): c.add_cookie_header(req) h = req.get_header("Cookie") - self.assert_("PART_NUMBER=ROCKET_LAUNCHER_0001" in h and + self.assertTrue("PART_NUMBER=ROCKET_LAUNCHER_0001" in h and "CUSTOMER=WILE_E_COYOTE" in h) headers.append('Set-Cookie: SHIPPING=FEDEX; path=/foo') @@ -1190,7 +1190,7 @@ class LWPCookieTests(TestCase): c.add_cookie_header(req) h = req.get_header("Cookie") - self.assert_("PART_NUMBER=ROCKET_LAUNCHER_0001" in h and + self.assertTrue("PART_NUMBER=ROCKET_LAUNCHER_0001" in h and "CUSTOMER=WILE_E_COYOTE" in h and "SHIPPING=FEDEX" not in h) @@ -1198,7 +1198,7 @@ class LWPCookieTests(TestCase): c.add_cookie_header(req) h = req.get_header("Cookie") - self.assert_(("PART_NUMBER=ROCKET_LAUNCHER_0001" in h and + self.assertTrue(("PART_NUMBER=ROCKET_LAUNCHER_0001" in h and "CUSTOMER=WILE_E_COYOTE" in h and h.startswith("SHIPPING=FEDEX;"))) @@ -1252,7 +1252,7 @@ class LWPCookieTests(TestCase): req = Request("http://www.acme.com/ammo") c.add_cookie_header(req) - self.assert_(re.search(r"PART_NUMBER=RIDING_ROCKET_0023;\s*" + self.assertTrue(re.search(r"PART_NUMBER=RIDING_ROCKET_0023;\s*" "PART_NUMBER=ROCKET_LAUNCHER_0001", req.get_header("Cookie"))) @@ -1288,7 +1288,7 @@ class LWPCookieTests(TestCase): cookie = interact_2965( c, 'http://www.acme.com/acme/login', 'Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"') - self.assert_(not cookie) + self.assertTrue(not cookie) # # 3. User Agent -> Server @@ -1310,7 +1310,7 @@ class LWPCookieTests(TestCase): cookie = interact_2965(c, 'http://www.acme.com/acme/pickitem', 'Part_Number="Rocket_Launcher_0001"; ' 'Version="1"; Path="/acme"'); - self.assert_(re.search( + self.assertTrue(re.search( r'^\$Version="?1"?; Customer="?WILE_E_COYOTE"?; \$Path="/acme"$', cookie)) @@ -1335,10 +1335,10 @@ class LWPCookieTests(TestCase): cookie = interact_2965(c, "http://www.acme.com/acme/shipping", 'Shipping="FedEx"; Version="1"; Path="/acme"') - self.assert_(re.search(r'^\$Version="?1"?;', cookie)) - self.assert_(re.search(r'Part_Number="?Rocket_Launcher_0001"?;' + self.assertTrue(re.search(r'^\$Version="?1"?;', cookie)) + self.assertTrue(re.search(r'Part_Number="?Rocket_Launcher_0001"?;' '\s*\$Path="\/acme"', cookie)) - self.assert_(re.search(r'Customer="?WILE_E_COYOTE"?;\s*\$Path="\/acme"', + self.assertTrue(re.search(r'Customer="?WILE_E_COYOTE"?;\s*\$Path="\/acme"', cookie)) # @@ -1360,7 +1360,7 @@ class LWPCookieTests(TestCase): # Transaction is complete. cookie = interact_2965(c, "http://www.acme.com/acme/process") - self.assert_( + self.assertTrue( re.search(r'Shipping="?FedEx"?;\s*\$Path="\/acme"', cookie) and "WILE_E_COYOTE" in cookie) @@ -1411,7 +1411,7 @@ class LWPCookieTests(TestCase): # than once. cookie = interact_2965(c, "http://www.acme.com/acme/ammo/...") - self.assert_( + self.assertTrue( re.search(r"Riding_Rocket_0023.*Rocket_Launcher_0001", cookie)) # A subsequent request by the user agent to the (same) server for a URL of @@ -1424,7 +1424,7 @@ class LWPCookieTests(TestCase): # the server. cookie = interact_2965(c, "http://www.acme.com/acme/parts/") - self.assert_("Rocket_Launcher_0001" in cookie and + self.assertTrue("Rocket_Launcher_0001" in cookie and "Riding_Rocket_0023" not in cookie) def test_rejection(self): @@ -1440,7 +1440,7 @@ class LWPCookieTests(TestCase): # illegal domain (no embedded dots) cookie = interact_2965(c, "http://www.acme.com", 'foo=bar; domain=".com"; version=1') - self.assert_(not c) + self.assertTrue(not c) # legal domain cookie = interact_2965(c, "http://www.acme.com", @@ -1533,11 +1533,11 @@ class LWPCookieTests(TestCase): c, "http://www.acme.com/foo%2f%25/<<%0anewå/æøå", 'bar=baz; path="/foo/"; version=1'); version_re = re.compile(r'^\$version=\"?1\"?', re.I) - self.assert_("foo=bar" in cookie and version_re.search(cookie)) + self.assertTrue("foo=bar" in cookie and version_re.search(cookie)) cookie = interact_2965( c, "http://www.acme.com/foo/%25/<<%0anewå/æøå") - self.assert_(not cookie) + self.assertTrue(not cookie) # unicode URL doesn't raise exception cookie = interact_2965(c, u"http://www.acme.com/\xfc") @@ -1579,11 +1579,11 @@ class LWPCookieTests(TestCase): new_c = save_and_restore(c, True) self.assertEquals(len(new_c), 6) # none discarded - self.assert_("name='foo1', value='bar'" in repr(new_c)) + self.assertTrue("name='foo1', value='bar'" in repr(new_c)) new_c = save_and_restore(c, False) self.assertEquals(len(new_c), 4) # 2 of them discarded on save - self.assert_("name='foo1', value='bar'" in repr(new_c)) + self.assertTrue("name='foo1', value='bar'" in repr(new_c)) def test_netscape_misc(self): # Some additional Netscape cookies tests. @@ -1608,7 +1608,7 @@ class LWPCookieTests(TestCase): req = Request("http://foo.bar.acme.com/foo") c.add_cookie_header(req) - self.assert_( + self.assertTrue( "PART_NUMBER=3,4" in req.get_header("Cookie") and "Customer=WILE_E_COYOTE" in req.get_header("Cookie")) @@ -1621,11 +1621,11 @@ class LWPCookieTests(TestCase): "foo1=bar; PORT; Discard; Version=1;") cookie = interact_2965(c, "http://example/", 'foo2=bar; domain=".local"; Version=1') - self.assert_("foo1=bar" in cookie) + self.assertTrue("foo1=bar" in cookie) interact_2965(c, "http://example/", 'foo3=bar; Version=1') cookie = interact_2965(c, "http://example/") - self.assert_("foo2=bar" in cookie and len(c) == 3) + self.assertTrue("foo2=bar" in cookie and len(c) == 3) def test_intranet_domains_ns(self): from cookielib import CookieJar, DefaultCookiePolicy @@ -1635,10 +1635,10 @@ class LWPCookieTests(TestCase): cookie = interact_netscape(c, "http://example/", 'foo2=bar; domain=.local') self.assertEquals(len(c), 2) - self.assert_("foo1=bar" in cookie) + self.assertTrue("foo1=bar" in cookie) cookie = interact_netscape(c, "http://example/") - self.assert_("foo2=bar" in cookie) + self.assertTrue("foo2=bar" in cookie) self.assertEquals(len(c), 2) def test_empty_path(self): @@ -1713,7 +1713,7 @@ class LWPCookieTests(TestCase): key = "%s_after" % cookie.value counter[key] = counter[key] + 1 - self.assert_(not ( + self.assertTrue(not ( # a permanent cookie got lost accidentally counter["perm_after"] != counter["perm_before"] or # a session cookie hasn't been cleared diff --git a/Lib/test/test_copy.py b/Lib/test/test_copy.py index a8be887..ccbd231 100644 --- a/Lib/test/test_copy.py +++ b/Lib/test/test_copy.py @@ -13,8 +13,8 @@ class TestCopy(unittest.TestCase): # Attempt full line coverage of copy.py from top to bottom def test_exceptions(self): - self.assert_(copy.Error is copy.error) - self.assert_(issubclass(copy.Error, Exception)) + self.assertTrue(copy.Error is copy.error) + self.assertTrue(issubclass(copy.Error, Exception)) # The copy() method @@ -55,7 +55,7 @@ class TestCopy(unittest.TestCase): raise test_support.TestFailed, "shouldn't call this" x = C() y = copy.copy(x) - self.assert_(y is x) + self.assertTrue(y is x) def test_copy_reduce(self): class C(object): @@ -63,7 +63,7 @@ class TestCopy(unittest.TestCase): return "" x = C() y = copy.copy(x) - self.assert_(y is x) + self.assertTrue(y is x) def test_copy_cant(self): class C(object): @@ -87,7 +87,7 @@ class TestCopy(unittest.TestCase): "hello", u"hello\u1234", f.func_code, NewStyle, xrange(10), Classic, max] for x in tests: - self.assert_(copy.copy(x) is x, repr(x)) + self.assertTrue(copy.copy(x) is x, repr(x)) def test_copy_list(self): x = [1, 2, 3] @@ -181,9 +181,9 @@ class TestCopy(unittest.TestCase): x = [x, x] y = copy.deepcopy(x) self.assertEqual(y, x) - self.assert_(y is not x) - self.assert_(y[0] is not x[0]) - self.assert_(y[0] is y[1]) + self.assertTrue(y is not x) + self.assertTrue(y[0] is not x[0]) + self.assertTrue(y[0] is y[1]) def test_deepcopy_issubclass(self): # XXX Note: there's no way to test the TypeError coming out of @@ -228,7 +228,7 @@ class TestCopy(unittest.TestCase): raise test_support.TestFailed, "shouldn't call this" x = C() y = copy.deepcopy(x) - self.assert_(y is x) + self.assertTrue(y is x) def test_deepcopy_reduce(self): class C(object): @@ -236,7 +236,7 @@ class TestCopy(unittest.TestCase): return "" x = C() y = copy.deepcopy(x) - self.assert_(y is x) + self.assertTrue(y is x) def test_deepcopy_cant(self): class C(object): @@ -260,61 +260,61 @@ class TestCopy(unittest.TestCase): "hello", u"hello\u1234", f.func_code, NewStyle, xrange(10), Classic, max] for x in tests: - self.assert_(copy.deepcopy(x) is x, repr(x)) + self.assertTrue(copy.deepcopy(x) is x, repr(x)) def test_deepcopy_list(self): x = [[1, 2], 3] y = copy.deepcopy(x) self.assertEqual(y, x) - self.assert_(x is not y) - self.assert_(x[0] is not y[0]) + self.assertTrue(x is not y) + self.assertTrue(x[0] is not y[0]) def test_deepcopy_reflexive_list(self): x = [] x.append(x) y = copy.deepcopy(x) self.assertRaises(RuntimeError, cmp, y, x) - self.assert_(y is not x) - self.assert_(y[0] is y) + self.assertTrue(y is not x) + self.assertTrue(y[0] is y) self.assertEqual(len(y), 1) def test_deepcopy_tuple(self): x = ([1, 2], 3) y = copy.deepcopy(x) self.assertEqual(y, x) - self.assert_(x is not y) - self.assert_(x[0] is not y[0]) + self.assertTrue(x is not y) + self.assertTrue(x[0] is not y[0]) def test_deepcopy_reflexive_tuple(self): x = ([],) x[0].append(x) y = copy.deepcopy(x) self.assertRaises(RuntimeError, cmp, y, x) - self.assert_(y is not x) - self.assert_(y[0] is not x[0]) - self.assert_(y[0][0] is y) + self.assertTrue(y is not x) + self.assertTrue(y[0] is not x[0]) + self.assertTrue(y[0][0] is y) def test_deepcopy_dict(self): x = {"foo": [1, 2], "bar": 3} y = copy.deepcopy(x) self.assertEqual(y, x) - self.assert_(x is not y) - self.assert_(x["foo"] is not y["foo"]) + self.assertTrue(x is not y) + self.assertTrue(x["foo"] is not y["foo"]) def test_deepcopy_reflexive_dict(self): x = {} x['foo'] = x y = copy.deepcopy(x) self.assertRaises(RuntimeError, cmp, y, x) - self.assert_(y is not x) - self.assert_(y['foo'] is y) + self.assertTrue(y is not x) + self.assertTrue(y['foo'] is y) self.assertEqual(len(y), 1) def test_deepcopy_keepalive(self): memo = {} x = 42 y = copy.deepcopy(x, memo) - self.assert_(memo[id(x)] is x) + self.assertTrue(memo[id(x)] is x) def test_deepcopy_inst_vanilla(self): class C: @@ -325,7 +325,7 @@ class TestCopy(unittest.TestCase): x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) - self.assert_(y.foo is not x.foo) + self.assertTrue(y.foo is not x.foo) def test_deepcopy_inst_deepcopy(self): class C: @@ -338,8 +338,8 @@ class TestCopy(unittest.TestCase): x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) - self.assert_(y is not x) - self.assert_(y.foo is not x.foo) + self.assertTrue(y is not x) + self.assertTrue(y.foo is not x.foo) def test_deepcopy_inst_getinitargs(self): class C: @@ -352,8 +352,8 @@ class TestCopy(unittest.TestCase): x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) - self.assert_(y is not x) - self.assert_(y.foo is not x.foo) + self.assertTrue(y is not x) + self.assertTrue(y.foo is not x.foo) def test_deepcopy_inst_getstate(self): class C: @@ -366,8 +366,8 @@ class TestCopy(unittest.TestCase): x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) - self.assert_(y is not x) - self.assert_(y.foo is not x.foo) + self.assertTrue(y is not x) + self.assertTrue(y.foo is not x.foo) def test_deepcopy_inst_setstate(self): class C: @@ -380,8 +380,8 @@ class TestCopy(unittest.TestCase): x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) - self.assert_(y is not x) - self.assert_(y.foo is not x.foo) + self.assertTrue(y is not x) + self.assertTrue(y.foo is not x.foo) def test_deepcopy_inst_getstate_setstate(self): class C: @@ -396,8 +396,8 @@ class TestCopy(unittest.TestCase): x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) - self.assert_(y is not x) - self.assert_(y.foo is not x.foo) + self.assertTrue(y is not x) + self.assertTrue(y.foo is not x.foo) def test_deepcopy_reflexive_inst(self): class C: @@ -405,8 +405,8 @@ class TestCopy(unittest.TestCase): x = C() x.foo = x y = copy.deepcopy(x) - self.assert_(y is not x) - self.assert_(y.foo is y) + self.assertTrue(y is not x) + self.assertTrue(y.foo is y) # _reconstruct() @@ -416,9 +416,9 @@ class TestCopy(unittest.TestCase): return "" x = C() y = copy.copy(x) - self.assert_(y is x) + self.assertTrue(y is x) y = copy.deepcopy(x) - self.assert_(y is x) + self.assertTrue(y is x) def test_reconstruct_nostate(self): class C(object): @@ -427,9 +427,9 @@ class TestCopy(unittest.TestCase): x = C() x.foo = 42 y = copy.copy(x) - self.assert_(y.__class__ is x.__class__) + self.assertTrue(y.__class__ is x.__class__) y = copy.deepcopy(x) - self.assert_(y.__class__ is x.__class__) + self.assertTrue(y.__class__ is x.__class__) def test_reconstruct_state(self): class C(object): @@ -444,7 +444,7 @@ class TestCopy(unittest.TestCase): self.assertEqual(y, x) y = copy.deepcopy(x) self.assertEqual(y, x) - self.assert_(y.foo is not x.foo) + self.assertTrue(y.foo is not x.foo) def test_reconstruct_state_setstate(self): class C(object): @@ -461,7 +461,7 @@ class TestCopy(unittest.TestCase): self.assertEqual(y, x) y = copy.deepcopy(x) self.assertEqual(y, x) - self.assert_(y.foo is not x.foo) + self.assertTrue(y.foo is not x.foo) def test_reconstruct_reflexive(self): class C(object): @@ -469,8 +469,8 @@ class TestCopy(unittest.TestCase): x = C() x.foo = x y = copy.deepcopy(x) - self.assert_(y is not x) - self.assert_(y.foo is y) + self.assertTrue(y is not x) + self.assertTrue(y.foo is y) # Additions for Python 2.3 and pickle protocol 2 @@ -485,12 +485,12 @@ class TestCopy(unittest.TestCase): x = C([[1, 2], 3]) y = copy.copy(x) self.assertEqual(x, y) - self.assert_(x is not y) - self.assert_(x[0] is y[0]) + self.assertTrue(x is not y) + self.assertTrue(x[0] is y[0]) y = copy.deepcopy(x) self.assertEqual(x, y) - self.assert_(x is not y) - self.assert_(x[0] is not y[0]) + self.assertTrue(x is not y) + self.assertTrue(x[0] is not y[0]) def test_reduce_5tuple(self): class C(dict): @@ -503,12 +503,12 @@ class TestCopy(unittest.TestCase): x = C([("foo", [1, 2]), ("bar", 3)]) y = copy.copy(x) self.assertEqual(x, y) - self.assert_(x is not y) - self.assert_(x["foo"] is y["foo"]) + self.assertTrue(x is not y) + self.assertTrue(x["foo"] is y["foo"]) y = copy.deepcopy(x) self.assertEqual(x, y) - self.assert_(x is not y) - self.assert_(x["foo"] is not y["foo"]) + self.assertTrue(x is not y) + self.assertTrue(x["foo"] is not y["foo"]) def test_copy_slots(self): class C(object): @@ -516,7 +516,7 @@ class TestCopy(unittest.TestCase): x = C() x.foo = [42] y = copy.copy(x) - self.assert_(x.foo is y.foo) + self.assertTrue(x.foo is y.foo) def test_deepcopy_slots(self): class C(object): @@ -525,7 +525,7 @@ class TestCopy(unittest.TestCase): x.foo = [42] y = copy.deepcopy(x) self.assertEqual(x.foo, y.foo) - self.assert_(x.foo is not y.foo) + self.assertTrue(x.foo is not y.foo) def test_copy_list_subclass(self): class C(list): @@ -535,8 +535,8 @@ class TestCopy(unittest.TestCase): y = copy.copy(x) self.assertEqual(list(x), list(y)) self.assertEqual(x.foo, y.foo) - self.assert_(x[0] is y[0]) - self.assert_(x.foo is y.foo) + self.assertTrue(x[0] is y[0]) + self.assertTrue(x.foo is y.foo) def test_deepcopy_list_subclass(self): class C(list): @@ -546,8 +546,8 @@ class TestCopy(unittest.TestCase): y = copy.deepcopy(x) self.assertEqual(list(x), list(y)) self.assertEqual(x.foo, y.foo) - self.assert_(x[0] is not y[0]) - self.assert_(x.foo is not y.foo) + self.assertTrue(x[0] is not y[0]) + self.assertTrue(x.foo is not y.foo) def test_copy_tuple_subclass(self): class C(tuple): @@ -564,8 +564,8 @@ class TestCopy(unittest.TestCase): self.assertEqual(tuple(x), ([1, 2], 3)) y = copy.deepcopy(x) self.assertEqual(tuple(y), ([1, 2], 3)) - self.assert_(x is not y) - self.assert_(x[0] is not y[0]) + self.assertTrue(x is not y) + self.assertTrue(x[0] is not y[0]) def test_getstate_exc(self): class EvilState(object): diff --git a/Lib/test/test_copy_reg.py b/Lib/test/test_copy_reg.py index c3d3964..efe2b4d 100644 --- a/Lib/test/test_copy_reg.py +++ b/Lib/test/test_copy_reg.py @@ -51,10 +51,10 @@ class CopyRegTestCase(unittest.TestCase): mod, func, code) copy_reg.add_extension(mod, func, code) # Should be in the registry. - self.assert_(copy_reg._extension_registry[mod, func] == code) - self.assert_(copy_reg._inverted_registry[code] == (mod, func)) + self.assertTrue(copy_reg._extension_registry[mod, func] == code) + self.assertTrue(copy_reg._inverted_registry[code] == (mod, func)) # Shouldn't be in the cache. - self.assert_(code not in copy_reg._extension_cache) + self.assertTrue(code not in copy_reg._extension_cache) # Redundant registration should be OK. copy_reg.add_extension(mod, func, code) # shouldn't blow up # Conflicting code. @@ -81,7 +81,7 @@ class CopyRegTestCase(unittest.TestCase): e.restore() # Shouldn't be there anymore. - self.assert_((mod, func) not in copy_reg._extension_registry) + self.assertTrue((mod, func) not in copy_reg._extension_registry) # The code *may* be in copy_reg._extension_registry, though, if # we happened to pick on a registered code. So don't check for # that. diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py index 5544904..aeb68bb 100644 --- a/Lib/test/test_csv.py +++ b/Lib/test/test_csv.py @@ -326,7 +326,7 @@ class TestDialectRegistry(unittest.TestCase): expected_dialects.sort() csv.register_dialect(name, myexceltsv) try: - self.failUnless(csv.get_dialect(name).delimiter, '\t') + self.assertTrue(csv.get_dialect(name).delimiter, '\t') got_dialects = csv.list_dialects() got_dialects.sort() self.assertEqual(expected_dialects, got_dialects) @@ -337,8 +337,8 @@ class TestDialectRegistry(unittest.TestCase): name = 'fedcba' csv.register_dialect(name, delimiter=';') try: - self.failUnless(csv.get_dialect(name).delimiter, '\t') - self.failUnless(list(csv.reader('X;Y;Z', name)), ['X', 'Y', 'Z']) + self.assertTrue(csv.get_dialect(name).delimiter, '\t') + self.assertTrue(list(csv.reader('X;Y;Z', name)), ['X', 'Y', 'Z']) finally: csv.unregister_dialect(name) @@ -935,7 +935,7 @@ Stonecutters Seafood and Chop House, Lemont, IL, 12/19/02, Week Back # given that all three lines in sample3 are equal, # I think that any character could have been 'guessed' as the # delimiter, depending on dictionary order - self.assert_(dialect.delimiter in self.sample3) + self.assertTrue(dialect.delimiter in self.sample3) dialect = sniffer.sniff(self.sample3, delimiters="?,") self.assertEqual(dialect.delimiter, "?") dialect = sniffer.sniff(self.sample3, delimiters="/,") diff --git a/Lib/test/test_datetime.py b/Lib/test/test_datetime.py index 24ec895..ad36398 100644 --- a/Lib/test/test_datetime.py +++ b/Lib/test/test_datetime.py @@ -79,9 +79,9 @@ class TestTZInfo(unittest.TestCase): def __init__(self, offset, name): self.__offset = offset self.__name = name - self.failUnless(issubclass(NotEnough, tzinfo)) + self.assertTrue(issubclass(NotEnough, tzinfo)) ne = NotEnough(3, "NotByALongShot") - self.failUnless(isinstance(ne, tzinfo)) + self.assertTrue(isinstance(ne, tzinfo)) dt = datetime.now() self.assertRaises(NotImplementedError, ne.tzname, dt) @@ -90,7 +90,7 @@ class TestTZInfo(unittest.TestCase): def test_normal(self): fo = FixedOffset(3, "Three") - self.failUnless(isinstance(fo, tzinfo)) + self.assertTrue(isinstance(fo, tzinfo)) for dt in datetime.now(), None: self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3)) self.assertEqual(fo.tzname(dt), "Three") @@ -101,25 +101,25 @@ class TestTZInfo(unittest.TestCase): # carry no data), but they need to be picklable anyway else # concrete subclasses can't be pickled. orig = tzinfo.__new__(tzinfo) - self.failUnless(type(orig) is tzinfo) + self.assertTrue(type(orig) is tzinfo) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) derived = unpickler.loads(green) - self.failUnless(type(derived) is tzinfo) + self.assertTrue(type(derived) is tzinfo) def test_pickling_subclass(self): # Make sure we can pickle/unpickle an instance of a subclass. offset = timedelta(minutes=-300) orig = PicklableFixedOffset(offset, 'cookie') - self.failUnless(isinstance(orig, tzinfo)) - self.failUnless(type(orig) is PicklableFixedOffset) + self.assertTrue(isinstance(orig, tzinfo)) + self.assertTrue(type(orig) is PicklableFixedOffset) self.assertEqual(orig.utcoffset(None), offset) self.assertEqual(orig.tzname(None), 'cookie') for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) derived = unpickler.loads(green) - self.failUnless(isinstance(derived, tzinfo)) - self.failUnless(type(derived) is PicklableFixedOffset) + self.assertTrue(isinstance(derived, tzinfo)) + self.assertTrue(type(derived) is PicklableFixedOffset) self.assertEqual(derived.utcoffset(None), offset) self.assertEqual(derived.tzname(None), 'cookie') @@ -136,16 +136,16 @@ class HarmlessMixedComparison: def test_harmless_mixed_comparison(self): me = self.theclass(1, 1, 1) - self.failIf(me == ()) - self.failUnless(me != ()) - self.failIf(() == me) - self.failUnless(() != me) + self.assertFalse(me == ()) + self.assertTrue(me != ()) + self.assertFalse(() == me) + self.assertTrue(() != me) - self.failUnless(me in [1, 20L, [], me]) - self.failIf(me not in [1, 20L, [], me]) + self.assertTrue(me in [1, 20L, [], me]) + self.assertFalse(me not in [1, 20L, [], me]) - self.failUnless([] in [me, 1, 20L, []]) - self.failIf([] not in [me, 1, 20L, []]) + self.assertTrue([] in [me, 1, 20L, []]) + self.assertFalse([] not in [me, 1, 20L, []]) def test_harmful_mixed_comparison(self): me = self.theclass(1, 1, 1) @@ -307,29 +307,29 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): def test_compare(self): t1 = timedelta(2, 3, 4) t2 = timedelta(2, 3, 4) - self.failUnless(t1 == t2) - self.failUnless(t1 <= t2) - self.failUnless(t1 >= t2) - self.failUnless(not t1 != t2) - self.failUnless(not t1 < t2) - self.failUnless(not t1 > t2) + self.assertTrue(t1 == t2) + self.assertTrue(t1 <= t2) + self.assertTrue(t1 >= t2) + self.assertTrue(not t1 != t2) + self.assertTrue(not t1 < t2) + self.assertTrue(not t1 > t2) self.assertEqual(cmp(t1, t2), 0) self.assertEqual(cmp(t2, t1), 0) for args in (3, 3, 3), (2, 4, 4), (2, 3, 5): t2 = timedelta(*args) # this is larger than t1 - self.failUnless(t1 < t2) - self.failUnless(t2 > t1) - self.failUnless(t1 <= t2) - self.failUnless(t2 >= t1) - self.failUnless(t1 != t2) - self.failUnless(t2 != t1) - self.failUnless(not t1 == t2) - self.failUnless(not t2 == t1) - self.failUnless(not t1 > t2) - self.failUnless(not t2 < t1) - self.failUnless(not t1 >= t2) - self.failUnless(not t2 <= t1) + self.assertTrue(t1 < t2) + self.assertTrue(t2 > t1) + self.assertTrue(t1 <= t2) + self.assertTrue(t2 >= t1) + self.assertTrue(t1 != t2) + self.assertTrue(t2 != t1) + self.assertTrue(not t1 == t2) + self.assertTrue(not t2 == t1) + self.assertTrue(not t1 > t2) + self.assertTrue(not t2 < t1) + self.assertTrue(not t1 >= t2) + self.assertTrue(not t2 <= t1) self.assertEqual(cmp(t1, t2), -1) self.assertEqual(cmp(t2, t1), 1) @@ -377,7 +377,7 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): # Verify td -> string -> td identity. s = repr(td) - self.failUnless(s.startswith('datetime.')) + self.assertTrue(s.startswith('datetime.')) s = s[9:] td2 = eval(s) self.assertEqual(td, td2) @@ -387,10 +387,10 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): self.assertEqual(td, td2) def test_resolution_info(self): - self.assert_(isinstance(timedelta.min, timedelta)) - self.assert_(isinstance(timedelta.max, timedelta)) - self.assert_(isinstance(timedelta.resolution, timedelta)) - self.assert_(timedelta.max > timedelta.min) + self.assertTrue(isinstance(timedelta.min, timedelta)) + self.assertTrue(isinstance(timedelta.max, timedelta)) + self.assertTrue(isinstance(timedelta.resolution, timedelta)) + self.assertTrue(timedelta.max > timedelta.min) self.assertEqual(timedelta.min, timedelta(-999999999)) self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1)) self.assertEqual(timedelta.resolution, timedelta(0, 0, 1)) @@ -437,11 +437,11 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): (-1, 24*3600-1, 999999)) def test_bool(self): - self.failUnless(timedelta(1)) - self.failUnless(timedelta(0, 1)) - self.failUnless(timedelta(0, 0, 1)) - self.failUnless(timedelta(microseconds=1)) - self.failUnless(not timedelta(0)) + self.assertTrue(timedelta(1)) + self.assertTrue(timedelta(0, 1)) + self.assertTrue(timedelta(0, 0, 1)) + self.assertTrue(timedelta(microseconds=1)) + self.assertTrue(not timedelta(0)) def test_subclass_timedelta(self): @@ -457,17 +457,17 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): return round(sum) t1 = T(days=1) - self.assert_(type(t1) is T) + self.assertTrue(type(t1) is T) self.assertEqual(t1.as_hours(), 24) t2 = T(days=-1, seconds=-3600) - self.assert_(type(t2) is T) + self.assertTrue(type(t2) is T) self.assertEqual(t2.as_hours(), -25) t3 = t1 + t2 - self.assert_(type(t3) is timedelta) + self.assertTrue(type(t3) is timedelta) t4 = T.from_td(t3) - self.assert_(type(t4) is T) + self.assertTrue(type(t4) is T) self.assertEqual(t3.days, t4.days) self.assertEqual(t3.seconds, t4.seconds) self.assertEqual(t3.microseconds, t4.microseconds) @@ -530,7 +530,7 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): self.theclass.today()): # Verify dt -> string -> date identity. s = repr(dt) - self.failUnless(s.startswith('datetime.')) + self.assertTrue(s.startswith('datetime.')) s = s[9:] dt2 = eval(s) self.assertEqual(dt, dt2) @@ -764,7 +764,7 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): # It worked or it didn't. If it didn't, assume it's reason #2, and # let the test pass if they're within half a second of each other. - self.failUnless(today == todayagain or + self.assertTrue(today == todayagain or abs(todayagain - today) < timedelta(seconds=0.5)) def test_weekday(self): @@ -901,10 +901,10 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): self.assertEqual(b.__format__(fmt), 'B') def test_resolution_info(self): - self.assert_(isinstance(self.theclass.min, self.theclass)) - self.assert_(isinstance(self.theclass.max, self.theclass)) - self.assert_(isinstance(self.theclass.resolution, timedelta)) - self.assert_(self.theclass.max > self.theclass.min) + self.assertTrue(isinstance(self.theclass.min, self.theclass)) + self.assertTrue(isinstance(self.theclass.max, self.theclass)) + self.assertTrue(isinstance(self.theclass.resolution, timedelta)) + self.assertTrue(self.theclass.max > self.theclass.min) def test_extreme_timedelta(self): big = self.theclass.max - self.theclass.min @@ -952,29 +952,29 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): def test_compare(self): t1 = self.theclass(2, 3, 4) t2 = self.theclass(2, 3, 4) - self.failUnless(t1 == t2) - self.failUnless(t1 <= t2) - self.failUnless(t1 >= t2) - self.failUnless(not t1 != t2) - self.failUnless(not t1 < t2) - self.failUnless(not t1 > t2) + self.assertTrue(t1 == t2) + self.assertTrue(t1 <= t2) + self.assertTrue(t1 >= t2) + self.assertTrue(not t1 != t2) + self.assertTrue(not t1 < t2) + self.assertTrue(not t1 > t2) self.assertEqual(cmp(t1, t2), 0) self.assertEqual(cmp(t2, t1), 0) for args in (3, 3, 3), (2, 4, 4), (2, 3, 5): t2 = self.theclass(*args) # this is larger than t1 - self.failUnless(t1 < t2) - self.failUnless(t2 > t1) - self.failUnless(t1 <= t2) - self.failUnless(t2 >= t1) - self.failUnless(t1 != t2) - self.failUnless(t2 != t1) - self.failUnless(not t1 == t2) - self.failUnless(not t2 == t1) - self.failUnless(not t1 > t2) - self.failUnless(not t2 < t1) - self.failUnless(not t1 >= t2) - self.failUnless(not t2 <= t1) + self.assertTrue(t1 < t2) + self.assertTrue(t2 > t1) + self.assertTrue(t1 <= t2) + self.assertTrue(t2 >= t1) + self.assertTrue(t1 != t2) + self.assertTrue(t2 != t1) + self.assertTrue(not t1 == t2) + self.assertTrue(not t2 == t1) + self.assertTrue(not t1 > t2) + self.assertTrue(not t2 < t1) + self.assertTrue(not t1 >= t2) + self.assertTrue(not t2 <= t1) self.assertEqual(cmp(t1, t2), -1) self.assertEqual(cmp(t2, t1), 1) @@ -1028,13 +1028,13 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): their = Comparable() self.assertEqual(cmp(our, their), 0) self.assertEqual(cmp(their, our), 0) - self.failUnless(our == their) - self.failUnless(their == our) + self.assertTrue(our == their) + self.assertTrue(their == our) def test_bool(self): # All dates are considered true. - self.failUnless(self.theclass.min) - self.failUnless(self.theclass.max) + self.assertTrue(self.theclass.min) + self.assertTrue(self.theclass.max) def test_strftime_out_of_range(self): # For nasty technical reasons, we can't handle years before 1900. @@ -1157,7 +1157,7 @@ class TestDateTime(TestDate): self.theclass.now()): # Verify dt -> string -> datetime identity. s = repr(dt) - self.failUnless(s.startswith('datetime.')) + self.assertTrue(s.startswith('datetime.')) s = s[9:] dt2 = eval(s) self.assertEqual(dt, dt2) @@ -1230,7 +1230,7 @@ class TestDateTime(TestDate): dt2 = self.theclass(2002, 3, 1, 10, 0, 0) dt3 = self.theclass(2002, 3, 1, 9, 0, 0) self.assertEqual(dt1, dt3) - self.assert_(dt2 > dt3) + self.assertTrue(dt2 > dt3) # Make sure comparison doesn't forget microseconds, and isn't done # via comparing a float timestamp (an IEEE double doesn't have enough @@ -1241,7 +1241,7 @@ class TestDateTime(TestDate): us = timedelta(microseconds=1) dt2 = dt1 + us self.assertEqual(dt2 - dt1, us) - self.assert_(dt1 < dt2) + self.assertTrue(dt1 < dt2) def test_strftime_with_bad_tzname_replace(self): # verify ok if tzinfo.tzname().replace() returns a non-string @@ -1421,12 +1421,12 @@ class TestDateTime(TestDate): args = [2000, 11, 29, 20, 58, 16, 999998] t1 = self.theclass(*args) t2 = self.theclass(*args) - self.failUnless(t1 == t2) - self.failUnless(t1 <= t2) - self.failUnless(t1 >= t2) - self.failUnless(not t1 != t2) - self.failUnless(not t1 < t2) - self.failUnless(not t1 > t2) + self.assertTrue(t1 == t2) + self.assertTrue(t1 <= t2) + self.assertTrue(t1 >= t2) + self.assertTrue(not t1 != t2) + self.assertTrue(not t1 < t2) + self.assertTrue(not t1 > t2) self.assertEqual(cmp(t1, t2), 0) self.assertEqual(cmp(t2, t1), 0) @@ -1434,18 +1434,18 @@ class TestDateTime(TestDate): newargs = args[:] newargs[i] = args[i] + 1 t2 = self.theclass(*newargs) # this is larger than t1 - self.failUnless(t1 < t2) - self.failUnless(t2 > t1) - self.failUnless(t1 <= t2) - self.failUnless(t2 >= t1) - self.failUnless(t1 != t2) - self.failUnless(t2 != t1) - self.failUnless(not t1 == t2) - self.failUnless(not t2 == t1) - self.failUnless(not t1 > t2) - self.failUnless(not t2 < t1) - self.failUnless(not t1 >= t2) - self.failUnless(not t2 <= t1) + self.assertTrue(t1 < t2) + self.assertTrue(t2 > t1) + self.assertTrue(t1 <= t2) + self.assertTrue(t2 >= t1) + self.assertTrue(t1 != t2) + self.assertTrue(t2 != t1) + self.assertTrue(not t1 == t2) + self.assertTrue(not t2 == t1) + self.assertTrue(not t1 > t2) + self.assertTrue(not t2 < t1) + self.assertTrue(not t1 >= t2) + self.assertTrue(not t2 <= t1) self.assertEqual(cmp(t1, t2), -1) self.assertEqual(cmp(t2, t1), 1) @@ -1526,7 +1526,7 @@ class TestDateTime(TestDate): if abs(from_timestamp - from_now) <= tolerance: break # Else try again a few times. - self.failUnless(abs(from_timestamp - from_now) <= tolerance) + self.assertTrue(abs(from_timestamp - from_now) <= tolerance) def test_strptime(self): import _strptime @@ -1695,7 +1695,7 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase): # Verify t -> string -> time identity. s = repr(t) - self.failUnless(s.startswith('datetime.')) + self.assertTrue(s.startswith('datetime.')) s = s[9:] t2 = eval(s) self.assertEqual(t, t2) @@ -1709,12 +1709,12 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase): args = [1, 2, 3, 4] t1 = self.theclass(*args) t2 = self.theclass(*args) - self.failUnless(t1 == t2) - self.failUnless(t1 <= t2) - self.failUnless(t1 >= t2) - self.failUnless(not t1 != t2) - self.failUnless(not t1 < t2) - self.failUnless(not t1 > t2) + self.assertTrue(t1 == t2) + self.assertTrue(t1 <= t2) + self.assertTrue(t1 >= t2) + self.assertTrue(not t1 != t2) + self.assertTrue(not t1 < t2) + self.assertTrue(not t1 > t2) self.assertEqual(cmp(t1, t2), 0) self.assertEqual(cmp(t2, t1), 0) @@ -1722,18 +1722,18 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase): newargs = args[:] newargs[i] = args[i] + 1 t2 = self.theclass(*newargs) # this is larger than t1 - self.failUnless(t1 < t2) - self.failUnless(t2 > t1) - self.failUnless(t1 <= t2) - self.failUnless(t2 >= t1) - self.failUnless(t1 != t2) - self.failUnless(t2 != t1) - self.failUnless(not t1 == t2) - self.failUnless(not t2 == t1) - self.failUnless(not t1 > t2) - self.failUnless(not t2 < t1) - self.failUnless(not t1 >= t2) - self.failUnless(not t2 <= t1) + self.assertTrue(t1 < t2) + self.assertTrue(t2 > t1) + self.assertTrue(t1 <= t2) + self.assertTrue(t2 >= t1) + self.assertTrue(t1 != t2) + self.assertTrue(t2 != t1) + self.assertTrue(not t1 == t2) + self.assertTrue(not t2 == t1) + self.assertTrue(not t1 > t2) + self.assertTrue(not t2 < t1) + self.assertTrue(not t1 >= t2) + self.assertTrue(not t2 <= t1) self.assertEqual(cmp(t1, t2), -1) self.assertEqual(cmp(t2, t1), 1) @@ -1886,10 +1886,10 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase): "%s(23, 15)" % name) def test_resolution_info(self): - self.assert_(isinstance(self.theclass.min, self.theclass)) - self.assert_(isinstance(self.theclass.max, self.theclass)) - self.assert_(isinstance(self.theclass.resolution, timedelta)) - self.assert_(self.theclass.max > self.theclass.min) + self.assertTrue(isinstance(self.theclass.min, self.theclass)) + self.assertTrue(isinstance(self.theclass.max, self.theclass)) + self.assertTrue(isinstance(self.theclass.resolution, timedelta)) + self.assertTrue(self.theclass.max > self.theclass.min) def test_pickling(self): args = 20, 59, 16, 64**2 @@ -1909,12 +1909,12 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase): def test_bool(self): cls = self.theclass - self.failUnless(cls(1)) - self.failUnless(cls(0, 1)) - self.failUnless(cls(0, 0, 1)) - self.failUnless(cls(0, 0, 0, 1)) - self.failUnless(not cls(0)) - self.failUnless(not cls()) + self.assertTrue(cls(1)) + self.assertTrue(cls(0, 1)) + self.assertTrue(cls(0, 0, 1)) + self.assertTrue(cls(0, 0, 0, 1)) + self.assertTrue(not cls(0)) + self.assertTrue(not cls()) def test_replace(self): cls = self.theclass @@ -2011,7 +2011,7 @@ class TZInfoBase: def utcoffset(self, dt): pass b = BetterTry() t = cls(1, 1, 1, tzinfo=b) - self.failUnless(t.tzinfo is b) + self.assertTrue(t.tzinfo is b) def test_utc_offset_out_of_bounds(self): class Edgy(tzinfo): @@ -2050,9 +2050,9 @@ class TZInfoBase: for t in (cls(1, 1, 1), cls(1, 1, 1, tzinfo=None), cls(1, 1, 1, tzinfo=C1())): - self.failUnless(t.utcoffset() is None) - self.failUnless(t.dst() is None) - self.failUnless(t.tzname() is None) + self.assertTrue(t.utcoffset() is None) + self.assertTrue(t.dst() is None) + self.assertTrue(t.tzname() is None) class C3(tzinfo): def utcoffset(self, dt): return timedelta(minutes=-1439) @@ -2146,7 +2146,7 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase): self.assertEqual(t.minute, 0) self.assertEqual(t.second, 0) self.assertEqual(t.microsecond, 0) - self.failUnless(t.tzinfo is None) + self.assertTrue(t.tzinfo is None) def test_zones(self): est = FixedOffset(-300, "EST", 1) @@ -2161,25 +2161,25 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase): self.assertEqual(t1.tzinfo, est) self.assertEqual(t2.tzinfo, utc) self.assertEqual(t3.tzinfo, met) - self.failUnless(t4.tzinfo is None) + self.assertTrue(t4.tzinfo is None) self.assertEqual(t5.tzinfo, utc) self.assertEqual(t1.utcoffset(), timedelta(minutes=-300)) self.assertEqual(t2.utcoffset(), timedelta(minutes=0)) self.assertEqual(t3.utcoffset(), timedelta(minutes=60)) - self.failUnless(t4.utcoffset() is None) + self.assertTrue(t4.utcoffset() is None) self.assertRaises(TypeError, t1.utcoffset, "no args") self.assertEqual(t1.tzname(), "EST") self.assertEqual(t2.tzname(), "UTC") self.assertEqual(t3.tzname(), "MET") - self.failUnless(t4.tzname() is None) + self.assertTrue(t4.tzname() is None) self.assertRaises(TypeError, t1.tzname, "no args") self.assertEqual(t1.dst(), timedelta(minutes=1)) self.assertEqual(t2.dst(), timedelta(minutes=-2)) self.assertEqual(t3.dst(), timedelta(minutes=3)) - self.failUnless(t4.dst() is None) + self.assertTrue(t4.dst() is None) self.assertRaises(TypeError, t1.dst, "no args") self.assertEqual(hash(t1), hash(t2)) @@ -2255,7 +2255,7 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase): green = pickler.dumps(orig, proto) derived = unpickler.loads(green) self.assertEqual(orig, derived) - self.failUnless(isinstance(derived.tzinfo, PicklableFixedOffset)) + self.assertTrue(isinstance(derived.tzinfo, PicklableFixedOffset)) self.assertEqual(derived.utcoffset(), timedelta(minutes=-300)) self.assertEqual(derived.tzname(), 'cookie') @@ -2264,20 +2264,20 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase): cls = self.theclass t = cls(0, tzinfo=FixedOffset(-300, "")) - self.failUnless(t) + self.assertTrue(t) t = cls(5, tzinfo=FixedOffset(-300, "")) - self.failUnless(t) + self.assertTrue(t) t = cls(5, tzinfo=FixedOffset(300, "")) - self.failUnless(not t) + self.assertTrue(not t) t = cls(23, 59, tzinfo=FixedOffset(23*60 + 59, "")) - self.failUnless(not t) + self.assertTrue(not t) # Mostly ensuring this doesn't overflow internally. t = cls(0, tzinfo=FixedOffset(23*60 + 59, "")) - self.failUnless(t) + self.assertTrue(t) # But this should yield a value error -- the utcoffset is bogus. t = cls(0, tzinfo=FixedOffset(24*60, "")) @@ -2311,13 +2311,13 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase): # Ensure we can get rid of a tzinfo. self.assertEqual(base.tzname(), "+100") base2 = base.replace(tzinfo=None) - self.failUnless(base2.tzinfo is None) - self.failUnless(base2.tzname() is None) + self.assertTrue(base2.tzinfo is None) + self.assertTrue(base2.tzname() is None) # Ensure we can add one. base3 = base2.replace(tzinfo=z100) self.assertEqual(base, base3) - self.failUnless(base.tzinfo is base3.tzinfo) + self.assertTrue(base.tzinfo is base3.tzinfo) # Out of bounds. base = cls(1) @@ -2354,7 +2354,7 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase): # But if they're not identical, it isn't ignored. t2 = t2.replace(tzinfo=Varies()) - self.failUnless(t1 < t2) # t1's offset counter still going up + self.assertTrue(t1 < t2) # t1's offset counter still going up def test_subclass_timetz(self): @@ -2410,12 +2410,12 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): tzinfo=FixedOffset(-1439, "")) # Make sure those compare correctly, and w/o overflow. - self.failUnless(t1 < t2) - self.failUnless(t1 != t2) - self.failUnless(t2 > t1) + self.assertTrue(t1 < t2) + self.assertTrue(t1 != t2) + self.assertTrue(t2 > t1) - self.failUnless(t1 == t1) - self.failUnless(t2 == t2) + self.assertTrue(t1 == t1) + self.assertTrue(t2 == t2) # Equal afer adjustment. t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, "")) @@ -2424,21 +2424,21 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): # Change t1 not to subtract a minute, and t1 should be larger. t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(0, "")) - self.failUnless(t1 > t2) + self.assertTrue(t1 > t2) # Change t1 to subtract 2 minutes, and t1 should be smaller. t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(2, "")) - self.failUnless(t1 < t2) + self.assertTrue(t1 < t2) # Back to the original t1, but make seconds resolve it. t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""), second=1) - self.failUnless(t1 > t2) + self.assertTrue(t1 > t2) # Likewise, but make microseconds resolve it. t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""), microsecond=1) - self.failUnless(t1 > t2) + self.assertTrue(t1 > t2) # Make t2 naive and it should fail. t2 = self.theclass.min @@ -2482,7 +2482,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): green = pickler.dumps(orig, proto) derived = unpickler.loads(green) self.assertEqual(orig, derived) - self.failUnless(isinstance(derived.tzinfo, + self.assertTrue(isinstance(derived.tzinfo, PicklableFixedOffset)) self.assertEqual(derived.utcoffset(), timedelta(minutes=-300)) self.assertEqual(derived.tzname(), 'cookie') @@ -2553,7 +2553,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): tz55 = FixedOffset(-330, "west 5:30") timeaware = now.time().replace(tzinfo=tz55) nowaware = self.theclass.combine(now.date(), timeaware) - self.failUnless(nowaware.tzinfo is tz55) + self.assertTrue(nowaware.tzinfo is tz55) self.assertEqual(nowaware.timetz(), timeaware) # Can't mix aware and non-aware. @@ -2572,15 +2572,15 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): # Adding a delta should preserve tzinfo. delta = timedelta(weeks=1, minutes=12, microseconds=5678) nowawareplus = nowaware + delta - self.failUnless(nowaware.tzinfo is tz55) + self.assertTrue(nowaware.tzinfo is tz55) nowawareplus2 = delta + nowaware - self.failUnless(nowawareplus2.tzinfo is tz55) + self.assertTrue(nowawareplus2.tzinfo is tz55) self.assertEqual(nowawareplus, nowawareplus2) # that - delta should be what we started with, and that - what we # started with should be delta. diff = nowawareplus - delta - self.failUnless(diff.tzinfo is tz55) + self.assertTrue(diff.tzinfo is tz55) self.assertEqual(nowaware, diff) self.assertRaises(TypeError, lambda: delta - nowawareplus) self.assertEqual(nowawareplus - nowaware, delta) @@ -2589,7 +2589,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): tzr = FixedOffset(random.randrange(-1439, 1440), "randomtimezone") # Attach it to nowawareplus. nowawareplus = nowawareplus.replace(tzinfo=tzr) - self.failUnless(nowawareplus.tzinfo is tzr) + self.assertTrue(nowawareplus.tzinfo is tzr) # Make sure the difference takes the timezone adjustments into account. got = nowaware - nowawareplus # Expected: (nowaware base - nowaware offset) - @@ -2616,7 +2616,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): off42 = FixedOffset(42, "42") another = meth(off42) again = meth(tz=off42) - self.failUnless(another.tzinfo is again.tzinfo) + self.assertTrue(another.tzinfo is again.tzinfo) self.assertEqual(another.utcoffset(), timedelta(minutes=42)) # Bad argument with and w/o naming the keyword. self.assertRaises(TypeError, meth, 16) @@ -2633,7 +2633,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): utc = FixedOffset(0, "utc", 0) for dummy in range(3): now = datetime.now(weirdtz) - self.failUnless(now.tzinfo is weirdtz) + self.assertTrue(now.tzinfo is weirdtz) utcnow = datetime.utcnow().replace(tzinfo=utc) now2 = utcnow.astimezone(weirdtz) if abs(now - now2) < timedelta(seconds=30): @@ -2654,7 +2654,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): off42 = FixedOffset(42, "42") another = meth(ts, off42) again = meth(ts, tz=off42) - self.failUnless(another.tzinfo is again.tzinfo) + self.assertTrue(another.tzinfo is again.tzinfo) self.assertEqual(another.utcoffset(), timedelta(minutes=42)) # Bad argument with and w/o naming the keyword. self.assertRaises(TypeError, meth, ts, 16) @@ -2848,13 +2848,13 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): # Ensure we can get rid of a tzinfo. self.assertEqual(base.tzname(), "+100") base2 = base.replace(tzinfo=None) - self.failUnless(base2.tzinfo is None) - self.failUnless(base2.tzname() is None) + self.assertTrue(base2.tzinfo is None) + self.assertTrue(base2.tzname() is None) # Ensure we can add one. base3 = base2.replace(tzinfo=z100) self.assertEqual(base, base3) - self.failUnless(base.tzinfo is base3.tzinfo) + self.assertTrue(base.tzinfo is base3.tzinfo) # Out of bounds. base = cls(2000, 2, 29) @@ -2867,20 +2867,20 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): fm5h = FixedOffset(-timedelta(hours=5), "m300") dt = self.theclass.now(tz=f44m) - self.failUnless(dt.tzinfo is f44m) + self.assertTrue(dt.tzinfo is f44m) # Replacing with degenerate tzinfo raises an exception. self.assertRaises(ValueError, dt.astimezone, fnone) # Ditto with None tz. self.assertRaises(TypeError, dt.astimezone, None) # Replacing with same tzinfo makes no change. x = dt.astimezone(dt.tzinfo) - self.failUnless(x.tzinfo is f44m) + self.assertTrue(x.tzinfo is f44m) self.assertEqual(x.date(), dt.date()) self.assertEqual(x.time(), dt.time()) # Replacing with different tzinfo does adjust. got = dt.astimezone(fm5h) - self.failUnless(got.tzinfo is fm5h) + self.assertTrue(got.tzinfo is fm5h) self.assertEqual(got.utcoffset(), timedelta(hours=-5)) expected = dt - dt.utcoffset() # in effect, convert to UTC expected += fm5h.utcoffset(dt) # and from there to local time @@ -2888,7 +2888,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): self.assertEqual(got.date(), expected.date()) self.assertEqual(got.time(), expected.time()) self.assertEqual(got.timetz(), expected.timetz()) - self.failUnless(got.tzinfo is expected.tzinfo) + self.assertTrue(got.tzinfo is expected.tzinfo) self.assertEqual(got, expected) def test_aware_subtract(self): @@ -2963,7 +2963,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): # But if they're not identical, it isn't ignored. t2 = t2.replace(tzinfo=Varies()) - self.failUnless(t1 < t2) # t1's offset counter still going up + self.assertTrue(t1 < t2) # t1's offset counter still going up def test_subclass_datetimetz(self): @@ -3314,10 +3314,10 @@ class Oddballs(unittest.TestCase): # type comparison, despite that datetime is a subclass of date. as_date = date.today() as_datetime = datetime.combine(as_date, time()) - self.assert_(as_date != as_datetime) - self.assert_(as_datetime != as_date) - self.assert_(not as_date == as_datetime) - self.assert_(not as_datetime == as_date) + self.assertTrue(as_date != as_datetime) + self.assertTrue(as_datetime != as_date) + self.assertTrue(not as_date == as_datetime) + self.assertTrue(not as_datetime == as_date) self.assertRaises(TypeError, lambda: as_date < as_datetime) self.assertRaises(TypeError, lambda: as_datetime < as_date) self.assertRaises(TypeError, lambda: as_date <= as_datetime) @@ -3329,9 +3329,9 @@ class Oddballs(unittest.TestCase): # Neverthelss, comparison should work with the base-class (date) # projection if use of a date method is forced. - self.assert_(as_date.__eq__(as_datetime)) + self.assertTrue(as_date.__eq__(as_datetime)) different_day = (as_date.day + 1) % 20 + 1 - self.assert_(not as_date.__eq__(as_datetime.replace(day= + self.assertTrue(not as_date.__eq__(as_datetime.replace(day= different_day))) # And date should compare with other subclasses of date. If a diff --git a/Lib/test/test_dbm.py b/Lib/test/test_dbm.py index 1627fff..43f8a5b 100755 --- a/Lib/test/test_dbm.py +++ b/Lib/test/test_dbm.py @@ -21,9 +21,9 @@ class DbmTestCase(unittest.TestCase): self.d[k] = v self.assertEqual(sorted(self.d.keys()), sorted(k for (k, v) in a)) for k, v in a: - self.assert_(k in self.d) + self.assertTrue(k in self.d) self.assertEqual(self.d[k], v) - self.assert_('xxx' not in self.d) + self.assertTrue('xxx' not in self.d) self.assertRaises(KeyError, lambda: self.d['xxx']) self.d.close() diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py index 7f95983..1ce65ec 100644 --- a/Lib/test/test_decimal.py +++ b/Lib/test/test_decimal.py @@ -513,7 +513,7 @@ class DecimalExplicitConstructionTest(unittest.TestCase): # from int d = nc.create_decimal(456) - self.failUnless(isinstance(d, Decimal)) + self.assertTrue(isinstance(d, Decimal)) self.assertEqual(nc.create_decimal(45678), nc.create_decimal('457E+2')) @@ -1061,12 +1061,12 @@ class DecimalArithmeticOperatorsTest(unittest.TestCase): f = Decimal('2') for x, y in [(n, n), (n, i), (i, n), (n, f), (f, n), (s, n), (n, s), (s, i), (i, s), (s, f), (f, s), (s, s)]: - self.assert_(x != y) - self.assert_(not (x == y)) - self.assert_(not (x < y)) - self.assert_(not (x <= y)) - self.assert_(not (x > y)) - self.assert_(not (x >= y)) + self.assertTrue(x != y) + self.assertTrue(not (x == y)) + self.assertTrue(not (x < y)) + self.assertTrue(not (x <= y)) + self.assertTrue(not (x > y)) + self.assertTrue(not (x >= y)) # The following are two functions used to test threading in the next class @@ -1139,22 +1139,22 @@ class DecimalUsabilityTest(unittest.TestCase): dc = Decimal('45') #two Decimals - self.failUnless(dc > da) - self.failUnless(dc >= da) - self.failUnless(da < dc) - self.failUnless(da <= dc) - self.failUnless(da == db) - self.failUnless(da != dc) - self.failUnless(da <= db) - self.failUnless(da >= db) + self.assertTrue(dc > da) + self.assertTrue(dc >= da) + self.assertTrue(da < dc) + self.assertTrue(da <= dc) + self.assertTrue(da == db) + self.assertTrue(da != dc) + self.assertTrue(da <= db) + self.assertTrue(da >= db) self.assertEqual(cmp(dc,da), 1) self.assertEqual(cmp(da,dc), -1) self.assertEqual(cmp(da,db), 0) #a Decimal and an int - self.failUnless(dc > 23) - self.failUnless(23 < dc) - self.failUnless(dc == 45) + self.assertTrue(dc > 23) + self.assertTrue(23 < dc) + self.assertTrue(dc == 45) self.assertEqual(cmp(dc,23), 1) self.assertEqual(cmp(23,dc), -1) self.assertEqual(cmp(dc,45), 0) @@ -1221,8 +1221,8 @@ class DecimalUsabilityTest(unittest.TestCase): #the same hash that to an int self.assertEqual(hash(Decimal(23)), hash(23)) self.assertRaises(TypeError, hash, Decimal('NaN')) - self.assert_(hash(Decimal('Inf'))) - self.assert_(hash(Decimal('-Inf'))) + self.assertTrue(hash(Decimal('Inf'))) + self.assertTrue(hash(Decimal('-Inf'))) # check that the value of the hash doesn't depend on the # current context (issue #1757) @@ -1249,22 +1249,22 @@ class DecimalUsabilityTest(unittest.TestCase): l2 = 28 #between Decimals - self.failUnless(min(d1,d2) is d1) - self.failUnless(min(d2,d1) is d1) - self.failUnless(max(d1,d2) is d2) - self.failUnless(max(d2,d1) is d2) + self.assertTrue(min(d1,d2) is d1) + self.assertTrue(min(d2,d1) is d1) + self.assertTrue(max(d1,d2) is d2) + self.assertTrue(max(d2,d1) is d2) #between Decimal and long - self.failUnless(min(d1,l2) is d1) - self.failUnless(min(l2,d1) is d1) - self.failUnless(max(l1,d2) is d2) - self.failUnless(max(d2,l1) is d2) + self.assertTrue(min(d1,l2) is d1) + self.assertTrue(min(l2,d1) is d1) + self.assertTrue(max(l1,d2) is d2) + self.assertTrue(max(d2,l1) is d2) def test_as_nonzero(self): #as false - self.failIf(Decimal(0)) + self.assertFalse(Decimal(0)) #as true - self.failUnless(Decimal('0.372')) + self.assertTrue(Decimal('0.372')) def test_tostring_methods(self): #Test str and repr methods. @@ -1459,10 +1459,10 @@ class DecimalUsabilityTest(unittest.TestCase): class DecimalPythonAPItests(unittest.TestCase): def test_abc(self): - self.assert_(issubclass(Decimal, numbers.Number)) - self.assert_(not issubclass(Decimal, numbers.Real)) - self.assert_(isinstance(Decimal(0), numbers.Number)) - self.assert_(not isinstance(Decimal(0), numbers.Real)) + self.assertTrue(issubclass(Decimal, numbers.Number)) + self.assertTrue(not issubclass(Decimal, numbers.Real)) + self.assertTrue(isinstance(Decimal(0), numbers.Number)) + self.assertTrue(not isinstance(Decimal(0), numbers.Real)) def test_pickle(self): d = Decimal('-3.141590000') @@ -1501,9 +1501,9 @@ class DecimalPythonAPItests(unittest.TestCase): '0.1000000000000000055511151231257827021181583404541015625') bigint = 12345678901234567890123456789 self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint)) - self.assert_(MyDecimal.from_float(float('nan')).is_qnan()) - self.assert_(MyDecimal.from_float(float('inf')).is_infinite()) - self.assert_(MyDecimal.from_float(float('-inf')).is_infinite()) + self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan()) + self.assertTrue(MyDecimal.from_float(float('inf')).is_infinite()) + self.assertTrue(MyDecimal.from_float(float('-inf')).is_infinite()) self.assertEqual(str(MyDecimal.from_float(float('nan'))), str(Decimal('NaN'))) self.assertEqual(str(MyDecimal.from_float(float('inf'))), @@ -1550,8 +1550,8 @@ class ContextAPItests(unittest.TestCase): self.assertEqual(v1, v2) def test_equality_with_other_types(self): - self.assert_(Decimal(10) in ['a', 1.0, Decimal(10), (1,2), {}]) - self.assert_(Decimal(10) not in ['a', 1.0, (1,2), {}]) + self.assertTrue(Decimal(10) in ['a', 1.0, Decimal(10), (1,2), {}]) + self.assertTrue(Decimal(10) not in ['a', 1.0, (1,2), {}]) def test_copy(self): # All copies should be deep @@ -1571,9 +1571,9 @@ class WithStatementTest(unittest.TestCase): with localcontext() as enter_ctx: set_ctx = getcontext() final_ctx = getcontext() - self.assert_(orig_ctx is final_ctx, 'did not restore context correctly') - self.assert_(orig_ctx is not set_ctx, 'did not copy the context') - self.assert_(set_ctx is enter_ctx, '__enter__ returned wrong context') + self.assertTrue(orig_ctx is final_ctx, 'did not restore context correctly') + self.assertTrue(orig_ctx is not set_ctx, 'did not copy the context') + self.assertTrue(set_ctx is enter_ctx, '__enter__ returned wrong context') def test_localcontextarg(self): # Use a copy of the supplied context in the block @@ -1582,10 +1582,10 @@ class WithStatementTest(unittest.TestCase): with localcontext(new_ctx) as enter_ctx: set_ctx = getcontext() final_ctx = getcontext() - self.assert_(orig_ctx is final_ctx, 'did not restore context correctly') - self.assert_(set_ctx.prec == new_ctx.prec, 'did not set correct context') - self.assert_(new_ctx is not set_ctx, 'did not copy the context') - self.assert_(set_ctx is enter_ctx, '__enter__ returned wrong context') + self.assertTrue(orig_ctx is final_ctx, 'did not restore context correctly') + self.assertTrue(set_ctx.prec == new_ctx.prec, 'did not set correct context') + self.assertTrue(new_ctx is not set_ctx, 'did not copy the context') + self.assertTrue(set_ctx is enter_ctx, '__enter__ returned wrong context') class ContextFlags(unittest.TestCase): def test_flags_irrelevant(self): diff --git a/Lib/test/test_defaultdict.py b/Lib/test/test_defaultdict.py index 5935e05..71d69c3 100644 --- a/Lib/test/test_defaultdict.py +++ b/Lib/test/test_defaultdict.py @@ -24,21 +24,21 @@ class TestDefaultDict(unittest.TestCase): d1[13] d1[14] self.assertEqual(d1, {12: [42, 24], 13: [], 14: []}) - self.assert_(d1[12] is not d1[13] is not d1[14]) + self.assertTrue(d1[12] is not d1[13] is not d1[14]) d2 = defaultdict(list, foo=1, bar=2) self.assertEqual(d2.default_factory, list) self.assertEqual(d2, {"foo": 1, "bar": 2}) self.assertEqual(d2["foo"], 1) self.assertEqual(d2["bar"], 2) self.assertEqual(d2[42], []) - self.assert_("foo" in d2) - self.assert_("foo" in d2.keys()) - self.assert_("bar" in d2) - self.assert_("bar" in d2.keys()) - self.assert_(42 in d2) - self.assert_(42 in d2.keys()) - self.assert_(12 not in d2) - self.assert_(12 not in d2.keys()) + self.assertTrue("foo" in d2) + self.assertTrue("foo" in d2.keys()) + self.assertTrue("bar" in d2) + self.assertTrue("bar" in d2.keys()) + self.assertTrue(42 in d2) + self.assertTrue(42 in d2.keys()) + self.assertTrue(12 not in d2) + self.assertTrue(12 not in d2.keys()) d2.default_factory = None self.assertEqual(d2.default_factory, None) try: @@ -67,7 +67,7 @@ class TestDefaultDict(unittest.TestCase): self.assertEqual(repr(d2), "defaultdict(<type 'int'>, {12: 42})") def foo(): return 43 d3 = defaultdict(foo) - self.assert_(d3.default_factory is foo) + self.assertTrue(d3.default_factory is foo) d3[13] self.assertEqual(repr(d3), "defaultdict(%s, {13: 43})" % repr(foo)) @@ -126,7 +126,7 @@ class TestDefaultDict(unittest.TestCase): d2 = copy.deepcopy(d1) self.assertEqual(d2.default_factory, foobar) self.assertEqual(d2, d1) - self.assert_(d1[1] is not d2[1]) + self.assertTrue(d1[1] is not d2[1]) d1.default_factory = list d2 = copy.deepcopy(d1) self.assertEqual(d2.default_factory, list) @@ -149,7 +149,7 @@ class TestDefaultDict(unittest.TestCase): def _factory(self): return [] d = sub() - self.assert_(repr(d).startswith( + self.assertTrue(repr(d).startswith( "defaultdict(<bound method sub._factory of defaultdict(...")) # NOTE: printing a subclass of a builtin type does not call its diff --git a/Lib/test/test_deque.py b/Lib/test/test_deque.py index a68d014..86810f2 100644 --- a/Lib/test/test_deque.py +++ b/Lib/test/test_deque.py @@ -188,9 +188,9 @@ class TestBasic(unittest.TestCase): self.assertEqual(len(d), n-i) j = random.randrange(-len(d), len(d)) val = d[j] - self.assert_(val in d) + self.assertTrue(val in d) del d[j] - self.assert_(val not in d) + self.assertTrue(val not in d) self.assertEqual(len(d), 0) def test_rotate(self): @@ -291,7 +291,7 @@ class TestBasic(unittest.TestCase): self.assertRaises(RuntimeError, d.remove, 'c') for x, y in zip(d, e): # verify that original order and values are retained. - self.assert_(x is y) + self.assertTrue(x is y) # Handle evil mutator for match in (True, False): @@ -305,7 +305,7 @@ class TestBasic(unittest.TestCase): e = eval(repr(d)) self.assertEqual(list(d), list(e)) d.append(d) - self.assert_('...' in repr(d)) + self.assertTrue('...' in repr(d)) def test_print(self): d = deque(xrange(200)) @@ -460,7 +460,7 @@ class TestBasic(unittest.TestCase): obj.x = iter(container) del obj, container gc.collect() - self.assert_(ref() is None, "Cycle was not collected") + self.assertTrue(ref() is None, "Cycle was not collected") class TestVariousIteratorArgs(unittest.TestCase): diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py index f160286..6dc27be 100644 --- a/Lib/test/test_descr.py +++ b/Lib/test/test_descr.py @@ -409,12 +409,12 @@ class ClassPropertiesAndMethods(unittest.TestCase): def test_python_dicts(self): # Testing Python subclass of dict... - self.assert_(issubclass(dict, dict)) - self.assert_(isinstance({}, dict)) + self.assertTrue(issubclass(dict, dict)) + self.assertTrue(isinstance({}, dict)) d = dict() self.assertEqual(d, {}) - self.assert_(d.__class__ is dict) - self.assert_(isinstance(d, dict)) + self.assertTrue(d.__class__ is dict) + self.assertTrue(isinstance(d, dict)) class C(dict): state = -1 def __init__(self_local, *a, **kw): @@ -427,13 +427,13 @@ class ClassPropertiesAndMethods(unittest.TestCase): def __getitem__(self, key): return self.get(key, 0) def __setitem__(self_local, key, value): - self.assert_(isinstance(key, type(0))) + self.assertTrue(isinstance(key, type(0))) dict.__setitem__(self_local, key, value) def setstate(self, state): self.state = state def getstate(self): return self.state - self.assert_(issubclass(C, dict)) + self.assertTrue(issubclass(C, dict)) a1 = C(12) self.assertEqual(a1.state, 12) a2 = C(foo=1, bar=2) @@ -527,7 +527,7 @@ class ClassPropertiesAndMethods(unittest.TestCase): return 42 self.assertEqual(C.name, 'C') self.assertEqual(C.bases, ()) - self.assert_('spam' in C.dict) + self.assertTrue('spam' in C.dict) c = C() self.assertEqual(c.spam(), 42) @@ -594,7 +594,7 @@ class ClassPropertiesAndMethods(unittest.TestCase): def _set_x(self, x): self.__x = -x a = A() - self.assert_(not hasattr(a, "x")) + self.assertTrue(not hasattr(a, "x")) a.x = 12 self.assertEqual(a.x, 12) self.assertEqual(a._A__x, -12) @@ -1171,7 +1171,7 @@ order (MRO) for bases """ class D(object): __slots__ = ["__dict__"] a = D() - self.assert_(hasattr(a, "__dict__")) + self.assertTrue(hasattr(a, "__dict__")) self.assertFalse(hasattr(a, "__weakref__")) a.foo = 42 self.assertEqual(a.__dict__, {"foo": 42}) @@ -1179,7 +1179,7 @@ order (MRO) for bases """ class W(object): __slots__ = ["__weakref__"] a = W() - self.assert_(hasattr(a, "__weakref__")) + self.assertTrue(hasattr(a, "__weakref__")) self.assertFalse(hasattr(a, "__dict__")) try: a.foo = 42 @@ -1191,16 +1191,16 @@ order (MRO) for bases """ class C1(W, D): __slots__ = [] a = C1() - self.assert_(hasattr(a, "__dict__")) - self.assert_(hasattr(a, "__weakref__")) + self.assertTrue(hasattr(a, "__dict__")) + self.assertTrue(hasattr(a, "__weakref__")) a.foo = 42 self.assertEqual(a.__dict__, {"foo": 42}) class C2(D, W): __slots__ = [] a = C2() - self.assert_(hasattr(a, "__dict__")) - self.assert_(hasattr(a, "__weakref__")) + self.assertTrue(hasattr(a, "__dict__")) + self.assertTrue(hasattr(a, "__weakref__")) a.foo = 42 self.assertEqual(a.__dict__, {"foo": 42}) @@ -1217,7 +1217,7 @@ order (MRO) for bases """ MyABC.register(Unrelated) u = Unrelated() - self.assert_(isinstance(u, MyABC)) + self.assertTrue(isinstance(u, MyABC)) # This used to crash self.assertRaises(TypeError, MyABC.a.__set__, u, 3) @@ -1473,7 +1473,7 @@ order (MRO) for bases """ class E: # *not* subclassing from C foo = C.foo self.assertEqual(E().foo, C.foo) # i.e., unbound - self.assert_(repr(C.foo.__get__(C())).startswith("<bound method ")) + self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method ")) def test_compattr(self): # Testing computed attributes... @@ -1664,7 +1664,7 @@ order (MRO) for bases """ class E(object): foo = C.foo self.assertEqual(E().foo, C.foo) # i.e., unbound - self.assert_(repr(C.foo.__get__(C(1))).startswith("<bound method ")) + self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method ")) def test_special_method_lookup(self): # The lookup of special methods bypasses __getattr__ and @@ -1776,22 +1776,22 @@ order (MRO) for bases """ raise IndexError c1 = C() c2 = C() - self.assert_(not not c1) # What? + self.assertTrue(not not c1) # What? self.assertNotEqual(id(c1), id(c2)) hash(c1) hash(c2) self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2))) self.assertEqual(c1, c1) - self.assert_(c1 != c2) - self.assert_(not c1 != c1) - self.assert_(not c1 == c2) + self.assertTrue(c1 != c2) + self.assertTrue(not c1 != c1) + self.assertTrue(not c1 == c2) # Note that the module name appears in str/repr, and that varies # depending on whether this test is run standalone or from a framework. - self.assert_(str(c1).find('C object at ') >= 0) + self.assertTrue(str(c1).find('C object at ') >= 0) self.assertEqual(str(c1), repr(c1)) - self.assert_(-1 not in c1) + self.assertTrue(-1 not in c1) for i in range(10): - self.assert_(i in c1) + self.assertTrue(i in c1) self.assertFalse(10 in c1) # Test the default behavior for dynamic classes class D(object): @@ -1800,22 +1800,22 @@ order (MRO) for bases """ raise IndexError d1 = D() d2 = D() - self.assert_(not not d1) + self.assertTrue(not not d1) self.assertNotEqual(id(d1), id(d2)) hash(d1) hash(d2) self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2))) self.assertEqual(d1, d1) self.assertNotEqual(d1, d2) - self.assert_(not d1 != d1) - self.assert_(not d1 == d2) + self.assertTrue(not d1 != d1) + self.assertTrue(not d1 == d2) # Note that the module name appears in str/repr, and that varies # depending on whether this test is run standalone or from a framework. - self.assert_(str(d1).find('D object at ') >= 0) + self.assertTrue(str(d1).find('D object at ') >= 0) self.assertEqual(str(d1), repr(d1)) - self.assert_(-1 not in d1) + self.assertTrue(-1 not in d1) for i in range(10): - self.assert_(i in d1) + self.assertTrue(i in d1) self.assertFalse(10 in d1) # Test overridden behavior for static classes class Proxy(object): @@ -1841,11 +1841,11 @@ order (MRO) for bases """ p1 = Proxy(1) p_1 = Proxy(-1) self.assertFalse(p0) - self.assert_(not not p1) + self.assertTrue(not not p1) self.assertEqual(hash(p0), hash(0)) self.assertEqual(p0, p0) self.assertNotEqual(p0, p1) - self.assert_(not p0 != p0) + self.assertTrue(not p0 != p0) self.assertEqual(not p0, p1) self.assertEqual(cmp(p0, p1), -1) self.assertEqual(cmp(p0, p0), 0) @@ -1855,7 +1855,7 @@ order (MRO) for bases """ p10 = Proxy(range(10)) self.assertFalse(-1 in p10) for i in range(10): - self.assert_(i in p10) + self.assertTrue(i in p10) self.assertFalse(10 in p10) # Test overridden behavior for dynamic classes class DProxy(object): @@ -1881,7 +1881,7 @@ order (MRO) for bases """ p1 = DProxy(1) p_1 = DProxy(-1) self.assertFalse(p0) - self.assert_(not not p1) + self.assertTrue(not not p1) self.assertEqual(hash(p0), hash(0)) self.assertEqual(p0, p0) self.assertNotEqual(p0, p1) @@ -1895,7 +1895,7 @@ order (MRO) for bases """ p10 = DProxy(range(10)) self.assertFalse(-1 in p10) for i in range(10): - self.assert_(i in p10) + self.assertTrue(i in p10) self.assertFalse(10 in p10) # Safety test for __cmp__ @@ -1975,7 +1975,7 @@ order (MRO) for bases """ try: weakref.ref(no) except TypeError, msg: - self.assert_(str(msg).find("weak reference") >= 0) + self.assertTrue(str(msg).find("weak reference") >= 0) else: self.fail("weakref.ref(no) should be illegal") class Weak(object): @@ -2012,18 +2012,18 @@ order (MRO) for bases """ self.assertFalse(hasattr(a, "x")) raw = C.__dict__['x'] - self.assert_(isinstance(raw, property)) + self.assertTrue(isinstance(raw, property)) attrs = dir(raw) - self.assert_("__doc__" in attrs) - self.assert_("fget" in attrs) - self.assert_("fset" in attrs) - self.assert_("fdel" in attrs) + self.assertTrue("__doc__" in attrs) + self.assertTrue("fget" in attrs) + self.assertTrue("fset" in attrs) + self.assertTrue("fdel" in attrs) self.assertEqual(raw.__doc__, "I'm the x property.") - self.assert_(raw.fget is C.__dict__['getx']) - self.assert_(raw.fset is C.__dict__['setx']) - self.assert_(raw.fdel is C.__dict__['delx']) + self.assertTrue(raw.fget is C.__dict__['getx']) + self.assertTrue(raw.fset is C.__dict__['setx']) + self.assertTrue(raw.fdel is C.__dict__['delx']) for attr in "__doc__", "fget", "fset", "fdel": try: @@ -2085,7 +2085,7 @@ order (MRO) for bases """ self.assertEqual(C.foo.__doc__, "hello") self.assertFalse(hasattr(c, "foo")) c.foo = -42 - self.assert_(hasattr(c, '_foo')) + self.assertTrue(hasattr(c, '_foo')) self.assertEqual(c._foo, 42) self.assertEqual(c.foo, 42) del c.foo @@ -2236,7 +2236,7 @@ order (MRO) for bases """ cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__'] self.assertEqual(dir(C), cstuff) - self.assert_('im_self' in dir(C.Cmethod)) + self.assertTrue('im_self' in dir(C.Cmethod)) c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__. self.assertEqual(dir(c), cstuff) @@ -2244,7 +2244,7 @@ order (MRO) for bases """ c.cdata = 2 c.cmethod = lambda self: 0 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod']) - self.assert_('im_self' in dir(c.Cmethod)) + self.assertTrue('im_self' in dir(c.Cmethod)) class A(C): Adata = 1 @@ -2252,10 +2252,10 @@ order (MRO) for bases """ astuff = ['Adata', 'Amethod'] + cstuff self.assertEqual(dir(A), astuff) - self.assert_('im_self' in dir(A.Amethod)) + self.assertTrue('im_self' in dir(A.Amethod)) a = A() self.assertEqual(dir(a), astuff) - self.assert_('im_self' in dir(a.Amethod)) + self.assertTrue('im_self' in dir(a.Amethod)) a.adata = 42 a.amethod = lambda self: 3 self.assertEqual(dir(a), astuff + ['adata', 'amethod']) @@ -2274,12 +2274,12 @@ order (MRO) for bases """ c = C() self.assertEqual(interesting(dir(c)), cstuff) - self.assert_('im_self' in dir(C.Cmethod)) + self.assertTrue('im_self' in dir(C.Cmethod)) c.cdata = 2 c.cmethod = lambda self: 0 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod']) - self.assert_('im_self' in dir(c.Cmethod)) + self.assertTrue('im_self' in dir(c.Cmethod)) class A(C): Adata = 1 @@ -2287,13 +2287,13 @@ order (MRO) for bases """ astuff = ['Adata', 'Amethod'] + cstuff self.assertEqual(interesting(dir(A)), astuff) - self.assert_('im_self' in dir(A.Amethod)) + self.assertTrue('im_self' in dir(A.Amethod)) a = A() self.assertEqual(interesting(dir(a)), astuff) a.adata = 42 a.amethod = lambda self: 3 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod']) - self.assert_('im_self' in dir(a.Amethod)) + self.assertTrue('im_self' in dir(a.Amethod)) # Try a module subclass. import sys @@ -2477,13 +2477,13 @@ order (MRO) for bases """ a = hexint(12345) self.assertEqual(a, 12345) self.assertEqual(int(a), 12345) - self.assert_(int(a).__class__ is int) + self.assertTrue(int(a).__class__ is int) self.assertEqual(hash(a), hash(12345)) - self.assert_((+a).__class__ is int) - self.assert_((a >> 0).__class__ is int) - self.assert_((a << 0).__class__ is int) - self.assert_((hexint(0) << 12).__class__ is int) - self.assert_((hexint(0) >> 12).__class__ is int) + self.assertTrue((+a).__class__ is int) + self.assertTrue((a >> 0).__class__ is int) + self.assertTrue((a << 0).__class__ is int) + self.assertTrue((hexint(0) << 12).__class__ is int) + self.assertTrue((hexint(0) >> 12).__class__ is int) class octlong(long): __slots__ = [] @@ -2503,36 +2503,36 @@ order (MRO) for bases """ self.assertEqual(a, 12345L) self.assertEqual(long(a), 12345L) self.assertEqual(hash(a), hash(12345L)) - self.assert_(long(a).__class__ is long) - self.assert_((+a).__class__ is long) - self.assert_((-a).__class__ is long) - self.assert_((-octlong(0)).__class__ is long) - self.assert_((a >> 0).__class__ is long) - self.assert_((a << 0).__class__ is long) - self.assert_((a - 0).__class__ is long) - self.assert_((a * 1).__class__ is long) - self.assert_((a ** 1).__class__ is long) - self.assert_((a // 1).__class__ is long) - self.assert_((1 * a).__class__ is long) - self.assert_((a | 0).__class__ is long) - self.assert_((a ^ 0).__class__ is long) - self.assert_((a & -1L).__class__ is long) - self.assert_((octlong(0) << 12).__class__ is long) - self.assert_((octlong(0) >> 12).__class__ is long) - self.assert_(abs(octlong(0)).__class__ is long) + self.assertTrue(long(a).__class__ is long) + self.assertTrue((+a).__class__ is long) + self.assertTrue((-a).__class__ is long) + self.assertTrue((-octlong(0)).__class__ is long) + self.assertTrue((a >> 0).__class__ is long) + self.assertTrue((a << 0).__class__ is long) + self.assertTrue((a - 0).__class__ is long) + self.assertTrue((a * 1).__class__ is long) + self.assertTrue((a ** 1).__class__ is long) + self.assertTrue((a // 1).__class__ is long) + self.assertTrue((1 * a).__class__ is long) + self.assertTrue((a | 0).__class__ is long) + self.assertTrue((a ^ 0).__class__ is long) + self.assertTrue((a & -1L).__class__ is long) + self.assertTrue((octlong(0) << 12).__class__ is long) + self.assertTrue((octlong(0) >> 12).__class__ is long) + self.assertTrue(abs(octlong(0)).__class__ is long) # Because octlong overrides __add__, we can't check the absence of +0 # optimizations using octlong. class longclone(long): pass a = longclone(1) - self.assert_((a + 0).__class__ is long) - self.assert_((0 + a).__class__ is long) + self.assertTrue((a + 0).__class__ is long) + self.assertTrue((0 + a).__class__ is long) # Check that negative clones don't segfault a = longclone(-1) self.assertEqual(a.__dict__, {}) - self.assertEqual(long(a), -1) # self.assert_ PyNumber_Long() copies the sign bit + self.assertEqual(long(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit class precfloat(float): __slots__ = ['prec'] @@ -2544,9 +2544,9 @@ order (MRO) for bases """ a = precfloat(12345) self.assertEqual(a, 12345.0) self.assertEqual(float(a), 12345.0) - self.assert_(float(a).__class__ is float) + self.assertTrue(float(a).__class__ is float) self.assertEqual(hash(a), hash(12345.0)) - self.assert_((+a).__class__ is float) + self.assertTrue((+a).__class__ is float) class madcomplex(complex): def __repr__(self): @@ -2594,20 +2594,20 @@ order (MRO) for bases """ self.assertEqual(v, t) a = madtuple((1,2,3,4,5)) self.assertEqual(tuple(a), (1,2,3,4,5)) - self.assert_(tuple(a).__class__ is tuple) + self.assertTrue(tuple(a).__class__ is tuple) self.assertEqual(hash(a), hash((1,2,3,4,5))) - self.assert_(a[:].__class__ is tuple) - self.assert_((a * 1).__class__ is tuple) - self.assert_((a * 0).__class__ is tuple) - self.assert_((a + ()).__class__ is tuple) + self.assertTrue(a[:].__class__ is tuple) + self.assertTrue((a * 1).__class__ is tuple) + self.assertTrue((a * 0).__class__ is tuple) + self.assertTrue((a + ()).__class__ is tuple) a = madtuple(()) self.assertEqual(tuple(a), ()) - self.assert_(tuple(a).__class__ is tuple) - self.assert_((a + a).__class__ is tuple) - self.assert_((a * 0).__class__ is tuple) - self.assert_((a * 1).__class__ is tuple) - self.assert_((a * 2).__class__ is tuple) - self.assert_(a[:].__class__ is tuple) + self.assertTrue(tuple(a).__class__ is tuple) + self.assertTrue((a + a).__class__ is tuple) + self.assertTrue((a * 0).__class__ is tuple) + self.assertTrue((a * 1).__class__ is tuple) + self.assertTrue((a * 2).__class__ is tuple) + self.assertTrue(a[:].__class__ is tuple) class madstring(str): _rev = None @@ -2629,51 +2629,51 @@ order (MRO) for bases """ self.assertEqual(u, s) s = madstring("12345") self.assertEqual(str(s), "12345") - self.assert_(str(s).__class__ is str) + self.assertTrue(str(s).__class__ is str) base = "\x00" * 5 s = madstring(base) self.assertEqual(s, base) self.assertEqual(str(s), base) - self.assert_(str(s).__class__ is str) + self.assertTrue(str(s).__class__ is str) self.assertEqual(hash(s), hash(base)) self.assertEqual({s: 1}[base], 1) self.assertEqual({base: 1}[s], 1) - self.assert_((s + "").__class__ is str) + self.assertTrue((s + "").__class__ is str) self.assertEqual(s + "", base) - self.assert_(("" + s).__class__ is str) + self.assertTrue(("" + s).__class__ is str) self.assertEqual("" + s, base) - self.assert_((s * 0).__class__ is str) + self.assertTrue((s * 0).__class__ is str) self.assertEqual(s * 0, "") - self.assert_((s * 1).__class__ is str) + self.assertTrue((s * 1).__class__ is str) self.assertEqual(s * 1, base) - self.assert_((s * 2).__class__ is str) + self.assertTrue((s * 2).__class__ is str) self.assertEqual(s * 2, base + base) - self.assert_(s[:].__class__ is str) + self.assertTrue(s[:].__class__ is str) self.assertEqual(s[:], base) - self.assert_(s[0:0].__class__ is str) + self.assertTrue(s[0:0].__class__ is str) self.assertEqual(s[0:0], "") - self.assert_(s.strip().__class__ is str) + self.assertTrue(s.strip().__class__ is str) self.assertEqual(s.strip(), base) - self.assert_(s.lstrip().__class__ is str) + self.assertTrue(s.lstrip().__class__ is str) self.assertEqual(s.lstrip(), base) - self.assert_(s.rstrip().__class__ is str) + self.assertTrue(s.rstrip().__class__ is str) self.assertEqual(s.rstrip(), base) identitytab = ''.join([chr(i) for i in range(256)]) - self.assert_(s.translate(identitytab).__class__ is str) + self.assertTrue(s.translate(identitytab).__class__ is str) self.assertEqual(s.translate(identitytab), base) - self.assert_(s.translate(identitytab, "x").__class__ is str) + self.assertTrue(s.translate(identitytab, "x").__class__ is str) self.assertEqual(s.translate(identitytab, "x"), base) self.assertEqual(s.translate(identitytab, "\x00"), "") - self.assert_(s.replace("x", "x").__class__ is str) + self.assertTrue(s.replace("x", "x").__class__ is str) self.assertEqual(s.replace("x", "x"), base) - self.assert_(s.ljust(len(s)).__class__ is str) + self.assertTrue(s.ljust(len(s)).__class__ is str) self.assertEqual(s.ljust(len(s)), base) - self.assert_(s.rjust(len(s)).__class__ is str) + self.assertTrue(s.rjust(len(s)).__class__ is str) self.assertEqual(s.rjust(len(s)), base) - self.assert_(s.center(len(s)).__class__ is str) + self.assertTrue(s.center(len(s)).__class__ is str) self.assertEqual(s.center(len(s)), base) - self.assert_(s.lower().__class__ is str) + self.assertTrue(s.lower().__class__ is str) self.assertEqual(s.lower(), base) class madunicode(unicode): @@ -2692,47 +2692,47 @@ order (MRO) for bases """ base = u"12345" u = madunicode(base) self.assertEqual(unicode(u), base) - self.assert_(unicode(u).__class__ is unicode) + self.assertTrue(unicode(u).__class__ is unicode) self.assertEqual(hash(u), hash(base)) self.assertEqual({u: 1}[base], 1) self.assertEqual({base: 1}[u], 1) - self.assert_(u.strip().__class__ is unicode) + self.assertTrue(u.strip().__class__ is unicode) self.assertEqual(u.strip(), base) - self.assert_(u.lstrip().__class__ is unicode) + self.assertTrue(u.lstrip().__class__ is unicode) self.assertEqual(u.lstrip(), base) - self.assert_(u.rstrip().__class__ is unicode) + self.assertTrue(u.rstrip().__class__ is unicode) self.assertEqual(u.rstrip(), base) - self.assert_(u.replace(u"x", u"x").__class__ is unicode) + self.assertTrue(u.replace(u"x", u"x").__class__ is unicode) self.assertEqual(u.replace(u"x", u"x"), base) - self.assert_(u.replace(u"xy", u"xy").__class__ is unicode) + self.assertTrue(u.replace(u"xy", u"xy").__class__ is unicode) self.assertEqual(u.replace(u"xy", u"xy"), base) - self.assert_(u.center(len(u)).__class__ is unicode) + self.assertTrue(u.center(len(u)).__class__ is unicode) self.assertEqual(u.center(len(u)), base) - self.assert_(u.ljust(len(u)).__class__ is unicode) + self.assertTrue(u.ljust(len(u)).__class__ is unicode) self.assertEqual(u.ljust(len(u)), base) - self.assert_(u.rjust(len(u)).__class__ is unicode) + self.assertTrue(u.rjust(len(u)).__class__ is unicode) self.assertEqual(u.rjust(len(u)), base) - self.assert_(u.lower().__class__ is unicode) + self.assertTrue(u.lower().__class__ is unicode) self.assertEqual(u.lower(), base) - self.assert_(u.upper().__class__ is unicode) + self.assertTrue(u.upper().__class__ is unicode) self.assertEqual(u.upper(), base) - self.assert_(u.capitalize().__class__ is unicode) + self.assertTrue(u.capitalize().__class__ is unicode) self.assertEqual(u.capitalize(), base) - self.assert_(u.title().__class__ is unicode) + self.assertTrue(u.title().__class__ is unicode) self.assertEqual(u.title(), base) - self.assert_((u + u"").__class__ is unicode) + self.assertTrue((u + u"").__class__ is unicode) self.assertEqual(u + u"", base) - self.assert_((u"" + u).__class__ is unicode) + self.assertTrue((u"" + u).__class__ is unicode) self.assertEqual(u"" + u, base) - self.assert_((u * 0).__class__ is unicode) + self.assertTrue((u * 0).__class__ is unicode) self.assertEqual(u * 0, u"") - self.assert_((u * 1).__class__ is unicode) + self.assertTrue((u * 1).__class__ is unicode) self.assertEqual(u * 1, base) - self.assert_((u * 2).__class__ is unicode) + self.assertTrue((u * 2).__class__ is unicode) self.assertEqual(u * 2, base + base) - self.assert_(u[:].__class__ is unicode) + self.assertTrue(u[:].__class__ is unicode) self.assertEqual(u[:], base) - self.assert_(u[0:0].__class__ is unicode) + self.assertTrue(u[0:0].__class__ is unicode) self.assertEqual(u[0:0], u"") class sublist(list): @@ -2851,7 +2851,7 @@ order (MRO) for bases """ self.assertEqual(d[cistr('one')], 1) self.assertEqual(d[cistr('tWo')], 2) self.assertEqual(d[cistr('THrEE')], 3) - self.assert_(cistr('ONe') in d) + self.assertTrue(cistr('ONe') in d) self.assertEqual(d.get(cistr('thrEE')), 3) def test_classic_comparisons(self): @@ -2878,12 +2878,12 @@ order (MRO) for bases """ c = {1: c1, 2: c2, 3: c3} for x in 1, 2, 3: for y in 1, 2, 3: - self.assert_(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) + self.assertTrue(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) for op in "<", "<=", "==", "!=", ">", ">=": - self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), + self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y)) - self.assert_(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y)) - self.assert_(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) + self.assertTrue(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y)) + self.assertTrue(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) def test_rich_comparisons(self): # Testing rich comparisons... @@ -2956,11 +2956,11 @@ order (MRO) for bases """ for x in 1, 2, 3: for y in 1, 2, 3: for op in "<", "<=", "==", "!=", ">", ">=": - self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), + self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y)) - self.assert_(eval("c[x] %s y" % op) == eval("x %s y" % op), + self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y)) - self.assert_(eval("x %s c[y]" % op) == eval("x %s y" % op), + self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y)) def test_coercions(self): @@ -3026,9 +3026,9 @@ order (MRO) for bases """ for cls2 in C, D, E, F: x = cls() x.__class__ = cls2 - self.assert_(x.__class__ is cls2) + self.assertTrue(x.__class__ is cls2) x.__class__ = cls - self.assert_(x.__class__ is cls) + self.assertTrue(x.__class__ is cls) def cant(x, C): try: x.__class__ = C @@ -3090,11 +3090,11 @@ order (MRO) for bases """ x = cls() x.a = 1 x.__class__ = cls2 - self.assert_(x.__class__ is cls2, + self.assertTrue(x.__class__ is cls2, "assigning %r as __class__ for %r silently failed" % (cls2, x)) self.assertEqual(x.a, 1) x.__class__ = cls - self.assert_(x.__class__ is cls, + self.assertTrue(x.__class__ is cls, "assigning %r as __class__ for %r silently failed" % (cls, x)) self.assertEqual(x.a, 1) for cls in G, J, K, L, M, N, P, R, list, Int: @@ -3264,7 +3264,7 @@ order (MRO) for bases """ for cls in C, C1, C2: s = p.dumps(cls, bin) cls2 = p.loads(s) - self.assert_(cls2 is cls) + self.assertTrue(cls2 is cls) a = C1(1, 2); a.append(42); a.append(24) b = C2("hello", "world", 42) @@ -3294,7 +3294,7 @@ order (MRO) for bases """ import copy for cls in C, C1, C2: cls2 = copy.deepcopy(cls) - self.assert_(cls2 is cls) + self.assertTrue(cls2 is cls) a = C1(1, 2); a.append(42); a.append(24) b = C2("hello", "world", 42) @@ -3866,8 +3866,8 @@ order (MRO) for bases """ __slots__=() if test_support.check_impl_detail(): self.assertEqual(C.__basicsize__, B.__basicsize__) - self.assert_(hasattr(C, '__dict__')) - self.assert_(hasattr(C, '__weakref__')) + self.assertTrue(hasattr(C, '__dict__')) + self.assertTrue(hasattr(C, '__weakref__')) C().x = 2 def test_rmul(self): @@ -4224,29 +4224,29 @@ order (MRO) for bases """ pass a = C() pa = Proxy(a) - self.assert_(isinstance(a, C)) # Baseline - self.assert_(isinstance(pa, C)) # Test + self.assertTrue(isinstance(a, C)) # Baseline + self.assertTrue(isinstance(pa, C)) # Test # Test with a classic subclass class D(C): pass a = D() pa = Proxy(a) - self.assert_(isinstance(a, C)) # Baseline - self.assert_(isinstance(pa, C)) # Test + self.assertTrue(isinstance(a, C)) # Baseline + self.assertTrue(isinstance(pa, C)) # Test # Test with a new-style class class C(object): pass a = C() pa = Proxy(a) - self.assert_(isinstance(a, C)) # Baseline - self.assert_(isinstance(pa, C)) # Test + self.assertTrue(isinstance(a, C)) # Baseline + self.assertTrue(isinstance(pa, C)) # Test # Test with a new-style subclass class D(C): pass a = D() pa = Proxy(a) - self.assert_(isinstance(a, C)) # Baseline - self.assert_(isinstance(pa, C)) # Test + self.assertTrue(isinstance(a, C)) # Baseline + self.assertTrue(isinstance(pa, C)) # Test def test_proxy_super(self): # Testing super() for a proxy object... @@ -4373,17 +4373,17 @@ order (MRO) for bases """ l = [] self.assertEqual(l.__add__, l.__add__) self.assertEqual(l.__add__, [].__add__) - self.assert_(l.__add__ != [5].__add__) - self.assert_(l.__add__ != l.__mul__) - self.assert_(l.__add__.__name__ == '__add__') + self.assertTrue(l.__add__ != [5].__add__) + self.assertTrue(l.__add__ != l.__mul__) + self.assertTrue(l.__add__.__name__ == '__add__') if hasattr(l.__add__, '__self__'): # CPython - self.assert_(l.__add__.__self__ is l) - self.assert_(l.__add__.__objclass__ is list) + self.assertTrue(l.__add__.__self__ is l) + self.assertTrue(l.__add__.__objclass__ is list) else: # Python implementations where [].__add__ is a normal bound method - self.assert_(l.__add__.im_self is l) - self.assert_(l.__add__.im_class is list) + self.assertTrue(l.__add__.im_self is l) + self.assertTrue(l.__add__.im_class is list) self.assertEqual(l.__add__.__doc__, list.__add__.__doc__) try: hash(l.__add__) diff --git a/Lib/test/test_dict.py b/Lib/test/test_dict.py index b73a53f..075f9dc 100644 --- a/Lib/test/test_dict.py +++ b/Lib/test/test_dict.py @@ -9,7 +9,7 @@ class DictTest(unittest.TestCase): def test_constructor(self): # calling built-in types without argument must return empty self.assertEqual(dict(), {}) - self.assert_(dict() is not {}) + self.assertTrue(dict() is not {}) def test_literal_constructor(self): # check literal constructor for different sized dicts (to exercise the BUILD_MAP oparg @@ -23,18 +23,18 @@ class DictTest(unittest.TestCase): self.assertEqual(eval(dictliteral), dict(items)) def test_bool(self): - self.assert_(not {}) - self.assert_({1: 2}) - self.assert_(bool({}) is False) - self.assert_(bool({1: 2}) is True) + self.assertTrue(not {}) + self.assertTrue({1: 2}) + self.assertTrue(bool({}) is False) + self.assertTrue(bool({1: 2}) is True) def test_keys(self): d = {} self.assertEqual(d.keys(), []) d = {'a': 1, 'b': 2} k = d.keys() - self.assert_(d.has_key('a')) - self.assert_(d.has_key('b')) + self.assertTrue(d.has_key('a')) + self.assertTrue(d.has_key('b')) self.assertRaises(TypeError, d.keys, None) @@ -57,7 +57,7 @@ class DictTest(unittest.TestCase): def test_has_key(self): d = {} - self.assert_(not d.has_key('a')) + self.assertTrue(not d.has_key('a')) d = {'a': 1, 'b': 2} k = d.keys() k.sort() @@ -67,12 +67,12 @@ class DictTest(unittest.TestCase): def test_contains(self): d = {} - self.assert_(not ('a' in d)) - self.assert_('a' not in d) + self.assertTrue(not ('a' in d)) + self.assertTrue('a' not in d) d = {'a': 1, 'b': 2} - self.assert_('a' in d) - self.assert_('b' in d) - self.assert_('c' not in d) + self.assertTrue('a' in d) + self.assertTrue('b' in d) + self.assertTrue('c' not in d) self.assertRaises(TypeError, d.__contains__) @@ -206,7 +206,7 @@ class DictTest(unittest.TestCase): def test_fromkeys(self): self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) d = {} - self.assert_(not(d.fromkeys('abc') is d)) + self.assertTrue(not(d.fromkeys('abc') is d)) self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0}) self.assertEqual(d.fromkeys([]), {}) @@ -217,14 +217,14 @@ class DictTest(unittest.TestCase): class dictlike(dict): pass self.assertEqual(dictlike.fromkeys('a'), {'a':None}) self.assertEqual(dictlike().fromkeys('a'), {'a':None}) - self.assert_(type(dictlike.fromkeys('a')) is dictlike) - self.assert_(type(dictlike().fromkeys('a')) is dictlike) + self.assertTrue(type(dictlike.fromkeys('a')) is dictlike) + self.assertTrue(type(dictlike().fromkeys('a')) is dictlike) class mydict(dict): def __new__(cls): return UserDict.UserDict() ud = mydict.fromkeys('ab') self.assertEqual(ud, {'a':None, 'b':None}) - self.assert_(isinstance(ud, UserDict.UserDict)) + self.assertTrue(isinstance(ud, UserDict.UserDict)) self.assertRaises(TypeError, dict.fromkeys) class Exc(Exception): pass @@ -261,10 +261,10 @@ class DictTest(unittest.TestCase): def test_get(self): d = {} - self.assert_(d.get('c') is None) + self.assertTrue(d.get('c') is None) self.assertEqual(d.get('c', 3), 3) d = {'a' : 1, 'b' : 2} - self.assert_(d.get('c') is None) + self.assertTrue(d.get('c') is None) self.assertEqual(d.get('c', 3), 3) self.assertEqual(d.get('a'), 1) self.assertEqual(d.get('a', 3), 1) @@ -274,9 +274,9 @@ class DictTest(unittest.TestCase): def test_setdefault(self): # dict.setdefault() d = {} - self.assert_(d.setdefault('key0') is None) + self.assertTrue(d.setdefault('key0') is None) d.setdefault('key0', []) - self.assert_(d.setdefault('key0') is None) + self.assertTrue(d.setdefault('key0') is None) d.setdefault('key', []).append(3) self.assertEqual(d['key'][0], 3) d.setdefault('key', []).append(4) @@ -318,9 +318,9 @@ class DictTest(unittest.TestCase): self.assertEqual(va, int(ka)) kb, vb = tb = b.popitem() self.assertEqual(vb, int(kb)) - self.assert_(not(copymode < 0 and ta != tb)) - self.assert_(not a) - self.assert_(not b) + self.assertTrue(not(copymode < 0 and ta != tb)) + self.assertTrue(not a) + self.assertTrue(not b) d = {} self.assertRaises(KeyError, d.popitem) @@ -395,8 +395,8 @@ class DictTest(unittest.TestCase): self.assertRaises(Exc, repr, d) def test_le(self): - self.assert_(not ({} < {})) - self.assert_(not ({1: 2} < {1L: 2L})) + self.assertTrue(not ({} < {})) + self.assertTrue(not ({1: 2} < {1L: 2L})) class Exc(Exception): pass @@ -430,8 +430,8 @@ class DictTest(unittest.TestCase): d = D({1: 2, 3: 4}) self.assertEqual(d[1], 2) self.assertEqual(d[3], 4) - self.assert_(2 not in d) - self.assert_(2 not in d.keys()) + self.assertTrue(2 not in d) + self.assertTrue(2 not in d.keys()) self.assertEqual(d[2], 42) class E(dict): def __missing__(self, key): @@ -567,7 +567,7 @@ class DictTest(unittest.TestCase): obj.x = i(container) del obj, container gc.collect() - self.assert_(ref() is None, "Cycle was not collected") + self.assertTrue(ref() is None, "Cycle was not collected") def _not_tracked(self, t): # Nested containers can take several collections to untrack diff --git a/Lib/test/test_dircache.py b/Lib/test/test_dircache.py index 276c52a..56799da 100644 --- a/Lib/test/test_dircache.py +++ b/Lib/test/test_dircache.py @@ -38,7 +38,7 @@ class DircacheTests(unittest.TestCase): self.assertEquals(entries, []) # Check that cache is actually caching, not just passing through. - self.assert_(dircache.listdir(self.tempdir) is entries) + self.assertTrue(dircache.listdir(self.tempdir) is entries) # Directories aren't "files" on Windows, and directory mtime has # nothing to do with when files under a directory get created. @@ -53,7 +53,7 @@ class DircacheTests(unittest.TestCase): self.writeTemp("test1") entries = dircache.listdir(self.tempdir) self.assertEquals(entries, ['test1']) - self.assert_(dircache.listdir(self.tempdir) is entries) + self.assertTrue(dircache.listdir(self.tempdir) is entries) ## UNSUCCESSFUL CASES self.assertRaises(OSError, dircache.listdir, self.tempdir+"_nonexistent") diff --git a/Lib/test/test_docxmlrpc.py b/Lib/test/test_docxmlrpc.py index 57813c9..01ae461 100644 --- a/Lib/test/test_docxmlrpc.py +++ b/Lib/test/test_docxmlrpc.py @@ -105,7 +105,7 @@ class DocXMLRPCHTTPGETServer(unittest.TestCase): self.client.request("GET", "/") response = self.client.getresponse() - self.assert_( + self.assertTrue( """<dl><dt><a name="-<lambda>"><strong><lambda></strong></a>(x, y)</dt></dl>""" in response.read()) @@ -119,7 +119,7 @@ class DocXMLRPCHTTPGETServer(unittest.TestCase): self.client.request("GET", "/") response = self.client.getresponse() - self.assert_( # This is ugly ... how can it be made better? + self.assertTrue( # This is ugly ... how can it be made better? """<dl><dt><a name="-add"><strong>add</strong></a>(x, y)</dt><dd><tt>Add two instances together. This follows <a href="http://www.python.org/dev/peps/pep-0008/">PEP008</a>, but has nothing<br>\nto do with <a href="http://www.rfc-editor.org/rfc/rfc1952.txt">RFC1952</a>. Case should matter: pEp008 and rFC1952. Things<br>\nthat start with http and ftp should be auto-linked, too:<br>\n<a href="http://google.com">http://google.com</a>.</tt></dd></dl>""" in response.read()) @@ -132,7 +132,7 @@ class DocXMLRPCHTTPGETServer(unittest.TestCase): self.client.request("GET", "/") response = self.client.getresponse() - self.assert_( + self.assertTrue( """<dl><dt><a name="-system.listMethods"><strong>system.listMethods</strong></a>()</dt><dd><tt><a href="#-system.listMethods">system.listMethods</a>() => [\'add\', \'subtract\', \'multiple\']<br>\n <br>\nReturns a list of the methods supported by the server.</tt></dd></dl>\n <dl><dt><a name="-system.methodHelp"><strong>system.methodHelp</strong></a>(method_name)</dt><dd><tt><a href="#-system.methodHelp">system.methodHelp</a>(\'add\') => "Adds two integers together"<br>\n <br>\nReturns a string containing documentation for the specified method.</tt></dd></dl>\n <dl><dt><a name="-system.methodSignature"><strong>system.methodSignature</strong></a>(method_name)</dt><dd><tt><a href="#-system.methodSignature">system.methodSignature</a>(\'add\') => [double, int, int]<br>\n <br>\nReturns a list describing the signature of the method. In the<br>\nabove example, the add method takes two integers as arguments<br>\nand returns a double result.<br>\n <br>\nThis server does NOT support system.methodSignature.</tt></dd></dl>""" in response.read()) @@ -142,7 +142,7 @@ class DocXMLRPCHTTPGETServer(unittest.TestCase): self.client.request("GET", "/") response = self.client.getresponse() - self.assert_("""Try self.<strong>add</strong>, too.""" in + self.assertTrue("""Try self.<strong>add</strong>, too.""" in response.read()) def test_main(): diff --git a/Lib/test/test_dummy_thread.py b/Lib/test/test_dummy_thread.py index 58faeb4..74de86a 100644 --- a/Lib/test/test_dummy_thread.py +++ b/Lib/test/test_dummy_thread.py @@ -24,43 +24,43 @@ class LockTests(unittest.TestCase): def test_initlock(self): #Make sure locks start locked - self.failUnless(not self.lock.locked(), + self.assertTrue(not self.lock.locked(), "Lock object is not initialized unlocked.") def test_release(self): # Test self.lock.release() self.lock.acquire() self.lock.release() - self.failUnless(not self.lock.locked(), + self.assertTrue(not self.lock.locked(), "Lock object did not release properly.") def test_improper_release(self): #Make sure release of an unlocked thread raises _thread.error - self.failUnlessRaises(_thread.error, self.lock.release) + self.assertRaises(_thread.error, self.lock.release) def test_cond_acquire_success(self): #Make sure the conditional acquiring of the lock works. - self.failUnless(self.lock.acquire(0), + self.assertTrue(self.lock.acquire(0), "Conditional acquiring of the lock failed.") def test_cond_acquire_fail(self): #Test acquiring locked lock returns False self.lock.acquire(0) - self.failUnless(not self.lock.acquire(0), + self.assertTrue(not self.lock.acquire(0), "Conditional acquiring of a locked lock incorrectly " "succeeded.") def test_uncond_acquire_success(self): #Make sure unconditional acquiring of a lock works. self.lock.acquire() - self.failUnless(self.lock.locked(), + self.assertTrue(self.lock.locked(), "Uncondional locking failed.") def test_uncond_acquire_return_val(self): #Make sure that an unconditional locking returns True. - self.failUnless(self.lock.acquire(1) is True, + self.assertTrue(self.lock.acquire(1) is True, "Unconditional locking did not return True.") - self.failUnless(self.lock.acquire() is True) + self.assertTrue(self.lock.acquire() is True) def test_uncond_acquire_blocking(self): #Make sure that unconditional acquiring of a locked lock blocks. @@ -80,7 +80,7 @@ class LockTests(unittest.TestCase): end_time = int(time.time()) if test_support.verbose: print "done" - self.failUnless((end_time - start_time) >= DELAY, + self.assertTrue((end_time - start_time) >= DELAY, "Blocking by unconditional acquiring failed.") class MiscTests(unittest.TestCase): @@ -88,18 +88,18 @@ class MiscTests(unittest.TestCase): def test_exit(self): #Make sure _thread.exit() raises SystemExit - self.failUnlessRaises(SystemExit, _thread.exit) + self.assertRaises(SystemExit, _thread.exit) def test_ident(self): #Test sanity of _thread.get_ident() - self.failUnless(isinstance(_thread.get_ident(), int), + self.assertTrue(isinstance(_thread.get_ident(), int), "_thread.get_ident() returned a non-integer") - self.failUnless(_thread.get_ident() != 0, + self.assertTrue(_thread.get_ident() != 0, "_thread.get_ident() returned 0") def test_LockType(self): #Make sure _thread.LockType is the same type as _thread.allocate_locke() - self.failUnless(isinstance(_thread.allocate_lock(), _thread.LockType), + self.assertTrue(isinstance(_thread.allocate_lock(), _thread.LockType), "_thread.LockType is not an instance of what is " "returned by _thread.allocate_lock()") @@ -108,13 +108,13 @@ class MiscTests(unittest.TestCase): # should raise KeyboardInterrupt upon completion. def call_interrupt(): _thread.interrupt_main() - self.failUnlessRaises(KeyboardInterrupt, _thread.start_new_thread, + self.assertRaises(KeyboardInterrupt, _thread.start_new_thread, call_interrupt, tuple()) def test_interrupt_in_main(self): # Make sure that if interrupt_main is called in main threat that # KeyboardInterrupt is raised instantly. - self.failUnlessRaises(KeyboardInterrupt, _thread.interrupt_main) + self.assertRaises(KeyboardInterrupt, _thread.interrupt_main) class ThreadTests(unittest.TestCase): """Test thread creation.""" @@ -128,16 +128,16 @@ class ThreadTests(unittest.TestCase): testing_queue = Queue.Queue(1) _thread.start_new_thread(arg_tester, (testing_queue, True, True)) result = testing_queue.get() - self.failUnless(result[0] and result[1], + self.assertTrue(result[0] and result[1], "Argument passing for thread creation using tuple failed") _thread.start_new_thread(arg_tester, tuple(), {'queue':testing_queue, 'arg1':True, 'arg2':True}) result = testing_queue.get() - self.failUnless(result[0] and result[1], + self.assertTrue(result[0] and result[1], "Argument passing for thread creation using kwargs failed") _thread.start_new_thread(arg_tester, (testing_queue, True), {'arg2':True}) result = testing_queue.get() - self.failUnless(result[0] and result[1], + self.assertTrue(result[0] and result[1], "Argument passing for thread creation using both tuple" " and kwargs failed") @@ -164,7 +164,7 @@ class ThreadTests(unittest.TestCase): time.sleep(DELAY) if test_support.verbose: print 'done' - self.failUnless(testing_queue.qsize() == thread_count, + self.assertTrue(testing_queue.qsize() == thread_count, "Not all %s threads executed properly after %s sec." % (thread_count, DELAY)) diff --git a/Lib/test/test_epoll.py b/Lib/test/test_epoll.py index 15c9869..b113547 100644 --- a/Lib/test/test_epoll.py +++ b/Lib/test/test_epoll.py @@ -71,10 +71,10 @@ class TestEPoll(unittest.TestCase): ep = select.epoll(16) except OSError, e: raise AssertionError(str(e)) - self.assert_(ep.fileno() > 0, ep.fileno()) - self.assert_(not ep.closed) + self.assertTrue(ep.fileno() > 0, ep.fileno()) + self.assertTrue(not ep.closed) ep.close() - self.assert_(ep.closed) + self.assertTrue(ep.closed) self.assertRaises(ValueError, ep.fileno) def test_badcreate(self): @@ -141,7 +141,7 @@ class TestEPoll(unittest.TestCase): try: ep2.poll(1, 4) except IOError, e: - self.failUnlessEqual(e.args[0], errno.EBADF, e) + self.assertEqual(e.args[0], errno.EBADF, e) else: self.fail("epoll on closed fd didn't raise EBADF") @@ -157,7 +157,7 @@ class TestEPoll(unittest.TestCase): now = time.time() events = ep.poll(1, 4) then = time.time() - self.failIf(then - now > 0.1, then - now) + self.assertFalse(then - now > 0.1, then - now) events.sort() expected = [(client.fileno(), select.EPOLLOUT), @@ -165,12 +165,12 @@ class TestEPoll(unittest.TestCase): expected.sort() self.assertEquals(events, expected) - self.failIf(then - now > 0.01, then - now) + self.assertFalse(then - now > 0.01, then - now) now = time.time() events = ep.poll(timeout=2.1, maxevents=4) then = time.time() - self.failIf(events) + self.assertFalse(events) client.send("Hello!") server.send("world!!!") @@ -178,7 +178,7 @@ class TestEPoll(unittest.TestCase): now = time.time() events = ep.poll(1, 4) then = time.time() - self.failIf(then - now > 0.01) + self.assertFalse(then - now > 0.01) events.sort() expected = [(client.fileno(), select.EPOLLIN | select.EPOLLOUT), @@ -192,7 +192,7 @@ class TestEPoll(unittest.TestCase): now = time.time() events = ep.poll(1, 4) then = time.time() - self.failIf(then - now > 0.01) + self.assertFalse(then - now > 0.01) expected = [(server.fileno(), select.EPOLLOUT)] self.assertEquals(events, expected) @@ -211,7 +211,7 @@ class TestEPoll(unittest.TestCase): now = time.time() events = ep.poll(1, 4) then = time.time() - self.failIf(then - now > 0.01) + self.assertFalse(then - now > 0.01) server.close() ep.unregister(fd) diff --git a/Lib/test/test_errno.py b/Lib/test/test_errno.py index 9523907..4adc1f0 100755 --- a/Lib/test/test_errno.py +++ b/Lib/test/test_errno.py @@ -14,13 +14,13 @@ class ErrnoAttributeTests(unittest.TestCase): def test_for_improper_attributes(self): # No unexpected attributes should be on the module. for error_code in std_c_errors: - self.assert_(hasattr(errno, error_code), + self.assertTrue(hasattr(errno, error_code), "errno is missing %s" % error_code) def test_using_errorcode(self): # Every key value in errno.errorcode should be on the module. for value in errno.errorcode.itervalues(): - self.assert_(hasattr(errno, value), 'no %s attr in errno' % value) + self.assertTrue(hasattr(errno, value), 'no %s attr in errno' % value) class ErrorcodeTests(unittest.TestCase): @@ -28,7 +28,7 @@ class ErrorcodeTests(unittest.TestCase): def test_attributes_in_errorcode(self): for attribute in errno.__dict__.iterkeys(): if attribute.isupper(): - self.assert_(getattr(errno, attribute) in errno.errorcode, + self.assertTrue(getattr(errno, attribute) in errno.errorcode, 'no %s attr in errno.errorcode' % attribute) diff --git a/Lib/test/test_exceptions.py b/Lib/test/test_exceptions.py index 06a2378..6cfbd09 100644 --- a/Lib/test/test_exceptions.py +++ b/Lib/test/test_exceptions.py @@ -162,7 +162,7 @@ class ExceptionTests(unittest.TestCase): exc, err, tb = sys.exc_info() co = tb.tb_frame.f_code self.assertEquals(co.co_name, "test_capi1") - self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py')) + self.assertTrue(co.co_filename.endswith('test_exceptions'+os.extsep+'py')) else: self.fail("Expected exception") @@ -174,7 +174,7 @@ class ExceptionTests(unittest.TestCase): exc, err, tb = sys.exc_info() co = tb.tb_frame.f_code self.assertEquals(co.co_name, "__init__") - self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py')) + self.assertTrue(co.co_filename.endswith('test_exceptions'+os.extsep+'py')) co2 = tb.tb_frame.f_back.f_code self.assertEquals(co2.co_name, "test_capi2") else: @@ -190,12 +190,12 @@ class ExceptionTests(unittest.TestCase): except NameError: pass else: - self.failUnlessEqual(str(WindowsError(1001)), + self.assertEqual(str(WindowsError(1001)), "1001") - self.failUnlessEqual(str(WindowsError(1001, "message")), + self.assertEqual(str(WindowsError(1001, "message")), "[Error 1001] message") - self.failUnlessEqual(WindowsError(1001, "message").errno, 22) - self.failUnlessEqual(WindowsError(1001, "message").winerror, 1001) + self.assertEqual(WindowsError(1001, "message").errno, 22) + self.assertEqual(WindowsError(1001, "message").winerror, 1001) def testAttributes(self): # test that exception attributes are happy @@ -308,7 +308,7 @@ class ExceptionTests(unittest.TestCase): # going through the 'args' attribute. args = (1, 2, 3) exc = BaseException(*args) - self.failUnlessEqual(exc[:], args) + self.assertEqual(exc[:], args) def testKeywordArgs(self): # test that builtin exception don't take keyword args, @@ -350,11 +350,11 @@ class ExceptionTests(unittest.TestCase): def testUnicodeStrUsage(self): # Make sure both instances and classes have a str and unicode # representation. - self.failUnless(str(Exception)) - self.failUnless(unicode(Exception)) - self.failUnless(str(Exception('a'))) - self.failUnless(unicode(Exception(u'a'))) - self.failUnless(unicode(Exception(u'\xe1'))) + self.assertTrue(str(Exception)) + self.assertTrue(unicode(Exception)) + self.assertTrue(str(Exception('a'))) + self.assertTrue(unicode(Exception(u'a'))) + self.assertTrue(unicode(Exception(u'\xe1'))) def test_badisinstance(self): # Bug #2542: if issubclass(e, MyException) raises an exception, @@ -386,8 +386,8 @@ class ExceptionTests(unittest.TestCase): except RuntimeError: return sys.exc_info() e, v, tb = g() - self.assert_(e is RuntimeError, e) - self.assert_("maximum recursion depth exceeded" in str(v), v) + self.assertTrue(e is RuntimeError, e) + self.assertTrue("maximum recursion depth exceeded" in str(v), v) def test_main(): diff --git a/Lib/test/test_file.py b/Lib/test/test_file.py index 1974f56..7d3e72d 100644 --- a/Lib/test/test_file.py +++ b/Lib/test/test_file.py @@ -88,13 +88,13 @@ class AutoFileTests(unittest.TestCase): def testErrors(self): f = self.f self.assertEquals(f.name, TESTFN) - self.assert_(not f.isatty()) - self.assert_(not f.closed) + self.assertTrue(not f.isatty()) + self.assertTrue(not f.closed) if hasattr(f, "readinto"): self.assertRaises((IOError, TypeError), f.readinto, "") f.close() - self.assert_(f.closed) + self.assertTrue(f.closed) def testMethods(self): methods = [('fileno', ()), @@ -116,7 +116,7 @@ class AutoFileTests(unittest.TestCase): # __exit__ should close the file self.f.__exit__(None, None, None) - self.assert_(self.f.closed) + self.assertTrue(self.f.closed) for methodname, args in methods: method = getattr(self.f, methodname) diff --git a/Lib/test/test_file2k.py b/Lib/test/test_file2k.py index a134a89..6520292 100644 --- a/Lib/test/test_file2k.py +++ b/Lib/test/test_file2k.py @@ -83,17 +83,17 @@ class AutoFileTests(unittest.TestCase): def testRepr(self): # verify repr works - self.assert_(repr(self.f).startswith("<open file '" + TESTFN)) + self.assertTrue(repr(self.f).startswith("<open file '" + TESTFN)) def testErrors(self): f = self.f self.assertEquals(f.name, TESTFN) - self.assert_(not f.isatty()) - self.assert_(not f.closed) + self.assertTrue(not f.isatty()) + self.assertTrue(not f.closed) self.assertRaises(TypeError, f.readinto, "") f.close() - self.assert_(f.closed) + self.assertTrue(f.closed) def testMethods(self): methods = ['fileno', 'flush', 'isatty', 'next', 'read', 'readinto', @@ -104,7 +104,7 @@ class AutoFileTests(unittest.TestCase): # __exit__ should close the file self.f.__exit__(None, None, None) - self.assert_(self.f.closed) + self.assertTrue(self.f.closed) for methodname in methods: method = getattr(self.f, methodname) @@ -172,7 +172,7 @@ class OtherFileTests(unittest.TestCase): def testUnicodeOpen(self): # verify repr works for unicode too f = open(unicode(TESTFN), "w") - self.assert_(repr(f).startswith("<open file u'" + TESTFN)) + self.assertTrue(repr(f).startswith("<open file u'" + TESTFN)) f.close() os.unlink(TESTFN) @@ -365,7 +365,7 @@ class FileSubclassTests(unittest.TestCase): with C(TESTFN, 'w') as f: pass - self.failUnless(f.subclass_closed) + self.assertTrue(f.subclass_closed) class FileThreadingTests(unittest.TestCase): diff --git a/Lib/test/test_filecmp.py b/Lib/test/test_filecmp.py index 503562b..f76ba0b 100644 --- a/Lib/test/test_filecmp.py +++ b/Lib/test/test_filecmp.py @@ -25,19 +25,19 @@ class FileCompareTestCase(unittest.TestCase): os.unlink(self.name_diff) def test_matching(self): - self.failUnless(filecmp.cmp(self.name, self.name_same), + self.assertTrue(filecmp.cmp(self.name, self.name_same), "Comparing file to itself fails") - self.failUnless(filecmp.cmp(self.name, self.name_same, shallow=False), + self.assertTrue(filecmp.cmp(self.name, self.name_same, shallow=False), "Comparing file to itself fails") - self.failUnless(filecmp.cmp(self.name, self.name, shallow=False), + self.assertTrue(filecmp.cmp(self.name, self.name, shallow=False), "Comparing file to identical file fails") - self.failUnless(filecmp.cmp(self.name, self.name), + self.assertTrue(filecmp.cmp(self.name, self.name), "Comparing file to identical file fails") def test_different(self): - self.failIf(filecmp.cmp(self.name, self.name_diff), + self.assertFalse(filecmp.cmp(self.name, self.name_diff), "Mismatched files compare as equal") - self.failIf(filecmp.cmp(self.name, self.dir), + self.assertFalse(filecmp.cmp(self.name, self.dir), "File and directory compare as equal") class DirCompareTestCase(unittest.TestCase): @@ -69,19 +69,19 @@ class DirCompareTestCase(unittest.TestCase): shutil.rmtree(self.dir_diff) def test_cmpfiles(self): - self.failUnless(filecmp.cmpfiles(self.dir, self.dir, ['file']) == + self.assertTrue(filecmp.cmpfiles(self.dir, self.dir, ['file']) == (['file'], [], []), "Comparing directory to itself fails") - self.failUnless(filecmp.cmpfiles(self.dir, self.dir_same, ['file']) == + self.assertTrue(filecmp.cmpfiles(self.dir, self.dir_same, ['file']) == (['file'], [], []), "Comparing directory to same fails") # Try it with shallow=False - self.failUnless(filecmp.cmpfiles(self.dir, self.dir, ['file'], + self.assertTrue(filecmp.cmpfiles(self.dir, self.dir, ['file'], shallow=False) == (['file'], [], []), "Comparing directory to itself fails") - self.failUnless(filecmp.cmpfiles(self.dir, self.dir_same, ['file'], + self.assertTrue(filecmp.cmpfiles(self.dir, self.dir_same, ['file'], shallow=False), "Comparing directory to same fails") @@ -90,7 +90,7 @@ class DirCompareTestCase(unittest.TestCase): output.write('Different contents.\n') output.close() - self.failIf(filecmp.cmpfiles(self.dir, self.dir_same, + self.assertFalse(filecmp.cmpfiles(self.dir, self.dir_same, ['file', 'file2']) == (['file'], ['file2'], []), "Comparing mismatched directories fails") @@ -103,28 +103,28 @@ class DirCompareTestCase(unittest.TestCase): self.assertEqual([d.left_list, d.right_list],[['file'], ['FiLe']]) else: self.assertEqual([d.left_list, d.right_list],[['file'], ['file']]) - self.failUnless(d.common == ['file']) - self.failUnless(d.left_only == d.right_only == []) - self.failUnless(d.same_files == ['file']) - self.failUnless(d.diff_files == []) + self.assertTrue(d.common == ['file']) + self.assertTrue(d.left_only == d.right_only == []) + self.assertTrue(d.same_files == ['file']) + self.assertTrue(d.diff_files == []) # Check attributes for comparison of two different directories d = filecmp.dircmp(self.dir, self.dir_diff) - self.failUnless(d.left_list == ['file']) - self.failUnless(d.right_list == ['file', 'file2']) - self.failUnless(d.common == ['file']) - self.failUnless(d.left_only == []) - self.failUnless(d.right_only == ['file2']) - self.failUnless(d.same_files == ['file']) - self.failUnless(d.diff_files == []) + self.assertTrue(d.left_list == ['file']) + self.assertTrue(d.right_list == ['file', 'file2']) + self.assertTrue(d.common == ['file']) + self.assertTrue(d.left_only == []) + self.assertTrue(d.right_only == ['file2']) + self.assertTrue(d.same_files == ['file']) + self.assertTrue(d.diff_files == []) # Add different file2 output = open(os.path.join(self.dir, 'file2'), 'w') output.write('Different contents.\n') output.close() d = filecmp.dircmp(self.dir, self.dir_diff) - self.failUnless(d.same_files == ['file']) - self.failUnless(d.diff_files == ['file2']) + self.assertTrue(d.same_files == ['file']) + self.assertTrue(d.diff_files == ['file2']) def test_main(): diff --git a/Lib/test/test_fileinput.py b/Lib/test/test_fileinput.py index 9fb3ea7..84aed1a 100644 --- a/Lib/test/test_fileinput.py +++ b/Lib/test/test_fileinput.py @@ -65,8 +65,8 @@ class BufferSizesTests(unittest.TestCase): self.assertEqual(fi.filename(), t2) self.assertEqual(fi.lineno(), 21) self.assertEqual(fi.filelineno(), 6) - self.failIf(fi.isfirstline()) - self.failIf(fi.isstdin()) + self.assertFalse(fi.isfirstline()) + self.assertFalse(fi.isstdin()) if verbose: print '%s. Nextfile (bs=%s)' % (start+2, bs) @@ -134,7 +134,7 @@ class FileInputTests(unittest.TestCase): self.assertEqual(fi.filename(), t3) line = fi.readline() - self.failIf(line) + self.assertFalse(line) self.assertEqual(fi.lineno(), 1) self.assertEqual(fi.filelineno(), 0) self.assertEqual(fi.filename(), t4) diff --git a/Lib/test/test_fileio.py b/Lib/test/test_fileio.py index e8d6362..87bf015 100644 --- a/Lib/test/test_fileio.py +++ b/Lib/test/test_fileio.py @@ -82,17 +82,17 @@ class AutoFileTests(unittest.TestCase): def testErrors(self): f = self.f - self.assert_(not f.isatty()) - self.assert_(not f.closed) + self.assertTrue(not f.isatty()) + self.assertTrue(not f.closed) #self.assertEquals(f.name, TESTFN) self.assertRaises(ValueError, f.read, 10) # Open for reading f.close() - self.assert_(f.closed) + self.assertTrue(f.closed) f = _FileIO(TESTFN, 'r') self.assertRaises(TypeError, f.readinto, "") - self.assert_(not f.closed) + self.assertTrue(not f.closed) f.close() - self.assert_(f.closed) + self.assertTrue(f.closed) def testMethods(self): methods = ['fileno', 'isatty', 'read', 'readinto', @@ -102,7 +102,7 @@ class AutoFileTests(unittest.TestCase): methods.remove('truncate') self.f.close() - self.assert_(self.f.closed) + self.assertTrue(self.f.closed) for methodname in methods: method = getattr(self.f, methodname) diff --git a/Lib/test/test_float.py b/Lib/test/test_float.py index 345a815..844a649 100644 --- a/Lib/test/test_float.py +++ b/Lib/test/test_float.py @@ -148,9 +148,9 @@ class FormatFunctionsTestCase(unittest.TestCase): float.__setformat__('float', self.save_formats['float']) def test_getformat(self): - self.assert_(float.__getformat__('double') in + self.assertTrue(float.__getformat__('double') in ['unknown', 'IEEE, big-endian', 'IEEE, little-endian']) - self.assert_(float.__getformat__('float') in + self.assertTrue(float.__getformat__('float') in ['unknown', 'IEEE, big-endian', 'IEEE, little-endian']) self.assertRaises(ValueError, float.__getformat__, 'chicken') self.assertRaises(TypeError, float.__getformat__, 1) @@ -340,12 +340,12 @@ class ReprTestCase(unittest.TestCase): # ways to create and represent inf and nan class InfNanTest(unittest.TestCase): def test_inf_from_str(self): - self.assert_(isinf(float("inf"))) - self.assert_(isinf(float("+inf"))) - self.assert_(isinf(float("-inf"))) - self.assert_(isinf(float("infinity"))) - self.assert_(isinf(float("+infinity"))) - self.assert_(isinf(float("-infinity"))) + self.assertTrue(isinf(float("inf"))) + self.assertTrue(isinf(float("+inf"))) + self.assertTrue(isinf(float("-inf"))) + self.assertTrue(isinf(float("infinity"))) + self.assertTrue(isinf(float("+infinity"))) + self.assertTrue(isinf(float("-infinity"))) self.assertEqual(repr(float("inf")), "inf") self.assertEqual(repr(float("+inf")), "inf") @@ -387,9 +387,9 @@ class InfNanTest(unittest.TestCase): self.assertEqual(str(-1e300 * 1e300), "-inf") def test_nan_from_str(self): - self.assert_(isnan(float("nan"))) - self.assert_(isnan(float("+nan"))) - self.assert_(isnan(float("-nan"))) + self.assertTrue(isnan(float("nan"))) + self.assertTrue(isnan(float("+nan"))) + self.assertTrue(isnan(float("-nan"))) self.assertEqual(repr(float("nan")), "nan") self.assertEqual(repr(float("+nan")), "nan") @@ -418,14 +418,14 @@ class InfNanTest(unittest.TestCase): self.assertEqual(str(-1e300 * 1e300 * 0), "nan") def notest_float_nan(self): - self.assert_(NAN.is_nan()) - self.failIf(INF.is_nan()) - self.failIf((0.).is_nan()) + self.assertTrue(NAN.is_nan()) + self.assertFalse(INF.is_nan()) + self.assertFalse((0.).is_nan()) def notest_float_inf(self): - self.assert_(INF.is_inf()) - self.failIf(NAN.is_inf()) - self.failIf((0.).is_inf()) + self.assertTrue(INF.is_inf()) + self.assertFalse(NAN.is_inf()) + self.assertFalse((0.).is_inf()) fromHex = float.fromhex toHex = float.hex diff --git a/Lib/test/test_fnmatch.py b/Lib/test/test_fnmatch.py index 9abcbd6..e6173ed 100644 --- a/Lib/test/test_fnmatch.py +++ b/Lib/test/test_fnmatch.py @@ -9,11 +9,11 @@ from fnmatch import fnmatch, fnmatchcase class FnmatchTestCase(unittest.TestCase): def check_match(self, filename, pattern, should_match=1): if should_match: - self.assert_(fnmatch(filename, pattern), + self.assertTrue(fnmatch(filename, pattern), "expected %r to match pattern %r" % (filename, pattern)) else: - self.assert_(not fnmatch(filename, pattern), + self.assertTrue(not fnmatch(filename, pattern), "expected %r not to match pattern %r" % (filename, pattern)) diff --git a/Lib/test/test_ftplib.py b/Lib/test/test_ftplib.py index c48497d..8b0bb07 100644 --- a/Lib/test/test_ftplib.py +++ b/Lib/test/test_ftplib.py @@ -438,7 +438,7 @@ class TestTimeouts(TestCase): def testTimeoutDefault(self): # default -- use global socket timeout - self.assert_(socket.getdefaulttimeout() is None) + self.assertTrue(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(30) try: ftp = ftplib.FTP("localhost") @@ -450,7 +450,7 @@ class TestTimeouts(TestCase): def testTimeoutNone(self): # no timeout -- do not use global socket timeout - self.assert_(socket.getdefaulttimeout() is None) + self.assertTrue(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(30) try: ftp = ftplib.FTP("localhost", timeout=None) diff --git a/Lib/test/test_funcattrs.py b/Lib/test/test_funcattrs.py index 2961cd2..6350aad 100644 --- a/Lib/test/test_funcattrs.py +++ b/Lib/test/test_funcattrs.py @@ -31,14 +31,14 @@ class FunctionPropertiesTest(FuncAttrsTest): def test_dir_includes_correct_attrs(self): self.b.known_attr = 7 - self.assert_('known_attr' in dir(self.b), + self.assertTrue('known_attr' in dir(self.b), "set attributes not in dir listing of method") # Test on underlying function object of method self.f.a.im_func.known_attr = 7 - self.assert_('known_attr' in dir(self.f.a), + self.assertTrue('known_attr' in dir(self.f.a), "set attribute on unbound method implementation in class not in " "dir") - self.assert_('known_attr' in dir(self.fi.a), + self.assertTrue('known_attr' in dir(self.fi.a), "set attribute on unbound method implementations, should show up" " in next dir") @@ -279,10 +279,10 @@ class StaticMethodAttrsTest(unittest.TestCase): pass c = classmethod(f) - self.assert_(c.__func__ is f) + self.assertTrue(c.__func__ is f) s = staticmethod(f) - self.assert_(s.__func__ is f) + self.assertTrue(s.__func__ is f) def test_main(): diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py index cd645d3..ab5bac2 100644 --- a/Lib/test/test_functools.py +++ b/Lib/test/test_functools.py @@ -96,7 +96,7 @@ class TestPartial(unittest.TestCase): p = self.thetype(capture, *args) expected = args + ('x',) got, empty = p('x') - self.failUnless(expected == got and empty == {}) + self.assertTrue(expected == got and empty == {}) def test_keyword(self): # make sure keyword arguments are captured correctly @@ -104,15 +104,15 @@ class TestPartial(unittest.TestCase): p = self.thetype(capture, a=a) expected = {'a':a,'x':None} empty, got = p(x=None) - self.failUnless(expected == got and empty == ()) + self.assertTrue(expected == got and empty == ()) def test_no_side_effects(self): # make sure there are no side effects that affect subsequent calls p = self.thetype(capture, 0, a=1) args1, kw1 = p(1, b=2) - self.failUnless(args1 == (0,1) and kw1 == {'a':1,'b':2}) + self.assertTrue(args1 == (0,1) and kw1 == {'a':1,'b':2}) args2, kw2 = p() - self.failUnless(args2 == (0,) and kw2 == {'a':1}) + self.assertTrue(args2 == (0,) and kw2 == {'a':1}) def test_error_propagation(self): def f(x, y): @@ -172,13 +172,13 @@ class TestUpdateWrapper(unittest.TestCase): updated=functools.WRAPPER_UPDATES): # Check attributes were assigned for name in assigned: - self.failUnless(getattr(wrapper, name) is getattr(wrapped, name)) + self.assertTrue(getattr(wrapper, name) is getattr(wrapped, name)) # Check attributes were updated for name in updated: wrapper_attr = getattr(wrapper, name) wrapped_attr = getattr(wrapped, name) for key in wrapped_attr: - self.failUnless(wrapped_attr[key] is wrapper_attr[key]) + self.assertTrue(wrapped_attr[key] is wrapper_attr[key]) def test_default_update(self): def f(): @@ -204,7 +204,7 @@ class TestUpdateWrapper(unittest.TestCase): self.check_wrapper(wrapper, f, (), ()) self.assertEqual(wrapper.__name__, 'wrapper') self.assertEqual(wrapper.__doc__, None) - self.failIf(hasattr(wrapper, 'attr')) + self.assertFalse(hasattr(wrapper, 'attr')) def test_selective_update(self): def f(): @@ -229,7 +229,7 @@ class TestUpdateWrapper(unittest.TestCase): pass functools.update_wrapper(wrapper, max) self.assertEqual(wrapper.__name__, 'max') - self.assert_(wrapper.__doc__.startswith('max(')) + self.assertTrue(wrapper.__doc__.startswith('max(')) class TestWraps(TestUpdateWrapper): @@ -257,7 +257,7 @@ class TestWraps(TestUpdateWrapper): self.check_wrapper(wrapper, f, (), ()) self.assertEqual(wrapper.__name__, 'wrapper') self.assertEqual(wrapper.__doc__, None) - self.failIf(hasattr(wrapper, 'attr')) + self.assertFalse(hasattr(wrapper, 'attr')) def test_selective_update(self): def f(): diff --git a/Lib/test/test_future4.py b/Lib/test/test_future4.py index 2580c55..53f8add 100644 --- a/Lib/test/test_future4.py +++ b/Lib/test/test_future4.py @@ -5,7 +5,7 @@ from test import test_support class TestFuture(unittest.TestCase): def assertType(self, obj, typ): - self.assert_(type(obj) is typ, + self.assertTrue(type(obj) is typ, "type(%r) is %r, not %r" % (obj, type(obj), typ)) def test_unicode_strings(self): diff --git a/Lib/test/test_gdbm.py b/Lib/test/test_gdbm.py index 131d22b..e76cc03 100755 --- a/Lib/test/test_gdbm.py +++ b/Lib/test/test_gdbm.py @@ -24,10 +24,10 @@ class TestGdbm(unittest.TestCase): self.g['12345678910'] = '019237410982340912840198242' key_set = set(self.g.keys()) self.assertEqual(key_set, frozenset(['a', '12345678910'])) - self.assert_(self.g.has_key('a')) + self.assertTrue(self.g.has_key('a')) key = self.g.firstkey() while key: - self.assert_(key in key_set) + self.assertTrue(key in key_set) key_set.remove(key) key = self.g.nextkey(key) self.assertRaises(KeyError, lambda: self.g['xxx']) @@ -65,7 +65,7 @@ class TestGdbm(unittest.TestCase): self.g['x'] = 'x' * 10000 size1 = os.path.getsize(filename) - self.assert_(size0 < size1) + self.assertTrue(size0 < size1) del self.g['x'] # 'size' is supposed to be the same even after deleting an entry. @@ -73,7 +73,7 @@ class TestGdbm(unittest.TestCase): self.g.reorganize() size2 = os.path.getsize(filename) - self.assert_(size1 > size2 >= size0) + self.assertTrue(size1 > size2 >= size0) def test_main(): diff --git a/Lib/test/test_genericpath.py b/Lib/test/test_genericpath.py index 53c4607..c8f359d 100644 --- a/Lib/test/test_genericpath.py +++ b/Lib/test/test_genericpath.py @@ -6,7 +6,7 @@ import genericpath class AllCommonTest(unittest.TestCase): def assertIs(self, a, b): - self.assert_(a is b) + self.assertTrue(a is b) def test_commonprefix(self): self.assertEqual( @@ -50,7 +50,7 @@ class AllCommonTest(unittest.TestCase): f.close() self.assertEqual(d, "foobar") - self.assert_( + self.assertTrue( genericpath.getctime(test_support.TESTFN) <= genericpath.getmtime(test_support.TESTFN) ) diff --git a/Lib/test/test_getargs2.py b/Lib/test/test_getargs2.py index 9b90a69..d7866ca 100644 --- a/Lib/test/test_getargs2.py +++ b/Lib/test/test_getargs2.py @@ -67,69 +67,69 @@ class Unsigned_TestCase(unittest.TestCase): def test_b(self): from _testcapi import getargs_b # b returns 'unsigned char', and does range checking (0 ... UCHAR_MAX) - self.failUnlessEqual(3, getargs_b(3.14)) - self.failUnlessEqual(99, getargs_b(Long())) - self.failUnlessEqual(99, getargs_b(Int())) + self.assertEqual(3, getargs_b(3.14)) + self.assertEqual(99, getargs_b(Long())) + self.assertEqual(99, getargs_b(Int())) self.assertRaises(OverflowError, getargs_b, -1) - self.failUnlessEqual(0, getargs_b(0)) - self.failUnlessEqual(UCHAR_MAX, getargs_b(UCHAR_MAX)) + self.assertEqual(0, getargs_b(0)) + self.assertEqual(UCHAR_MAX, getargs_b(UCHAR_MAX)) self.assertRaises(OverflowError, getargs_b, UCHAR_MAX + 1) - self.failUnlessEqual(42, getargs_b(42)) - self.failUnlessEqual(42, getargs_b(42L)) + self.assertEqual(42, getargs_b(42)) + self.assertEqual(42, getargs_b(42L)) self.assertRaises(OverflowError, getargs_b, VERY_LARGE) def test_B(self): from _testcapi import getargs_B # B returns 'unsigned char', no range checking - self.failUnlessEqual(3, getargs_B(3.14)) - self.failUnlessEqual(99, getargs_B(Long())) - self.failUnlessEqual(99, getargs_B(Int())) + self.assertEqual(3, getargs_B(3.14)) + self.assertEqual(99, getargs_B(Long())) + self.assertEqual(99, getargs_B(Int())) - self.failUnlessEqual(UCHAR_MAX, getargs_B(-1)) - self.failUnlessEqual(UCHAR_MAX, getargs_B(-1L)) - self.failUnlessEqual(0, getargs_B(0)) - self.failUnlessEqual(UCHAR_MAX, getargs_B(UCHAR_MAX)) - self.failUnlessEqual(0, getargs_B(UCHAR_MAX+1)) + self.assertEqual(UCHAR_MAX, getargs_B(-1)) + self.assertEqual(UCHAR_MAX, getargs_B(-1L)) + self.assertEqual(0, getargs_B(0)) + self.assertEqual(UCHAR_MAX, getargs_B(UCHAR_MAX)) + self.assertEqual(0, getargs_B(UCHAR_MAX+1)) - self.failUnlessEqual(42, getargs_B(42)) - self.failUnlessEqual(42, getargs_B(42L)) - self.failUnlessEqual(UCHAR_MAX & VERY_LARGE, getargs_B(VERY_LARGE)) + self.assertEqual(42, getargs_B(42)) + self.assertEqual(42, getargs_B(42L)) + self.assertEqual(UCHAR_MAX & VERY_LARGE, getargs_B(VERY_LARGE)) def test_H(self): from _testcapi import getargs_H # H returns 'unsigned short', no range checking - self.failUnlessEqual(3, getargs_H(3.14)) - self.failUnlessEqual(99, getargs_H(Long())) - self.failUnlessEqual(99, getargs_H(Int())) + self.assertEqual(3, getargs_H(3.14)) + self.assertEqual(99, getargs_H(Long())) + self.assertEqual(99, getargs_H(Int())) - self.failUnlessEqual(USHRT_MAX, getargs_H(-1)) - self.failUnlessEqual(0, getargs_H(0)) - self.failUnlessEqual(USHRT_MAX, getargs_H(USHRT_MAX)) - self.failUnlessEqual(0, getargs_H(USHRT_MAX+1)) + self.assertEqual(USHRT_MAX, getargs_H(-1)) + self.assertEqual(0, getargs_H(0)) + self.assertEqual(USHRT_MAX, getargs_H(USHRT_MAX)) + self.assertEqual(0, getargs_H(USHRT_MAX+1)) - self.failUnlessEqual(42, getargs_H(42)) - self.failUnlessEqual(42, getargs_H(42L)) + self.assertEqual(42, getargs_H(42)) + self.assertEqual(42, getargs_H(42L)) - self.failUnlessEqual(VERY_LARGE & USHRT_MAX, getargs_H(VERY_LARGE)) + self.assertEqual(VERY_LARGE & USHRT_MAX, getargs_H(VERY_LARGE)) def test_I(self): from _testcapi import getargs_I # I returns 'unsigned int', no range checking - self.failUnlessEqual(3, getargs_I(3.14)) - self.failUnlessEqual(99, getargs_I(Long())) - self.failUnlessEqual(99, getargs_I(Int())) + self.assertEqual(3, getargs_I(3.14)) + self.assertEqual(99, getargs_I(Long())) + self.assertEqual(99, getargs_I(Int())) - self.failUnlessEqual(UINT_MAX, getargs_I(-1)) - self.failUnlessEqual(0, getargs_I(0)) - self.failUnlessEqual(UINT_MAX, getargs_I(UINT_MAX)) - self.failUnlessEqual(0, getargs_I(UINT_MAX+1)) + self.assertEqual(UINT_MAX, getargs_I(-1)) + self.assertEqual(0, getargs_I(0)) + self.assertEqual(UINT_MAX, getargs_I(UINT_MAX)) + self.assertEqual(0, getargs_I(UINT_MAX+1)) - self.failUnlessEqual(42, getargs_I(42)) - self.failUnlessEqual(42, getargs_I(42L)) + self.assertEqual(42, getargs_I(42)) + self.assertEqual(42, getargs_I(42L)) - self.failUnlessEqual(VERY_LARGE & UINT_MAX, getargs_I(VERY_LARGE)) + self.assertEqual(VERY_LARGE & UINT_MAX, getargs_I(VERY_LARGE)) def test_k(self): from _testcapi import getargs_k @@ -139,64 +139,64 @@ class Unsigned_TestCase(unittest.TestCase): self.assertRaises(TypeError, getargs_k, Long()) self.assertRaises(TypeError, getargs_k, Int()) - self.failUnlessEqual(ULONG_MAX, getargs_k(-1)) - self.failUnlessEqual(0, getargs_k(0)) - self.failUnlessEqual(ULONG_MAX, getargs_k(ULONG_MAX)) - self.failUnlessEqual(0, getargs_k(ULONG_MAX+1)) + self.assertEqual(ULONG_MAX, getargs_k(-1)) + self.assertEqual(0, getargs_k(0)) + self.assertEqual(ULONG_MAX, getargs_k(ULONG_MAX)) + self.assertEqual(0, getargs_k(ULONG_MAX+1)) - self.failUnlessEqual(42, getargs_k(42)) - self.failUnlessEqual(42, getargs_k(42L)) + self.assertEqual(42, getargs_k(42)) + self.assertEqual(42, getargs_k(42L)) - self.failUnlessEqual(VERY_LARGE & ULONG_MAX, getargs_k(VERY_LARGE)) + self.assertEqual(VERY_LARGE & ULONG_MAX, getargs_k(VERY_LARGE)) class Signed_TestCase(unittest.TestCase): def test_i(self): from _testcapi import getargs_i # i returns 'int', and does range checking (INT_MIN ... INT_MAX) - self.failUnlessEqual(3, getargs_i(3.14)) - self.failUnlessEqual(99, getargs_i(Long())) - self.failUnlessEqual(99, getargs_i(Int())) + self.assertEqual(3, getargs_i(3.14)) + self.assertEqual(99, getargs_i(Long())) + self.assertEqual(99, getargs_i(Int())) self.assertRaises(OverflowError, getargs_i, INT_MIN-1) - self.failUnlessEqual(INT_MIN, getargs_i(INT_MIN)) - self.failUnlessEqual(INT_MAX, getargs_i(INT_MAX)) + self.assertEqual(INT_MIN, getargs_i(INT_MIN)) + self.assertEqual(INT_MAX, getargs_i(INT_MAX)) self.assertRaises(OverflowError, getargs_i, INT_MAX+1) - self.failUnlessEqual(42, getargs_i(42)) - self.failUnlessEqual(42, getargs_i(42L)) + self.assertEqual(42, getargs_i(42)) + self.assertEqual(42, getargs_i(42L)) self.assertRaises(OverflowError, getargs_i, VERY_LARGE) def test_l(self): from _testcapi import getargs_l # l returns 'long', and does range checking (LONG_MIN ... LONG_MAX) - self.failUnlessEqual(3, getargs_l(3.14)) - self.failUnlessEqual(99, getargs_l(Long())) - self.failUnlessEqual(99, getargs_l(Int())) + self.assertEqual(3, getargs_l(3.14)) + self.assertEqual(99, getargs_l(Long())) + self.assertEqual(99, getargs_l(Int())) self.assertRaises(OverflowError, getargs_l, LONG_MIN-1) - self.failUnlessEqual(LONG_MIN, getargs_l(LONG_MIN)) - self.failUnlessEqual(LONG_MAX, getargs_l(LONG_MAX)) + self.assertEqual(LONG_MIN, getargs_l(LONG_MIN)) + self.assertEqual(LONG_MAX, getargs_l(LONG_MAX)) self.assertRaises(OverflowError, getargs_l, LONG_MAX+1) - self.failUnlessEqual(42, getargs_l(42)) - self.failUnlessEqual(42, getargs_l(42L)) + self.assertEqual(42, getargs_l(42)) + self.assertEqual(42, getargs_l(42L)) self.assertRaises(OverflowError, getargs_l, VERY_LARGE) def test_n(self): from _testcapi import getargs_n # n returns 'Py_ssize_t', and does range checking # (PY_SSIZE_T_MIN ... PY_SSIZE_T_MAX) - self.failUnlessEqual(3, getargs_n(3.14)) - self.failUnlessEqual(99, getargs_n(Long())) - self.failUnlessEqual(99, getargs_n(Int())) + self.assertEqual(3, getargs_n(3.14)) + self.assertEqual(99, getargs_n(Long())) + self.assertEqual(99, getargs_n(Int())) self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MIN-1) - self.failUnlessEqual(PY_SSIZE_T_MIN, getargs_n(PY_SSIZE_T_MIN)) - self.failUnlessEqual(PY_SSIZE_T_MAX, getargs_n(PY_SSIZE_T_MAX)) + self.assertEqual(PY_SSIZE_T_MIN, getargs_n(PY_SSIZE_T_MIN)) + self.assertEqual(PY_SSIZE_T_MAX, getargs_n(PY_SSIZE_T_MAX)) self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MAX+1) - self.failUnlessEqual(42, getargs_n(42)) - self.failUnlessEqual(42, getargs_n(42L)) + self.assertEqual(42, getargs_n(42)) + self.assertEqual(42, getargs_n(42L)) self.assertRaises(OverflowError, getargs_n, VERY_LARGE) @@ -204,18 +204,18 @@ class LongLong_TestCase(unittest.TestCase): def test_L(self): from _testcapi import getargs_L # L returns 'long long', and does range checking (LLONG_MIN ... LLONG_MAX) - self.failUnlessRaises(TypeError, getargs_L, "Hello") - self.failUnlessEqual(3, getargs_L(3.14)) - self.failUnlessEqual(99, getargs_L(Long())) - self.failUnlessEqual(99, getargs_L(Int())) + self.assertRaises(TypeError, getargs_L, "Hello") + self.assertEqual(3, getargs_L(3.14)) + self.assertEqual(99, getargs_L(Long())) + self.assertEqual(99, getargs_L(Int())) self.assertRaises(OverflowError, getargs_L, LLONG_MIN-1) - self.failUnlessEqual(LLONG_MIN, getargs_L(LLONG_MIN)) - self.failUnlessEqual(LLONG_MAX, getargs_L(LLONG_MAX)) + self.assertEqual(LLONG_MIN, getargs_L(LLONG_MIN)) + self.assertEqual(LLONG_MAX, getargs_L(LLONG_MAX)) self.assertRaises(OverflowError, getargs_L, LLONG_MAX+1) - self.failUnlessEqual(42, getargs_L(42)) - self.failUnlessEqual(42, getargs_L(42L)) + self.assertEqual(42, getargs_L(42)) + self.assertEqual(42, getargs_L(42L)) self.assertRaises(OverflowError, getargs_L, VERY_LARGE) def test_K(self): @@ -224,14 +224,14 @@ class LongLong_TestCase(unittest.TestCase): self.assertRaises(TypeError, getargs_K, 3.14) self.assertRaises(TypeError, getargs_K, Long()) self.assertRaises(TypeError, getargs_K, Int()) - self.failUnlessEqual(ULLONG_MAX, getargs_K(ULLONG_MAX)) - self.failUnlessEqual(0, getargs_K(0)) - self.failUnlessEqual(0, getargs_K(ULLONG_MAX+1)) + self.assertEqual(ULLONG_MAX, getargs_K(ULLONG_MAX)) + self.assertEqual(0, getargs_K(0)) + self.assertEqual(0, getargs_K(ULLONG_MAX+1)) - self.failUnlessEqual(42, getargs_K(42)) - self.failUnlessEqual(42, getargs_K(42L)) + self.assertEqual(42, getargs_K(42)) + self.assertEqual(42, getargs_K(42L)) - self.failUnlessEqual(VERY_LARGE & ULLONG_MAX, getargs_K(VERY_LARGE)) + self.assertEqual(VERY_LARGE & ULLONG_MAX, getargs_K(VERY_LARGE)) class Tuple_TestCase(unittest.TestCase): diff --git a/Lib/test/test_getopt.py b/Lib/test/test_getopt.py index 9031058..4729301 100644 --- a/Lib/test/test_getopt.py +++ b/Lib/test/test_getopt.py @@ -23,21 +23,21 @@ class GetoptTests(unittest.TestCase): self.assertRaises(getopt.GetoptError, *args, **kwargs) def test_short_has_arg(self): - self.failUnless(getopt.short_has_arg('a', 'a:')) - self.failIf(getopt.short_has_arg('a', 'a')) + self.assertTrue(getopt.short_has_arg('a', 'a:')) + self.assertFalse(getopt.short_has_arg('a', 'a')) self.assertError(getopt.short_has_arg, 'a', 'b') def test_long_has_args(self): has_arg, option = getopt.long_has_args('abc', ['abc=']) - self.failUnless(has_arg) + self.assertTrue(has_arg) self.assertEqual(option, 'abc') has_arg, option = getopt.long_has_args('abc', ['abc']) - self.failIf(has_arg) + self.assertFalse(has_arg) self.assertEqual(option, 'abc') has_arg, option = getopt.long_has_args('abc', ['abcd']) - self.failIf(has_arg) + self.assertFalse(has_arg) self.assertEqual(option, 'abcd') self.assertError(getopt.long_has_args, 'abc', ['def']) diff --git a/Lib/test/test_gettext.py b/Lib/test/test_gettext.py index dca99cb..d60ece7 100644 --- a/Lib/test/test_gettext.py +++ b/Lib/test/test_gettext.py @@ -306,7 +306,7 @@ class UnicodeTranslationsTest(GettextBaseTest): self._ = self.t.ugettext def test_unicode_msgid(self): - unless = self.failUnless + unless = self.assertTrue unless(isinstance(self._(''), unicode)) unless(isinstance(self._(u''), unicode)) diff --git a/Lib/test/test_grammar.py b/Lib/test/test_grammar.py index 17f9f4c..27966ed 100644 --- a/Lib/test/test_grammar.py +++ b/Lib/test/test_grammar.py @@ -36,8 +36,8 @@ class TokenTests(unittest.TestCase): if maxint == 2147483647: self.assertEquals(-2147483647-1, -020000000000) # XXX -2147483648 - self.assert_(037777777777 > 0) - self.assert_(0xffffffff > 0) + self.assertTrue(037777777777 > 0) + self.assertTrue(0xffffffff > 0) for s in '2147483648', '040000000000', '0x100000000': try: x = eval(s) @@ -45,8 +45,8 @@ class TokenTests(unittest.TestCase): self.fail("OverflowError on huge integer literal %r" % s) elif maxint == 9223372036854775807: self.assertEquals(-9223372036854775807-1, -01000000000000000000000) - self.assert_(01777777777777777777777 > 0) - self.assert_(0xffffffffffffffff > 0) + self.assertTrue(01777777777777777777777 > 0) + self.assertTrue(0xffffffffffffffff > 0) for s in '9223372036854775808', '02000000000000000000000', \ '0x10000000000000000': try: @@ -81,15 +81,15 @@ class TokenTests(unittest.TestCase): x = 3.1e4 def testStringLiterals(self): - x = ''; y = ""; self.assert_(len(x) == 0 and x == y) - x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39) - x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34) + x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y) + x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39) + x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34) x = "doesn't \"shrink\" does it" y = 'doesn\'t "shrink" does it' - self.assert_(len(x) == 24 and x == y) + self.assertTrue(len(x) == 24 and x == y) x = "does \"shrink\" doesn't it" y = 'does "shrink" doesn\'t it' - self.assert_(len(x) == 24 and x == y) + self.assertTrue(len(x) == 24 and x == y) x = """ The "quick" brown fox @@ -550,7 +550,7 @@ hello world self.fail('exec ... in g (%s), l (%s)' %(g,l)) def testAssert(self): - # assert_stmt: 'assert' test [',' test] + # assertTruestmt: 'assert' test [',' test] assert 1 assert 1, 1 assert lambda x:x diff --git a/Lib/test/test_grp.py b/Lib/test/test_grp.py index b38b94c..829e15b 100755 --- a/Lib/test/test_grp.py +++ b/Lib/test/test_grp.py @@ -12,13 +12,13 @@ class GroupDatabaseTestCase(unittest.TestCase): # attributes promised by the docs self.assertEqual(len(value), 4) self.assertEqual(value[0], value.gr_name) - self.assert_(isinstance(value.gr_name, basestring)) + self.assertTrue(isinstance(value.gr_name, basestring)) self.assertEqual(value[1], value.gr_passwd) - self.assert_(isinstance(value.gr_passwd, basestring)) + self.assertTrue(isinstance(value.gr_passwd, basestring)) self.assertEqual(value[2], value.gr_gid) - self.assert_(isinstance(value.gr_gid, int)) + self.assertTrue(isinstance(value.gr_gid, int)) self.assertEqual(value[3], value.gr_mem) - self.assert_(isinstance(value.gr_mem, list)) + self.assertTrue(isinstance(value.gr_mem, list)) def test_values(self): entries = grp.getgrall() diff --git a/Lib/test/test_gzip.py b/Lib/test/test_gzip.py index b7250db..8ae31b2 100644 --- a/Lib/test/test_gzip.py +++ b/Lib/test/test_gzip.py @@ -91,7 +91,7 @@ class TestGzip(unittest.TestCase): while 1: L = f.readline(line_length) if L == "" and line_length != 0: break - self.assert_(len(L) <= line_length) + self.assertTrue(len(L) <= line_length) line_length = (line_length + 1) % 50 f.close() @@ -157,7 +157,7 @@ class TestGzip(unittest.TestCase): def test_1647484(self): for mode in ('wb', 'rb'): f = gzip.GzipFile(self.filename, mode) - self.assert_(hasattr(f, "name")) + self.assertTrue(hasattr(f, "name")) self.assertEqual(f.name, self.filename) f.close() @@ -169,7 +169,7 @@ class TestGzip(unittest.TestCase): fRead = gzip.GzipFile(self.filename) dataRead = fRead.read() self.assertEqual(dataRead, data1) - self.assert_(hasattr(fRead, 'mtime')) + self.assertTrue(hasattr(fRead, 'mtime')) self.assertEqual(fRead.mtime, mtime) fRead.close() diff --git a/Lib/test/test_hash.py b/Lib/test/test_hash.py index fa0fb23..18ec04e 100644 --- a/Lib/test/test_hash.py +++ b/Lib/test/test_hash.py @@ -105,7 +105,7 @@ class HashInheritanceTestCase(unittest.TestCase): objects = (self.default_expected + self.fixed_expected) for obj in objects: - self.assert_(isinstance(obj, Hashable), repr(obj)) + self.assertTrue(isinstance(obj, Hashable), repr(obj)) def test_not_hashable(self): for obj in self.error_expected: diff --git a/Lib/test/test_hashlib.py b/Lib/test/test_hashlib.py index e77b246..0183714 100644 --- a/Lib/test/test_hashlib.py +++ b/Lib/test/test_hashlib.py @@ -37,12 +37,12 @@ class HashLibTestCase(unittest.TestCase): except ValueError: pass else: - self.assert_(0 == "hashlib didn't reject bogus hash name") + self.assertTrue(0 == "hashlib didn't reject bogus hash name") def test_hexdigest(self): for name in self.supported_hash_names: h = hashlib.new(name) - self.assert_(hexstr(h.digest()) == h.hexdigest()) + self.assertTrue(hexstr(h.digest()) == h.hexdigest()) def test_large_update(self): aas = 'a' * 128 diff --git a/Lib/test/test_heapq.py b/Lib/test/test_heapq.py index 7e3c7a1..e377384 100644 --- a/Lib/test/test_heapq.py +++ b/Lib/test/test_heapq.py @@ -46,7 +46,7 @@ class TestHeap(unittest.TestCase): for pos, item in enumerate(heap): if pos: # pos 0 has no parent parentpos = (pos-1) >> 1 - self.assert_(heap[parentpos] <= item) + self.assertTrue(heap[parentpos] <= item) def test_heapify(self): for size in range(30): diff --git a/Lib/test/test_hmac.py b/Lib/test/test_hmac.py index d97583f..30bb4fe 100644 --- a/Lib/test/test_hmac.py +++ b/Lib/test/test_hmac.py @@ -260,7 +260,7 @@ class SanityTestCase(unittest.TestCase): # Testing if HMAC defaults to MD5 algorithm. # NOTE: this whitebox test depends on the hmac class internals h = hmac.HMAC("key") - self.failUnless(h.digest_cons == hashlib.md5) + self.assertTrue(h.digest_cons == hashlib.md5) def test_exercise_all_methods(self): # Exercising all methods once. @@ -280,11 +280,11 @@ class CopyTestCase(unittest.TestCase): # Testing if attributes are of same type. h1 = hmac.HMAC("key") h2 = h1.copy() - self.failUnless(h1.digest_cons == h2.digest_cons, + self.assertTrue(h1.digest_cons == h2.digest_cons, "digest constructors don't match.") - self.failUnless(type(h1.inner) == type(h2.inner), + self.assertTrue(type(h1.inner) == type(h2.inner), "Types of inner don't match.") - self.failUnless(type(h1.outer) == type(h2.outer), + self.assertTrue(type(h1.outer) == type(h2.outer), "Types of outer don't match.") def test_realcopy(self): @@ -292,10 +292,10 @@ class CopyTestCase(unittest.TestCase): h1 = hmac.HMAC("key") h2 = h1.copy() # Using id() in case somebody has overridden __cmp__. - self.failUnless(id(h1) != id(h2), "No real copy of the HMAC instance.") - self.failUnless(id(h1.inner) != id(h2.inner), + self.assertTrue(id(h1) != id(h2), "No real copy of the HMAC instance.") + self.assertTrue(id(h1.inner) != id(h2.inner), "No real copy of the attribute 'inner'.") - self.failUnless(id(h1.outer) != id(h2.outer), + self.assertTrue(id(h1.outer) != id(h2.outer), "No real copy of the attribute 'outer'.") def test_equality(self): @@ -303,9 +303,9 @@ class CopyTestCase(unittest.TestCase): h1 = hmac.HMAC("key") h1.update("some random text") h2 = h1.copy() - self.failUnless(h1.digest() == h2.digest(), + self.assertTrue(h1.digest() == h2.digest(), "Digest of copy doesn't match original digest.") - self.failUnless(h1.hexdigest() == h2.hexdigest(), + self.assertTrue(h1.hexdigest() == h2.hexdigest(), "Hexdigest of copy doesn't match original hexdigest.") def test_main(): diff --git a/Lib/test/test_hotshot.py b/Lib/test/test_hotshot.py index fa6b2f1..38a8ddd 100644 --- a/Lib/test/test_hotshot.py +++ b/Lib/test/test_hotshot.py @@ -64,11 +64,11 @@ class HotShotTestCase(unittest.TestCase): def run_test(self, callable, events, profiler=None): if profiler is None: profiler = self.new_profiler() - self.failUnless(not profiler._prof.closed) + self.assertTrue(not profiler._prof.closed) profiler.runcall(callable) - self.failUnless(not profiler._prof.closed) + self.assertTrue(not profiler._prof.closed) profiler.close() - self.failUnless(profiler._prof.closed) + self.assertTrue(profiler._prof.closed) self.check_events(events) def test_addinfo(self): @@ -80,7 +80,7 @@ class HotShotTestCase(unittest.TestCase): log = self.get_logreader() info = log._info list(log) - self.failUnless(info["test-key"] == ["test-value"]) + self.assertTrue(info["test-key"] == ["test-value"]) def test_line_numbers(self): def f(): diff --git a/Lib/test/test_httplib.py b/Lib/test/test_httplib.py index 54a2b0e..77e9887 100644 --- a/Lib/test/test_httplib.py +++ b/Lib/test/test_httplib.py @@ -239,7 +239,7 @@ class TimeoutTest(TestCase): HTTPConnection and into the socket. ''' # default -- use global socket timeout - self.assert_(socket.getdefaulttimeout() is None) + self.assertTrue(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(30) try: httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT) @@ -250,7 +250,7 @@ class TimeoutTest(TestCase): httpConn.close() # no timeout -- do not use global socket default - self.assert_(socket.getdefaulttimeout() is None) + self.assertTrue(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(30) try: httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT, diff --git a/Lib/test/test_httpservers.py b/Lib/test/test_httpservers.py index 6edc7d3..228d82b 100644 --- a/Lib/test/test_httpservers.py +++ b/Lib/test/test_httpservers.py @@ -216,9 +216,9 @@ class SimpleHTTPServerTestCase(BaseTestCase): def check_status_and_reason(self, response, status, data=None): body = response.read() - self.assert_(response) + self.assertTrue(response) self.assertEquals(response.status, status) - self.assert_(response.reason != None) + self.assertTrue(response.reason != None) if data: self.assertEqual(data, body) diff --git a/Lib/test/test_imp.py b/Lib/test/test_imp.py index c9682ab..f4a1649 100644 --- a/Lib/test/test_imp.py +++ b/Lib/test/test_imp.py @@ -8,7 +8,7 @@ class LockTests(unittest.TestCase): """Very basic test of import lock functions.""" def verify_lock_state(self, expected): - self.failUnlessEqual(imp.lock_held(), expected, + self.assertEqual(imp.lock_held(), expected, "expected imp.lock_held() to be %r" % expected) def testLock(self): LOOPS = 50 diff --git a/Lib/test/test_import.py b/Lib/test/test_import.py index e107931..9b75b04 100644 --- a/Lib/test/test_import.py +++ b/Lib/test/test_import.py @@ -161,7 +161,7 @@ class ImportTest(unittest.TestCase): sys.path.insert(0, os.curdir) try: mod = __import__(TESTFN) - self.assert_(TESTFN in sys.modules, "expected module in sys.modules") + self.assertTrue(TESTFN in sys.modules, "expected module in sys.modules") self.assertEquals(mod.a, 1, "module has wrong attribute values") self.assertEquals(mod.b, 2, "module has wrong attribute values") @@ -181,7 +181,7 @@ class ImportTest(unittest.TestCase): # But we still expect the module to be in sys.modules. mod = sys.modules.get(TESTFN) - self.failIf(mod is None, "expected module to still be in sys.modules") + self.assertFalse(mod is None, "expected module to still be in sys.modules") # We should have replaced a w/ 10, but the old b value should # stick. @@ -208,12 +208,12 @@ class ImportTest(unittest.TestCase): # import x.y.z binds x in the current namespace import test as x import test.test_support - self.assert_(x is test, x.__name__) - self.assert_(hasattr(test.test_support, "__file__")) + self.assertTrue(x is test, x.__name__) + self.assertTrue(hasattr(test.test_support, "__file__")) # import x.y.z as w binds z as w import test.test_support as y - self.assert_(y is test.test_support, y.__name__) + self.assertTrue(y is test.test_support, y.__name__) def test_import_initless_directory_warning(self): with warnings.catch_warnings(): @@ -394,14 +394,14 @@ class RelativeImport(unittest.TestCase): ns = dict(__package__='foo', __name__='test.notarealmodule') with check_warnings() as w: check_absolute() - self.assert_('foo' in str(w.message)) + self.assertTrue('foo' in str(w.message)) self.assertEqual(w.category, RuntimeWarning) self.assertRaises(SystemError, check_relative) # Check relative fails with __package__ and __name__ wrong ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule') with check_warnings() as w: check_absolute() - self.assert_('foo' in str(w.message)) + self.assertTrue('foo' in str(w.message)) self.assertEqual(w.category, RuntimeWarning) self.assertRaises(SystemError, check_relative) # Check both fail with package set to a non-string diff --git a/Lib/test/test_importhooks.py b/Lib/test/test_importhooks.py index 643ecce..7fd8c62 100644 --- a/Lib/test/test_importhooks.py +++ b/Lib/test/test_importhooks.py @@ -177,11 +177,11 @@ class ImportHooksTestCase(ImportHooksBaseTestCase): TestImporter.modules['reloadmodule'] = (False, test_co) import reloadmodule - self.failIf(hasattr(reloadmodule,'reloaded')) + self.assertFalse(hasattr(reloadmodule,'reloaded')) TestImporter.modules['reloadmodule'] = (False, reload_co) reload(reloadmodule) - self.failUnless(hasattr(reloadmodule,'reloaded')) + self.assertTrue(hasattr(reloadmodule,'reloaded')) import hooktestpackage.oldabs self.assertEqual(hooktestpackage.oldabs.get_name(), diff --git a/Lib/test/test_index.py b/Lib/test/test_index.py index 75f2434..2e997c7 100644 --- a/Lib/test/test_index.py +++ b/Lib/test/test_index.py @@ -60,10 +60,10 @@ class BaseTestCase(unittest.TestCase): def test_error(self): self.o.ind = 'dumb' self.n.ind = 'bad' - self.failUnlessRaises(TypeError, operator.index, self.o) - self.failUnlessRaises(TypeError, operator.index, self.n) - self.failUnlessRaises(TypeError, slice(self.o).indices, 0) - self.failUnlessRaises(TypeError, slice(self.n).indices, 0) + self.assertRaises(TypeError, operator.index, self.o) + self.assertRaises(TypeError, operator.index, self.n) + self.assertRaises(TypeError, slice(self.o).indices, 0) + self.assertRaises(TypeError, slice(self.n).indices, 0) class SeqTestCase(unittest.TestCase): @@ -115,11 +115,11 @@ class SeqTestCase(unittest.TestCase): self.o.ind = 'dumb' self.n.ind = 'bad' indexobj = lambda x, obj: obj.seq[x] - self.failUnlessRaises(TypeError, indexobj, self.o, self) - self.failUnlessRaises(TypeError, indexobj, self.n, self) + self.assertRaises(TypeError, indexobj, self.o, self) + self.assertRaises(TypeError, indexobj, self.n, self) sliceobj = lambda x, obj: obj.seq[x:] - self.failUnlessRaises(TypeError, sliceobj, self.o, self) - self.failUnlessRaises(TypeError, sliceobj, self.n, self) + self.assertRaises(TypeError, sliceobj, self.o, self) + self.assertRaises(TypeError, sliceobj, self.n, self) class ListTestCase(SeqTestCase): @@ -152,7 +152,7 @@ class ListTestCase(SeqTestCase): lst = [5, 6, 7, 8, 9, 11] l2 = lst.__imul__(self.n) - self.assert_(l2 is lst) + self.assertTrue(l2 is lst) self.assertEqual(lst, [5, 6, 7, 8, 9, 11] * 3) @@ -206,8 +206,8 @@ class OverflowTestCase(unittest.TestCase): self._getitem_helper(Empty) def test_sequence_repeat(self): - self.failUnlessRaises(OverflowError, lambda: "a" * self.pos) - self.failUnlessRaises(OverflowError, lambda: "a" * self.neg) + self.assertRaises(OverflowError, lambda: "a" * self.pos) + self.assertRaises(OverflowError, lambda: "a" * self.neg) def test_main(): diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py index 144f89c..e4c4ee8 100644 --- a/Lib/test/test_inspect.py +++ b/Lib/test/test_inspect.py @@ -43,13 +43,13 @@ class IsTestBase(unittest.TestCase): def istest(self, predicate, exp): obj = eval(exp) - self.failUnless(predicate(obj), '%s(%s)' % (predicate.__name__, exp)) + self.assertTrue(predicate(obj), '%s(%s)' % (predicate.__name__, exp)) for other in self.predicates - set([predicate]): if predicate == inspect.isgeneratorfunction and\ other == inspect.isfunction: continue - self.failIf(other(obj), 'not %s(%s)' % (other.__name__, exp)) + self.assertFalse(other(obj), 'not %s(%s)' % (other.__name__, exp)) def generator_function_example(self): for i in xrange(2): @@ -83,15 +83,15 @@ class TestPredicates(IsTestBase): self.istest(inspect.isgetsetdescriptor, 'type(tb.tb_frame).f_locals') else: - self.failIf(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals)) + self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals)) if hasattr(types, 'MemberDescriptorType'): self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days') else: - self.failIf(inspect.ismemberdescriptor(datetime.timedelta.days)) + self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days)) def test_isroutine(self): - self.assert_(inspect.isroutine(mod.spam)) - self.assert_(inspect.isroutine([].count)) + self.assertTrue(inspect.isroutine(mod.spam)) + self.assertTrue(inspect.isroutine([].count)) def test_isclass(self): self.istest(inspect.isclass, 'mod.StupidGit') @@ -112,8 +112,8 @@ class TestPredicates(IsTestBase): x = C() x.a = 42 members = dict(inspect.getmembers(x)) - self.assert_('a' in members) - self.assert_('b' not in members) + self.assertTrue('a' in members) + self.assertTrue('b' not in members) class TestInterpreterStack(IsTestBase): @@ -127,7 +127,7 @@ class TestInterpreterStack(IsTestBase): self.istest(inspect.isframe, 'mod.fr') def test_stack(self): - self.assert_(len(mod.st) >= 5) + self.assertTrue(len(mod.st) >= 5) self.assertEqual(mod.st[0][1:], (modfile, 16, 'eggs', [' st = inspect.stack()\n'], 0)) self.assertEqual(mod.st[1][1:], @@ -419,23 +419,23 @@ class TestClassesAndFunctions(unittest.TestCase): datablob = '1' attrs = attrs_wo_objs(A) - self.assert_(('s', 'static method', A) in attrs, 'missing static method') - self.assert_(('c', 'class method', A) in attrs, 'missing class method') - self.assert_(('p', 'property', A) in attrs, 'missing property') - self.assert_(('m', 'method', A) in attrs, 'missing plain method') - self.assert_(('m1', 'method', A) in attrs, 'missing plain method') - self.assert_(('datablob', 'data', A) in attrs, 'missing data') + self.assertTrue(('s', 'static method', A) in attrs, 'missing static method') + self.assertTrue(('c', 'class method', A) in attrs, 'missing class method') + self.assertTrue(('p', 'property', A) in attrs, 'missing property') + self.assertTrue(('m', 'method', A) in attrs, 'missing plain method') + self.assertTrue(('m1', 'method', A) in attrs, 'missing plain method') + self.assertTrue(('datablob', 'data', A) in attrs, 'missing data') class B(A): def m(self): pass attrs = attrs_wo_objs(B) - self.assert_(('s', 'static method', A) in attrs, 'missing static method') - self.assert_(('c', 'class method', A) in attrs, 'missing class method') - self.assert_(('p', 'property', A) in attrs, 'missing property') - self.assert_(('m', 'method', B) in attrs, 'missing plain method') - self.assert_(('m1', 'method', A) in attrs, 'missing plain method') - self.assert_(('datablob', 'data', A) in attrs, 'missing data') + self.assertTrue(('s', 'static method', A) in attrs, 'missing static method') + self.assertTrue(('c', 'class method', A) in attrs, 'missing class method') + self.assertTrue(('p', 'property', A) in attrs, 'missing property') + self.assertTrue(('m', 'method', B) in attrs, 'missing plain method') + self.assertTrue(('m1', 'method', A) in attrs, 'missing plain method') + self.assertTrue(('datablob', 'data', A) in attrs, 'missing data') class C(A): @@ -443,23 +443,23 @@ class TestClassesAndFunctions(unittest.TestCase): def c(self): pass attrs = attrs_wo_objs(C) - self.assert_(('s', 'static method', A) in attrs, 'missing static method') - self.assert_(('c', 'method', C) in attrs, 'missing plain method') - self.assert_(('p', 'property', A) in attrs, 'missing property') - self.assert_(('m', 'method', C) in attrs, 'missing plain method') - self.assert_(('m1', 'method', A) in attrs, 'missing plain method') - self.assert_(('datablob', 'data', A) in attrs, 'missing data') + self.assertTrue(('s', 'static method', A) in attrs, 'missing static method') + self.assertTrue(('c', 'method', C) in attrs, 'missing plain method') + self.assertTrue(('p', 'property', A) in attrs, 'missing property') + self.assertTrue(('m', 'method', C) in attrs, 'missing plain method') + self.assertTrue(('m1', 'method', A) in attrs, 'missing plain method') + self.assertTrue(('datablob', 'data', A) in attrs, 'missing data') class D(B, C): def m1(self): pass attrs = attrs_wo_objs(D) - self.assert_(('s', 'static method', A) in attrs, 'missing static method') - self.assert_(('c', 'class method', A) in attrs, 'missing class method') - self.assert_(('p', 'property', A) in attrs, 'missing property') - self.assert_(('m', 'method', B) in attrs, 'missing plain method') - self.assert_(('m1', 'method', D) in attrs, 'missing plain method') - self.assert_(('datablob', 'data', A) in attrs, 'missing data') + self.assertTrue(('s', 'static method', A) in attrs, 'missing static method') + self.assertTrue(('c', 'class method', A) in attrs, 'missing class method') + self.assertTrue(('p', 'property', A) in attrs, 'missing property') + self.assertTrue(('m', 'method', B) in attrs, 'missing plain method') + self.assertTrue(('m1', 'method', D) in attrs, 'missing plain method') + self.assertTrue(('datablob', 'data', A) in attrs, 'missing data') # Repeat all that, but w/ new-style classes. def test_classify_newstyle(self): @@ -481,24 +481,24 @@ class TestClassesAndFunctions(unittest.TestCase): datablob = '1' attrs = attrs_wo_objs(A) - self.assert_(('s', 'static method', A) in attrs, 'missing static method') - self.assert_(('c', 'class method', A) in attrs, 'missing class method') - self.assert_(('p', 'property', A) in attrs, 'missing property') - self.assert_(('m', 'method', A) in attrs, 'missing plain method') - self.assert_(('m1', 'method', A) in attrs, 'missing plain method') - self.assert_(('datablob', 'data', A) in attrs, 'missing data') + self.assertTrue(('s', 'static method', A) in attrs, 'missing static method') + self.assertTrue(('c', 'class method', A) in attrs, 'missing class method') + self.assertTrue(('p', 'property', A) in attrs, 'missing property') + self.assertTrue(('m', 'method', A) in attrs, 'missing plain method') + self.assertTrue(('m1', 'method', A) in attrs, 'missing plain method') + self.assertTrue(('datablob', 'data', A) in attrs, 'missing data') class B(A): def m(self): pass attrs = attrs_wo_objs(B) - self.assert_(('s', 'static method', A) in attrs, 'missing static method') - self.assert_(('c', 'class method', A) in attrs, 'missing class method') - self.assert_(('p', 'property', A) in attrs, 'missing property') - self.assert_(('m', 'method', B) in attrs, 'missing plain method') - self.assert_(('m1', 'method', A) in attrs, 'missing plain method') - self.assert_(('datablob', 'data', A) in attrs, 'missing data') + self.assertTrue(('s', 'static method', A) in attrs, 'missing static method') + self.assertTrue(('c', 'class method', A) in attrs, 'missing class method') + self.assertTrue(('p', 'property', A) in attrs, 'missing property') + self.assertTrue(('m', 'method', B) in attrs, 'missing plain method') + self.assertTrue(('m1', 'method', A) in attrs, 'missing plain method') + self.assertTrue(('datablob', 'data', A) in attrs, 'missing data') class C(A): @@ -507,24 +507,24 @@ class TestClassesAndFunctions(unittest.TestCase): def c(self): pass attrs = attrs_wo_objs(C) - self.assert_(('s', 'static method', A) in attrs, 'missing static method') - self.assert_(('c', 'method', C) in attrs, 'missing plain method') - self.assert_(('p', 'property', A) in attrs, 'missing property') - self.assert_(('m', 'method', C) in attrs, 'missing plain method') - self.assert_(('m1', 'method', A) in attrs, 'missing plain method') - self.assert_(('datablob', 'data', A) in attrs, 'missing data') + self.assertTrue(('s', 'static method', A) in attrs, 'missing static method') + self.assertTrue(('c', 'method', C) in attrs, 'missing plain method') + self.assertTrue(('p', 'property', A) in attrs, 'missing property') + self.assertTrue(('m', 'method', C) in attrs, 'missing plain method') + self.assertTrue(('m1', 'method', A) in attrs, 'missing plain method') + self.assertTrue(('datablob', 'data', A) in attrs, 'missing data') class D(B, C): def m1(self): pass attrs = attrs_wo_objs(D) - self.assert_(('s', 'static method', A) in attrs, 'missing static method') - self.assert_(('c', 'method', C) in attrs, 'missing plain method') - self.assert_(('p', 'property', A) in attrs, 'missing property') - self.assert_(('m', 'method', B) in attrs, 'missing plain method') - self.assert_(('m1', 'method', D) in attrs, 'missing plain method') - self.assert_(('datablob', 'data', A) in attrs, 'missing data') + self.assertTrue(('s', 'static method', A) in attrs, 'missing static method') + self.assertTrue(('c', 'method', C) in attrs, 'missing plain method') + self.assertTrue(('p', 'property', A) in attrs, 'missing property') + self.assertTrue(('m', 'method', B) in attrs, 'missing plain method') + self.assertTrue(('m1', 'method', D) in attrs, 'missing plain method') + self.assertTrue(('datablob', 'data', A) in attrs, 'missing data') def test_main(): run_unittest(TestDecorators, TestRetrievingSourceCode, TestOneliners, diff --git a/Lib/test/test_int.py b/Lib/test/test_int.py index 514a98e..e4cac0c 100644 --- a/Lib/test/test_int.py +++ b/Lib/test/test_int.py @@ -76,15 +76,15 @@ class IntTestCases(unittest.TestCase): s = repr(-1-sys.maxint) x = int(s) self.assertEqual(x+1, -sys.maxint) - self.assert_(isinstance(x, int)) + self.assertTrue(isinstance(x, int)) # should return long self.assertEqual(int(s[1:]), sys.maxint+1) # should return long x = int(1e100) - self.assert_(isinstance(x, long)) + self.assertTrue(isinstance(x, long)) x = int(-1e100) - self.assert_(isinstance(x, long)) + self.assertTrue(isinstance(x, long)) # SF bug 434186: 0x80000000/2 != 0x80000000>>1. @@ -102,11 +102,11 @@ class IntTestCases(unittest.TestCase): self.assertRaises(ValueError, int, '123\x00 245', 20) x = int('1' * 600) - self.assert_(isinstance(x, long)) + self.assertTrue(isinstance(x, long)) if have_unicode: x = int(unichr(0x661) * 600) - self.assert_(isinstance(x, long)) + self.assertTrue(isinstance(x, long)) self.assertRaises(TypeError, int, 1, 12) @@ -249,7 +249,7 @@ class IntTestCases(unittest.TestCase): self.assertEqual(k, len(bin(x).lstrip('-0b'))) # Behaviour as specified in the docs if x != 0: - self.assert_(2**(k-1) <= abs(x) < 2**k) + self.assertTrue(2**(k-1) <= abs(x) < 2**k) else: self.assertEqual(k, 0) # Alternative definition: x.bit_length() == 1 + floor(log_2(x)) diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py index 3751e6f..76ce347 100644 --- a/Lib/test/test_io.py +++ b/Lib/test/test_io.py @@ -396,7 +396,7 @@ class IOTest(unittest.TestCase): with self.open(support.TESTFN, "ab") as f: self.assertEqual(f.tell(), 3) with self.open(support.TESTFN, "a") as f: - self.assert_(f.tell() > 0) + self.assertTrue(f.tell() > 0) def test_destructor(self): record = [] @@ -514,7 +514,7 @@ class IOTest(unittest.TestCase): wr = weakref.ref(f) del f support.gc_collect() - self.assert_(wr() is None, wr) + self.assertTrue(wr() is None, wr) with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.read(), b"abcxxx") @@ -622,8 +622,8 @@ class CommonBufferedTests: if s: # The destructor *may* have printed an unraisable error, check it self.assertEqual(len(s.splitlines()), 1) - self.assert_(s.startswith("Exception IOError: "), s) - self.assert_(s.endswith(" ignored"), s) + self.assertTrue(s.startswith("Exception IOError: "), s) + self.assertTrue(s.endswith(" ignored"), s) def test_repr(self): raw = self.MockRawIO() @@ -720,7 +720,7 @@ class BufferedReaderTest(unittest.TestCase, CommonBufferedTests): self.assertEquals(b"e", bufio.read(1)) self.assertEquals(b"fg", bufio.read()) self.assertEquals(b"", bufio.peek(1)) - self.assert_(None is bufio.read()) + self.assertTrue(None is bufio.read()) self.assertEquals(b"", bufio.read()) def test_read_past_eof(self): @@ -822,7 +822,7 @@ class CBufferedReaderTest(BufferedReaderTest): wr = weakref.ref(f) del f support.gc_collect() - self.assert_(wr() is None, wr) + self.assertTrue(wr() is None, wr) class PyBufferedReaderTest(BufferedReaderTest): tp = pyio.BufferedReader @@ -871,7 +871,7 @@ class BufferedWriterTest(unittest.TestCase, CommonBufferedTests): flushed = b"".join(writer._write_stack) # At least (total - 8) bytes were implicitly flushed, perhaps more # depending on the implementation. - self.assert_(flushed.startswith(contents[:-8]), flushed) + self.assertTrue(flushed.startswith(contents[:-8]), flushed) def check_writes(self, intermediate_func): # Lots of writes, test the flushed output is as expected. @@ -1083,7 +1083,7 @@ class CBufferedWriterTest(BufferedWriterTest): wr = weakref.ref(f) del f support.gc_collect() - self.assert_(wr() is None, wr) + self.assertTrue(wr() is None, wr) with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.read(), b"123xxx") @@ -1573,7 +1573,7 @@ class TextIOWrapperTest(unittest.TestCase): t = self.TextIOWrapper(b, encoding="utf8") self.assertEqual(t.encoding, "utf8") t = self.TextIOWrapper(b) - self.assert_(t.encoding is not None) + self.assertTrue(t.encoding is not None) codecs.lookup(t.encoding) def test_encoding_errors_reading(self): @@ -1743,8 +1743,8 @@ class TextIOWrapperTest(unittest.TestCase): if s: # The destructor *may* have printed an unraisable error, check it self.assertEqual(len(s.splitlines()), 1) - self.assert_(s.startswith("Exception IOError: "), s) - self.assert_(s.endswith(" ignored"), s) + self.assertTrue(s.startswith("Exception IOError: "), s) + self.assertTrue(s.endswith(" ignored"), s) # Systematic tests of the text I/O API @@ -2064,7 +2064,7 @@ class CTextIOWrapperTest(TextIOWrapperTest): wr = weakref.ref(t) del t support.gc_collect() - self.assert_(wr() is None, wr) + self.assertTrue(wr() is None, wr) with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.read(), b"456def") @@ -2288,7 +2288,7 @@ class MiscIOTest(unittest.TestCase): wr = weakref.ref(c) del c, b support.gc_collect() - self.assert_(wr() is None, wr) + self.assertTrue(wr() is None, wr) def test_abcs(self): # Test the visible base classes are ABCs. diff --git a/Lib/test/test_ioctl.py b/Lib/test/test_ioctl.py index 823d954..b996216 100644 --- a/Lib/test/test_ioctl.py +++ b/Lib/test/test_ioctl.py @@ -24,7 +24,7 @@ class IoctlTests(unittest.TestCase): tty = open("/dev/tty", "r") r = fcntl.ioctl(tty, termios.TIOCGPGRP, " ") rpgrp = struct.unpack("i", r)[0] - self.assert_(rpgrp in ids, "%s not in %s" % (rpgrp, ids)) + self.assertTrue(rpgrp in ids, "%s not in %s" % (rpgrp, ids)) def test_ioctl_mutate(self): import array @@ -34,7 +34,7 @@ class IoctlTests(unittest.TestCase): r = fcntl.ioctl(tty, termios.TIOCGPGRP, buf, 1) rpgrp = buf[0] self.assertEquals(r, 0) - self.assert_(rpgrp in ids, "%s not in %s" % (rpgrp, ids)) + self.assertTrue(rpgrp in ids, "%s not in %s" % (rpgrp, ids)) def test_ioctl_signed_unsigned_code_param(self): if not pty: diff --git a/Lib/test/test_iter.py b/Lib/test/test_iter.py index e847018..f5d6e68 100644 --- a/Lib/test/test_iter.py +++ b/Lib/test/test_iter.py @@ -75,7 +75,7 @@ class TestCase(unittest.TestCase): seq = range(10) it = iter(seq) it2 = iter(it) - self.assert_(it is it2) + self.assertTrue(it is it2) # Test that for loops over iterators work def test_iter_for_loop(self): @@ -566,23 +566,23 @@ class TestCase(unittest.TestCase): def test_in_and_not_in(self): for sc5 in IteratingSequenceClass(5), SequenceClass(5): for i in range(5): - self.assert_(i in sc5) + self.assertTrue(i in sc5) for i in "abc", -1, 5, 42.42, (3, 4), [], {1: 1}, 3-12j, sc5: - self.assert_(i not in sc5) + self.assertTrue(i not in sc5) self.assertRaises(TypeError, lambda: 3 in 12) self.assertRaises(TypeError, lambda: 3 not in map) d = {"one": 1, "two": 2, "three": 3, 1j: 2j} for k in d: - self.assert_(k in d) - self.assert_(k not in d.itervalues()) + self.assertTrue(k in d) + self.assertTrue(k not in d.itervalues()) for v in d.values(): - self.assert_(v in d.itervalues()) - self.assert_(v not in d) + self.assertTrue(v in d.itervalues()) + self.assertTrue(v not in d) for k, v in d.iteritems(): - self.assert_((k, v) in d.iteritems()) - self.assert_((v, k) not in d.iteritems()) + self.assertTrue((k, v) in d.iteritems()) + self.assertTrue((v, k) not in d.iteritems()) f = open(TESTFN, "w") try: @@ -593,9 +593,9 @@ class TestCase(unittest.TestCase): try: for chunk in "abc": f.seek(0, 0) - self.assert_(chunk not in f) + self.assertTrue(chunk not in f) f.seek(0, 0) - self.assert_((chunk + "\n") in f) + self.assertTrue((chunk + "\n") in f) finally: f.close() try: diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py index 31d10dc..f88b094 100644 --- a/Lib/test/test_itertools.py +++ b/Lib/test/test_itertools.py @@ -127,7 +127,7 @@ class TestBasicOps(unittest.TestCase): self.assertEqual(len(c), r) # r-length combinations self.assertEqual(len(set(c)), r) # no duplicate elements self.assertEqual(list(c), sorted(c)) # keep original ordering - self.assert_(all(e in values for e in c)) # elements taken from input iterable + self.assertTrue(all(e in values for e in c)) # elements taken from input iterable self.assertEqual(list(c), [e for e in values if e in c]) # comb is a subsequence of the input iterable self.assertEqual(result, list(combinations1(values, r))) # matches first pure python version @@ -191,14 +191,14 @@ class TestBasicOps(unittest.TestCase): if n == 0 or r <= 1: self.assertEquals(result, regular_combs) # cases that should be identical else: - self.assert_(set(result) >= set(regular_combs)) # rest should be supersets of regular combs + self.assertTrue(set(result) >= set(regular_combs)) # rest should be supersets of regular combs for c in result: self.assertEqual(len(c), r) # r-length combinations noruns = [k for k,v in groupby(c)] # combo without consecutive repeats self.assertEqual(len(noruns), len(set(noruns))) # no repeats other than consecutive self.assertEqual(list(c), sorted(c)) # keep original ordering - self.assert_(all(e in values for e in c)) # elements taken from input iterable + self.assertTrue(all(e in values for e in c)) # elements taken from input iterable self.assertEqual(noruns, [e for e in values if e in c]) # comb is a subsequence of the input iterable self.assertEqual(result, list(cwr1(values, r))) # matches first pure python version @@ -261,7 +261,7 @@ class TestBasicOps(unittest.TestCase): for p in result: self.assertEqual(len(p), r) # r-length permutations self.assertEqual(len(set(p)), r) # no duplicate elements - self.assert_(all(e in values for e in p)) # elements taken from input iterable + self.assertTrue(all(e in values for e in p)) # elements taken from input iterable self.assertEqual(result, list(permutations1(values, r))) # matches first pure python version self.assertEqual(result, list(permutations2(values, r))) # matches second pure python version if r == n: @@ -821,7 +821,7 @@ class TestBasicOps(unittest.TestCase): # tee pass-through to copyable iterator a, b = tee('abc') c, d = tee(a) - self.assert_(a is c) + self.assertTrue(a is c) # test tee_new t1, t2 = tee('abc') @@ -829,7 +829,7 @@ class TestBasicOps(unittest.TestCase): self.assertRaises(TypeError, tnew) self.assertRaises(TypeError, tnew, 10) t3 = tnew(t1) - self.assert_(list(t1) == list(t2) == list(t3) == list('abc')) + self.assertTrue(list(t1) == list(t2) == list(t3) == list('abc')) # test that tee objects are weak referencable a, b = tee(xrange(10)) @@ -1336,7 +1336,7 @@ class SubclassWithKwargsTest(unittest.TestCase): Subclass(newarg=1) except TypeError, err: # we expect type errors because of wrong argument count - self.failIf("does not take keyword arguments" in err.args[0]) + self.assertFalse("does not take keyword arguments" in err.args[0]) libreftest = """ Doctest for examples in the library reference: libitertools.tex diff --git a/Lib/test/test_kqueue.py b/Lib/test/test_kqueue.py index 6216850..901295b 100644 --- a/Lib/test/test_kqueue.py +++ b/Lib/test/test_kqueue.py @@ -15,10 +15,10 @@ if not hasattr(select, "kqueue"): class TestKQueue(unittest.TestCase): def test_create_queue(self): kq = select.kqueue() - self.assert_(kq.fileno() > 0, kq.fileno()) - self.assert_(not kq.closed) + self.assertTrue(kq.fileno() > 0, kq.fileno()) + self.assertTrue(not kq.closed) kq.close() - self.assert_(kq.closed) + self.assertTrue(kq.closed) self.assertRaises(ValueError, kq.fileno) def test_create_event(self): @@ -34,8 +34,8 @@ class TestKQueue(unittest.TestCase): self.assertEqual(ev, ev) self.assertNotEqual(ev, other) self.assertEqual(cmp(ev, other), -1) - self.assert_(ev < other) - self.assert_(other >= ev) + self.assertTrue(ev < other) + self.assertTrue(other >= ev) self.assertRaises(TypeError, cmp, ev, None) self.assertRaises(TypeError, cmp, ev, 1) self.assertRaises(TypeError, cmp, ev, "ev") diff --git a/Lib/test/test_largefile.py b/Lib/test/test_largefile.py index ddbcc06..c4faead 100644 --- a/Lib/test/test_largefile.py +++ b/Lib/test/test_largefile.py @@ -145,7 +145,7 @@ class LargeFileTest(unittest.TestCase): for pos in (2**31-1, 2**31, 2**31+1): with self.open(TESTFN, 'rb') as f: f.seek(pos) - self.assert_(f.seekable()) + self.assertTrue(f.seekable()) def test_main(): diff --git a/Lib/test/test_list.py b/Lib/test/test_list.py index 167293a..6e080dc 100644 --- a/Lib/test/test_list.py +++ b/Lib/test/test_list.py @@ -9,7 +9,7 @@ class ListTest(list_tests.CommonTest): l0_3 = [0, 1, 2, 3] l0_3_bis = list(l0_3) self.assertEqual(l0_3, l0_3_bis) - self.assert_(l0_3 is not l0_3_bis) + self.assertTrue(l0_3 is not l0_3_bis) self.assertEqual(list(()), []) self.assertEqual(list((0, 1, 2, 3)), [0, 1, 2, 3]) self.assertEqual(list(''), []) @@ -39,11 +39,11 @@ class ListTest(list_tests.CommonTest): def test_truth(self): super(ListTest, self).test_truth() - self.assert_(not []) - self.assert_([42]) + self.assertTrue(not []) + self.assertTrue([42]) def test_identity(self): - self.assert_([] is not []) + self.assertTrue([] is not []) def test_len(self): super(ListTest, self).test_len() diff --git a/Lib/test/test_logging.py b/Lib/test/test_logging.py index 1e81568..9e866b7 100644 --- a/Lib/test/test_logging.py +++ b/Lib/test/test_logging.py @@ -99,7 +99,7 @@ class BaseTest(unittest.TestCase): finally: logging._releaseLock() - def assert_log_lines(self, expected_values, stream=None): + def assertTruelog_lines(self, expected_values, stream=None): """Match the collected log lines against the regular expression self.expected_log_pat, and compare the extracted group values to the expected_values list of tuples.""" @@ -165,7 +165,7 @@ class BuiltinLevelsTest(BaseTest): INF.debug(m()) - self.assert_log_lines([ + self.assertTruelog_lines([ ('ERR', 'CRITICAL', '1'), ('ERR', 'ERROR', '2'), ('INF', 'CRITICAL', '3'), @@ -197,7 +197,7 @@ class BuiltinLevelsTest(BaseTest): INF_ERR.info(m()) INF_ERR.debug(m()) - self.assert_log_lines([ + self.assertTruelog_lines([ ('INF.ERR', 'CRITICAL', '1'), ('INF.ERR', 'ERROR', '2'), ]) @@ -228,7 +228,7 @@ class BuiltinLevelsTest(BaseTest): INF_ERR_UNDEF.info(m()) INF_ERR_UNDEF.debug(m()) - self.assert_log_lines([ + self.assertTruelog_lines([ ('INF.UNDEF', 'CRITICAL', '1'), ('INF.UNDEF', 'ERROR', '2'), ('INF.UNDEF', 'WARNING', '3'), @@ -256,7 +256,7 @@ class BuiltinLevelsTest(BaseTest): GRANDCHILD.debug(m()) CHILD.debug(m()) - self.assert_log_lines([ + self.assertTruelog_lines([ ('INF.BADPARENT.UNDEF', 'CRITICAL', '1'), ('INF.BADPARENT.UNDEF', 'INFO', '2'), ('INF.BADPARENT', 'CRITICAL', '3'), @@ -285,7 +285,7 @@ class BasicFilterTest(BaseTest): spam_eggs_fish.info(self.next_message()) # Good. spam_bakedbeans.info(self.next_message()) - self.assert_log_lines([ + self.assertTruelog_lines([ ('spam.eggs', 'INFO', '2'), ('spam.eggs.fish', 'INFO', '3'), ]) @@ -367,7 +367,7 @@ class CustomLevelsAndFiltersTest(BaseTest): self.root_logger.setLevel(VERBOSE) # Levels >= 'Verbose' are good. self.log_at_all_levels(self.root_logger) - self.assert_log_lines([ + self.assertTruelog_lines([ ('Verbose', '5'), ('Sociable', '6'), ('Effusive', '7'), @@ -382,7 +382,7 @@ class CustomLevelsAndFiltersTest(BaseTest): try: # Levels >= 'Sociable' are good. self.log_at_all_levels(self.root_logger) - self.assert_log_lines([ + self.assertTruelog_lines([ ('Sociable', '6'), ('Effusive', '7'), ('Terse', '8'), @@ -413,12 +413,12 @@ class CustomLevelsAndFiltersTest(BaseTest): ('Taciturn', '9'), ('Silent', '10'), ] - self.assert_log_lines(first_lines) + self.assertTruelog_lines(first_lines) specific_filter = VerySpecificFilter() self.root_logger.addFilter(specific_filter) self.log_at_all_levels(self.root_logger) - self.assert_log_lines(first_lines + [ + self.assertTruelog_lines(first_lines + [ # Not only 'Garrulous' is still missing, but also 'Sociable' # and 'Taciturn' ('Boring', '11'), @@ -458,9 +458,9 @@ class MemoryHandlerTest(BaseTest): # The memory handler flushes to its target handler based on specific # criteria (message count and message level). self.mem_logger.debug(self.next_message()) - self.assert_log_lines([]) + self.assertTruelog_lines([]) self.mem_logger.info(self.next_message()) - self.assert_log_lines([]) + self.assertTruelog_lines([]) # This will flush because the level is >= logging.WARNING self.mem_logger.warn(self.next_message()) lines = [ @@ -468,19 +468,19 @@ class MemoryHandlerTest(BaseTest): ('INFO', '2'), ('WARNING', '3'), ] - self.assert_log_lines(lines) + self.assertTruelog_lines(lines) for n in (4, 14): for i in range(9): self.mem_logger.debug(self.next_message()) - self.assert_log_lines(lines) + self.assertTruelog_lines(lines) # This will flush because it's the 10th message since the last # flush. self.mem_logger.debug(self.next_message()) lines = lines + [('DEBUG', str(i)) for i in range(n, n + 10)] - self.assert_log_lines(lines) + self.assertTruelog_lines(lines) self.mem_logger.debug(self.next_message()) - self.assert_log_lines(lines) + self.assertTruelog_lines(lines) class ExceptionFormatter(logging.Formatter): @@ -650,11 +650,11 @@ class ConfigFileTest(BaseTest): logger.info(self.next_message()) # Outputs a message logger.error(self.next_message()) - self.assert_log_lines([ + self.assertTruelog_lines([ ('ERROR', '2'), ], stream=output) # Original logger output is empty. - self.assert_log_lines([]) + self.assertTruelog_lines([]) def test_config1_ok(self, config=config1): # A config file defining a sub-parser as well. @@ -664,12 +664,12 @@ class ConfigFileTest(BaseTest): # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) - self.assert_log_lines([ + self.assertTruelog_lines([ ('INFO', '1'), ('ERROR', '2'), ], stream=output) # Original logger output is empty. - self.assert_log_lines([]) + self.assertTruelog_lines([]) def test_config2_failure(self): # A simple config file which overrides the default settings. @@ -692,7 +692,7 @@ class ConfigFileTest(BaseTest): self.assertEquals(output.getvalue(), "ERROR:root:just testing\nGot a [RuntimeError]\n") # Original logger output is empty - self.assert_log_lines([]) + self.assertTruelog_lines([]) def test_config5_ok(self): self.test_config1_ok(config=self.config5) @@ -826,7 +826,7 @@ class MemoryTest(BaseTest): key = id(obj), repr(obj) self._survivors[key] = weakref.ref(obj) - def _assert_survival(self): + def _assertTruesurvival(self): """Assert that all objects watched for survival have survived.""" # Trigger cycle breaking. gc.collect() @@ -847,16 +847,16 @@ class MemoryTest(BaseTest): foo.setLevel(logging.DEBUG) self.root_logger.debug(self.next_message()) foo.debug(self.next_message()) - self.assert_log_lines([ + self.assertTruelog_lines([ ('foo', 'DEBUG', '2'), ]) del foo # foo has survived. - self._assert_survival() + self._assertTruesurvival() # foo has retained its settings. bar = logging.getLogger("foo") bar.debug(self.next_message()) - self.assert_log_lines([ + self.assertTruelog_lines([ ('foo', 'DEBUG', '2'), ('foo', 'DEBUG', '3'), ]) @@ -881,7 +881,7 @@ class EncodingTest(BaseTest): # check we wrote exactly those bytes, ignoring trailing \n etc f = open(fn) try: - self.failUnlessEqual(f.read().rstrip(), data) + self.assertEqual(f.read().rstrip(), data) finally: f.close() finally: diff --git a/Lib/test/test_long.py b/Lib/test/test_long.py index a20c3fc..1943518 100644 --- a/Lib/test/test_long.py +++ b/Lib/test/test_long.py @@ -88,7 +88,7 @@ class LongTest(unittest.TestCase): # The sign of the number is also random. def getran(self, ndigits): - self.assert_(ndigits > 0) + self.assertTrue(ndigits > 0) nbits_hi = ndigits * SHIFT nbits_lo = nbits_hi - SHIFT + 1 answer = 0L @@ -97,13 +97,13 @@ class LongTest(unittest.TestCase): while nbits < nbits_lo: bits = (r >> 1) + 1 bits = min(bits, nbits_hi - nbits) - self.assert_(1 <= bits <= SHIFT) + self.assertTrue(1 <= bits <= SHIFT) nbits = nbits + bits answer = answer << bits if r & 1: answer = answer | ((1 << bits) - 1) r = int(random.random() * (SHIFT * 2)) - self.assert_(nbits_lo <= nbits <= nbits_hi) + self.assertTrue(nbits_lo <= nbits <= nbits_hi) if random.random() < 0.5: answer = -answer return answer @@ -129,9 +129,9 @@ class LongTest(unittest.TestCase): eq(r, r2, Frm("divmod returns different mod than %% for %r and %r", x, y)) eq(x, q*y + r, Frm("x != q*y + r after divmod on x=%r, y=%r", x, y)) if y > 0: - self.assert_(0 <= r < y, Frm("bad mod from divmod on %r and %r", x, y)) + self.assertTrue(0 <= r < y, Frm("bad mod from divmod on %r and %r", x, y)) else: - self.assert_(y < r <= 0, Frm("bad mod from divmod on %r and %r", x, y)) + self.assertTrue(y < r <= 0, Frm("bad mod from divmod on %r and %r", x, y)) def test_division(self): digits = range(1, MAXDIGITS+1) + range(KARATSUBA_CUTOFF, @@ -552,7 +552,7 @@ class LongTest(unittest.TestCase): y = int(x) except OverflowError: self.fail("int(long(sys.maxint) + 1) mustn't overflow") - self.assert_(isinstance(y, long), + self.assertTrue(isinstance(y, long), "int(long(sys.maxint) + 1) should have returned long") x = hugeneg_aslong - 1 @@ -560,14 +560,14 @@ class LongTest(unittest.TestCase): y = int(x) except OverflowError: self.fail("int(long(-sys.maxint-1) - 1) mustn't overflow") - self.assert_(isinstance(y, long), + self.assertTrue(isinstance(y, long), "int(long(-sys.maxint-1) - 1) should have returned long") class long2(long): pass x = long2(1L<<100) y = int(x) - self.assert_(type(y) is long, + self.assertTrue(type(y) is long, "overflowing int conversion must return long not long subtype") # long -> Py_ssize_t conversion @@ -850,7 +850,7 @@ class LongTest(unittest.TestCase): self.assertEqual(k, len(bin(x).lstrip('-0b'))) # Behaviour as specified in the docs if x != 0: - self.assert_(2**(k-1) <= abs(x) < 2**k) + self.assertTrue(2**(k-1) <= abs(x) < 2**k) else: self.assertEqual(k, 0) # Alternative definition: x.bit_length() == 1 + floor(log_2(x)) diff --git a/Lib/test/test_macpath.py b/Lib/test/test_macpath.py index 2449b0a..4541eb9 100644 --- a/Lib/test/test_macpath.py +++ b/Lib/test/test_macpath.py @@ -6,26 +6,26 @@ import unittest class MacPathTestCase(unittest.TestCase): def test_abspath(self): - self.assert_(macpath.abspath("xx:yy") == "xx:yy") + self.assertTrue(macpath.abspath("xx:yy") == "xx:yy") def test_isabs(self): isabs = macpath.isabs - self.assert_(isabs("xx:yy")) - self.assert_(isabs("xx:yy:")) - self.assert_(isabs("xx:")) - self.failIf(isabs("foo")) - self.failIf(isabs(":foo")) - self.failIf(isabs(":foo:bar")) - self.failIf(isabs(":foo:bar:")) + self.assertTrue(isabs("xx:yy")) + self.assertTrue(isabs("xx:yy:")) + self.assertTrue(isabs("xx:")) + self.assertFalse(isabs("foo")) + self.assertFalse(isabs(":foo")) + self.assertFalse(isabs(":foo:bar")) + self.assertFalse(isabs(":foo:bar:")) def test_commonprefix(self): commonprefix = macpath.commonprefix - self.assert_(commonprefix(["home:swenson:spam", "home:swen:spam"]) + self.assertTrue(commonprefix(["home:swenson:spam", "home:swen:spam"]) == "home:swen") - self.assert_(commonprefix([":home:swen:spam", ":home:swen:eggs"]) + self.assertTrue(commonprefix([":home:swen:spam", ":home:swen:eggs"]) == ":home:swen:") - self.assert_(commonprefix([":home:swen:spam", ":home:swen:spam"]) + self.assertTrue(commonprefix([":home:swen:spam", ":home:swen:spam"]) == ":home:swen:spam") def test_split(self): diff --git a/Lib/test/test_mailbox.py b/Lib/test/test_mailbox.py index 6342676..26758a3 100644 --- a/Lib/test/test_mailbox.py +++ b/Lib/test/test_mailbox.py @@ -22,17 +22,17 @@ class TestBase(unittest.TestCase): def _check_sample(self, msg): # Inspect a mailbox.Message representation of the sample message - self.assert_(isinstance(msg, email.message.Message)) - self.assert_(isinstance(msg, mailbox.Message)) + self.assertTrue(isinstance(msg, email.message.Message)) + self.assertTrue(isinstance(msg, mailbox.Message)) for key, value in _sample_headers.iteritems(): - self.assert_(value in msg.get_all(key)) - self.assert_(msg.is_multipart()) - self.assert_(len(msg.get_payload()) == len(_sample_payloads)) + self.assertTrue(value in msg.get_all(key)) + self.assertTrue(msg.is_multipart()) + self.assertTrue(len(msg.get_payload()) == len(_sample_payloads)) for i, payload in enumerate(_sample_payloads): part = msg.get_payload(i) - self.assert_(isinstance(part, email.message.Message)) - self.assert_(not isinstance(part, mailbox.Message)) - self.assert_(part.get_payload() == payload) + self.assertTrue(isinstance(part, email.message.Message)) + self.assertTrue(not isinstance(part, mailbox.Message)) + self.assertTrue(part.get_payload() == payload) def _delete_recursively(self, target): # Delete a file or delete a directory recursively @@ -65,16 +65,16 @@ class TestMailbox(TestBase): # Add copies of a sample message keys = [] keys.append(self._box.add(self._template % 0)) - self.assert_(len(self._box) == 1) + self.assertTrue(len(self._box) == 1) keys.append(self._box.add(mailbox.Message(_sample_message))) - self.assert_(len(self._box) == 2) + self.assertTrue(len(self._box) == 2) keys.append(self._box.add(email.message_from_string(_sample_message))) - self.assert_(len(self._box) == 3) + self.assertTrue(len(self._box) == 3) keys.append(self._box.add(StringIO.StringIO(_sample_message))) - self.assert_(len(self._box) == 4) + self.assertTrue(len(self._box) == 4) keys.append(self._box.add(_sample_message)) - self.assert_(len(self._box) == 5) - self.assert_(self._box.get_string(keys[0]) == self._template % 0) + self.assertTrue(len(self._box) == 5) + self.assertTrue(self._box.get_string(keys[0]) == self._template % 0) for i in (1, 2, 3, 4): self._check_sample(self._box[keys[i]]) @@ -90,23 +90,23 @@ class TestMailbox(TestBase): # (Used by test_remove() and test_delitem().) key0 = self._box.add(self._template % 0) key1 = self._box.add(self._template % 1) - self.assert_(len(self._box) == 2) + self.assertTrue(len(self._box) == 2) method(key0) l = len(self._box) - self.assert_(l == 1, "actual l: %s" % l) + self.assertTrue(l == 1, "actual l: %s" % l) self.assertRaises(KeyError, lambda: self._box[key0]) self.assertRaises(KeyError, lambda: method(key0)) - self.assert_(self._box.get_string(key1) == self._template % 1) + self.assertTrue(self._box.get_string(key1) == self._template % 1) key2 = self._box.add(self._template % 2) - self.assert_(len(self._box) == 2) + self.assertTrue(len(self._box) == 2) method(key2) l = len(self._box) - self.assert_(l == 1, "actual l: %s" % l) + self.assertTrue(l == 1, "actual l: %s" % l) self.assertRaises(KeyError, lambda: self._box[key2]) self.assertRaises(KeyError, lambda: method(key2)) - self.assert_(self._box.get_string(key1) == self._template % 1) + self.assertTrue(self._box.get_string(key1) == self._template % 1) method(key1) - self.assert_(len(self._box) == 0) + self.assertTrue(len(self._box) == 0) self.assertRaises(KeyError, lambda: self._box[key1]) self.assertRaises(KeyError, lambda: method(key1)) @@ -114,35 +114,35 @@ class TestMailbox(TestBase): # Discard messages key0 = self._box.add(self._template % 0) key1 = self._box.add(self._template % 1) - self.assert_(len(self._box) == 2) + self.assertTrue(len(self._box) == 2) self._box.discard(key0) - self.assert_(len(self._box) == 1) + self.assertTrue(len(self._box) == 1) self.assertRaises(KeyError, lambda: self._box[key0]) self._box.discard(key0) - self.assert_(len(self._box) == 1) + self.assertTrue(len(self._box) == 1) self.assertRaises(KeyError, lambda: self._box[key0]) def test_get(self): # Retrieve messages using get() key0 = self._box.add(self._template % 0) msg = self._box.get(key0) - self.assert_(msg['from'] == 'foo') - self.assert_(msg.get_payload() == '0') - self.assert_(self._box.get('foo') is None) - self.assert_(self._box.get('foo', False) is False) + self.assertTrue(msg['from'] == 'foo') + self.assertTrue(msg.get_payload() == '0') + self.assertTrue(self._box.get('foo') is None) + self.assertTrue(self._box.get('foo', False) is False) self._box.close() self._box = self._factory(self._path, factory=rfc822.Message) key1 = self._box.add(self._template % 1) msg = self._box.get(key1) - self.assert_(msg['from'] == 'foo') - self.assert_(msg.fp.read() == '1') + self.assertTrue(msg['from'] == 'foo') + self.assertTrue(msg.fp.read() == '1') def test_getitem(self): # Retrieve message using __getitem__() key0 = self._box.add(self._template % 0) msg = self._box[key0] - self.assert_(msg['from'] == 'foo') - self.assert_(msg.get_payload() == '0') + self.assertTrue(msg['from'] == 'foo') + self.assertTrue(msg.get_payload() == '0') self.assertRaises(KeyError, lambda: self._box['foo']) self._box.discard(key0) self.assertRaises(KeyError, lambda: self._box[key0]) @@ -152,25 +152,25 @@ class TestMailbox(TestBase): key0 = self._box.add(self._template % 0) key1 = self._box.add(_sample_message) msg0 = self._box.get_message(key0) - self.assert_(isinstance(msg0, mailbox.Message)) - self.assert_(msg0['from'] == 'foo') - self.assert_(msg0.get_payload() == '0') + self.assertTrue(isinstance(msg0, mailbox.Message)) + self.assertTrue(msg0['from'] == 'foo') + self.assertTrue(msg0.get_payload() == '0') self._check_sample(self._box.get_message(key1)) def test_get_string(self): # Get string representations of messages key0 = self._box.add(self._template % 0) key1 = self._box.add(_sample_message) - self.assert_(self._box.get_string(key0) == self._template % 0) - self.assert_(self._box.get_string(key1) == _sample_message) + self.assertTrue(self._box.get_string(key0) == self._template % 0) + self.assertTrue(self._box.get_string(key1) == _sample_message) def test_get_file(self): # Get file representations of messages key0 = self._box.add(self._template % 0) key1 = self._box.add(_sample_message) - self.assert_(self._box.get_file(key0).read().replace(os.linesep, '\n') + self.assertTrue(self._box.get_file(key0).read().replace(os.linesep, '\n') == self._template % 0) - self.assert_(self._box.get_file(key1).read().replace(os.linesep, '\n') + self.assertTrue(self._box.get_file(key1).read().replace(os.linesep, '\n') == _sample_message) def test_iterkeys(self): @@ -221,15 +221,15 @@ class TestMailbox(TestBase): returned_keys.append(key) returned_values.append(value) if do_keys: - self.assert_(len(keys) == len(returned_keys)) - self.assert_(set(keys) == set(returned_keys)) + self.assertTrue(len(keys) == len(returned_keys)) + self.assertTrue(set(keys) == set(returned_keys)) if do_values: count = 0 for value in returned_values: - self.assert_(value['from'] == 'foo') - self.assert_(int(value.get_payload()) < repetitions) + self.assertTrue(value['from'] == 'foo') + self.assertTrue(int(value.get_payload()) < repetitions) count += 1 - self.assert_(len(values) == count) + self.assertTrue(len(values) == count) def test_has_key(self): # Check existence of keys using has_key() @@ -241,61 +241,61 @@ class TestMailbox(TestBase): def _test_has_key_or_contains(self, method): # (Used by test_has_key() and test_contains().) - self.assert_(not method('foo')) + self.assertTrue(not method('foo')) key0 = self._box.add(self._template % 0) - self.assert_(method(key0)) - self.assert_(not method('foo')) + self.assertTrue(method(key0)) + self.assertTrue(not method('foo')) key1 = self._box.add(self._template % 1) - self.assert_(method(key1)) - self.assert_(method(key0)) - self.assert_(not method('foo')) + self.assertTrue(method(key1)) + self.assertTrue(method(key0)) + self.assertTrue(not method('foo')) self._box.remove(key0) - self.assert_(not method(key0)) - self.assert_(method(key1)) - self.assert_(not method('foo')) + self.assertTrue(not method(key0)) + self.assertTrue(method(key1)) + self.assertTrue(not method('foo')) self._box.remove(key1) - self.assert_(not method(key1)) - self.assert_(not method(key0)) - self.assert_(not method('foo')) + self.assertTrue(not method(key1)) + self.assertTrue(not method(key0)) + self.assertTrue(not method('foo')) def test_len(self, repetitions=10): # Get message count keys = [] for i in xrange(repetitions): - self.assert_(len(self._box) == i) + self.assertTrue(len(self._box) == i) keys.append(self._box.add(self._template % i)) - self.assert_(len(self._box) == i + 1) + self.assertTrue(len(self._box) == i + 1) for i in xrange(repetitions): - self.assert_(len(self._box) == repetitions - i) + self.assertTrue(len(self._box) == repetitions - i) self._box.remove(keys[i]) - self.assert_(len(self._box) == repetitions - i - 1) + self.assertTrue(len(self._box) == repetitions - i - 1) def test_set_item(self): # Modify messages using __setitem__() key0 = self._box.add(self._template % 'original 0') - self.assert_(self._box.get_string(key0) == \ + self.assertTrue(self._box.get_string(key0) == \ self._template % 'original 0') key1 = self._box.add(self._template % 'original 1') - self.assert_(self._box.get_string(key1) == \ + self.assertTrue(self._box.get_string(key1) == \ self._template % 'original 1') self._box[key0] = self._template % 'changed 0' - self.assert_(self._box.get_string(key0) == \ + self.assertTrue(self._box.get_string(key0) == \ self._template % 'changed 0') self._box[key1] = self._template % 'changed 1' - self.assert_(self._box.get_string(key1) == \ + self.assertTrue(self._box.get_string(key1) == \ self._template % 'changed 1') self._box[key0] = _sample_message self._check_sample(self._box[key0]) self._box[key1] = self._box[key0] self._check_sample(self._box[key1]) self._box[key0] = self._template % 'original 0' - self.assert_(self._box.get_string(key0) == + self.assertTrue(self._box.get_string(key0) == self._template % 'original 0') self._check_sample(self._box[key1]) self.assertRaises(KeyError, lambda: self._box.__setitem__('foo', 'bar')) self.assertRaises(KeyError, lambda: self._box['foo']) - self.assert_(len(self._box) == 2) + self.assertTrue(len(self._box) == 2) def test_clear(self, iterations=10): # Remove all messages using clear() @@ -303,29 +303,29 @@ class TestMailbox(TestBase): for i in xrange(iterations): self._box.add(self._template % i) for i, key in enumerate(keys): - self.assert_(self._box.get_string(key) == self._template % i) + self.assertTrue(self._box.get_string(key) == self._template % i) self._box.clear() - self.assert_(len(self._box) == 0) + self.assertTrue(len(self._box) == 0) for i, key in enumerate(keys): self.assertRaises(KeyError, lambda: self._box.get_string(key)) def test_pop(self): # Get and remove a message using pop() key0 = self._box.add(self._template % 0) - self.assert_(key0 in self._box) + self.assertTrue(key0 in self._box) key1 = self._box.add(self._template % 1) - self.assert_(key1 in self._box) - self.assert_(self._box.pop(key0).get_payload() == '0') - self.assert_(key0 not in self._box) - self.assert_(key1 in self._box) + self.assertTrue(key1 in self._box) + self.assertTrue(self._box.pop(key0).get_payload() == '0') + self.assertTrue(key0 not in self._box) + self.assertTrue(key1 in self._box) key2 = self._box.add(self._template % 2) - self.assert_(key2 in self._box) - self.assert_(self._box.pop(key2).get_payload() == '2') - self.assert_(key2 not in self._box) - self.assert_(key1 in self._box) - self.assert_(self._box.pop(key1).get_payload() == '1') - self.assert_(key1 not in self._box) - self.assert_(len(self._box) == 0) + self.assertTrue(key2 in self._box) + self.assertTrue(self._box.pop(key2).get_payload() == '2') + self.assertTrue(key2 not in self._box) + self.assertTrue(key1 in self._box) + self.assertTrue(self._box.pop(key1).get_payload() == '1') + self.assertTrue(key1 not in self._box) + self.assertTrue(len(self._box) == 0) def test_popitem(self, iterations=10): # Get and remove an arbitrary (key, message) using popitem() @@ -335,11 +335,11 @@ class TestMailbox(TestBase): seen = [] for i in xrange(10): key, msg = self._box.popitem() - self.assert_(key in keys) - self.assert_(key not in seen) + self.assertTrue(key in keys) + self.assertTrue(key not in seen) seen.append(key) - self.assert_(int(msg.get_payload()) == keys.index(key)) - self.assert_(len(self._box) == 0) + self.assertTrue(int(msg.get_payload()) == keys.index(key)) + self.assertTrue(len(self._box) == 0) for key in keys: self.assertRaises(KeyError, lambda: self._box[key]) @@ -350,31 +350,31 @@ class TestMailbox(TestBase): key2 = self._box.add(self._template % 'original 2') self._box.update({key0: self._template % 'changed 0', key2: _sample_message}) - self.assert_(len(self._box) == 3) - self.assert_(self._box.get_string(key0) == + self.assertTrue(len(self._box) == 3) + self.assertTrue(self._box.get_string(key0) == self._template % 'changed 0') - self.assert_(self._box.get_string(key1) == + self.assertTrue(self._box.get_string(key1) == self._template % 'original 1') self._check_sample(self._box[key2]) self._box.update([(key2, self._template % 'changed 2'), (key1, self._template % 'changed 1'), (key0, self._template % 'original 0')]) - self.assert_(len(self._box) == 3) - self.assert_(self._box.get_string(key0) == + self.assertTrue(len(self._box) == 3) + self.assertTrue(self._box.get_string(key0) == self._template % 'original 0') - self.assert_(self._box.get_string(key1) == + self.assertTrue(self._box.get_string(key1) == self._template % 'changed 1') - self.assert_(self._box.get_string(key2) == + self.assertTrue(self._box.get_string(key2) == self._template % 'changed 2') self.assertRaises(KeyError, lambda: self._box.update({'foo': 'bar', key0: self._template % "changed 0"})) - self.assert_(len(self._box) == 3) - self.assert_(self._box.get_string(key0) == + self.assertTrue(len(self._box) == 3) + self.assertTrue(self._box.get_string(key0) == self._template % "changed 0") - self.assert_(self._box.get_string(key1) == + self.assertTrue(self._box.get_string(key1) == self._template % "changed 1") - self.assert_(self._box.get_string(key2) == + self.assertTrue(self._box.get_string(key2) == self._template % "changed 2") def test_flush(self): @@ -383,11 +383,11 @@ class TestMailbox(TestBase): def test_lock_unlock(self): # Lock and unlock the mailbox - self.assert_(not os.path.exists(self._get_lock_path())) + self.assertTrue(not os.path.exists(self._get_lock_path())) self._box.lock() - self.assert_(os.path.exists(self._get_lock_path())) + self.assertTrue(os.path.exists(self._get_lock_path())) self._box.unlock() - self.assert_(not os.path.exists(self._get_lock_path())) + self.assertTrue(not os.path.exists(self._get_lock_path())) def test_close(self): # Close mailbox and flush changes to disk @@ -403,9 +403,9 @@ class TestMailbox(TestBase): self._box.close() self._box = self._factory(self._path) keys = self._box.keys() - self.assert_(len(keys) == 3) + self.assertTrue(len(keys) == 3) for key in keys: - self.assert_(self._box.get_string(key) in contents) + self.assertTrue(self._box.get_string(key) in contents) def test_dump_message(self): # Write message representations to disk @@ -413,7 +413,7 @@ class TestMailbox(TestBase): _sample_message, StringIO.StringIO(_sample_message)): output = StringIO.StringIO() self._box._dump_message(input, output) - self.assert_(output.getvalue() == + self.assertTrue(output.getvalue() == _sample_message.replace('\n', os.linesep)) output = StringIO.StringIO() self.assertRaises(TypeError, @@ -474,7 +474,7 @@ class TestMaildir(TestMailbox): msg.set_subdir('cur') msg.set_info('foo') key = self._box.add(msg) - self.assert_(os.path.exists(os.path.join(self._path, 'cur', '%s%sfoo' % + self.assertTrue(os.path.exists(os.path.join(self._path, 'cur', '%s%sfoo' % (key, self._box.colon)))) def test_get_MM(self): @@ -484,9 +484,9 @@ class TestMaildir(TestMailbox): msg.set_flags('RF') key = self._box.add(msg) msg_returned = self._box.get_message(key) - self.assert_(isinstance(msg_returned, mailbox.MaildirMessage)) - self.assert_(msg_returned.get_subdir() == 'cur') - self.assert_(msg_returned.get_flags() == 'FR') + self.assertTrue(isinstance(msg_returned, mailbox.MaildirMessage)) + self.assertTrue(msg_returned.get_subdir() == 'cur') + self.assertTrue(msg_returned.get_flags() == 'FR') def test_set_MM(self): # Set with a MaildirMessage instance @@ -494,22 +494,22 @@ class TestMaildir(TestMailbox): msg0.set_flags('TP') key = self._box.add(msg0) msg_returned = self._box.get_message(key) - self.assert_(msg_returned.get_subdir() == 'new') - self.assert_(msg_returned.get_flags() == 'PT') + self.assertTrue(msg_returned.get_subdir() == 'new') + self.assertTrue(msg_returned.get_flags() == 'PT') msg1 = mailbox.MaildirMessage(self._template % 1) self._box[key] = msg1 msg_returned = self._box.get_message(key) - self.assert_(msg_returned.get_subdir() == 'new') - self.assert_(msg_returned.get_flags() == '') - self.assert_(msg_returned.get_payload() == '1') + self.assertTrue(msg_returned.get_subdir() == 'new') + self.assertTrue(msg_returned.get_flags() == '') + self.assertTrue(msg_returned.get_payload() == '1') msg2 = mailbox.MaildirMessage(self._template % 2) msg2.set_info('2,S') self._box[key] = msg2 self._box[key] = self._template % 3 msg_returned = self._box.get_message(key) - self.assert_(msg_returned.get_subdir() == 'new') - self.assert_(msg_returned.get_flags() == 'S') - self.assert_(msg_returned.get_payload() == '3') + self.assertTrue(msg_returned.get_subdir() == 'new') + self.assertTrue(msg_returned.get_flags() == 'S') + self.assertTrue(msg_returned.get_payload() == '3') def test_consistent_factory(self): # Add a message. @@ -524,7 +524,7 @@ class TestMaildir(TestMailbox): box = mailbox.Maildir(self._path, factory=FakeMessage) box.colon = self._box.colon msg2 = box.get_message(key) - self.assert_(isinstance(msg2, FakeMessage)) + self.assertTrue(isinstance(msg2, FakeMessage)) def test_initialize_new(self): # Initialize a non-existent mailbox @@ -552,15 +552,15 @@ class TestMaildir(TestMailbox): for subdir in '', 'tmp', 'new', 'cur': path = os.path.join(self._path, subdir) mode = os.stat(path)[stat.ST_MODE] - self.assert_(stat.S_ISDIR(mode), "Not a directory: '%s'" % path) + self.assertTrue(stat.S_ISDIR(mode), "Not a directory: '%s'" % path) def test_list_folders(self): # List folders self._box.add_folder('one') self._box.add_folder('two') self._box.add_folder('three') - self.assert_(len(self._box.list_folders()) == 3) - self.assert_(set(self._box.list_folders()) == + self.assertTrue(len(self._box.list_folders()) == 3) + self.assertTrue(set(self._box.list_folders()) == set(('one', 'two', 'three'))) def test_get_folder(self): @@ -568,29 +568,29 @@ class TestMaildir(TestMailbox): self._box.add_folder('foo.bar') folder0 = self._box.get_folder('foo.bar') folder0.add(self._template % 'bar') - self.assert_(os.path.isdir(os.path.join(self._path, '.foo.bar'))) + self.assertTrue(os.path.isdir(os.path.join(self._path, '.foo.bar'))) folder1 = self._box.get_folder('foo.bar') - self.assert_(folder1.get_string(folder1.keys()[0]) == \ + self.assertTrue(folder1.get_string(folder1.keys()[0]) == \ self._template % 'bar') def test_add_and_remove_folders(self): # Delete folders self._box.add_folder('one') self._box.add_folder('two') - self.assert_(len(self._box.list_folders()) == 2) - self.assert_(set(self._box.list_folders()) == set(('one', 'two'))) + self.assertTrue(len(self._box.list_folders()) == 2) + self.assertTrue(set(self._box.list_folders()) == set(('one', 'two'))) self._box.remove_folder('one') - self.assert_(len(self._box.list_folders()) == 1) - self.assert_(set(self._box.list_folders()) == set(('two',))) + self.assertTrue(len(self._box.list_folders()) == 1) + self.assertTrue(set(self._box.list_folders()) == set(('two',))) self._box.add_folder('three') - self.assert_(len(self._box.list_folders()) == 2) - self.assert_(set(self._box.list_folders()) == set(('two', 'three'))) + self.assertTrue(len(self._box.list_folders()) == 2) + self.assertTrue(set(self._box.list_folders()) == set(('two', 'three'))) self._box.remove_folder('three') - self.assert_(len(self._box.list_folders()) == 1) - self.assert_(set(self._box.list_folders()) == set(('two',))) + self.assertTrue(len(self._box.list_folders()) == 1) + self.assertTrue(set(self._box.list_folders()) == set(('two',))) self._box.remove_folder('two') - self.assert_(len(self._box.list_folders()) == 0) - self.assert_(self._box.list_folders() == []) + self.assertTrue(len(self._box.list_folders()) == 0) + self.assertTrue(self._box.list_folders() == []) def test_clean(self): # Remove old files from 'tmp' @@ -603,14 +603,14 @@ class TestMaildir(TestMailbox): f.write("@") f.close() self._box.clean() - self.assert_(os.path.exists(foo_path)) - self.assert_(os.path.exists(bar_path)) + self.assertTrue(os.path.exists(foo_path)) + self.assertTrue(os.path.exists(bar_path)) foo_stat = os.stat(foo_path) os.utime(foo_path, (time.time() - 129600 - 2, foo_stat.st_mtime)) self._box.clean() - self.assert_(not os.path.exists(foo_path)) - self.assert_(os.path.exists(bar_path)) + self.assertTrue(not os.path.exists(foo_path)) + self.assertTrue(os.path.exists(bar_path)) def test_create_tmp(self, repetitions=10): # Create files in tmp directory @@ -630,49 +630,49 @@ class TestMaildir(TestMailbox): "tmp")), "File in wrong location: '%s'" % head) match = pattern.match(tail) - self.assert_(match is not None, "Invalid file name: '%s'" % tail) + self.assertTrue(match is not None, "Invalid file name: '%s'" % tail) groups = match.groups() if previous_groups is not None: - self.assert_(int(groups[0] >= previous_groups[0]), + self.assertTrue(int(groups[0] >= previous_groups[0]), "Non-monotonic seconds: '%s' before '%s'" % (previous_groups[0], groups[0])) - self.assert_(int(groups[1] >= previous_groups[1]) or + self.assertTrue(int(groups[1] >= previous_groups[1]) or groups[0] != groups[1], "Non-monotonic milliseconds: '%s' before '%s'" % (previous_groups[1], groups[1])) - self.assert_(int(groups[2]) == pid, + self.assertTrue(int(groups[2]) == pid, "Process ID mismatch: '%s' should be '%s'" % (groups[2], pid)) - self.assert_(int(groups[3]) == int(previous_groups[3]) + 1, + self.assertTrue(int(groups[3]) == int(previous_groups[3]) + 1, "Non-sequential counter: '%s' before '%s'" % (previous_groups[3], groups[3])) - self.assert_(groups[4] == hostname, + self.assertTrue(groups[4] == hostname, "Host name mismatch: '%s' should be '%s'" % (groups[4], hostname)) previous_groups = groups tmp_file.write(_sample_message) tmp_file.seek(0) - self.assert_(tmp_file.read() == _sample_message) + self.assertTrue(tmp_file.read() == _sample_message) tmp_file.close() file_count = len(os.listdir(os.path.join(self._path, "tmp"))) - self.assert_(file_count == repetitions, + self.assertTrue(file_count == repetitions, "Wrong file count: '%s' should be '%s'" % (file_count, repetitions)) def test_refresh(self): # Update the table of contents - self.assert_(self._box._toc == {}) + self.assertTrue(self._box._toc == {}) key0 = self._box.add(self._template % 0) key1 = self._box.add(self._template % 1) - self.assert_(self._box._toc == {}) + self.assertTrue(self._box._toc == {}) self._box._refresh() - self.assert_(self._box._toc == {key0: os.path.join('new', key0), + self.assertTrue(self._box._toc == {key0: os.path.join('new', key0), key1: os.path.join('new', key1)}) key2 = self._box.add(self._template % 2) - self.assert_(self._box._toc == {key0: os.path.join('new', key0), + self.assertTrue(self._box._toc == {key0: os.path.join('new', key0), key1: os.path.join('new', key1)}) self._box._refresh() - self.assert_(self._box._toc == {key0: os.path.join('new', key0), + self.assertTrue(self._box._toc == {key0: os.path.join('new', key0), key1: os.path.join('new', key1), key2: os.path.join('new', key2)}) @@ -680,11 +680,11 @@ class TestMaildir(TestMailbox): # Look up message subpaths in the TOC self.assertRaises(KeyError, lambda: self._box._lookup('foo')) key0 = self._box.add(self._template % 0) - self.assert_(self._box._lookup(key0) == os.path.join('new', key0)) + self.assertTrue(self._box._lookup(key0) == os.path.join('new', key0)) os.remove(os.path.join(self._path, 'new', key0)) - self.assert_(self._box._toc == {key0: os.path.join('new', key0)}) + self.assertTrue(self._box._toc == {key0: os.path.join('new', key0)}) self.assertRaises(KeyError, lambda: self._box._lookup(key0)) - self.assert_(self._box._toc == {}) + self.assertTrue(self._box._toc == {}) def test_lock_unlock(self): # Lock and unlock the mailbox. For Maildir, this does nothing. @@ -698,10 +698,10 @@ class TestMaildir(TestMailbox): return None box = self._factory(self._path, factory=dummy_factory) folder = box.add_folder('folder1') - self.assert_(folder._factory is dummy_factory) + self.assertTrue(folder._factory is dummy_factory) folder1_alias = box.get_folder('folder1') - self.assert_(folder1_alias._factory is dummy_factory) + self.assertTrue(folder1_alias._factory is dummy_factory) def test_directory_in_folder (self): # Test that mailboxes still work if there's a stray extra directory @@ -728,7 +728,7 @@ class TestMaildir(TestMailbox): os.umask(orig_umask) path = os.path.join(self._path, self._box._lookup(key)) mode = os.stat(path).st_mode - self.assert_(mode & 0111 == 0) + self.assertTrue(mode & 0111 == 0) def test_folder_file_perms(self): # From bug #3228, we want to verify that the file created inside a Maildir @@ -790,8 +790,8 @@ class _TestMboxMMDF(TestMailbox): def test_add_from_string(self): # Add a string starting with 'From ' to the mailbox key = self._box.add('From foo@bar blah\nFrom: foo\n\n0') - self.assert_(self._box[key].get_from() == 'foo@bar blah') - self.assert_(self._box[key].get_payload() == '0') + self.assertTrue(self._box[key].get_from() == 'foo@bar blah') + self.assertTrue(self._box[key].get_payload() == '0') def test_add_mbox_or_mmdf_message(self): # Add an mboxMessage or MMDFMessage @@ -807,11 +807,11 @@ class _TestMboxMMDF(TestMailbox): self._box.close() mtime = os.path.getmtime(self._path) self._box = self._factory(self._path) - self.assert_(len(self._box) == 3) + self.assertTrue(len(self._box) == 3) for key in self._box.iterkeys(): - self.assert_(self._box.get_string(key) in values) + self.assertTrue(self._box.get_string(key) in values) self._box.close() - self.assert_(mtime == os.path.getmtime(self._path)) + self.assertTrue(mtime == os.path.getmtime(self._path)) def test_add_and_close(self): # Verifying that closing a mailbox doesn't change added items @@ -823,7 +823,7 @@ class _TestMboxMMDF(TestMailbox): self._box._file.seek(0) contents = self._box._file.read() self._box.close() - self.assert_(contents == open(self._path, 'rb').read()) + self.assertTrue(contents == open(self._path, 'rb').read()) self._box = self._factory(self._path) def test_lock_conflict(self): @@ -864,7 +864,7 @@ class _TestMboxMMDF(TestMailbox): self._box.lock() key2 = self._box.add(msg) self._box.flush() - self.assert_(self._box._locked) + self.assertTrue(self._box._locked) self._box.close() @@ -905,8 +905,8 @@ class TestMH(TestMailbox): self._box.add_folder('one') self._box.add_folder('two') self._box.add_folder('three') - self.assert_(len(self._box.list_folders()) == 3) - self.assert_(set(self._box.list_folders()) == + self.assertTrue(len(self._box.list_folders()) == 3) + self.assertTrue(set(self._box.list_folders()) == set(('one', 'two', 'three'))) def test_get_folder(self): @@ -918,54 +918,54 @@ class TestMH(TestMailbox): new_folder = self._box.add_folder('foo.bar') folder0 = self._box.get_folder('foo.bar') folder0.add(self._template % 'bar') - self.assert_(os.path.isdir(os.path.join(self._path, 'foo.bar'))) + self.assertTrue(os.path.isdir(os.path.join(self._path, 'foo.bar'))) folder1 = self._box.get_folder('foo.bar') - self.assert_(folder1.get_string(folder1.keys()[0]) == \ + self.assertTrue(folder1.get_string(folder1.keys()[0]) == \ self._template % 'bar') # Test for bug #1569790: verify that folders returned by .get_folder() # use the same factory function. - self.assert_(new_folder._factory is self._box._factory) - self.assert_(folder0._factory is self._box._factory) + self.assertTrue(new_folder._factory is self._box._factory) + self.assertTrue(folder0._factory is self._box._factory) def test_add_and_remove_folders(self): # Delete folders self._box.add_folder('one') self._box.add_folder('two') - self.assert_(len(self._box.list_folders()) == 2) - self.assert_(set(self._box.list_folders()) == set(('one', 'two'))) + self.assertTrue(len(self._box.list_folders()) == 2) + self.assertTrue(set(self._box.list_folders()) == set(('one', 'two'))) self._box.remove_folder('one') - self.assert_(len(self._box.list_folders()) == 1) - self.assert_(set(self._box.list_folders()) == set(('two',))) + self.assertTrue(len(self._box.list_folders()) == 1) + self.assertTrue(set(self._box.list_folders()) == set(('two',))) self._box.add_folder('three') - self.assert_(len(self._box.list_folders()) == 2) - self.assert_(set(self._box.list_folders()) == set(('two', 'three'))) + self.assertTrue(len(self._box.list_folders()) == 2) + self.assertTrue(set(self._box.list_folders()) == set(('two', 'three'))) self._box.remove_folder('three') - self.assert_(len(self._box.list_folders()) == 1) - self.assert_(set(self._box.list_folders()) == set(('two',))) + self.assertTrue(len(self._box.list_folders()) == 1) + self.assertTrue(set(self._box.list_folders()) == set(('two',))) self._box.remove_folder('two') - self.assert_(len(self._box.list_folders()) == 0) - self.assert_(self._box.list_folders() == []) + self.assertTrue(len(self._box.list_folders()) == 0) + self.assertTrue(self._box.list_folders() == []) def test_sequences(self): # Get and set sequences - self.assert_(self._box.get_sequences() == {}) + self.assertTrue(self._box.get_sequences() == {}) msg0 = mailbox.MHMessage(self._template % 0) msg0.add_sequence('foo') key0 = self._box.add(msg0) - self.assert_(self._box.get_sequences() == {'foo':[key0]}) + self.assertTrue(self._box.get_sequences() == {'foo':[key0]}) msg1 = mailbox.MHMessage(self._template % 1) msg1.set_sequences(['bar', 'replied', 'foo']) key1 = self._box.add(msg1) - self.assert_(self._box.get_sequences() == + self.assertTrue(self._box.get_sequences() == {'foo':[key0, key1], 'bar':[key1], 'replied':[key1]}) msg0.set_sequences(['flagged']) self._box[key0] = msg0 - self.assert_(self._box.get_sequences() == + self.assertTrue(self._box.get_sequences() == {'foo':[key1], 'bar':[key1], 'replied':[key1], 'flagged':[key0]}) self._box.remove(key1) - self.assert_(self._box.get_sequences() == {'flagged':[key0]}) + self.assertTrue(self._box.get_sequences() == {'flagged':[key0]}) def test_issue2625(self): msg0 = mailbox.MHMessage(self._template % 0) @@ -987,19 +987,19 @@ class TestMH(TestMailbox): key1 = self._box.add(msg1) key2 = self._box.add(msg2) key3 = self._box.add(msg3) - self.assert_(self._box.get_sequences() == + self.assertTrue(self._box.get_sequences() == {'foo':[key0,key1,key2,key3], 'unseen':[key0], 'flagged':[key2], 'bar':[key3], 'replied':[key3]}) self._box.remove(key2) - self.assert_(self._box.get_sequences() == + self.assertTrue(self._box.get_sequences() == {'foo':[key0,key1,key3], 'unseen':[key0], 'bar':[key3], 'replied':[key3]}) self._box.pack() - self.assert_(self._box.keys() == [1, 2, 3]) + self.assertTrue(self._box.keys() == [1, 2, 3]) key0 = key0 key1 = key0 + 1 key2 = key1 + 1 - self.assert_(self._box.get_sequences() == + self.assertTrue(self._box.get_sequences() == {'foo':[1, 2, 3], 'unseen':[1], 'bar':[3], 'replied':[3]}) # Test case for packing while holding the mailbox locked. @@ -1013,7 +1013,7 @@ class TestMH(TestMailbox): self._box.lock() self._box.pack() self._box.unlock() - self.assert_(self._box.get_sequences() == + self.assertTrue(self._box.get_sequences() == {'foo':[1, 2, 3, 4, 5], 'unseen':[1], 'bar':[3], 'replied':[3]}) @@ -1033,21 +1033,21 @@ class TestBabyl(TestMailbox): def test_labels(self): # Get labels from the mailbox - self.assert_(self._box.get_labels() == []) + self.assertTrue(self._box.get_labels() == []) msg0 = mailbox.BabylMessage(self._template % 0) msg0.add_label('foo') key0 = self._box.add(msg0) - self.assert_(self._box.get_labels() == ['foo']) + self.assertTrue(self._box.get_labels() == ['foo']) msg1 = mailbox.BabylMessage(self._template % 1) msg1.set_labels(['bar', 'answered', 'foo']) key1 = self._box.add(msg1) - self.assert_(set(self._box.get_labels()) == set(['foo', 'bar'])) + self.assertTrue(set(self._box.get_labels()) == set(['foo', 'bar'])) msg0.set_labels(['blah', 'filed']) self._box[key0] = msg0 - self.assert_(set(self._box.get_labels()) == + self.assertTrue(set(self._box.get_labels()) == set(['foo', 'bar', 'blah'])) self._box.remove(key1) - self.assert_(set(self._box.get_labels()) == set(['blah'])) + self.assertTrue(set(self._box.get_labels()) == set(['blah'])) class TestMessage(TestBase): @@ -1087,12 +1087,12 @@ class TestMessage(TestBase): # Initialize without arguments msg = self._factory() self._post_initialize_hook(msg) - self.assert_(isinstance(msg, email.message.Message)) - self.assert_(isinstance(msg, mailbox.Message)) - self.assert_(isinstance(msg, self._factory)) - self.assert_(msg.keys() == []) - self.assert_(not msg.is_multipart()) - self.assert_(msg.get_payload() == None) + self.assertTrue(isinstance(msg, email.message.Message)) + self.assertTrue(isinstance(msg, mailbox.Message)) + self.assertTrue(isinstance(msg, self._factory)) + self.assertTrue(msg.keys() == []) + self.assertTrue(not msg.is_multipart()) + self.assertTrue(msg.get_payload() == None) def test_initialize_incorrectly(self): # Initialize with invalid argument @@ -1127,72 +1127,72 @@ class TestMaildirMessage(TestMessage): _factory = mailbox.MaildirMessage def _post_initialize_hook(self, msg): - self.assert_(msg._subdir == 'new') - self.assert_(msg._info == '') + self.assertTrue(msg._subdir == 'new') + self.assertTrue(msg._info == '') def test_subdir(self): # Use get_subdir() and set_subdir() msg = mailbox.MaildirMessage(_sample_message) - self.assert_(msg.get_subdir() == 'new') + self.assertTrue(msg.get_subdir() == 'new') msg.set_subdir('cur') - self.assert_(msg.get_subdir() == 'cur') + self.assertTrue(msg.get_subdir() == 'cur') msg.set_subdir('new') - self.assert_(msg.get_subdir() == 'new') + self.assertTrue(msg.get_subdir() == 'new') self.assertRaises(ValueError, lambda: msg.set_subdir('tmp')) - self.assert_(msg.get_subdir() == 'new') + self.assertTrue(msg.get_subdir() == 'new') msg.set_subdir('new') - self.assert_(msg.get_subdir() == 'new') + self.assertTrue(msg.get_subdir() == 'new') self._check_sample(msg) def test_flags(self): # Use get_flags(), set_flags(), add_flag(), remove_flag() msg = mailbox.MaildirMessage(_sample_message) - self.assert_(msg.get_flags() == '') - self.assert_(msg.get_subdir() == 'new') + self.assertTrue(msg.get_flags() == '') + self.assertTrue(msg.get_subdir() == 'new') msg.set_flags('F') - self.assert_(msg.get_subdir() == 'new') - self.assert_(msg.get_flags() == 'F') + self.assertTrue(msg.get_subdir() == 'new') + self.assertTrue(msg.get_flags() == 'F') msg.set_flags('SDTP') - self.assert_(msg.get_flags() == 'DPST') + self.assertTrue(msg.get_flags() == 'DPST') msg.add_flag('FT') - self.assert_(msg.get_flags() == 'DFPST') + self.assertTrue(msg.get_flags() == 'DFPST') msg.remove_flag('TDRP') - self.assert_(msg.get_flags() == 'FS') - self.assert_(msg.get_subdir() == 'new') + self.assertTrue(msg.get_flags() == 'FS') + self.assertTrue(msg.get_subdir() == 'new') self._check_sample(msg) def test_date(self): # Use get_date() and set_date() msg = mailbox.MaildirMessage(_sample_message) - self.assert_(abs(msg.get_date() - time.time()) < 60) + self.assertTrue(abs(msg.get_date() - time.time()) < 60) msg.set_date(0.0) - self.assert_(msg.get_date() == 0.0) + self.assertTrue(msg.get_date() == 0.0) def test_info(self): # Use get_info() and set_info() msg = mailbox.MaildirMessage(_sample_message) - self.assert_(msg.get_info() == '') + self.assertTrue(msg.get_info() == '') msg.set_info('1,foo=bar') - self.assert_(msg.get_info() == '1,foo=bar') + self.assertTrue(msg.get_info() == '1,foo=bar') self.assertRaises(TypeError, lambda: msg.set_info(None)) self._check_sample(msg) def test_info_and_flags(self): # Test interaction of info and flag methods msg = mailbox.MaildirMessage(_sample_message) - self.assert_(msg.get_info() == '') + self.assertTrue(msg.get_info() == '') msg.set_flags('SF') - self.assert_(msg.get_flags() == 'FS') - self.assert_(msg.get_info() == '2,FS') + self.assertTrue(msg.get_flags() == 'FS') + self.assertTrue(msg.get_info() == '2,FS') msg.set_info('1,') - self.assert_(msg.get_flags() == '') - self.assert_(msg.get_info() == '1,') + self.assertTrue(msg.get_flags() == '') + self.assertTrue(msg.get_info() == '1,') msg.remove_flag('RPT') - self.assert_(msg.get_flags() == '') - self.assert_(msg.get_info() == '1,') + self.assertTrue(msg.get_flags() == '') + self.assertTrue(msg.get_info() == '1,') msg.add_flag('D') - self.assert_(msg.get_flags() == 'D') - self.assert_(msg.get_info() == '2,D') + self.assertTrue(msg.get_flags() == 'D') + self.assertTrue(msg.get_info() == '2,D') self._check_sample(msg) @@ -1208,14 +1208,14 @@ class _TestMboxMMDFMessage(TestMessage): msg = mailbox.Message(_sample_message) msg.set_unixfrom('From foo@bar blah') msg = mailbox.mboxMessage(msg) - self.assert_(msg.get_from() == 'foo@bar blah', msg.get_from()) + self.assertTrue(msg.get_from() == 'foo@bar blah', msg.get_from()) def test_from(self): # Get and set "From " line msg = mailbox.mboxMessage(_sample_message) self._check_from(msg) msg.set_from('foo bar') - self.assert_(msg.get_from() == 'foo bar') + self.assertTrue(msg.get_from() == 'foo bar') msg.set_from('foo@bar', True) self._check_from(msg, 'foo@bar') msg.set_from('blah@temp', time.localtime()) @@ -1224,22 +1224,22 @@ class _TestMboxMMDFMessage(TestMessage): def test_flags(self): # Use get_flags(), set_flags(), add_flag(), remove_flag() msg = mailbox.mboxMessage(_sample_message) - self.assert_(msg.get_flags() == '') + self.assertTrue(msg.get_flags() == '') msg.set_flags('F') - self.assert_(msg.get_flags() == 'F') + self.assertTrue(msg.get_flags() == 'F') msg.set_flags('XODR') - self.assert_(msg.get_flags() == 'RODX') + self.assertTrue(msg.get_flags() == 'RODX') msg.add_flag('FA') - self.assert_(msg.get_flags() == 'RODFAX') + self.assertTrue(msg.get_flags() == 'RODFAX') msg.remove_flag('FDXA') - self.assert_(msg.get_flags() == 'RO') + self.assertTrue(msg.get_flags() == 'RO') self._check_sample(msg) def _check_from(self, msg, sender=None): # Check contents of "From " line if sender is None: sender = "MAILER-DAEMON" - self.assert_(re.match(sender + r" \w{3} \w{3} [\d ]\d [\d ]\d:\d{2}:" + self.assertTrue(re.match(sender + r" \w{3} \w{3} [\d ]\d [\d ]\d:\d{2}:" r"\d{2} \d{4}", msg.get_from()) is not None) @@ -1253,30 +1253,30 @@ class TestMHMessage(TestMessage): _factory = mailbox.MHMessage def _post_initialize_hook(self, msg): - self.assert_(msg._sequences == []) + self.assertTrue(msg._sequences == []) def test_sequences(self): # Get, set, join, and leave sequences msg = mailbox.MHMessage(_sample_message) - self.assert_(msg.get_sequences() == []) + self.assertTrue(msg.get_sequences() == []) msg.set_sequences(['foobar']) - self.assert_(msg.get_sequences() == ['foobar']) + self.assertTrue(msg.get_sequences() == ['foobar']) msg.set_sequences([]) - self.assert_(msg.get_sequences() == []) + self.assertTrue(msg.get_sequences() == []) msg.add_sequence('unseen') - self.assert_(msg.get_sequences() == ['unseen']) + self.assertTrue(msg.get_sequences() == ['unseen']) msg.add_sequence('flagged') - self.assert_(msg.get_sequences() == ['unseen', 'flagged']) + self.assertTrue(msg.get_sequences() == ['unseen', 'flagged']) msg.add_sequence('flagged') - self.assert_(msg.get_sequences() == ['unseen', 'flagged']) + self.assertTrue(msg.get_sequences() == ['unseen', 'flagged']) msg.remove_sequence('unseen') - self.assert_(msg.get_sequences() == ['flagged']) + self.assertTrue(msg.get_sequences() == ['flagged']) msg.add_sequence('foobar') - self.assert_(msg.get_sequences() == ['flagged', 'foobar']) + self.assertTrue(msg.get_sequences() == ['flagged', 'foobar']) msg.remove_sequence('replied') - self.assert_(msg.get_sequences() == ['flagged', 'foobar']) + self.assertTrue(msg.get_sequences() == ['flagged', 'foobar']) msg.set_sequences(['foobar', 'replied']) - self.assert_(msg.get_sequences() == ['foobar', 'replied']) + self.assertTrue(msg.get_sequences() == ['foobar', 'replied']) class TestBabylMessage(TestMessage): @@ -1284,54 +1284,54 @@ class TestBabylMessage(TestMessage): _factory = mailbox.BabylMessage def _post_initialize_hook(self, msg): - self.assert_(msg._labels == []) + self.assertTrue(msg._labels == []) def test_labels(self): # Get, set, join, and leave labels msg = mailbox.BabylMessage(_sample_message) - self.assert_(msg.get_labels() == []) + self.assertTrue(msg.get_labels() == []) msg.set_labels(['foobar']) - self.assert_(msg.get_labels() == ['foobar']) + self.assertTrue(msg.get_labels() == ['foobar']) msg.set_labels([]) - self.assert_(msg.get_labels() == []) + self.assertTrue(msg.get_labels() == []) msg.add_label('filed') - self.assert_(msg.get_labels() == ['filed']) + self.assertTrue(msg.get_labels() == ['filed']) msg.add_label('resent') - self.assert_(msg.get_labels() == ['filed', 'resent']) + self.assertTrue(msg.get_labels() == ['filed', 'resent']) msg.add_label('resent') - self.assert_(msg.get_labels() == ['filed', 'resent']) + self.assertTrue(msg.get_labels() == ['filed', 'resent']) msg.remove_label('filed') - self.assert_(msg.get_labels() == ['resent']) + self.assertTrue(msg.get_labels() == ['resent']) msg.add_label('foobar') - self.assert_(msg.get_labels() == ['resent', 'foobar']) + self.assertTrue(msg.get_labels() == ['resent', 'foobar']) msg.remove_label('unseen') - self.assert_(msg.get_labels() == ['resent', 'foobar']) + self.assertTrue(msg.get_labels() == ['resent', 'foobar']) msg.set_labels(['foobar', 'answered']) - self.assert_(msg.get_labels() == ['foobar', 'answered']) + self.assertTrue(msg.get_labels() == ['foobar', 'answered']) def test_visible(self): # Get, set, and update visible headers msg = mailbox.BabylMessage(_sample_message) visible = msg.get_visible() - self.assert_(visible.keys() == []) - self.assert_(visible.get_payload() is None) + self.assertTrue(visible.keys() == []) + self.assertTrue(visible.get_payload() is None) visible['User-Agent'] = 'FooBar 1.0' visible['X-Whatever'] = 'Blah' - self.assert_(msg.get_visible().keys() == []) + self.assertTrue(msg.get_visible().keys() == []) msg.set_visible(visible) visible = msg.get_visible() - self.assert_(visible.keys() == ['User-Agent', 'X-Whatever']) - self.assert_(visible['User-Agent'] == 'FooBar 1.0') - self.assert_(visible['X-Whatever'] == 'Blah') - self.assert_(visible.get_payload() is None) + self.assertTrue(visible.keys() == ['User-Agent', 'X-Whatever']) + self.assertTrue(visible['User-Agent'] == 'FooBar 1.0') + self.assertTrue(visible['X-Whatever'] == 'Blah') + self.assertTrue(visible.get_payload() is None) msg.update_visible() - self.assert_(visible.keys() == ['User-Agent', 'X-Whatever']) - self.assert_(visible.get_payload() is None) + self.assertTrue(visible.keys() == ['User-Agent', 'X-Whatever']) + self.assertTrue(visible.get_payload() is None) visible = msg.get_visible() - self.assert_(visible.keys() == ['User-Agent', 'Date', 'From', 'To', + self.assertTrue(visible.keys() == ['User-Agent', 'Date', 'From', 'To', 'Subject']) for header in ('User-Agent', 'Date', 'From', 'To', 'Subject'): - self.assert_(visible[header] == msg[header]) + self.assertTrue(visible[header] == msg[header]) class TestMMDFMessage(_TestMboxMMDFMessage): @@ -1374,9 +1374,9 @@ class TestMessageConversion(TestBase): date = msg_maildir.get_date() msg = mailbox.MaildirMessage(msg_maildir) self._check_sample(msg) - self.assert_(msg.get_flags() == 'DFPRST') - self.assert_(msg.get_subdir() == 'cur') - self.assert_(msg.get_date() == date) + self.assertTrue(msg.get_flags() == 'DFPRST') + self.assertTrue(msg.get_subdir() == 'cur') + self.assertTrue(msg.get_date() == date) def test_maildir_to_mboxmmdf(self): # Convert MaildirMessage to mboxmessage and MMDFMessage @@ -1388,11 +1388,11 @@ class TestMessageConversion(TestBase): for setting, result in pairs: msg_maildir.set_flags(setting) msg = class_(msg_maildir) - self.assert_(msg.get_flags() == result) - self.assert_(msg.get_from() == 'MAILER-DAEMON %s' % + self.assertTrue(msg.get_flags() == result) + self.assertTrue(msg.get_from() == 'MAILER-DAEMON %s' % time.asctime(time.gmtime(0.0))) msg_maildir.set_subdir('cur') - self.assert_(class_(msg_maildir).get_flags() == 'RODFA') + self.assertTrue(class_(msg_maildir).get_flags() == 'RODFA') def test_maildir_to_mh(self): # Convert MaildirMessage to MHMessage @@ -1402,7 +1402,7 @@ class TestMessageConversion(TestBase): ('T', ['unseen']), ('DFPRST', ['replied', 'flagged'])) for setting, result in pairs: msg_maildir.set_flags(setting) - self.assert_(mailbox.MHMessage(msg_maildir).get_sequences() == \ + self.assertTrue(mailbox.MHMessage(msg_maildir).get_sequences() == \ result) def test_maildir_to_babyl(self): @@ -1414,7 +1414,7 @@ class TestMessageConversion(TestBase): ('DFPRST', ['deleted', 'answered', 'forwarded'])) for setting, result in pairs: msg_maildir.set_flags(setting) - self.assert_(mailbox.BabylMessage(msg_maildir).get_labels() == \ + self.assertTrue(mailbox.BabylMessage(msg_maildir).get_labels() == \ result) def test_mboxmmdf_to_maildir(self): @@ -1427,10 +1427,10 @@ class TestMessageConversion(TestBase): for setting, result in pairs: msg_mboxMMDF.set_flags(setting) msg = mailbox.MaildirMessage(msg_mboxMMDF) - self.assert_(msg.get_flags() == result) - self.assert_(msg.get_date() == 0.0, msg.get_date()) + self.assertTrue(msg.get_flags() == result) + self.assertTrue(msg.get_date() == 0.0, msg.get_date()) msg_mboxMMDF.set_flags('O') - self.assert_(mailbox.MaildirMessage(msg_mboxMMDF).get_subdir() == \ + self.assertTrue(mailbox.MaildirMessage(msg_mboxMMDF).get_subdir() == \ 'cur') def test_mboxmmdf_to_mboxmmdf(self): @@ -1441,8 +1441,8 @@ class TestMessageConversion(TestBase): msg_mboxMMDF.set_from('foo@bar') for class2_ in (mailbox.mboxMessage, mailbox.MMDFMessage): msg2 = class2_(msg_mboxMMDF) - self.assert_(msg2.get_flags() == 'RODFA') - self.assert_(msg2.get_from() == 'foo@bar') + self.assertTrue(msg2.get_flags() == 'RODFA') + self.assertTrue(msg2.get_from() == 'foo@bar') def test_mboxmmdf_to_mh(self): # Convert mboxMessage and MMDFMessage to MHMessage @@ -1454,7 +1454,7 @@ class TestMessageConversion(TestBase): ('RODFA', ['replied', 'flagged'])) for setting, result in pairs: msg_mboxMMDF.set_flags(setting) - self.assert_(mailbox.MHMessage(msg_mboxMMDF).get_sequences() \ + self.assertTrue(mailbox.MHMessage(msg_mboxMMDF).get_sequences() \ == result) def test_mboxmmdf_to_babyl(self): @@ -1467,7 +1467,7 @@ class TestMessageConversion(TestBase): ('RODFA', ['deleted', 'answered'])) for setting, result in pairs: msg.set_flags(setting) - self.assert_(mailbox.BabylMessage(msg).get_labels() == result) + self.assertTrue(mailbox.BabylMessage(msg).get_labels() == result) def test_mh_to_maildir(self): # Convert MHMessage to MaildirMessage @@ -1475,14 +1475,14 @@ class TestMessageConversion(TestBase): for setting, result in pairs: msg = mailbox.MHMessage(_sample_message) msg.add_sequence(setting) - self.assert_(mailbox.MaildirMessage(msg).get_flags() == result) - self.assert_(mailbox.MaildirMessage(msg).get_subdir() == 'cur') + self.assertTrue(mailbox.MaildirMessage(msg).get_flags() == result) + self.assertTrue(mailbox.MaildirMessage(msg).get_subdir() == 'cur') msg = mailbox.MHMessage(_sample_message) msg.add_sequence('unseen') msg.add_sequence('replied') msg.add_sequence('flagged') - self.assert_(mailbox.MaildirMessage(msg).get_flags() == 'FR') - self.assert_(mailbox.MaildirMessage(msg).get_subdir() == 'cur') + self.assertTrue(mailbox.MaildirMessage(msg).get_flags() == 'FR') + self.assertTrue(mailbox.MaildirMessage(msg).get_subdir() == 'cur') def test_mh_to_mboxmmdf(self): # Convert MHMessage to mboxMessage and MMDFMessage @@ -1491,13 +1491,13 @@ class TestMessageConversion(TestBase): msg = mailbox.MHMessage(_sample_message) msg.add_sequence(setting) for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage): - self.assert_(class_(msg).get_flags() == result) + self.assertTrue(class_(msg).get_flags() == result) msg = mailbox.MHMessage(_sample_message) msg.add_sequence('unseen') msg.add_sequence('replied') msg.add_sequence('flagged') for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage): - self.assert_(class_(msg).get_flags() == 'OFA') + self.assertTrue(class_(msg).get_flags() == 'OFA') def test_mh_to_mh(self): # Convert MHMessage to MHMessage @@ -1505,7 +1505,7 @@ class TestMessageConversion(TestBase): msg.add_sequence('unseen') msg.add_sequence('replied') msg.add_sequence('flagged') - self.assert_(mailbox.MHMessage(msg).get_sequences() == \ + self.assertTrue(mailbox.MHMessage(msg).get_sequences() == \ ['unseen', 'replied', 'flagged']) def test_mh_to_babyl(self): @@ -1515,12 +1515,12 @@ class TestMessageConversion(TestBase): for setting, result in pairs: msg = mailbox.MHMessage(_sample_message) msg.add_sequence(setting) - self.assert_(mailbox.BabylMessage(msg).get_labels() == result) + self.assertTrue(mailbox.BabylMessage(msg).get_labels() == result) msg = mailbox.MHMessage(_sample_message) msg.add_sequence('unseen') msg.add_sequence('replied') msg.add_sequence('flagged') - self.assert_(mailbox.BabylMessage(msg).get_labels() == \ + self.assertTrue(mailbox.BabylMessage(msg).get_labels() == \ ['unseen', 'answered']) def test_babyl_to_maildir(self): @@ -1531,14 +1531,14 @@ class TestMessageConversion(TestBase): for setting, result in pairs: msg = mailbox.BabylMessage(_sample_message) msg.add_label(setting) - self.assert_(mailbox.MaildirMessage(msg).get_flags() == result) - self.assert_(mailbox.MaildirMessage(msg).get_subdir() == 'cur') + self.assertTrue(mailbox.MaildirMessage(msg).get_flags() == result) + self.assertTrue(mailbox.MaildirMessage(msg).get_subdir() == 'cur') msg = mailbox.BabylMessage(_sample_message) for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded', 'edited', 'resent'): msg.add_label(label) - self.assert_(mailbox.MaildirMessage(msg).get_flags() == 'PRT') - self.assert_(mailbox.MaildirMessage(msg).get_subdir() == 'cur') + self.assertTrue(mailbox.MaildirMessage(msg).get_flags() == 'PRT') + self.assertTrue(mailbox.MaildirMessage(msg).get_subdir() == 'cur') def test_babyl_to_mboxmmdf(self): # Convert BabylMessage to mboxMessage and MMDFMessage @@ -1549,13 +1549,13 @@ class TestMessageConversion(TestBase): for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage): msg = mailbox.BabylMessage(_sample_message) msg.add_label(setting) - self.assert_(class_(msg).get_flags() == result) + self.assertTrue(class_(msg).get_flags() == result) msg = mailbox.BabylMessage(_sample_message) for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded', 'edited', 'resent'): msg.add_label(label) for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage): - self.assert_(class_(msg).get_flags() == 'ODA') + self.assertTrue(class_(msg).get_flags() == 'ODA') def test_babyl_to_mh(self): # Convert BabylMessage to MHMessage @@ -1565,12 +1565,12 @@ class TestMessageConversion(TestBase): for setting, result in pairs: msg = mailbox.BabylMessage(_sample_message) msg.add_label(setting) - self.assert_(mailbox.MHMessage(msg).get_sequences() == result) + self.assertTrue(mailbox.MHMessage(msg).get_sequences() == result) msg = mailbox.BabylMessage(_sample_message) for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded', 'edited', 'resent'): msg.add_label(label) - self.assert_(mailbox.MHMessage(msg).get_sequences() == \ + self.assertTrue(mailbox.MHMessage(msg).get_sequences() == \ ['unseen', 'replied']) def test_babyl_to_babyl(self): @@ -1581,12 +1581,12 @@ class TestMessageConversion(TestBase): 'edited', 'resent'): msg.add_label(label) msg2 = mailbox.BabylMessage(msg) - self.assert_(msg2.get_labels() == ['unseen', 'deleted', 'filed', + self.assertTrue(msg2.get_labels() == ['unseen', 'deleted', 'filed', 'answered', 'forwarded', 'edited', 'resent']) - self.assert_(msg.get_visible().keys() == msg2.get_visible().keys()) + self.assertTrue(msg.get_visible().keys() == msg2.get_visible().keys()) for key in msg.get_visible().keys(): - self.assert_(msg.get_visible()[key] == msg2.get_visible()[key]) + self.assertTrue(msg.get_visible()[key] == msg2.get_visible()[key]) class TestProxyFileBase(TestBase): @@ -1594,69 +1594,69 @@ class TestProxyFileBase(TestBase): def _test_read(self, proxy): # Read by byte proxy.seek(0) - self.assert_(proxy.read() == 'bar') + self.assertTrue(proxy.read() == 'bar') proxy.seek(1) - self.assert_(proxy.read() == 'ar') + self.assertTrue(proxy.read() == 'ar') proxy.seek(0) - self.assert_(proxy.read(2) == 'ba') + self.assertTrue(proxy.read(2) == 'ba') proxy.seek(1) - self.assert_(proxy.read(-1) == 'ar') + self.assertTrue(proxy.read(-1) == 'ar') proxy.seek(2) - self.assert_(proxy.read(1000) == 'r') + self.assertTrue(proxy.read(1000) == 'r') def _test_readline(self, proxy): # Read by line proxy.seek(0) - self.assert_(proxy.readline() == 'foo' + os.linesep) - self.assert_(proxy.readline() == 'bar' + os.linesep) - self.assert_(proxy.readline() == 'fred' + os.linesep) - self.assert_(proxy.readline() == 'bob') + self.assertTrue(proxy.readline() == 'foo' + os.linesep) + self.assertTrue(proxy.readline() == 'bar' + os.linesep) + self.assertTrue(proxy.readline() == 'fred' + os.linesep) + self.assertTrue(proxy.readline() == 'bob') proxy.seek(2) - self.assert_(proxy.readline() == 'o' + os.linesep) + self.assertTrue(proxy.readline() == 'o' + os.linesep) proxy.seek(6 + 2 * len(os.linesep)) - self.assert_(proxy.readline() == 'fred' + os.linesep) + self.assertTrue(proxy.readline() == 'fred' + os.linesep) proxy.seek(6 + 2 * len(os.linesep)) - self.assert_(proxy.readline(2) == 'fr') - self.assert_(proxy.readline(-10) == 'ed' + os.linesep) + self.assertTrue(proxy.readline(2) == 'fr') + self.assertTrue(proxy.readline(-10) == 'ed' + os.linesep) def _test_readlines(self, proxy): # Read multiple lines proxy.seek(0) - self.assert_(proxy.readlines() == ['foo' + os.linesep, + self.assertTrue(proxy.readlines() == ['foo' + os.linesep, 'bar' + os.linesep, 'fred' + os.linesep, 'bob']) proxy.seek(0) - self.assert_(proxy.readlines(2) == ['foo' + os.linesep]) + self.assertTrue(proxy.readlines(2) == ['foo' + os.linesep]) proxy.seek(3 + len(os.linesep)) - self.assert_(proxy.readlines(4 + len(os.linesep)) == + self.assertTrue(proxy.readlines(4 + len(os.linesep)) == ['bar' + os.linesep, 'fred' + os.linesep]) proxy.seek(3) - self.assert_(proxy.readlines(1000) == [os.linesep, 'bar' + os.linesep, + self.assertTrue(proxy.readlines(1000) == [os.linesep, 'bar' + os.linesep, 'fred' + os.linesep, 'bob']) def _test_iteration(self, proxy): # Iterate by line proxy.seek(0) iterator = iter(proxy) - self.assert_(iterator.next() == 'foo' + os.linesep) - self.assert_(iterator.next() == 'bar' + os.linesep) - self.assert_(iterator.next() == 'fred' + os.linesep) - self.assert_(iterator.next() == 'bob') + self.assertTrue(iterator.next() == 'foo' + os.linesep) + self.assertTrue(iterator.next() == 'bar' + os.linesep) + self.assertTrue(iterator.next() == 'fred' + os.linesep) + self.assertTrue(iterator.next() == 'bob') self.assertRaises(StopIteration, lambda: iterator.next()) def _test_seek_and_tell(self, proxy): # Seek and use tell to check position proxy.seek(3) - self.assert_(proxy.tell() == 3) - self.assert_(proxy.read(len(os.linesep)) == os.linesep) + self.assertTrue(proxy.tell() == 3) + self.assertTrue(proxy.read(len(os.linesep)) == os.linesep) proxy.seek(2, 1) - self.assert_(proxy.read(1 + len(os.linesep)) == 'r' + os.linesep) + self.assertTrue(proxy.read(1 + len(os.linesep)) == 'r' + os.linesep) proxy.seek(-3 - len(os.linesep), 2) - self.assert_(proxy.read(3) == 'bar') + self.assertTrue(proxy.read(3) == 'bar') proxy.seek(2, 0) - self.assert_(proxy.read() == 'o' + os.linesep + 'bar' + os.linesep) + self.assertTrue(proxy.read() == 'o' + os.linesep + 'bar' + os.linesep) proxy.seek(100) - self.assert_(proxy.read() == '') + self.assertTrue(proxy.read() == '') def _test_close(self, proxy): # Close a file @@ -1679,11 +1679,11 @@ class TestProxyFile(TestProxyFileBase): self._file.write('foo') pos = self._file.tell() proxy0 = mailbox._ProxyFile(self._file) - self.assert_(proxy0.tell() == pos) - self.assert_(self._file.tell() == pos) + self.assertTrue(proxy0.tell() == pos) + self.assertTrue(self._file.tell() == pos) proxy1 = mailbox._ProxyFile(self._file, 0) - self.assert_(proxy1.tell() == 0) - self.assert_(self._file.tell() == pos) + self.assertTrue(proxy1.tell() == 0) + self.assertTrue(self._file.tell() == pos) def test_read(self): self._file.write('bar') @@ -1728,8 +1728,8 @@ class TestPartialFile(TestProxyFileBase): self._file.write('foo' + os.linesep + 'bar') pos = self._file.tell() proxy = mailbox._PartialFile(self._file, 2, 5) - self.assert_(proxy.tell() == 0) - self.assert_(self._file.tell() == pos) + self.assertTrue(proxy.tell() == 0) + self.assertTrue(self._file.tell() == pos) def test_read(self): self._file.write('***bar***') @@ -1821,36 +1821,36 @@ class MaildirTestCase(unittest.TestCase): # Test for regression on bug #117490: # Make sure the boxes attribute actually gets set. self.mbox = mailbox.Maildir(test_support.TESTFN) - #self.assert_(hasattr(self.mbox, "boxes")) - #self.assert_(len(self.mbox.boxes) == 0) - self.assert_(self.mbox.next() is None) - self.assert_(self.mbox.next() is None) + #self.assertTrue(hasattr(self.mbox, "boxes")) + #self.assertTrue(len(self.mbox.boxes) == 0) + self.assertTrue(self.mbox.next() is None) + self.assertTrue(self.mbox.next() is None) def test_nonempty_maildir_cur(self): self.createMessage("cur") self.mbox = mailbox.Maildir(test_support.TESTFN) - #self.assert_(len(self.mbox.boxes) == 1) - self.assert_(self.mbox.next() is not None) - self.assert_(self.mbox.next() is None) - self.assert_(self.mbox.next() is None) + #self.assertTrue(len(self.mbox.boxes) == 1) + self.assertTrue(self.mbox.next() is not None) + self.assertTrue(self.mbox.next() is None) + self.assertTrue(self.mbox.next() is None) def test_nonempty_maildir_new(self): self.createMessage("new") self.mbox = mailbox.Maildir(test_support.TESTFN) - #self.assert_(len(self.mbox.boxes) == 1) - self.assert_(self.mbox.next() is not None) - self.assert_(self.mbox.next() is None) - self.assert_(self.mbox.next() is None) + #self.assertTrue(len(self.mbox.boxes) == 1) + self.assertTrue(self.mbox.next() is not None) + self.assertTrue(self.mbox.next() is None) + self.assertTrue(self.mbox.next() is None) def test_nonempty_maildir_both(self): self.createMessage("cur") self.createMessage("new") self.mbox = mailbox.Maildir(test_support.TESTFN) - #self.assert_(len(self.mbox.boxes) == 2) - self.assert_(self.mbox.next() is not None) - self.assert_(self.mbox.next() is not None) - self.assert_(self.mbox.next() is None) - self.assert_(self.mbox.next() is None) + #self.assertTrue(len(self.mbox.boxes) == 2) + self.assertTrue(self.mbox.next() is not None) + self.assertTrue(self.mbox.next() is not None) + self.assertTrue(self.mbox.next() is None) + self.assertTrue(self.mbox.next() is None) def test_unix_mbox(self): ### should be better! diff --git a/Lib/test/test_marshal.py b/Lib/test/test_marshal.py index 943aa55..0cd46a2 100644 --- a/Lib/test/test_marshal.py +++ b/Lib/test/test_marshal.py @@ -189,7 +189,7 @@ class ContainerTestCase(unittest.TestCase): t = constructor(self.d.keys()) new = marshal.loads(marshal.dumps(t)) self.assertEqual(t, new) - self.assert_(isinstance(new, constructor)) + self.assertTrue(isinstance(new, constructor)) self.assertNotEqual(id(t), id(new)) marshal.dump(t, file(test_support.TESTFN, "wb")) new = marshal.load(file(test_support.TESTFN, "rb")) diff --git a/Lib/test/test_math.py b/Lib/test/test_math.py index 0108d49..3abb84a 100644 --- a/Lib/test/test_math.py +++ b/Lib/test/test_math.py @@ -72,7 +72,7 @@ class MathTests(unittest.TestCase): self.ftest('acos(1)', math.acos(1), 0) self.assertRaises(ValueError, math.acos, INF) self.assertRaises(ValueError, math.acos, NINF) - self.assert_(math.isnan(math.acos(NAN))) + self.assertTrue(math.isnan(math.acos(NAN))) def testAcosh(self): self.assertRaises(TypeError, math.acosh) @@ -82,7 +82,7 @@ class MathTests(unittest.TestCase): self.assertRaises(ValueError, math.acosh, -1) self.assertEquals(math.acosh(INF), INF) self.assertRaises(ValueError, math.acosh, NINF) - self.assert_(math.isnan(math.acosh(NAN))) + self.assertTrue(math.isnan(math.acosh(NAN))) def testAsin(self): self.assertRaises(TypeError, math.asin) @@ -91,7 +91,7 @@ class MathTests(unittest.TestCase): self.ftest('asin(1)', math.asin(1), math.pi/2) self.assertRaises(ValueError, math.asin, INF) self.assertRaises(ValueError, math.asin, NINF) - self.assert_(math.isnan(math.asin(NAN))) + self.assertTrue(math.isnan(math.asin(NAN))) def testAsinh(self): self.assertRaises(TypeError, math.asinh) @@ -100,7 +100,7 @@ class MathTests(unittest.TestCase): self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305) self.assertEquals(math.asinh(INF), INF) self.assertEquals(math.asinh(NINF), NINF) - self.assert_(math.isnan(math.asinh(NAN))) + self.assertTrue(math.isnan(math.asinh(NAN))) def testAtan(self): self.assertRaises(TypeError, math.atan) @@ -109,7 +109,7 @@ class MathTests(unittest.TestCase): self.ftest('atan(1)', math.atan(1), math.pi/4) self.ftest('atan(inf)', math.atan(INF), math.pi/2) self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2) - self.assert_(math.isnan(math.atan(NAN))) + self.assertTrue(math.isnan(math.atan(NAN))) def testAtanh(self): self.assertRaises(TypeError, math.atan) @@ -120,7 +120,7 @@ class MathTests(unittest.TestCase): self.assertRaises(ValueError, math.atanh, -1) self.assertRaises(ValueError, math.atanh, INF) self.assertRaises(ValueError, math.atanh, NINF) - self.assert_(math.isnan(math.atanh(NAN))) + self.assertTrue(math.isnan(math.atanh(NAN))) def testAtan2(self): self.assertRaises(TypeError, math.atan2) @@ -137,7 +137,7 @@ class MathTests(unittest.TestCase): self.assertEqual(math.atan2(0., 0.), 0.) self.assertEqual(math.atan2(0., 2.3), 0.) self.assertEqual(math.atan2(0., INF), 0.) - self.assert_(math.isnan(math.atan2(0., NAN))) + self.assertTrue(math.isnan(math.atan2(0., NAN))) # math.atan2(-0, x) self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi) self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi) @@ -145,7 +145,7 @@ class MathTests(unittest.TestCase): self.assertEqual(math.atan2(-0., 0.), -0.) self.assertEqual(math.atan2(-0., 2.3), -0.) self.assertEqual(math.atan2(-0., INF), -0.) - self.assert_(math.isnan(math.atan2(-0., NAN))) + self.assertTrue(math.isnan(math.atan2(-0., NAN))) # math.atan2(INF, x) self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4) self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2) @@ -153,7 +153,7 @@ class MathTests(unittest.TestCase): self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2) self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2) self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4) - self.assert_(math.isnan(math.atan2(INF, NAN))) + self.assertTrue(math.isnan(math.atan2(INF, NAN))) # math.atan2(NINF, x) self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4) self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2) @@ -161,27 +161,27 @@ class MathTests(unittest.TestCase): self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2) self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2) self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4) - self.assert_(math.isnan(math.atan2(NINF, NAN))) + self.assertTrue(math.isnan(math.atan2(NINF, NAN))) # math.atan2(+finite, x) self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi) self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2) self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2) self.assertEqual(math.atan2(2.3, INF), 0.) - self.assert_(math.isnan(math.atan2(2.3, NAN))) + self.assertTrue(math.isnan(math.atan2(2.3, NAN))) # math.atan2(-finite, x) self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi) self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2) self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2) self.assertEqual(math.atan2(-2.3, INF), -0.) - self.assert_(math.isnan(math.atan2(-2.3, NAN))) + self.assertTrue(math.isnan(math.atan2(-2.3, NAN))) # math.atan2(NAN, x) - self.assert_(math.isnan(math.atan2(NAN, NINF))) - self.assert_(math.isnan(math.atan2(NAN, -2.3))) - self.assert_(math.isnan(math.atan2(NAN, -0.))) - self.assert_(math.isnan(math.atan2(NAN, 0.))) - self.assert_(math.isnan(math.atan2(NAN, 2.3))) - self.assert_(math.isnan(math.atan2(NAN, INF))) - self.assert_(math.isnan(math.atan2(NAN, NAN))) + self.assertTrue(math.isnan(math.atan2(NAN, NINF))) + self.assertTrue(math.isnan(math.atan2(NAN, -2.3))) + self.assertTrue(math.isnan(math.atan2(NAN, -0.))) + self.assertTrue(math.isnan(math.atan2(NAN, 0.))) + self.assertTrue(math.isnan(math.atan2(NAN, 2.3))) + self.assertTrue(math.isnan(math.atan2(NAN, INF))) + self.assertTrue(math.isnan(math.atan2(NAN, NAN))) def testCeil(self): self.assertRaises(TypeError, math.ceil) @@ -197,7 +197,7 @@ class MathTests(unittest.TestCase): self.ftest('ceil(-1.5)', math.ceil(-1.5), -1) self.assertEquals(math.ceil(INF), INF) self.assertEquals(math.ceil(NINF), NINF) - self.assert_(math.isnan(math.ceil(NAN))) + self.assertTrue(math.isnan(math.ceil(NAN))) class TestCeil(object): def __float__(self): @@ -229,14 +229,14 @@ class MathTests(unittest.TestCase): self.assertEquals(copysign(INF, NINF), NINF) self.assertEquals(copysign(NINF, INF), INF) self.assertEquals(copysign(NINF, NINF), NINF) - self.assert_(math.isnan(copysign(NAN, 1.))) - self.assert_(math.isnan(copysign(NAN, INF))) - self.assert_(math.isnan(copysign(NAN, NINF))) - self.assert_(math.isnan(copysign(NAN, NAN))) + self.assertTrue(math.isnan(copysign(NAN, 1.))) + self.assertTrue(math.isnan(copysign(NAN, INF))) + self.assertTrue(math.isnan(copysign(NAN, NINF))) + self.assertTrue(math.isnan(copysign(NAN, NAN))) # copysign(INF, NAN) may be INF or it may be NINF, since # we don't know whether the sign bit of NAN is set on any # given platform. - self.assert_(math.isinf(copysign(INF, NAN))) + self.assertTrue(math.isinf(copysign(INF, NAN))) # similarly, copysign(2., NAN) could be 2. or -2. self.assertEquals(abs(copysign(2., NAN)), 2.) @@ -247,12 +247,12 @@ class MathTests(unittest.TestCase): self.ftest('cos(pi/2)', math.cos(math.pi/2), 0) self.ftest('cos(pi)', math.cos(math.pi), -1) try: - self.assert_(math.isnan(math.cos(INF))) - self.assert_(math.isnan(math.cos(NINF))) + self.assertTrue(math.isnan(math.cos(INF))) + self.assertTrue(math.isnan(math.cos(NINF))) except ValueError: self.assertRaises(ValueError, math.cos, INF) self.assertRaises(ValueError, math.cos, NINF) - self.assert_(math.isnan(math.cos(NAN))) + self.assertTrue(math.isnan(math.cos(NAN))) def testCosh(self): self.assertRaises(TypeError, math.cosh) @@ -260,7 +260,7 @@ class MathTests(unittest.TestCase): self.ftest('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert self.assertEquals(math.cosh(INF), INF) self.assertEquals(math.cosh(NINF), INF) - self.assert_(math.isnan(math.cosh(NAN))) + self.assertTrue(math.isnan(math.cosh(NAN))) def testDegrees(self): self.assertRaises(TypeError, math.degrees) @@ -275,7 +275,7 @@ class MathTests(unittest.TestCase): self.ftest('exp(1)', math.exp(1), math.e) self.assertEquals(math.exp(INF), INF) self.assertEquals(math.exp(NINF), 0.) - self.assert_(math.isnan(math.exp(NAN))) + self.assertTrue(math.isnan(math.exp(NAN))) def testFabs(self): self.assertRaises(TypeError, math.fabs) @@ -315,7 +315,7 @@ class MathTests(unittest.TestCase): self.ftest('floor(-1.23e167)', math.floor(-1.23e167), -1.23e167) self.assertEquals(math.ceil(INF), INF) self.assertEquals(math.ceil(NINF), NINF) - self.assert_(math.isnan(math.floor(NAN))) + self.assertTrue(math.isnan(math.floor(NAN))) class TestFloor(object): def __float__(self): @@ -338,9 +338,9 @@ class MathTests(unittest.TestCase): self.ftest('fmod(-10,1)', math.fmod(-10,1), 0) self.ftest('fmod(-10,0.5)', math.fmod(-10,0.5), 0) self.ftest('fmod(-10,1.5)', math.fmod(-10,1.5), -1) - self.assert_(math.isnan(math.fmod(NAN, 1.))) - self.assert_(math.isnan(math.fmod(1., NAN))) - self.assert_(math.isnan(math.fmod(NAN, NAN))) + self.assertTrue(math.isnan(math.fmod(NAN, 1.))) + self.assertTrue(math.isnan(math.fmod(1., NAN))) + self.assertTrue(math.isnan(math.fmod(NAN, NAN))) self.assertRaises(ValueError, math.fmod, 1., 0.) self.assertRaises(ValueError, math.fmod, INF, 1.) self.assertRaises(ValueError, math.fmod, NINF, 1.) @@ -367,7 +367,7 @@ class MathTests(unittest.TestCase): self.assertEquals(math.frexp(INF)[0], INF) self.assertEquals(math.frexp(NINF)[0], NINF) - self.assert_(math.isnan(math.frexp(NAN)[0])) + self.assertTrue(math.isnan(math.frexp(NAN)[0])) @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"), "test requires IEEE 754 doubles") @@ -469,8 +469,8 @@ class MathTests(unittest.TestCase): self.assertEqual(math.hypot(INF, NAN), INF) self.assertEqual(math.hypot(NAN, NINF), INF) self.assertEqual(math.hypot(NINF, NAN), INF) - self.assert_(math.isnan(math.hypot(1.0, NAN))) - self.assert_(math.isnan(math.hypot(NAN, -2.0))) + self.assertTrue(math.isnan(math.hypot(1.0, NAN))) + self.assertTrue(math.isnan(math.hypot(NAN, -2.0))) def testLdexp(self): self.assertRaises(TypeError, math.ldexp) @@ -484,7 +484,7 @@ class MathTests(unittest.TestCase): self.assertEquals(math.ldexp(-1., -1000000), -0.) self.assertEquals(math.ldexp(INF, 30), INF) self.assertEquals(math.ldexp(NINF, -213), NINF) - self.assert_(math.isnan(math.ldexp(NAN, 0))) + self.assertTrue(math.isnan(math.ldexp(NAN, 0))) # large second argument for n in [10**5, 10L**5, 10**10, 10L**10, 10**20, 10**40]: @@ -494,7 +494,7 @@ class MathTests(unittest.TestCase): self.assertEquals(math.ldexp(-1., -n), -0.) self.assertEquals(math.ldexp(0., -n), 0.) self.assertEquals(math.ldexp(-0., -n), -0.) - self.assert_(math.isnan(math.ldexp(NAN, -n))) + self.assertTrue(math.isnan(math.ldexp(NAN, -n))) self.assertRaises(OverflowError, math.ldexp, 1., n) self.assertRaises(OverflowError, math.ldexp, -1., n) @@ -502,7 +502,7 @@ class MathTests(unittest.TestCase): self.assertEquals(math.ldexp(-0., n), -0.) self.assertEquals(math.ldexp(INF, n), INF) self.assertEquals(math.ldexp(NINF, n), NINF) - self.assert_(math.isnan(math.ldexp(NAN, n))) + self.assertTrue(math.isnan(math.ldexp(NAN, n))) def testLog(self): self.assertRaises(TypeError, math.log) @@ -514,7 +514,7 @@ class MathTests(unittest.TestCase): self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2) self.assertEquals(math.log(INF), INF) self.assertRaises(ValueError, math.log, NINF) - self.assert_(math.isnan(math.log(NAN))) + self.assertTrue(math.isnan(math.log(NAN))) def testLog1p(self): self.assertRaises(TypeError, math.log1p) @@ -524,7 +524,7 @@ class MathTests(unittest.TestCase): self.ftest('log1p(1)', math.log1p(1), math.log(2)) self.assertEquals(math.log1p(INF), INF) self.assertRaises(ValueError, math.log1p, NINF) - self.assert_(math.isnan(math.log1p(NAN))) + self.assertTrue(math.isnan(math.log1p(NAN))) n= 2**90 self.assertAlmostEquals(math.log1p(n), 62.383246250395075) self.assertAlmostEquals(math.log1p(n), math.log1p(float(n))) @@ -536,7 +536,7 @@ class MathTests(unittest.TestCase): self.ftest('log10(10)', math.log10(10), 1) self.assertEquals(math.log(INF), INF) self.assertRaises(ValueError, math.log10, NINF) - self.assert_(math.isnan(math.log10(NAN))) + self.assertTrue(math.isnan(math.log10(NAN))) def testModf(self): self.assertRaises(TypeError, math.modf) @@ -553,8 +553,8 @@ class MathTests(unittest.TestCase): self.assertEquals(math.modf(NINF), (-0.0, NINF)) modf_nan = math.modf(NAN) - self.assert_(math.isnan(modf_nan[0])) - self.assert_(math.isnan(modf_nan[1])) + self.assertTrue(math.isnan(modf_nan[0])) + self.assertTrue(math.isnan(modf_nan[1])) def testPow(self): self.assertRaises(TypeError, math.pow) @@ -566,9 +566,9 @@ class MathTests(unittest.TestCase): self.assertEqual(math.pow(NINF, 1), NINF) self.assertEqual((math.pow(1, INF)), 1.) self.assertEqual((math.pow(1, NINF)), 1.) - self.assert_(math.isnan(math.pow(NAN, 1))) - self.assert_(math.isnan(math.pow(2, NAN))) - self.assert_(math.isnan(math.pow(0, NAN))) + self.assertTrue(math.isnan(math.pow(NAN, 1))) + self.assertTrue(math.isnan(math.pow(2, NAN))) + self.assertTrue(math.isnan(math.pow(0, NAN))) self.assertEqual(math.pow(1, NAN), 1) # pow(0., x) @@ -582,7 +582,7 @@ class MathTests(unittest.TestCase): self.assertRaises(ValueError, math.pow, 0., -2.3) self.assertRaises(ValueError, math.pow, 0., -3.) self.assertRaises(ValueError, math.pow, 0., NINF) - self.assert_(math.isnan(math.pow(0., NAN))) + self.assertTrue(math.isnan(math.pow(0., NAN))) # pow(INF, x) self.assertEqual(math.pow(INF, INF), INF) @@ -595,7 +595,7 @@ class MathTests(unittest.TestCase): self.assertEqual(math.pow(INF, -2.3), 0.) self.assertEqual(math.pow(INF, -3.), 0.) self.assertEqual(math.pow(INF, NINF), 0.) - self.assert_(math.isnan(math.pow(INF, NAN))) + self.assertTrue(math.isnan(math.pow(INF, NAN))) # pow(-0., x) self.assertEqual(math.pow(-0., INF), 0.) @@ -608,7 +608,7 @@ class MathTests(unittest.TestCase): self.assertRaises(ValueError, math.pow, -0., -2.3) self.assertRaises(ValueError, math.pow, -0., -3.) self.assertRaises(ValueError, math.pow, -0., NINF) - self.assert_(math.isnan(math.pow(-0., NAN))) + self.assertTrue(math.isnan(math.pow(-0., NAN))) # pow(NINF, x) self.assertEqual(math.pow(NINF, INF), INF) @@ -621,7 +621,7 @@ class MathTests(unittest.TestCase): self.assertEqual(math.pow(NINF, -2.3), 0.) self.assertEqual(math.pow(NINF, -3.), -0.) self.assertEqual(math.pow(NINF, NINF), 0.) - self.assert_(math.isnan(math.pow(NINF, NAN))) + self.assertTrue(math.isnan(math.pow(NINF, NAN))) # pow(-1, x) self.assertEqual(math.pow(-1., INF), 1.) @@ -634,7 +634,7 @@ class MathTests(unittest.TestCase): self.assertRaises(ValueError, math.pow, -1., -2.3) self.assertEqual(math.pow(-1., -3.), -1.) self.assertEqual(math.pow(-1., NINF), 1.) - self.assert_(math.isnan(math.pow(-1., NAN))) + self.assertTrue(math.isnan(math.pow(-1., NAN))) # pow(1, x) self.assertEqual(math.pow(1., INF), 1.) @@ -717,12 +717,12 @@ class MathTests(unittest.TestCase): self.ftest('sin(pi/2)', math.sin(math.pi/2), 1) self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1) try: - self.assert_(math.isnan(math.sin(INF))) - self.assert_(math.isnan(math.sin(NINF))) + self.assertTrue(math.isnan(math.sin(INF))) + self.assertTrue(math.isnan(math.sin(NINF))) except ValueError: self.assertRaises(ValueError, math.sin, INF) self.assertRaises(ValueError, math.sin, NINF) - self.assert_(math.isnan(math.sin(NAN))) + self.assertTrue(math.isnan(math.sin(NAN))) def testSinh(self): self.assertRaises(TypeError, math.sinh) @@ -731,7 +731,7 @@ class MathTests(unittest.TestCase): self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0) self.assertEquals(math.sinh(INF), INF) self.assertEquals(math.sinh(NINF), NINF) - self.assert_(math.isnan(math.sinh(NAN))) + self.assertTrue(math.isnan(math.sinh(NAN))) def testSqrt(self): self.assertRaises(TypeError, math.sqrt) @@ -740,7 +740,7 @@ class MathTests(unittest.TestCase): self.ftest('sqrt(4)', math.sqrt(4), 2) self.assertEquals(math.sqrt(INF), INF) self.assertRaises(ValueError, math.sqrt, NINF) - self.assert_(math.isnan(math.sqrt(NAN))) + self.assertTrue(math.isnan(math.sqrt(NAN))) def testTan(self): self.assertRaises(TypeError, math.tan) @@ -748,12 +748,12 @@ class MathTests(unittest.TestCase): self.ftest('tan(pi/4)', math.tan(math.pi/4), 1) self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1) try: - self.assert_(math.isnan(math.tan(INF))) - self.assert_(math.isnan(math.tan(NINF))) + self.assertTrue(math.isnan(math.tan(INF))) + self.assertTrue(math.isnan(math.tan(NINF))) except: self.assertRaises(ValueError, math.tan, INF) self.assertRaises(ValueError, math.tan, NINF) - self.assert_(math.isnan(math.tan(NAN))) + self.assertTrue(math.isnan(math.tan(NAN))) def testTanh(self): self.assertRaises(TypeError, math.tanh) @@ -761,7 +761,7 @@ class MathTests(unittest.TestCase): self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0) self.ftest('tanh(inf)', math.tanh(INF), 1) self.ftest('tanh(-inf)', math.tanh(NINF), -1) - self.assert_(math.isnan(math.tanh(NAN))) + self.assertTrue(math.isnan(math.tanh(NAN))) # check that tanh(-0.) == -0. on IEEE 754 systems if float.__getformat__("double").startswith("IEEE"): self.assertEqual(math.tanh(-0.), -0.) @@ -807,20 +807,20 @@ class MathTests(unittest.TestCase): self.assertEqual(math.copysign(4., -0.), -4.0) def testIsnan(self): - self.assert_(math.isnan(float("nan"))) - self.assert_(math.isnan(float("inf")* 0.)) - self.failIf(math.isnan(float("inf"))) - self.failIf(math.isnan(0.)) - self.failIf(math.isnan(1.)) + self.assertTrue(math.isnan(float("nan"))) + self.assertTrue(math.isnan(float("inf")* 0.)) + self.assertFalse(math.isnan(float("inf"))) + self.assertFalse(math.isnan(0.)) + self.assertFalse(math.isnan(1.)) def testIsinf(self): - self.assert_(math.isinf(float("inf"))) - self.assert_(math.isinf(float("-inf"))) - self.assert_(math.isinf(1E400)) - self.assert_(math.isinf(-1E400)) - self.failIf(math.isinf(float("nan"))) - self.failIf(math.isinf(0.)) - self.failIf(math.isinf(1.)) + self.assertTrue(math.isinf(float("inf"))) + self.assertTrue(math.isinf(float("-inf"))) + self.assertTrue(math.isinf(1E400)) + self.assertTrue(math.isinf(-1E400)) + self.assertFalse(math.isinf(float("nan"))) + self.assertFalse(math.isinf(0.)) + self.assertFalse(math.isinf(1.)) # RED_FLAG 16-Oct-2000 Tim # While 2.0 is more consistent about exceptions than previous releases, it diff --git a/Lib/test/test_memoryio.py b/Lib/test/test_memoryio.py index d1281b4..a69caae 100644 --- a/Lib/test/test_memoryio.py +++ b/Lib/test/test_memoryio.py @@ -225,8 +225,8 @@ class MemoryTestMixin: memio = self.ioclass(buf * 10) self.assertEqual(iter(memio), memio) - self.failUnless(hasattr(memio, '__iter__')) - self.failUnless(hasattr(memio, 'next')) + self.assertTrue(hasattr(memio, '__iter__')) + self.assertTrue(hasattr(memio, 'next')) i = 0 for line in memio: self.assertEqual(line, buf) diff --git a/Lib/test/test_memoryview.py b/Lib/test/test_memoryview.py index 705b2ce..571481e 100644 --- a/Lib/test/test_memoryview.py +++ b/Lib/test/test_memoryview.py @@ -28,7 +28,7 @@ class AbstractMemoryTests: oldrefcount = sys.getrefcount(b) m = self._view(b) self.assertEquals(m[0], item(b"a")) - self.assert_(isinstance(m[0], bytes), type(m[0])) + self.assertTrue(isinstance(m[0], bytes), type(m[0])) self.assertEquals(m[5], item(b"f")) self.assertEquals(m[-1], item(b"f")) self.assertEquals(m[-6], item(b"a")) @@ -119,7 +119,7 @@ class AbstractMemoryTests: expected = b"".join( self.getitem_type(c) for c in b"abcdef") self.assertEquals(b, expected) - self.assert_(isinstance(b, bytes), type(b)) + self.assertTrue(isinstance(b, bytes), type(b)) def test_tolist(self): for tp in self._types: @@ -212,7 +212,7 @@ class AbstractMemoryTests: b = m = o = None # The cycle must be broken gc.collect() - self.assert_(wr() is None, wr()) + self.assertTrue(wr() is None, wr()) # Variations on source objects for the buffer: bytes-like objects, then arrays @@ -291,8 +291,8 @@ class BytesMemoryviewTest(unittest.TestCase, def test_constructor(self): for tp in self._types: ob = tp(self._source) - self.assert_(memoryview(ob)) - self.assert_(memoryview(object=ob)) + self.assertTrue(memoryview(ob)) + self.assertTrue(memoryview(object=ob)) self.assertRaises(TypeError, memoryview) self.assertRaises(TypeError, memoryview, ob, ob) self.assertRaises(TypeError, memoryview, argument=ob) diff --git a/Lib/test/test_mhlib.py b/Lib/test/test_mhlib.py index f1afa67..d13febe 100644 --- a/Lib/test/test_mhlib.py +++ b/Lib/test/test_mhlib.py @@ -256,9 +256,9 @@ class MhlibTests(unittest.TestCase): eq = self.assertEquals mh.makefolder("dummy1") - self.assert_("dummy1" in mh.listfolders()) + self.assertTrue("dummy1" in mh.listfolders()) path = os.path.join(_mhpath, "dummy1") - self.assert_(os.path.exists(path)) + self.assertTrue(os.path.exists(path)) f = mh.openfolder('dummy1') def create(n): @@ -310,8 +310,8 @@ class MhlibTests(unittest.TestCase): mh.deletefolder('dummy1') mh.deletefolder('dummy2') - self.assert_('dummy1' not in mh.listfolders()) - self.assert_(not os.path.exists(path)) + self.assertTrue('dummy1' not in mh.listfolders()) + self.assertTrue(not os.path.exists(path)) def test_read(self): mh = getMH() diff --git a/Lib/test/test_mimetools.py b/Lib/test/test_mimetools.py index ed01ede..9f5bf77 100644 --- a/Lib/test/test_mimetools.py +++ b/Lib/test/test_mimetools.py @@ -31,7 +31,7 @@ class MimeToolsTest(unittest.TestCase): s = set([""]) for i in xrange(100): nb = mimetools.choose_boundary() - self.assert_(nb not in s) + self.assertTrue(nb not in s) s.add(nb) def test_message(self): diff --git a/Lib/test/test_mimetypes.py b/Lib/test/test_mimetypes.py index 0190c2f..cc1790e 100644 --- a/Lib/test/test_mimetypes.py +++ b/Lib/test/test_mimetypes.py @@ -47,7 +47,7 @@ class MimeTypesTestCase(unittest.TestCase): def test_guess_all_types(self): eq = self.assertEqual - unless = self.failUnless + unless = self.assertTrue # First try strict. Use a set here for testing the results because if # test_urllib2 is run before test_mimetypes, global state is modified # such that the 'all' set will have more items in it. diff --git a/Lib/test/test_minidom.py b/Lib/test/test_minidom.py index c2f6743..b95438d 100644 --- a/Lib/test/test_minidom.py +++ b/Lib/test/test_minidom.py @@ -734,7 +734,7 @@ class MinidomTest(unittest.TestCase): def check_clone_attribute(self, deep, testName): doc = parseString("<doc attr='value'/>") attr = doc.documentElement.getAttributeNode("attr") - self.failIfEqual(attr, None) + self.assertNotEqual(attr, None) clone = attr.cloneNode(deep) self.confirm(not clone.isSameNode(attr)) self.confirm(not attr.isSameNode(clone)) diff --git a/Lib/test/test_mmap.py b/Lib/test/test_mmap.py index 9e28b34..67cee7a 100644 --- a/Lib/test/test_mmap.py +++ b/Lib/test/test_mmap.py @@ -501,8 +501,8 @@ class MmapTests(unittest.TestCase): f.close() def test_error(self): - self.assert_(issubclass(mmap.error, EnvironmentError)) - self.assert_("mmap.error" in str(mmap.error)) + self.assertTrue(issubclass(mmap.error, EnvironmentError)) + self.assertTrue("mmap.error" in str(mmap.error)) def test_io_methods(self): data = "0123456789" diff --git a/Lib/test/test_module.py b/Lib/test/test_module.py index e0c7ec3..5bc33d4 100644 --- a/Lib/test/test_module.py +++ b/Lib/test/test_module.py @@ -10,7 +10,7 @@ class ModuleTests(unittest.TestCase): # An uninitialized module has no __dict__ or __name__, # and __doc__ is None foo = ModuleType.__new__(ModuleType) - self.failUnless(foo.__dict__ is None) + self.assertTrue(foo.__dict__ is None) try: s = foo.__name__ self.fail("__name__ = %s" % repr(s)) @@ -52,7 +52,7 @@ class ModuleTests(unittest.TestCase): self.assertEqual(foo.bar, 42) self.assertEqual(foo.__dict__, {"__name__": "foo", "__doc__": "foodoc", "bar": 42}) - self.failUnless(foo.__dict__ is d) + self.assertTrue(foo.__dict__ is d) def test_main(): run_unittest(ModuleTests) diff --git a/Lib/test/test_modulefinder.py b/Lib/test/test_modulefinder.py index 9d7f76a..8c76977 100644 --- a/Lib/test/test_modulefinder.py +++ b/Lib/test/test_modulefinder.py @@ -240,12 +240,12 @@ class ModuleFinderTest(unittest.TestCase): more = list(found - modules) less = list(modules - found) # check if we found what we expected, not more, not less - self.failUnlessEqual((more, less), ([], [])) + self.assertEqual((more, less), ([], [])) # check for missing and maybe missing modules bad, maybe = mf.any_missing_maybe() - self.failUnlessEqual(bad, missing) - self.failUnlessEqual(maybe, maybe_missing) + self.assertEqual(bad, missing) + self.assertEqual(maybe, maybe_missing) finally: distutils.dir_util.remove_tree(TEST_DIR) diff --git a/Lib/test/test_multibytecodec.py b/Lib/test/test_multibytecodec.py index 090374c..f23e6e0 100644 --- a/Lib/test/test_multibytecodec.py +++ b/Lib/test/test_multibytecodec.py @@ -222,10 +222,10 @@ class Test_ISO2022(unittest.TestCase): self.assertEqual(iso2022jp2.decode('iso2022-jp-2'), uni) def test_iso2022_jp_g0(self): - self.failIf('\x0e' in u'\N{SOFT HYPHEN}'.encode('iso-2022-jp-2')) + self.assertFalse('\x0e' in u'\N{SOFT HYPHEN}'.encode('iso-2022-jp-2')) for encoding in ('iso-2022-jp-2004', 'iso-2022-jp-3'): e = u'\u3406'.encode(encoding) - self.failIf(filter(lambda x: x >= '\x80', e)) + self.assertFalse(filter(lambda x: x >= '\x80', e)) def test_bug1572832(self): if sys.maxunicode >= 0x10000: diff --git a/Lib/test/test_mutex.py b/Lib/test/test_mutex.py index 4e3f7cd..2882213 100644 --- a/Lib/test/test_mutex.py +++ b/Lib/test/test_mutex.py @@ -9,14 +9,14 @@ class MutexTest(unittest.TestCase): def called_by_mutex(some_data): self.assertEqual(some_data, "spam") - self.assert_(m.test(), "mutex not held") + self.assertTrue(m.test(), "mutex not held") # Nested locking m.lock(called_by_mutex2, "eggs") def called_by_mutex2(some_data): self.assertEquals(some_data, "eggs") - self.assert_(m.test(), "mutex not held") - self.assert_(ready_for_2, + self.assertTrue(m.test(), "mutex not held") + self.assertTrue(ready_for_2, "called_by_mutex2 called too soon") m = mutex.mutex() @@ -26,7 +26,7 @@ class MutexTest(unittest.TestCase): # unlock both locks m.unlock() m.unlock() - self.failIf(m.test(), "mutex still held") + self.assertFalse(m.test(), "mutex still held") def test_main(): test.test_support.run_unittest(MutexTest) diff --git a/Lib/test/test_netrc.py b/Lib/test/test_netrc.py index b536255..50afe76 100644 --- a/Lib/test/test_netrc.py +++ b/Lib/test/test_netrc.py @@ -35,11 +35,11 @@ class NetrcTestCase(unittest.TestCase): os.unlink(temp_filename) def test_case_1(self): - self.assert_(self.netrc.macros == {'macro1':['line1\n', 'line2\n'], + self.assertTrue(self.netrc.macros == {'macro1':['line1\n', 'line2\n'], 'macro2':['line3\n', 'line4\n']} ) - self.assert_(self.netrc.hosts['foo'] == ('log1', 'acct1', 'pass1')) - self.assert_(self.netrc.hosts['default'] == ('log2', None, 'pass2')) + self.assertTrue(self.netrc.hosts['foo'] == ('log1', 'acct1', 'pass1')) + self.assertTrue(self.netrc.hosts['default'] == ('log2', None, 'pass2')) def test_main(): test_support.run_unittest(NetrcTestCase) diff --git a/Lib/test/test_new.py b/Lib/test/test_new.py index 231f4bb..a84b3d1 100644 --- a/Lib/test/test_new.py +++ b/Lib/test/test_new.py @@ -154,7 +154,7 @@ class NewTest(unittest.TestCase): d = new.code(argcount, nlocals, stacksize, flags, codestring, constants, t, varnames, filename, name, firstlineno, lnotab) - self.assert_(type(t[0]) is S, "eek, tuple changed under us!") + self.assertTrue(type(t[0]) is S, "eek, tuple changed under us!") def test_main(): test_support.run_unittest(NewTest) diff --git a/Lib/test/test_normalization.py b/Lib/test/test_normalization.py index e9056cd..0eea4bf 100644 --- a/Lib/test/test_normalization.py +++ b/Lib/test/test_normalization.py @@ -67,14 +67,14 @@ class NormalizationTest(unittest.TestCase): continue # Perform tests - self.failUnless(c2 == NFC(c1) == NFC(c2) == NFC(c3), line) - self.failUnless(c4 == NFC(c4) == NFC(c5), line) - self.failUnless(c3 == NFD(c1) == NFD(c2) == NFD(c3), line) - self.failUnless(c5 == NFD(c4) == NFD(c5), line) - self.failUnless(c4 == NFKC(c1) == NFKC(c2) == \ + self.assertTrue(c2 == NFC(c1) == NFC(c2) == NFC(c3), line) + self.assertTrue(c4 == NFC(c4) == NFC(c5), line) + self.assertTrue(c3 == NFD(c1) == NFD(c2) == NFD(c3), line) + self.assertTrue(c5 == NFD(c4) == NFD(c5), line) + self.assertTrue(c4 == NFKC(c1) == NFKC(c2) == \ NFKC(c3) == NFKC(c4) == NFKC(c5), line) - self.failUnless(c5 == NFKD(c1) == NFKD(c2) == \ + self.assertTrue(c5 == NFKD(c1) == NFKD(c2) == \ NFKD(c3) == NFKD(c4) == NFKD(c5), line) @@ -87,7 +87,7 @@ class NormalizationTest(unittest.TestCase): X = unichr(c) if X in part1_data: continue - self.failUnless(X == NFC(X) == NFD(X) == NFKC(X) == NFKD(X), c) + self.assertTrue(X == NFC(X) == NFD(X) == NFKC(X) == NFKD(X), c) def test_bug_834676(self): # Check for bug 834676 diff --git a/Lib/test/test_old_mailbox.py b/Lib/test/test_old_mailbox.py index 7bd5557..e61b19f 100644 --- a/Lib/test/test_old_mailbox.py +++ b/Lib/test/test_old_mailbox.py @@ -67,35 +67,35 @@ class MaildirTestCase(unittest.TestCase): """Test an empty maildir mailbox""" # Test for regression on bug #117490: self.mbox = mailbox.Maildir(test_support.TESTFN) - self.assert_(len(self.mbox) == 0) - self.assert_(self.mbox.next() is None) - self.assert_(self.mbox.next() is None) + self.assertTrue(len(self.mbox) == 0) + self.assertTrue(self.mbox.next() is None) + self.assertTrue(self.mbox.next() is None) def test_nonempty_maildir_cur(self): self.createMessage("cur") self.mbox = mailbox.Maildir(test_support.TESTFN) - self.assert_(len(self.mbox) == 1) - self.assert_(self.mbox.next() is not None) - self.assert_(self.mbox.next() is None) - self.assert_(self.mbox.next() is None) + self.assertTrue(len(self.mbox) == 1) + self.assertTrue(self.mbox.next() is not None) + self.assertTrue(self.mbox.next() is None) + self.assertTrue(self.mbox.next() is None) def test_nonempty_maildir_new(self): self.createMessage("new") self.mbox = mailbox.Maildir(test_support.TESTFN) - self.assert_(len(self.mbox) == 1) - self.assert_(self.mbox.next() is not None) - self.assert_(self.mbox.next() is None) - self.assert_(self.mbox.next() is None) + self.assertTrue(len(self.mbox) == 1) + self.assertTrue(self.mbox.next() is not None) + self.assertTrue(self.mbox.next() is None) + self.assertTrue(self.mbox.next() is None) def test_nonempty_maildir_both(self): self.createMessage("cur") self.createMessage("new") self.mbox = mailbox.Maildir(test_support.TESTFN) - self.assert_(len(self.mbox) == 2) - self.assert_(self.mbox.next() is not None) - self.assert_(self.mbox.next() is not None) - self.assert_(self.mbox.next() is None) - self.assert_(self.mbox.next() is None) + self.assertTrue(len(self.mbox) == 2) + self.assertTrue(self.mbox.next() is not None) + self.assertTrue(self.mbox.next() is not None) + self.assertTrue(self.mbox.next() is None) + self.assertTrue(self.mbox.next() is None) def test_unix_mbox(self): ### should be better! @@ -139,7 +139,7 @@ body4 """) f.close() box = mailbox.UnixMailbox(open(self._path, 'r')) - self.assert_(len(list(iter(box))) == 4) + self.assertTrue(len(list(iter(box))) == 4) # XXX We still need more tests! diff --git a/Lib/test/test_opcodes.py b/Lib/test/test_opcodes.py index 7985bf6..c03ca1d 100644 --- a/Lib/test/test_opcodes.py +++ b/Lib/test/test_opcodes.py @@ -64,7 +64,7 @@ class OpcodeTest(unittest.TestCase): try: raise DClass, a except DClass, v: - self.assert_(isinstance(v, DClass)) + self.assertTrue(isinstance(v, DClass)) else: self.fail("no exception") diff --git a/Lib/test/test_operator.py b/Lib/test/test_operator.py index 9bc0a4e..2758856 100644 --- a/Lib/test/test_operator.py +++ b/Lib/test/test_operator.py @@ -34,332 +34,332 @@ class Seq2(object): class OperatorTestCase(unittest.TestCase): def test_lt(self): - self.failUnlessRaises(TypeError, operator.lt) - self.failUnlessRaises(TypeError, operator.lt, 1j, 2j) - self.failIf(operator.lt(1, 0)) - self.failIf(operator.lt(1, 0.0)) - self.failIf(operator.lt(1, 1)) - self.failIf(operator.lt(1, 1.0)) - self.failUnless(operator.lt(1, 2)) - self.failUnless(operator.lt(1, 2.0)) + self.assertRaises(TypeError, operator.lt) + self.assertRaises(TypeError, operator.lt, 1j, 2j) + self.assertFalse(operator.lt(1, 0)) + self.assertFalse(operator.lt(1, 0.0)) + self.assertFalse(operator.lt(1, 1)) + self.assertFalse(operator.lt(1, 1.0)) + self.assertTrue(operator.lt(1, 2)) + self.assertTrue(operator.lt(1, 2.0)) def test_le(self): - self.failUnlessRaises(TypeError, operator.le) - self.failUnlessRaises(TypeError, operator.le, 1j, 2j) - self.failIf(operator.le(1, 0)) - self.failIf(operator.le(1, 0.0)) - self.failUnless(operator.le(1, 1)) - self.failUnless(operator.le(1, 1.0)) - self.failUnless(operator.le(1, 2)) - self.failUnless(operator.le(1, 2.0)) + self.assertRaises(TypeError, operator.le) + self.assertRaises(TypeError, operator.le, 1j, 2j) + self.assertFalse(operator.le(1, 0)) + self.assertFalse(operator.le(1, 0.0)) + self.assertTrue(operator.le(1, 1)) + self.assertTrue(operator.le(1, 1.0)) + self.assertTrue(operator.le(1, 2)) + self.assertTrue(operator.le(1, 2.0)) def test_eq(self): class C(object): def __eq__(self, other): raise SyntaxError __hash__ = None # Silence Py3k warning - self.failUnlessRaises(TypeError, operator.eq) - self.failUnlessRaises(SyntaxError, operator.eq, C(), C()) - self.failIf(operator.eq(1, 0)) - self.failIf(operator.eq(1, 0.0)) - self.failUnless(operator.eq(1, 1)) - self.failUnless(operator.eq(1, 1.0)) - self.failIf(operator.eq(1, 2)) - self.failIf(operator.eq(1, 2.0)) + self.assertRaises(TypeError, operator.eq) + self.assertRaises(SyntaxError, operator.eq, C(), C()) + self.assertFalse(operator.eq(1, 0)) + self.assertFalse(operator.eq(1, 0.0)) + self.assertTrue(operator.eq(1, 1)) + self.assertTrue(operator.eq(1, 1.0)) + self.assertFalse(operator.eq(1, 2)) + self.assertFalse(operator.eq(1, 2.0)) def test_ne(self): class C(object): def __ne__(self, other): raise SyntaxError - self.failUnlessRaises(TypeError, operator.ne) - self.failUnlessRaises(SyntaxError, operator.ne, C(), C()) - self.failUnless(operator.ne(1, 0)) - self.failUnless(operator.ne(1, 0.0)) - self.failIf(operator.ne(1, 1)) - self.failIf(operator.ne(1, 1.0)) - self.failUnless(operator.ne(1, 2)) - self.failUnless(operator.ne(1, 2.0)) + self.assertRaises(TypeError, operator.ne) + self.assertRaises(SyntaxError, operator.ne, C(), C()) + self.assertTrue(operator.ne(1, 0)) + self.assertTrue(operator.ne(1, 0.0)) + self.assertFalse(operator.ne(1, 1)) + self.assertFalse(operator.ne(1, 1.0)) + self.assertTrue(operator.ne(1, 2)) + self.assertTrue(operator.ne(1, 2.0)) def test_ge(self): - self.failUnlessRaises(TypeError, operator.ge) - self.failUnlessRaises(TypeError, operator.ge, 1j, 2j) - self.failUnless(operator.ge(1, 0)) - self.failUnless(operator.ge(1, 0.0)) - self.failUnless(operator.ge(1, 1)) - self.failUnless(operator.ge(1, 1.0)) - self.failIf(operator.ge(1, 2)) - self.failIf(operator.ge(1, 2.0)) + self.assertRaises(TypeError, operator.ge) + self.assertRaises(TypeError, operator.ge, 1j, 2j) + self.assertTrue(operator.ge(1, 0)) + self.assertTrue(operator.ge(1, 0.0)) + self.assertTrue(operator.ge(1, 1)) + self.assertTrue(operator.ge(1, 1.0)) + self.assertFalse(operator.ge(1, 2)) + self.assertFalse(operator.ge(1, 2.0)) def test_gt(self): - self.failUnlessRaises(TypeError, operator.gt) - self.failUnlessRaises(TypeError, operator.gt, 1j, 2j) - self.failUnless(operator.gt(1, 0)) - self.failUnless(operator.gt(1, 0.0)) - self.failIf(operator.gt(1, 1)) - self.failIf(operator.gt(1, 1.0)) - self.failIf(operator.gt(1, 2)) - self.failIf(operator.gt(1, 2.0)) + self.assertRaises(TypeError, operator.gt) + self.assertRaises(TypeError, operator.gt, 1j, 2j) + self.assertTrue(operator.gt(1, 0)) + self.assertTrue(operator.gt(1, 0.0)) + self.assertFalse(operator.gt(1, 1)) + self.assertFalse(operator.gt(1, 1.0)) + self.assertFalse(operator.gt(1, 2)) + self.assertFalse(operator.gt(1, 2.0)) def test_abs(self): - self.failUnlessRaises(TypeError, operator.abs) - self.failUnlessRaises(TypeError, operator.abs, None) - self.failUnless(operator.abs(-1) == 1) - self.failUnless(operator.abs(1) == 1) + self.assertRaises(TypeError, operator.abs) + self.assertRaises(TypeError, operator.abs, None) + self.assertTrue(operator.abs(-1) == 1) + self.assertTrue(operator.abs(1) == 1) def test_add(self): - self.failUnlessRaises(TypeError, operator.add) - self.failUnlessRaises(TypeError, operator.add, None, None) - self.failUnless(operator.add(3, 4) == 7) + self.assertRaises(TypeError, operator.add) + self.assertRaises(TypeError, operator.add, None, None) + self.assertTrue(operator.add(3, 4) == 7) def test_bitwise_and(self): - self.failUnlessRaises(TypeError, operator.and_) - self.failUnlessRaises(TypeError, operator.and_, None, None) - self.failUnless(operator.and_(0xf, 0xa) == 0xa) + self.assertRaises(TypeError, operator.and_) + self.assertRaises(TypeError, operator.and_, None, None) + self.assertTrue(operator.and_(0xf, 0xa) == 0xa) def test_concat(self): - self.failUnlessRaises(TypeError, operator.concat) - self.failUnlessRaises(TypeError, operator.concat, None, None) - self.failUnless(operator.concat('py', 'thon') == 'python') - self.failUnless(operator.concat([1, 2], [3, 4]) == [1, 2, 3, 4]) - self.failUnless(operator.concat(Seq1([5, 6]), Seq1([7])) == [5, 6, 7]) - self.failUnless(operator.concat(Seq2([5, 6]), Seq2([7])) == [5, 6, 7]) - self.failUnlessRaises(TypeError, operator.concat, 13, 29) + self.assertRaises(TypeError, operator.concat) + self.assertRaises(TypeError, operator.concat, None, None) + self.assertTrue(operator.concat('py', 'thon') == 'python') + self.assertTrue(operator.concat([1, 2], [3, 4]) == [1, 2, 3, 4]) + self.assertTrue(operator.concat(Seq1([5, 6]), Seq1([7])) == [5, 6, 7]) + self.assertTrue(operator.concat(Seq2([5, 6]), Seq2([7])) == [5, 6, 7]) + self.assertRaises(TypeError, operator.concat, 13, 29) def test_countOf(self): - self.failUnlessRaises(TypeError, operator.countOf) - self.failUnlessRaises(TypeError, operator.countOf, None, None) - self.failUnless(operator.countOf([1, 2, 1, 3, 1, 4], 3) == 1) - self.failUnless(operator.countOf([1, 2, 1, 3, 1, 4], 5) == 0) + self.assertRaises(TypeError, operator.countOf) + self.assertRaises(TypeError, operator.countOf, None, None) + self.assertTrue(operator.countOf([1, 2, 1, 3, 1, 4], 3) == 1) + self.assertTrue(operator.countOf([1, 2, 1, 3, 1, 4], 5) == 0) def test_delitem(self): a = [4, 3, 2, 1] - self.failUnlessRaises(TypeError, operator.delitem, a) - self.failUnlessRaises(TypeError, operator.delitem, a, None) - self.failUnless(operator.delitem(a, 1) is None) - self.assert_(a == [4, 2, 1]) + self.assertRaises(TypeError, operator.delitem, a) + self.assertRaises(TypeError, operator.delitem, a, None) + self.assertTrue(operator.delitem(a, 1) is None) + self.assertTrue(a == [4, 2, 1]) def test_delslice(self): a = range(10) - self.failUnlessRaises(TypeError, operator.delslice, a) - self.failUnlessRaises(TypeError, operator.delslice, a, None, None) - self.failUnless(operator.delslice(a, 2, 8) is None) - self.assert_(a == [0, 1, 8, 9]) + self.assertRaises(TypeError, operator.delslice, a) + self.assertRaises(TypeError, operator.delslice, a, None, None) + self.assertTrue(operator.delslice(a, 2, 8) is None) + self.assertTrue(a == [0, 1, 8, 9]) operator.delslice(a, 0, test_support.MAX_Py_ssize_t) - self.assert_(a == []) + self.assertTrue(a == []) def test_div(self): - self.failUnlessRaises(TypeError, operator.div, 5) - self.failUnlessRaises(TypeError, operator.div, None, None) - self.failUnless(operator.floordiv(5, 2) == 2) + self.assertRaises(TypeError, operator.div, 5) + self.assertRaises(TypeError, operator.div, None, None) + self.assertTrue(operator.floordiv(5, 2) == 2) def test_floordiv(self): - self.failUnlessRaises(TypeError, operator.floordiv, 5) - self.failUnlessRaises(TypeError, operator.floordiv, None, None) - self.failUnless(operator.floordiv(5, 2) == 2) + self.assertRaises(TypeError, operator.floordiv, 5) + self.assertRaises(TypeError, operator.floordiv, None, None) + self.assertTrue(operator.floordiv(5, 2) == 2) def test_truediv(self): - self.failUnlessRaises(TypeError, operator.truediv, 5) - self.failUnlessRaises(TypeError, operator.truediv, None, None) - self.failUnless(operator.truediv(5, 2) == 2.5) + self.assertRaises(TypeError, operator.truediv, 5) + self.assertRaises(TypeError, operator.truediv, None, None) + self.assertTrue(operator.truediv(5, 2) == 2.5) def test_getitem(self): a = range(10) - self.failUnlessRaises(TypeError, operator.getitem) - self.failUnlessRaises(TypeError, operator.getitem, a, None) - self.failUnless(operator.getitem(a, 2) == 2) + self.assertRaises(TypeError, operator.getitem) + self.assertRaises(TypeError, operator.getitem, a, None) + self.assertTrue(operator.getitem(a, 2) == 2) def test_getslice(self): a = range(10) - self.failUnlessRaises(TypeError, operator.getslice) - self.failUnlessRaises(TypeError, operator.getslice, a, None, None) - self.failUnless(operator.getslice(a, 4, 6) == [4, 5]) + self.assertRaises(TypeError, operator.getslice) + self.assertRaises(TypeError, operator.getslice, a, None, None) + self.assertTrue(operator.getslice(a, 4, 6) == [4, 5]) b = operator.getslice(a, 0, test_support.MAX_Py_ssize_t) - self.assert_(b == a) + self.assertTrue(b == a) def test_indexOf(self): - self.failUnlessRaises(TypeError, operator.indexOf) - self.failUnlessRaises(TypeError, operator.indexOf, None, None) - self.failUnless(operator.indexOf([4, 3, 2, 1], 3) == 1) + self.assertRaises(TypeError, operator.indexOf) + self.assertRaises(TypeError, operator.indexOf, None, None) + self.assertTrue(operator.indexOf([4, 3, 2, 1], 3) == 1) self.assertRaises(ValueError, operator.indexOf, [4, 3, 2, 1], 0) def test_invert(self): - self.failUnlessRaises(TypeError, operator.invert) - self.failUnlessRaises(TypeError, operator.invert, None) - self.failUnless(operator.inv(4) == -5) + self.assertRaises(TypeError, operator.invert) + self.assertRaises(TypeError, operator.invert, None) + self.assertTrue(operator.inv(4) == -5) def test_isCallable(self): - self.failUnlessRaises(TypeError, operator.isCallable) + self.assertRaises(TypeError, operator.isCallable) class C: pass def check(self, o, v): - self.assert_(operator.isCallable(o) == callable(o) == v) + self.assertTrue(operator.isCallable(o) == callable(o) == v) check(self, 4, 0) check(self, operator.isCallable, 1) check(self, C, 1) check(self, C(), 0) def test_isMappingType(self): - self.failUnlessRaises(TypeError, operator.isMappingType) - self.failIf(operator.isMappingType(1)) - self.failIf(operator.isMappingType(operator.isMappingType)) - self.failUnless(operator.isMappingType(operator.__dict__)) - self.failUnless(operator.isMappingType({})) + self.assertRaises(TypeError, operator.isMappingType) + self.assertFalse(operator.isMappingType(1)) + self.assertFalse(operator.isMappingType(operator.isMappingType)) + self.assertTrue(operator.isMappingType(operator.__dict__)) + self.assertTrue(operator.isMappingType({})) def test_isNumberType(self): - self.failUnlessRaises(TypeError, operator.isNumberType) - self.failUnless(operator.isNumberType(8)) - self.failUnless(operator.isNumberType(8j)) - self.failUnless(operator.isNumberType(8L)) - self.failUnless(operator.isNumberType(8.3)) - self.failIf(operator.isNumberType(dir())) + self.assertRaises(TypeError, operator.isNumberType) + self.assertTrue(operator.isNumberType(8)) + self.assertTrue(operator.isNumberType(8j)) + self.assertTrue(operator.isNumberType(8L)) + self.assertTrue(operator.isNumberType(8.3)) + self.assertFalse(operator.isNumberType(dir())) def test_isSequenceType(self): - self.failUnlessRaises(TypeError, operator.isSequenceType) - self.failUnless(operator.isSequenceType(dir())) - self.failUnless(operator.isSequenceType(())) - self.failUnless(operator.isSequenceType(xrange(10))) - self.failUnless(operator.isSequenceType('yeahbuddy')) - self.failIf(operator.isSequenceType(3)) + self.assertRaises(TypeError, operator.isSequenceType) + self.assertTrue(operator.isSequenceType(dir())) + self.assertTrue(operator.isSequenceType(())) + self.assertTrue(operator.isSequenceType(xrange(10))) + self.assertTrue(operator.isSequenceType('yeahbuddy')) + self.assertFalse(operator.isSequenceType(3)) class Dict(dict): pass - self.failIf(operator.isSequenceType(Dict())) + self.assertFalse(operator.isSequenceType(Dict())) def test_lshift(self): - self.failUnlessRaises(TypeError, operator.lshift) - self.failUnlessRaises(TypeError, operator.lshift, None, 42) - self.failUnless(operator.lshift(5, 1) == 10) - self.failUnless(operator.lshift(5, 0) == 5) + self.assertRaises(TypeError, operator.lshift) + self.assertRaises(TypeError, operator.lshift, None, 42) + self.assertTrue(operator.lshift(5, 1) == 10) + self.assertTrue(operator.lshift(5, 0) == 5) self.assertRaises(ValueError, operator.lshift, 2, -1) def test_mod(self): - self.failUnlessRaises(TypeError, operator.mod) - self.failUnlessRaises(TypeError, operator.mod, None, 42) - self.failUnless(operator.mod(5, 2) == 1) + self.assertRaises(TypeError, operator.mod) + self.assertRaises(TypeError, operator.mod, None, 42) + self.assertTrue(operator.mod(5, 2) == 1) def test_mul(self): - self.failUnlessRaises(TypeError, operator.mul) - self.failUnlessRaises(TypeError, operator.mul, None, None) - self.failUnless(operator.mul(5, 2) == 10) + self.assertRaises(TypeError, operator.mul) + self.assertRaises(TypeError, operator.mul, None, None) + self.assertTrue(operator.mul(5, 2) == 10) def test_neg(self): - self.failUnlessRaises(TypeError, operator.neg) - self.failUnlessRaises(TypeError, operator.neg, None) - self.failUnless(operator.neg(5) == -5) - self.failUnless(operator.neg(-5) == 5) - self.failUnless(operator.neg(0) == 0) - self.failUnless(operator.neg(-0) == 0) + self.assertRaises(TypeError, operator.neg) + self.assertRaises(TypeError, operator.neg, None) + self.assertTrue(operator.neg(5) == -5) + self.assertTrue(operator.neg(-5) == 5) + self.assertTrue(operator.neg(0) == 0) + self.assertTrue(operator.neg(-0) == 0) def test_bitwise_or(self): - self.failUnlessRaises(TypeError, operator.or_) - self.failUnlessRaises(TypeError, operator.or_, None, None) - self.failUnless(operator.or_(0xa, 0x5) == 0xf) + self.assertRaises(TypeError, operator.or_) + self.assertRaises(TypeError, operator.or_, None, None) + self.assertTrue(operator.or_(0xa, 0x5) == 0xf) def test_pos(self): - self.failUnlessRaises(TypeError, operator.pos) - self.failUnlessRaises(TypeError, operator.pos, None) - self.failUnless(operator.pos(5) == 5) - self.failUnless(operator.pos(-5) == -5) - self.failUnless(operator.pos(0) == 0) - self.failUnless(operator.pos(-0) == 0) + self.assertRaises(TypeError, operator.pos) + self.assertRaises(TypeError, operator.pos, None) + self.assertTrue(operator.pos(5) == 5) + self.assertTrue(operator.pos(-5) == -5) + self.assertTrue(operator.pos(0) == 0) + self.assertTrue(operator.pos(-0) == 0) def test_pow(self): - self.failUnlessRaises(TypeError, operator.pow) - self.failUnlessRaises(TypeError, operator.pow, None, None) - self.failUnless(operator.pow(3,5) == 3**5) - self.failUnless(operator.__pow__(3,5) == 3**5) + self.assertRaises(TypeError, operator.pow) + self.assertRaises(TypeError, operator.pow, None, None) + self.assertTrue(operator.pow(3,5) == 3**5) + self.assertTrue(operator.__pow__(3,5) == 3**5) self.assertRaises(TypeError, operator.pow, 1) self.assertRaises(TypeError, operator.pow, 1, 2, 3) def test_repeat(self): a = range(3) - self.failUnlessRaises(TypeError, operator.repeat) - self.failUnlessRaises(TypeError, operator.repeat, a, None) - self.failUnless(operator.repeat(a, 2) == a+a) - self.failUnless(operator.repeat(a, 1) == a) - self.failUnless(operator.repeat(a, 0) == []) + self.assertRaises(TypeError, operator.repeat) + self.assertRaises(TypeError, operator.repeat, a, None) + self.assertTrue(operator.repeat(a, 2) == a+a) + self.assertTrue(operator.repeat(a, 1) == a) + self.assertTrue(operator.repeat(a, 0) == []) a = (1, 2, 3) - self.failUnless(operator.repeat(a, 2) == a+a) - self.failUnless(operator.repeat(a, 1) == a) - self.failUnless(operator.repeat(a, 0) == ()) + self.assertTrue(operator.repeat(a, 2) == a+a) + self.assertTrue(operator.repeat(a, 1) == a) + self.assertTrue(operator.repeat(a, 0) == ()) a = '123' - self.failUnless(operator.repeat(a, 2) == a+a) - self.failUnless(operator.repeat(a, 1) == a) - self.failUnless(operator.repeat(a, 0) == '') + self.assertTrue(operator.repeat(a, 2) == a+a) + self.assertTrue(operator.repeat(a, 1) == a) + self.assertTrue(operator.repeat(a, 0) == '') a = Seq1([4, 5, 6]) - self.failUnless(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6]) - self.failUnless(operator.repeat(a, 1) == [4, 5, 6]) - self.failUnless(operator.repeat(a, 0) == []) + self.assertTrue(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6]) + self.assertTrue(operator.repeat(a, 1) == [4, 5, 6]) + self.assertTrue(operator.repeat(a, 0) == []) a = Seq2([4, 5, 6]) - self.failUnless(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6]) - self.failUnless(operator.repeat(a, 1) == [4, 5, 6]) - self.failUnless(operator.repeat(a, 0) == []) - self.failUnlessRaises(TypeError, operator.repeat, 6, 7) + self.assertTrue(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6]) + self.assertTrue(operator.repeat(a, 1) == [4, 5, 6]) + self.assertTrue(operator.repeat(a, 0) == []) + self.assertRaises(TypeError, operator.repeat, 6, 7) def test_rshift(self): - self.failUnlessRaises(TypeError, operator.rshift) - self.failUnlessRaises(TypeError, operator.rshift, None, 42) - self.failUnless(operator.rshift(5, 1) == 2) - self.failUnless(operator.rshift(5, 0) == 5) + self.assertRaises(TypeError, operator.rshift) + self.assertRaises(TypeError, operator.rshift, None, 42) + self.assertTrue(operator.rshift(5, 1) == 2) + self.assertTrue(operator.rshift(5, 0) == 5) self.assertRaises(ValueError, operator.rshift, 2, -1) def test_contains(self): - self.failUnlessRaises(TypeError, operator.contains) - self.failUnlessRaises(TypeError, operator.contains, None, None) - self.failUnless(operator.contains(range(4), 2)) - self.failIf(operator.contains(range(4), 5)) - self.failUnless(operator.sequenceIncludes(range(4), 2)) - self.failIf(operator.sequenceIncludes(range(4), 5)) + self.assertRaises(TypeError, operator.contains) + self.assertRaises(TypeError, operator.contains, None, None) + self.assertTrue(operator.contains(range(4), 2)) + self.assertFalse(operator.contains(range(4), 5)) + self.assertTrue(operator.sequenceIncludes(range(4), 2)) + self.assertFalse(operator.sequenceIncludes(range(4), 5)) def test_setitem(self): a = range(3) - self.failUnlessRaises(TypeError, operator.setitem, a) - self.failUnlessRaises(TypeError, operator.setitem, a, None, None) - self.failUnless(operator.setitem(a, 0, 2) is None) - self.assert_(a == [2, 1, 2]) + self.assertRaises(TypeError, operator.setitem, a) + self.assertRaises(TypeError, operator.setitem, a, None, None) + self.assertTrue(operator.setitem(a, 0, 2) is None) + self.assertTrue(a == [2, 1, 2]) self.assertRaises(IndexError, operator.setitem, a, 4, 2) def test_setslice(self): a = range(4) - self.failUnlessRaises(TypeError, operator.setslice, a) - self.failUnlessRaises(TypeError, operator.setslice, a, None, None, None) - self.failUnless(operator.setslice(a, 1, 3, [2, 1]) is None) - self.assert_(a == [0, 2, 1, 3]) + self.assertRaises(TypeError, operator.setslice, a) + self.assertRaises(TypeError, operator.setslice, a, None, None, None) + self.assertTrue(operator.setslice(a, 1, 3, [2, 1]) is None) + self.assertTrue(a == [0, 2, 1, 3]) operator.setslice(a, 0, test_support.MAX_Py_ssize_t, []) - self.assert_(a == []) + self.assertTrue(a == []) def test_sub(self): - self.failUnlessRaises(TypeError, operator.sub) - self.failUnlessRaises(TypeError, operator.sub, None, None) - self.failUnless(operator.sub(5, 2) == 3) + self.assertRaises(TypeError, operator.sub) + self.assertRaises(TypeError, operator.sub, None, None) + self.assertTrue(operator.sub(5, 2) == 3) def test_truth(self): class C(object): def __nonzero__(self): raise SyntaxError - self.failUnlessRaises(TypeError, operator.truth) - self.failUnlessRaises(SyntaxError, operator.truth, C()) - self.failUnless(operator.truth(5)) - self.failUnless(operator.truth([0])) - self.failIf(operator.truth(0)) - self.failIf(operator.truth([])) + self.assertRaises(TypeError, operator.truth) + self.assertRaises(SyntaxError, operator.truth, C()) + self.assertTrue(operator.truth(5)) + self.assertTrue(operator.truth([0])) + self.assertFalse(operator.truth(0)) + self.assertFalse(operator.truth([])) def test_bitwise_xor(self): - self.failUnlessRaises(TypeError, operator.xor) - self.failUnlessRaises(TypeError, operator.xor, None, None) - self.failUnless(operator.xor(0xb, 0xc) == 0x7) + self.assertRaises(TypeError, operator.xor) + self.assertRaises(TypeError, operator.xor, None, None) + self.assertTrue(operator.xor(0xb, 0xc) == 0x7) def test_is(self): a = b = 'xyzpdq' c = a[:3] + b[3:] - self.failUnlessRaises(TypeError, operator.is_) - self.failUnless(operator.is_(a, b)) - self.failIf(operator.is_(a,c)) + self.assertRaises(TypeError, operator.is_) + self.assertTrue(operator.is_(a, b)) + self.assertFalse(operator.is_(a,c)) def test_is_not(self): a = b = 'xyzpdq' c = a[:3] + b[3:] - self.failUnlessRaises(TypeError, operator.is_not) - self.failIf(operator.is_not(a, b)) - self.failUnless(operator.is_not(a,c)) + self.assertRaises(TypeError, operator.is_not) + self.assertFalse(operator.is_not(a, b)) + self.assertTrue(operator.is_not(a,c)) def test_attrgetter(self): class A: @@ -385,7 +385,7 @@ class OperatorTestCase(unittest.TestCase): class C(object): def __getattr__(self, name): raise SyntaxError - self.failUnlessRaises(SyntaxError, operator.attrgetter('foo'), C()) + self.assertRaises(SyntaxError, operator.attrgetter('foo'), C()) # recursive gets a = A() @@ -417,7 +417,7 @@ class OperatorTestCase(unittest.TestCase): class C(object): def __getitem__(self, name): raise SyntaxError - self.failUnlessRaises(SyntaxError, operator.itemgetter(42), C()) + self.assertRaises(SyntaxError, operator.itemgetter(42), C()) f = operator.itemgetter('name') self.assertRaises(TypeError, f, a) diff --git a/Lib/test/test_optparse.py b/Lib/test/test_optparse.py index 7483fe7..b11b8c9 100644 --- a/Lib/test/test_optparse.py +++ b/Lib/test/test_optparse.py @@ -116,7 +116,7 @@ Args were %(args)s.""" % locals ()) except expected_exception, err: actual_message = str(err) if isinstance(expected_message, retype): - self.assert_(expected_message.search(actual_message), + self.assertTrue(expected_message.search(actual_message), """\ expected exception message pattern: /%s/ @@ -175,7 +175,7 @@ and kwargs %(kwargs)r sys.stdout = save_stdout except InterceptedError, err: - self.assert_( + self.assertTrue( type(output) is types.StringType, "expected output to be an ordinary string, not %r" % type(output)) @@ -348,7 +348,7 @@ class TestOptionParser(BaseTest): def test_get_option(self): opt1 = self.parser.get_option("-v") - self.assert_(isinstance(opt1, Option)) + self.assertTrue(isinstance(opt1, Option)) self.assertEqual(opt1._short_opts, ["-v", "-n"]) self.assertEqual(opt1._long_opts, ["--verbose", "--noisy"]) self.assertEqual(opt1.action, "store_true") @@ -359,33 +359,33 @@ class TestOptionParser(BaseTest): opt2 = self.parser.get_option("--verbose") opt3 = self.parser.get_option("-n") opt4 = self.parser.get_option("--noisy") - self.assert_(opt1 is opt2 is opt3 is opt4) + self.assertTrue(opt1 is opt2 is opt3 is opt4) def test_has_option(self): - self.assert_(self.parser.has_option("-v")) - self.assert_(self.parser.has_option("--verbose")) + self.assertTrue(self.parser.has_option("-v")) + self.assertTrue(self.parser.has_option("--verbose")) - def assert_removed(self): - self.assert_(self.parser.get_option("-v") is None) - self.assert_(self.parser.get_option("--verbose") is None) - self.assert_(self.parser.get_option("-n") is None) - self.assert_(self.parser.get_option("--noisy") is None) + def assertTrueremoved(self): + self.assertTrue(self.parser.get_option("-v") is None) + self.assertTrue(self.parser.get_option("--verbose") is None) + self.assertTrue(self.parser.get_option("-n") is None) + self.assertTrue(self.parser.get_option("--noisy") is None) - self.failIf(self.parser.has_option("-v")) - self.failIf(self.parser.has_option("--verbose")) - self.failIf(self.parser.has_option("-n")) - self.failIf(self.parser.has_option("--noisy")) + self.assertFalse(self.parser.has_option("-v")) + self.assertFalse(self.parser.has_option("--verbose")) + self.assertFalse(self.parser.has_option("-n")) + self.assertFalse(self.parser.has_option("--noisy")) - self.assert_(self.parser.has_option("-q")) - self.assert_(self.parser.has_option("--silent")) + self.assertTrue(self.parser.has_option("-q")) + self.assertTrue(self.parser.has_option("--silent")) def test_remove_short_opt(self): self.parser.remove_option("-n") - self.assert_removed() + self.assertTrueremoved() def test_remove_long_opt(self): self.parser.remove_option("--verbose") - self.assert_removed() + self.assertTrueremoved() def test_remove_nonexistent(self): self.assertRaises(self.parser.remove_option, ('foo',), None, @@ -795,14 +795,14 @@ class TestBool(BaseTest): {'verbose': 0}, []) if hasattr(__builtins__, 'False'): - self.failUnless(options.verbose is False) + self.assertTrue(options.verbose is False) def test_bool_true(self): (options, args) = self.assertParseOK(["-v"], {'verbose': 1}, []) if hasattr(__builtins__, 'True'): - self.failUnless(options.verbose is True) + self.assertTrue(options.verbose is True) def test_bool_flicker_on_and_off(self): self.assertParseOK(["-qvq", "-q", "-v"], @@ -1008,7 +1008,7 @@ class TestOptionGroup(BaseTest): description="Some more options") group.set_title("Bacon") group.add_option("--bacon", type="int") - self.assert_(self.parser.get_option_group("--bacon"), group) + self.assertTrue(self.parser.get_option_group("--bacon"), group) # -- Test extending and parser.parse_args() ---------------------------- @@ -1104,15 +1104,15 @@ class TestCallback(BaseTest): if opt == "-x": self.assertEqual(option._short_opts, ["-x"]) self.assertEqual(option._long_opts, []) - self.assert_(parser_ is self.parser) - self.assert_(value is None) + self.assertTrue(parser_ is self.parser) + self.assertTrue(value is None) self.assertEqual(vars(parser_.values), {'filename': None}) parser_.values.x = 42 elif opt == "--file": self.assertEqual(option._short_opts, ["-f"]) self.assertEqual(option._long_opts, ["--file"]) - self.assert_(parser_ is self.parser) + self.assertTrue(parser_ is self.parser) self.assertEqual(value, "foo") self.assertEqual(vars(parser_.values), {'filename': None, 'x': 42}) @@ -1150,7 +1150,7 @@ class TestCallbackExtraArgs(BaseTest): def process_tuple(self, option, opt, value, parser_, len, type): self.assertEqual(len, 3) - self.assert_(type is int) + self.assertTrue(type is int) if opt == "-p": self.assertEqual(value, "1,2,3") @@ -1241,7 +1241,7 @@ class TestCallbackVarArgs(BaseTest): option_list=options) def variable_args(self, option, opt, value, parser): - self.assert_(value is None) + self.assertTrue(value is None) done = 0 value = [] rargs = parser.rargs @@ -1297,7 +1297,7 @@ class ConflictBase(BaseTest): class TestConflict(ConflictBase): """Use the default conflict resolution for Optik 1.2: error.""" - def assert_conflict_error(self, func): + def assertTrueconflict_error(self, func): err = self.assertRaises( func, ("-v", "--version"), {'action' : "callback", 'callback' : self.show_version, @@ -1309,11 +1309,11 @@ class TestConflict(ConflictBase): self.assertEqual(err.option_id, "-v/--version") def test_conflict_error(self): - self.assert_conflict_error(self.parser.add_option) + self.assertTrueconflict_error(self.parser.add_option) def test_conflict_error_group(self): group = OptionGroup(self.parser, "Group 1") - self.assert_conflict_error(group.add_option) + self.assertTrueconflict_error(group.add_option) def test_no_such_conflict_handler(self): self.assertRaises( @@ -1333,8 +1333,8 @@ class TestConflictResolve(ConflictBase): verbose_opt = self.parser.get_option("--verbose") version_opt = self.parser.get_option("--version") - self.assert_(v_opt is version_opt) - self.assert_(v_opt is not verbose_opt) + self.assertTrue(v_opt is version_opt) + self.assertTrue(v_opt is not verbose_opt) self.assertEqual(v_opt._long_opts, ["--version"]) self.assertEqual(version_opt._short_opts, ["-v"]) self.assertEqual(version_opt._long_opts, ["--version"]) diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py index 42716fe..fa82a75 100644 --- a/Lib/test/test_os.py +++ b/Lib/test/test_os.py @@ -22,7 +22,7 @@ class FileTests(unittest.TestCase): def test_access(self): f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR) os.close(f) - self.assert_(os.access(test_support.TESTFN, os.W_OK)) + self.assertTrue(os.access(test_support.TESTFN, os.W_OK)) def test_closerange(self): first = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR) @@ -65,7 +65,7 @@ class TemporaryFileTests(unittest.TestCase): def check_tempfile(self, name): # make sure it doesn't already exist: - self.failIf(os.path.exists(name), + self.assertFalse(os.path.exists(name), "file already exists for temporary file") # make sure we can create the file open(name, "w") @@ -82,7 +82,7 @@ class TemporaryFileTests(unittest.TestCase): self.check_tempfile(name) name = os.tempnam(test_support.TESTFN, "pfx") - self.assert_(os.path.basename(name)[:3] == "pfx") + self.assertTrue(os.path.basename(name)[:3] == "pfx") self.check_tempfile(name) def test_tmpfile(self): @@ -131,7 +131,7 @@ class TemporaryFileTests(unittest.TestCase): fp.seek(0,0) s = fp.read() fp.close() - self.assert_(s == "foobar") + self.assertTrue(s == "foobar") def test_tmpnam(self): import sys @@ -156,7 +156,7 @@ class TemporaryFileTests(unittest.TestCase): # the root of the current drive. That's a terrible place to # put temp files, and, depending on privileges, the user # may not even be able to open a file in the root directory. - self.failIf(os.path.exists(name), + self.assertFalse(os.path.exists(name), "file already exists for temporary file") else: self.check_tempfile(name) @@ -198,7 +198,7 @@ class StatAttributeTests(unittest.TestCase): def trunc(x): return x self.assertEquals(trunc(getattr(result, attr)), result[getattr(stat, name)]) - self.assert_(attr in members) + self.assertTrue(attr in members) try: result[200] @@ -464,7 +464,7 @@ class MakedirTests (unittest.TestCase): os.makedirs(path) # Try paths with a '.' in them - self.failUnlessRaises(OSError, os.makedirs, os.curdir) + self.assertRaises(OSError, os.makedirs, os.curdir) path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir) os.makedirs(path) path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4', diff --git a/Lib/test/test_ossaudiodev.py b/Lib/test/test_ossaudiodev.py index 34893f1..df04705 100644 --- a/Lib/test/test_ossaudiodev.py +++ b/Lib/test/test_ossaudiodev.py @@ -57,7 +57,7 @@ class OSSAudioDevTests(unittest.TestCase): dsp.fileno() # Make sure the read-only attributes work. - self.failIf(dsp.closed) + self.assertFalse(dsp.closed) self.assertEqual(dsp.name, "/dev/dsp") self.assertEqual(dsp.mode, "w", "bad dsp.mode: %r" % dsp.mode) @@ -83,7 +83,7 @@ class OSSAudioDevTests(unittest.TestCase): elapsed_time = t2 - t1 percent_diff = (abs(elapsed_time - expected_time) / expected_time) * 100 - self.failUnless(percent_diff <= 10.0, + self.assertTrue(percent_diff <= 10.0, "elapsed time > 10% off of expected time") def set_parameters(self, dsp): @@ -131,7 +131,7 @@ class OSSAudioDevTests(unittest.TestCase): ]: (fmt, channels, rate) = config result = dsp.setparameters(fmt, channels, rate, False) - self.failIfEqual(result, config, + self.assertNotEqual(result, config, "unexpectedly got requested configuration") try: @@ -155,7 +155,7 @@ class OSSAudioDevTests(unittest.TestCase): #self.set_bad_parameters(dsp) finally: dsp.close() - self.failUnless(dsp.closed) + self.assertTrue(dsp.closed) def test_main(): diff --git a/Lib/test/test_peepholer.py b/Lib/test/test_peepholer.py index 6638a5a..1f6efb5 100644 --- a/Lib/test/test_peepholer.py +++ b/Lib/test/test_peepholer.py @@ -25,8 +25,8 @@ class TestTranforms(unittest.TestCase): del x asm = disassemble(unot) for elem in ('UNARY_NOT', 'POP_JUMP_IF_FALSE'): - self.assert_(elem not in asm) - self.assert_('POP_JUMP_IF_TRUE' in asm) + self.assertTrue(elem not in asm) + self.assertTrue('POP_JUMP_IF_TRUE' in asm) def test_elim_inversion_of_is_or_in(self): for line, elem in ( @@ -36,7 +36,7 @@ class TestTranforms(unittest.TestCase): ('not a not in b', '(in)',), ): asm = dis_single(line) - self.assert_(elem in asm) + self.assertTrue(elem in asm) def test_none_as_constant(self): # LOAD_GLOBAL None --> LOAD_CONST None @@ -45,14 +45,14 @@ class TestTranforms(unittest.TestCase): return x asm = disassemble(f) for elem in ('LOAD_GLOBAL',): - self.assert_(elem not in asm) + self.assertTrue(elem not in asm) for elem in ('LOAD_CONST', '(None)'): - self.assert_(elem in asm) + self.assertTrue(elem in asm) def f(): 'Adding a docstring made this test fail in Py2.5.0' return None - self.assert_('LOAD_CONST' in disassemble(f)) - self.assert_('LOAD_GLOBAL' not in disassemble(f)) + self.assertTrue('LOAD_CONST' in disassemble(f)) + self.assertTrue('LOAD_GLOBAL' not in disassemble(f)) def test_while_one(self): # Skip over: LOAD_CONST trueconst POP_JUMP_IF_FALSE xx @@ -62,9 +62,9 @@ class TestTranforms(unittest.TestCase): return list asm = disassemble(f) for elem in ('LOAD_CONST', 'POP_JUMP_IF_FALSE'): - self.assert_(elem not in asm) + self.assertTrue(elem not in asm) for elem in ('JUMP_ABSOLUTE',): - self.assert_(elem in asm) + self.assertTrue(elem in asm) def test_pack_unpack(self): for line, elem in ( @@ -73,9 +73,9 @@ class TestTranforms(unittest.TestCase): ('a, b, c = a, b, c', 'ROT_THREE',), ): asm = dis_single(line) - self.assert_(elem in asm) - self.assert_('BUILD_TUPLE' not in asm) - self.assert_('UNPACK_TUPLE' not in asm) + self.assertTrue(elem in asm) + self.assertTrue('BUILD_TUPLE' not in asm) + self.assertTrue('UNPACK_TUPLE' not in asm) def test_folding_of_tuples_of_constants(self): for line, elem in ( @@ -86,8 +86,8 @@ class TestTranforms(unittest.TestCase): ('((1, 2), 3, 4)', '(((1, 2), 3, 4))'), ): asm = dis_single(line) - self.assert_(elem in asm) - self.assert_('BUILD_TUPLE' not in asm) + self.assertTrue(elem in asm) + self.assertTrue('BUILD_TUPLE' not in asm) # Bug 1053819: Tuple of constants misidentified when presented with: # . . . opcode_with_arg 100 unary_opcode BUILD_TUPLE 1 . . . @@ -125,17 +125,17 @@ class TestTranforms(unittest.TestCase): ('a = 13 | 7', '(15)'), # binary or ): asm = dis_single(line) - self.assert_(elem in asm, asm) - self.assert_('BINARY_' not in asm) + self.assertTrue(elem in asm, asm) + self.assertTrue('BINARY_' not in asm) # Verify that unfoldables are skipped asm = dis_single('a=2+"b"') - self.assert_('(2)' in asm) - self.assert_("('b')" in asm) + self.assertTrue('(2)' in asm) + self.assertTrue("('b')" in asm) # Verify that large sequences do not result from folding asm = dis_single('a="x"*1000') - self.assert_('(1000)' in asm) + self.assertTrue('(1000)' in asm) def test_folding_of_unaryops_on_constants(self): for line, elem in ( @@ -144,8 +144,8 @@ class TestTranforms(unittest.TestCase): ('~-2', '(1)'), # unary invert ): asm = dis_single(line) - self.assert_(elem in asm, asm) - self.assert_('UNARY_' not in asm) + self.assertTrue(elem in asm, asm) + self.assertTrue('UNARY_' not in asm) # Verify that unfoldables are skipped for line, elem in ( @@ -153,16 +153,16 @@ class TestTranforms(unittest.TestCase): ('~"abc"', "('abc')"), # unary invert ): asm = dis_single(line) - self.assert_(elem in asm, asm) - self.assert_('UNARY_' in asm) + self.assertTrue(elem in asm, asm) + self.assertTrue('UNARY_' in asm) def test_elim_extra_return(self): # RETURN LOAD_CONST None RETURN --> RETURN def f(x): return x asm = disassemble(f) - self.assert_('LOAD_CONST' not in asm) - self.assert_('(None)' not in asm) + self.assertTrue('LOAD_CONST' not in asm) + self.assertTrue('(None)' not in asm) self.assertEqual(asm.split().count('RETURN_VALUE'), 1) def test_elim_jump_to_return(self): @@ -170,8 +170,8 @@ class TestTranforms(unittest.TestCase): def f(cond, true_value, false_value): return true_value if cond else false_value asm = disassemble(f) - self.assert_('JUMP_FORWARD' not in asm) - self.assert_('JUMP_ABSOLUTE' not in asm) + self.assertTrue('JUMP_FORWARD' not in asm) + self.assertTrue('JUMP_ABSOLUTE' not in asm) self.assertEqual(asm.split().count('RETURN_VALUE'), 2) def test_elim_jump_after_return1(self): @@ -186,8 +186,8 @@ class TestTranforms(unittest.TestCase): return 5 return 6 asm = disassemble(f) - self.assert_('JUMP_FORWARD' not in asm) - self.assert_('JUMP_ABSOLUTE' not in asm) + self.assertTrue('JUMP_FORWARD' not in asm) + self.assertTrue('JUMP_ABSOLUTE' not in asm) self.assertEqual(asm.split().count('RETURN_VALUE'), 6) def test_elim_jump_after_return2(self): @@ -196,7 +196,7 @@ class TestTranforms(unittest.TestCase): while 1: if cond1: return 4 asm = disassemble(f) - self.assert_('JUMP_FORWARD' not in asm) + self.assertTrue('JUMP_FORWARD' not in asm) # There should be one jump for the while loop. self.assertEqual(asm.split().count('JUMP_ABSOLUTE'), 1) self.assertEqual(asm.split().count('RETURN_VALUE'), 2) diff --git a/Lib/test/test_pep247.py b/Lib/test/test_pep247.py index 691c85a..7d7425e 100644 --- a/Lib/test/test_pep247.py +++ b/Lib/test/test_pep247.py @@ -19,8 +19,8 @@ from test import test_support class Pep247Test(unittest.TestCase): def check_module(self, module, key=None): - self.assert_(hasattr(module, 'digest_size')) - self.assert_(module.digest_size is None or module.digest_size > 0) + self.assertTrue(hasattr(module, 'digest_size')) + self.assertTrue(module.digest_size is None or module.digest_size > 0) if not key is None: obj1 = module.new(key) @@ -41,7 +41,7 @@ class Pep247Test(unittest.TestCase): self.assertEquals(h1, h2) - self.assert_(hasattr(obj1, 'digest_size')) + self.assertTrue(hasattr(obj1, 'digest_size')) if not module.digest_size is None: self.assertEquals(obj1.digest_size, module.digest_size) diff --git a/Lib/test/test_pep277.py b/Lib/test/test_pep277.py index a61bcdf..4695e0a 100644 --- a/Lib/test/test_pep277.py +++ b/Lib/test/test_pep277.py @@ -82,8 +82,8 @@ class UnicodeFileTests(unittest.TestCase): sys.getfilesystemencoding())) sf2 = set(u"\\".join((unicode(test_support.TESTFN), f)) for f in f2) - self.failUnlessEqual(len(f1), len(self.files)) - self.failUnlessEqual(sf2, set(self.files)) + self.assertEqual(len(f1), len(self.files)) + self.assertEqual(sf2, set(self.files)) def test_rename(self): for name in self.files: diff --git a/Lib/test/test_pep352.py b/Lib/test/test_pep352.py index 5f578d2..d2429eb 100644 --- a/Lib/test/test_pep352.py +++ b/Lib/test/test_pep352.py @@ -19,7 +19,7 @@ class ExceptionClassTests(unittest.TestCase): inheritance hierarchy)""" def test_builtins_new_style(self): - self.failUnless(issubclass(Exception, object)) + self.assertTrue(issubclass(Exception, object)) def verify_instance_interface(self, ins): with warnings.catch_warnings(): @@ -41,7 +41,7 @@ class ExceptionClassTests(unittest.TestCase): last_exc = getattr(__builtin__, superclass_name) except AttributeError: self.fail("base class %s not a built-in" % superclass_name) - self.failUnless(superclass_name in exc_set) + self.assertTrue(superclass_name in exc_set) exc_set.discard(superclass_name) superclasses = [] # Loop will insert base exception last_depth = 0 @@ -68,20 +68,20 @@ class ExceptionClassTests(unittest.TestCase): elif last_depth > depth: while superclasses[-1][0] >= depth: superclasses.pop() - self.failUnless(issubclass(exc, superclasses[-1][1]), + self.assertTrue(issubclass(exc, superclasses[-1][1]), "%s is not a subclass of %s" % (exc.__name__, superclasses[-1][1].__name__)) try: # Some exceptions require arguments; just skip them self.verify_instance_interface(exc()) except TypeError: pass - self.failUnless(exc_name in exc_set) + self.assertTrue(exc_name in exc_set) exc_set.discard(exc_name) last_exc = exc last_depth = depth finally: inheritance_tree.close() - self.failUnlessEqual(len(exc_set), 0, "%s not accounted for" % exc_set) + self.assertEqual(len(exc_set), 0, "%s not accounted for" % exc_set) interface_tests = ("length", "args", "message", "str", "unicode", "repr", "indexing") diff --git a/Lib/test/test_pkg.py b/Lib/test/test_pkg.py index 3a954ca..e3b86e6 100644 --- a/Lib/test/test_pkg.py +++ b/Lib/test/test_pkg.py @@ -126,7 +126,7 @@ class Test(unittest.TestCase): self.assertEqual(subsub.__name__, "t2.sub.subsub") self.assertEqual(sub.subsub.__name__, "t2.sub.subsub") for name in ['spam', 'sub', 'subsub', 't2']: - self.failUnless(locals()["name"], "Failed to import %s" % name) + self.assertTrue(locals()["name"], "Failed to import %s" % name) import t2.sub import t2.sub.subsub @@ -136,7 +136,7 @@ class Test(unittest.TestCase): s = """ from t2 import * - self.failUnless(dir(), ['self', 'sub']) + self.assertTrue(dir(), ['self', 'sub']) """ self.run_code(s) @@ -254,25 +254,25 @@ class Test(unittest.TestCase): self.assertEqual(fixdir(dir(tas)), ['__doc__', '__file__', '__name__', '__package__', '__path__']) - self.failIf(t7) + self.assertFalse(t7) from t7 import sub as subpar self.assertEqual(fixdir(dir(subpar)), ['__doc__', '__file__', '__name__', '__package__', '__path__']) - self.failIf(t7) - self.failIf(sub) + self.assertFalse(t7) + self.assertFalse(sub) from t7.sub import subsub as subsubsub self.assertEqual(fixdir(dir(subsubsub)), ['__doc__', '__file__', '__name__', '__package__', '__path__', 'spam']) - self.failIf(t7) - self.failIf(sub) - self.failIf(subsub) + self.assertFalse(t7) + self.assertFalse(sub) + self.assertFalse(subsub) from t7.sub.subsub import spam as ham self.assertEqual(ham, 1) - self.failIf(t7) - self.failIf(sub) - self.failIf(subsub) + self.assertFalse(t7) + self.assertFalse(sub) + self.assertFalse(subsub) def test_main(): diff --git a/Lib/test/test_pkgimport.py b/Lib/test/test_pkgimport.py index c87c342..8aa224a 100644 --- a/Lib/test/test_pkgimport.py +++ b/Lib/test/test_pkgimport.py @@ -52,7 +52,7 @@ class TestImport(unittest.TestCase): try: __import__(self.module_name) except SyntaxError: pass else: raise RuntimeError, 'Failed to induce SyntaxError' - self.assert_(not sys.modules.has_key(self.module_name) and + self.assertTrue(not sys.modules.has_key(self.module_name) and not hasattr(sys.modules[self.package_name], 'foo')) # ...make up a variable name that isn't bound in __builtins__ diff --git a/Lib/test/test_platform.py b/Lib/test/test_platform.py index 0ca761c..63d5da21 100644 --- a/Lib/test/test_platform.py +++ b/Lib/test/test_platform.py @@ -125,12 +125,12 @@ class PlatformTest(unittest.TestCase): def test_uname(self): res = platform.uname() - self.assert_(any(res)) + self.assertTrue(any(res)) def test_java_ver(self): res = platform.java_ver() if sys.platform == 'java': - self.assert_(all(res)) + self.assertTrue(all(res)) def test_win32_ver(self): res = platform.win32_ver() @@ -155,7 +155,7 @@ class PlatformTest(unittest.TestCase): real_ver = ln.strip().split()[-1] break fd.close() - self.failIf(real_ver is None) + self.assertFalse(real_ver is None) self.assertEquals(res[0], real_ver) # res[1] claims to contain diff --git a/Lib/test/test_poplib.py b/Lib/test/test_poplib.py index ad4b8d3..506d183 100644 --- a/Lib/test/test_poplib.py +++ b/Lib/test/test_poplib.py @@ -246,7 +246,7 @@ if hasattr(poplib, 'POP3_SSL'): self.client = poplib.POP3_SSL(self.server.host, self.server.port) def test__all__(self): - self.assert_('POP3_SSL' in poplib.__all__) + self.assertTrue('POP3_SSL' in poplib.__all__) class TestTimeouts(TestCase): diff --git a/Lib/test/test_posix.py b/Lib/test/test_posix.py index 32cba13..a96309d 100644 --- a/Lib/test/test_posix.py +++ b/Lib/test/test_posix.py @@ -43,13 +43,13 @@ class PosixTester(unittest.TestCase): def test_statvfs(self): if hasattr(posix, 'statvfs'): - self.assert_(posix.statvfs(os.curdir)) + self.assertTrue(posix.statvfs(os.curdir)) def test_fstatvfs(self): if hasattr(posix, 'fstatvfs'): fp = open(test_support.TESTFN) try: - self.assert_(posix.fstatvfs(fp.fileno())) + self.assertTrue(posix.fstatvfs(fp.fileno())) finally: fp.close() @@ -69,7 +69,7 @@ class PosixTester(unittest.TestCase): fp = open(test_support.TESTFN) try: fd = posix.dup(fp.fileno()) - self.assert_(isinstance(fd, int)) + self.assertTrue(isinstance(fd, int)) os.close(fd) finally: fp.close() @@ -135,13 +135,13 @@ class PosixTester(unittest.TestCase): if hasattr(posix, 'fstat'): fp = open(test_support.TESTFN) try: - self.assert_(posix.fstat(fp.fileno())) + self.assertTrue(posix.fstat(fp.fileno())) finally: fp.close() def test_stat(self): if hasattr(posix, 'stat'): - self.assert_(posix.stat(test_support.TESTFN)) + self.assertTrue(posix.stat(test_support.TESTFN)) if hasattr(posix, 'chown'): def test_chown(self): @@ -177,21 +177,21 @@ class PosixTester(unittest.TestCase): def test_lsdir(self): if hasattr(posix, 'lsdir'): - self.assert_(test_support.TESTFN in posix.lsdir(os.curdir)) + self.assertTrue(test_support.TESTFN in posix.lsdir(os.curdir)) def test_access(self): if hasattr(posix, 'access'): - self.assert_(posix.access(test_support.TESTFN, os.R_OK)) + self.assertTrue(posix.access(test_support.TESTFN, os.R_OK)) def test_umask(self): if hasattr(posix, 'umask'): old_mask = posix.umask(0) - self.assert_(isinstance(old_mask, int)) + self.assertTrue(isinstance(old_mask, int)) posix.umask(old_mask) def test_strerror(self): if hasattr(posix, 'strerror'): - self.assert_(posix.strerror(0)) + self.assertTrue(posix.strerror(0)) def test_pipe(self): if hasattr(posix, 'pipe'): @@ -201,9 +201,9 @@ class PosixTester(unittest.TestCase): def test_tempnam(self): if hasattr(posix, 'tempnam'): - self.assert_(posix.tempnam()) - self.assert_(posix.tempnam(os.curdir)) - self.assert_(posix.tempnam(os.curdir, 'blah')) + self.assertTrue(posix.tempnam()) + self.assertTrue(posix.tempnam(os.curdir)) + self.assertTrue(posix.tempnam(os.curdir, 'blah')) def test_tmpfile(self): if hasattr(posix, 'tmpfile'): diff --git a/Lib/test/test_posixpath.py b/Lib/test/test_posixpath.py index 0a0a48b..3e8ffa9 100644 --- a/Lib/test/test_posixpath.py +++ b/Lib/test/test_posixpath.py @@ -26,7 +26,7 @@ class PosixPathTest(unittest.TestCase): safe_rmdir(test_support.TESTFN + suffix) def assertIs(self, a, b): - self.assert_(a is b) + self.assertTrue(a is b) def test_normcase(self): # Check that normcase() is idempotent @@ -134,8 +134,8 @@ class PosixPathTest(unittest.TestCase): for s1 in testlist: for s2 in testlist: p = posixpath.commonprefix([s1, s2]) - self.assert_(s1.startswith(p)) - self.assert_(s2.startswith(p)) + self.assertTrue(s1.startswith(p)) + self.assertTrue(s2.startswith(p)) if s1 != s2: n = len(p) self.assertNotEqual(s1[n:n+1], s2[n:n+1]) @@ -163,7 +163,7 @@ class PosixPathTest(unittest.TestCase): f.close() self.assertEqual(d, "foobar") - self.assert_( + self.assertTrue( posixpath.getctime(test_support.TESTFN) <= posixpath.getmtime(test_support.TESTFN) ) @@ -335,15 +335,15 @@ class PosixPathTest(unittest.TestCase): except ImportError: pass else: - self.assert_(isinstance(posixpath.expanduser("~/"), basestring)) + self.assertTrue(isinstance(posixpath.expanduser("~/"), basestring)) # if home directory == root directory, this test makes no sense if posixpath.expanduser("~") != '/': self.assertEqual( posixpath.expanduser("~") + "/", posixpath.expanduser("~/") ) - self.assert_(isinstance(posixpath.expanduser("~root/"), basestring)) - self.assert_(isinstance(posixpath.expanduser("~foo/"), basestring)) + self.assertTrue(isinstance(posixpath.expanduser("~root/"), basestring)) + self.assertTrue(isinstance(posixpath.expanduser("~foo/"), basestring)) with test_support.EnvironmentVarGuard() as env: env['HOME'] = '/' @@ -384,12 +384,12 @@ class PosixPathTest(unittest.TestCase): self.assertRaises(TypeError, posixpath.normpath) def test_abspath(self): - self.assert_("foo" in posixpath.abspath("foo")) + self.assertTrue("foo" in posixpath.abspath("foo")) self.assertRaises(TypeError, posixpath.abspath) def test_realpath(self): - self.assert_("foo" in realpath("foo")) + self.assertTrue("foo" in realpath("foo")) self.assertRaises(TypeError, posixpath.realpath) if hasattr(os, "symlink"): diff --git a/Lib/test/test_pprint.py b/Lib/test/test_pprint.py index 3f29038..71b904c 100644 --- a/Lib/test/test_pprint.py +++ b/Lib/test/test_pprint.py @@ -40,7 +40,7 @@ class QueryTestCase(unittest.TestCase): def test_basic(self): # Verify .isrecursive() and .isreadable() w/o recursion - verify = self.assert_ + verify = self.assertTrue pp = pprint.PrettyPrinter() for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, uni("yaddayadda"), self.a, self.b): @@ -63,7 +63,7 @@ class QueryTestCase(unittest.TestCase): self.d = {} self.d[0] = self.d[1] = self.d[2] = self.d - verify = self.assert_ + verify = self.assertTrue pp = pprint.PrettyPrinter() for icky in self.a, self.b, self.d, (self.d, self.d): @@ -91,7 +91,7 @@ class QueryTestCase(unittest.TestCase): def test_unreadable(self): # Not recursive but not readable anyway - verify = self.assert_ + verify = self.assertTrue pp = pprint.PrettyPrinter() for unreadable in type(3), pprint, pprint.isrecursive: # module-level convenience functions @@ -114,7 +114,7 @@ class QueryTestCase(unittest.TestCase): # it sorted a dict display if and only if the display required # multiple lines. For that reason, dicts with more than one element # aren't tested here. - verify = self.assert_ + verify = self.assertTrue for simple in (0, 0L, 0+0j, 0.0, "", uni(""), (), tuple2(), tuple3(), [], list2(), list3(), diff --git a/Lib/test/test_property.py b/Lib/test/test_property.py index 7a8003f..684f8fe 100644 --- a/Lib/test/test_property.py +++ b/Lib/test/test_property.py @@ -86,8 +86,8 @@ class PropertyTests(unittest.TestCase): self.assertEqual(base.spam, 10) self.assertEqual(base._spam, 10) delattr(base, "spam") - self.assert_(not hasattr(base, "spam")) - self.assert_(not hasattr(base, "_spam")) + self.assertTrue(not hasattr(base, "spam")) + self.assertTrue(not hasattr(base, "_spam")) base.spam = 20 self.assertEqual(base.spam, 20) self.assertEqual(base._spam, 20) diff --git a/Lib/test/test_pwd.py b/Lib/test/test_pwd.py index de4084e..fdc74b4 100644 --- a/Lib/test/test_pwd.py +++ b/Lib/test/test_pwd.py @@ -13,19 +13,19 @@ class PwdTest(unittest.TestCase): for e in entries: self.assertEqual(len(e), 7) self.assertEqual(e[0], e.pw_name) - self.assert_(isinstance(e.pw_name, basestring)) + self.assertTrue(isinstance(e.pw_name, basestring)) self.assertEqual(e[1], e.pw_passwd) - self.assert_(isinstance(e.pw_passwd, basestring)) + self.assertTrue(isinstance(e.pw_passwd, basestring)) self.assertEqual(e[2], e.pw_uid) - self.assert_(isinstance(e.pw_uid, int)) + self.assertTrue(isinstance(e.pw_uid, int)) self.assertEqual(e[3], e.pw_gid) - self.assert_(isinstance(e.pw_gid, int)) + self.assertTrue(isinstance(e.pw_gid, int)) self.assertEqual(e[4], e.pw_gecos) - self.assert_(isinstance(e.pw_gecos, basestring)) + self.assertTrue(isinstance(e.pw_gecos, basestring)) self.assertEqual(e[5], e.pw_dir) - self.assert_(isinstance(e.pw_dir, basestring)) + self.assertTrue(isinstance(e.pw_dir, basestring)) self.assertEqual(e[6], e.pw_shell) - self.assert_(isinstance(e.pw_shell, basestring)) + self.assertTrue(isinstance(e.pw_shell, basestring)) # The following won't work, because of duplicate entries # for one uid @@ -43,8 +43,8 @@ class PwdTest(unittest.TestCase): for e in entries: if not e[0] or e[0] == '+': continue # skip NIS entries etc. - self.assert_(pwd.getpwnam(e.pw_name) in entriesbyname[e.pw_name]) - self.assert_(pwd.getpwuid(e.pw_uid) in entriesbyuid[e.pw_uid]) + self.assertTrue(pwd.getpwnam(e.pw_name) in entriesbyname[e.pw_name]) + self.assertTrue(pwd.getpwuid(e.pw_uid) in entriesbyuid[e.pw_uid]) def test_errors(self): self.assertRaises(TypeError, pwd.getpwuid) diff --git a/Lib/test/test_py3kwarn.py b/Lib/test/test_py3kwarn.py index 7c25980..36c988f 100644 --- a/Lib/test/test_py3kwarn.py +++ b/Lib/test/test_py3kwarn.py @@ -317,7 +317,7 @@ class TestStdlibRemovals(unittest.TestCase): try: __import__(module_name, level=0) except DeprecationWarning as exc: - self.assert_(module_name in exc.args[0], + self.assertTrue(module_name in exc.args[0], "%s warning didn't contain module name" % module_name) except ImportError: diff --git a/Lib/test/test_pyclbr.py b/Lib/test/test_pyclbr.py index 5fbe75d..71dda22 100644 --- a/Lib/test/test_pyclbr.py +++ b/Lib/test/test_pyclbr.py @@ -35,7 +35,7 @@ class PyclbrTest(TestCase): ''' succeed iff hasattr(obj,attr) or attr in ignore. ''' if attr in ignore: return if not hasattr(obj, attr): print "???", attr - self.failUnless(hasattr(obj, attr), + self.assertTrue(hasattr(obj, attr), 'expected hasattr(%r, %r)' % (obj, attr)) @@ -44,7 +44,7 @@ class PyclbrTest(TestCase): if key in ignore: return if not obj.has_key(key): print >>sys.stderr, "***",key - self.failUnless(obj.has_key(key)) + self.assertTrue(obj.has_key(key)) def assertEqualsOrIgnored(self, a, b, ignore): ''' succeed iff a == b or a in ignore or b in ignore ''' @@ -92,12 +92,12 @@ class PyclbrTest(TestCase): self.assertHasattr(module, name, ignore) py_item = getattr(module, name) if isinstance(value, pyclbr.Function): - self.assert_(isinstance(py_item, (FunctionType, BuiltinFunctionType))) + self.assertTrue(isinstance(py_item, (FunctionType, BuiltinFunctionType))) if py_item.__module__ != moduleName: continue # skip functions that came from somewhere else self.assertEquals(py_item.__module__, value.module) else: - self.failUnless(isinstance(py_item, (ClassType, type))) + self.assertTrue(isinstance(py_item, (ClassType, type))) if py_item.__module__ != moduleName: continue # skip classes that came from somewhere else diff --git a/Lib/test/test_pydoc.py b/Lib/test/test_pydoc.py index c1c19f6..0faf4a1 100644 --- a/Lib/test/test_pydoc.py +++ b/Lib/test/test_pydoc.py @@ -294,7 +294,7 @@ class TestDescriptions(unittest.TestCase): # Check that pydocfodder module can be described from test import pydocfodder doc = pydoc.render_doc(pydocfodder) - self.assert_("pydocfodder" in doc) + self.assertTrue("pydocfodder" in doc) def test_classic_class(self): class C: "Classic class" @@ -302,7 +302,7 @@ class TestDescriptions(unittest.TestCase): self.assertEqual(pydoc.describe(C), 'class C') self.assertEqual(pydoc.describe(c), 'instance of C') expected = 'instance of C in module %s' % __name__ - self.assert_(expected in pydoc.render_doc(c)) + self.assertTrue(expected in pydoc.render_doc(c)) def test_class(self): class C(object): "New-style class" @@ -311,7 +311,7 @@ class TestDescriptions(unittest.TestCase): self.assertEqual(pydoc.describe(C), 'class C') self.assertEqual(pydoc.describe(c), 'C') expected = 'C in module %s object' % __name__ - self.assert_(expected in pydoc.render_doc(c)) + self.assertTrue(expected in pydoc.render_doc(c)) def test_main(): diff --git a/Lib/test/test_queue.py b/Lib/test/test_queue.py index e0eb8f4..2fa36b7 100644 --- a/Lib/test/test_queue.py +++ b/Lib/test/test_queue.py @@ -100,10 +100,10 @@ class BaseQueueTest(unittest.TestCase, BlockingTestMixin): "Didn't seem to queue the correct data!") for i in range(QUEUE_SIZE-1): q.put(i) - self.assert_(not q.empty(), "Queue should not be empty") - self.assert_(not q.full(), "Queue should not be full") + self.assertTrue(not q.empty(), "Queue should not be empty") + self.assertTrue(not q.full(), "Queue should not be full") q.put("last") - self.assert_(q.full(), "Queue should be full") + self.assertTrue(q.full(), "Queue should be full") try: q.put("full", block=0) self.fail("Didn't appear to block with a full queue") @@ -120,7 +120,7 @@ class BaseQueueTest(unittest.TestCase, BlockingTestMixin): # Empty it for i in range(QUEUE_SIZE): q.get() - self.assert_(q.empty(), "Queue should be empty") + self.assertTrue(q.empty(), "Queue should be empty") try: q.get(block=0) self.fail("Didn't appear to block with an empty queue") @@ -242,7 +242,7 @@ class FailingQueueTest(unittest.TestCase, BlockingTestMixin): except FailingQueueException: pass q.put("last") - self.assert_(q.full(), "Queue should be full") + self.assertTrue(q.full(), "Queue should be full") # Test a failing blocking put q.fail_next_put = True try: @@ -264,17 +264,17 @@ class FailingQueueTest(unittest.TestCase, BlockingTestMixin): # Check the Queue isn't damaged. # put failed, but get succeeded - re-add q.put("last") - self.assert_(q.full(), "Queue should be full") + self.assertTrue(q.full(), "Queue should be full") q.get() - self.assert_(not q.full(), "Queue should not be full") + self.assertTrue(not q.full(), "Queue should not be full") q.put("last") - self.assert_(q.full(), "Queue should be full") + self.assertTrue(q.full(), "Queue should be full") # Test a blocking put self.do_blocking_test(q.put, ("full",), q.get, ()) # Empty it for i in range(QUEUE_SIZE): q.get() - self.assert_(q.empty(), "Queue should be empty") + self.assertTrue(q.empty(), "Queue should be empty") q.put("first") q.fail_next_get = True try: @@ -282,16 +282,16 @@ class FailingQueueTest(unittest.TestCase, BlockingTestMixin): self.fail("The queue didn't fail when it should have") except FailingQueueException: pass - self.assert_(not q.empty(), "Queue should not be empty") + self.assertTrue(not q.empty(), "Queue should not be empty") q.fail_next_get = True try: q.get(timeout=0.1) self.fail("The queue didn't fail when it should have") except FailingQueueException: pass - self.assert_(not q.empty(), "Queue should not be empty") + self.assertTrue(not q.empty(), "Queue should not be empty") q.get() - self.assert_(q.empty(), "Queue should be empty") + self.assertTrue(q.empty(), "Queue should be empty") q.fail_next_get = True try: self.do_exceptional_blocking_test(q.get, (), q.put, ('empty',), @@ -300,9 +300,9 @@ class FailingQueueTest(unittest.TestCase, BlockingTestMixin): except FailingQueueException: pass # put succeeded, but get failed. - self.assert_(not q.empty(), "Queue should not be empty") + self.assertTrue(not q.empty(), "Queue should not be empty") q.get() - self.assert_(q.empty(), "Queue should be empty") + self.assertTrue(q.empty(), "Queue should be empty") def test_failing_queue(self): # Test to make sure a queue is functioning correctly. diff --git a/Lib/test/test_quopri.py b/Lib/test/test_quopri.py index 56a793c..406e5fc 100644 --- a/Lib/test/test_quopri.py +++ b/Lib/test/test_quopri.py @@ -130,17 +130,17 @@ zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz''') @withpythonimplementation def test_encodestring(self): for p, e in self.STRINGS: - self.assert_(quopri.encodestring(p) == e) + self.assertTrue(quopri.encodestring(p) == e) @withpythonimplementation def test_decodestring(self): for p, e in self.STRINGS: - self.assert_(quopri.decodestring(e) == p) + self.assertTrue(quopri.decodestring(e) == p) @withpythonimplementation def test_idempotent_string(self): for p, e in self.STRINGS: - self.assert_(quopri.decodestring(quopri.encodestring(e)) == e) + self.assertTrue(quopri.decodestring(quopri.encodestring(e)) == e) @withpythonimplementation def test_encode(self): @@ -148,7 +148,7 @@ zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz''') infp = cStringIO.StringIO(p) outfp = cStringIO.StringIO() quopri.encode(infp, outfp, quotetabs=False) - self.assert_(outfp.getvalue() == e) + self.assertTrue(outfp.getvalue() == e) @withpythonimplementation def test_decode(self): @@ -156,23 +156,23 @@ zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz''') infp = cStringIO.StringIO(e) outfp = cStringIO.StringIO() quopri.decode(infp, outfp) - self.assert_(outfp.getvalue() == p) + self.assertTrue(outfp.getvalue() == p) @withpythonimplementation def test_embedded_ws(self): for p, e in self.ESTRINGS: - self.assert_(quopri.encodestring(p, quotetabs=True) == e) - self.assert_(quopri.decodestring(e) == p) + self.assertTrue(quopri.encodestring(p, quotetabs=True) == e) + self.assertTrue(quopri.decodestring(e) == p) @withpythonimplementation def test_encode_header(self): for p, e in self.HSTRINGS: - self.assert_(quopri.encodestring(p, header=True) == e) + self.assertTrue(quopri.encodestring(p, header=True) == e) @withpythonimplementation def test_decode_header(self): for p, e in self.HSTRINGS: - self.assert_(quopri.decodestring(e, header=True) == p) + self.assertTrue(quopri.decodestring(e, header=True) == p) def test_scriptencode(self): (p, e) = self.STRINGS[-1] diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py index 8e4639e..30bd330 100644 --- a/Lib/test/test_random.py +++ b/Lib/test/test_random.py @@ -67,7 +67,7 @@ class TestBasicOps(unittest.TestCase): self.assertEqual(len(s), k) uniq = set(s) self.assertEqual(len(uniq), k) - self.failUnless(uniq <= set(population)) + self.assertTrue(uniq <= set(population)) self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0 def test_sample_distribution(self): @@ -112,7 +112,7 @@ class TestBasicOps(unittest.TestCase): samp = self.gen.sample(d, k) # Verify that we got ints back (keys); the values are complex. for x in samp: - self.assert_(type(x) is int) + self.assertTrue(type(x) is int) samp.sort() self.assertEqual(samp, range(N)) @@ -237,7 +237,7 @@ class SystemRandom_TestBasicOps(TestBasicOps): cum = 0 for i in xrange(100): r = self.gen.randrange(span) - self.assert_(0 <= r < span) + self.assertTrue(0 <= r < span) cum |= r self.assertEqual(cum, span-1) @@ -247,7 +247,7 @@ class SystemRandom_TestBasicOps(TestBasicOps): stop = self.gen.randrange(2 ** (i-2)) if stop <= start: return - self.assert_(start <= self.gen.randrange(start, stop) < stop) + self.assertTrue(start <= self.gen.randrange(start, stop) < stop) def test_rangelimits(self): for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]: @@ -257,7 +257,7 @@ class SystemRandom_TestBasicOps(TestBasicOps): def test_genrandbits(self): # Verify ranges for k in xrange(1, 1000): - self.assert_(0 <= self.gen.getrandbits(k) < 2**k) + self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k) # Verify all bits active getbits = self.gen.getrandbits @@ -283,17 +283,17 @@ class SystemRandom_TestBasicOps(TestBasicOps): numbits = i+1 k = int(1.00001 + _log(n, 2)) self.assertEqual(k, numbits) - self.assert_(n == 2**(k-1)) + self.assertTrue(n == 2**(k-1)) n += n - 1 # check 1 below the next power of two k = int(1.00001 + _log(n, 2)) - self.assert_(k in [numbits, numbits+1]) - self.assert_(2**k > n > 2**(k-2)) + self.assertTrue(k in [numbits, numbits+1]) + self.assertTrue(2**k > n > 2**(k-2)) n -= n >> 15 # check a little farther below the next power of two k = int(1.00001 + _log(n, 2)) self.assertEqual(k, numbits) # note the stronger assertion - self.assert_(2**k > n > 2**(k-1)) # note the stronger assertion + self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion class MersenneTwister_TestBasicOps(TestBasicOps): @@ -389,7 +389,7 @@ class MersenneTwister_TestBasicOps(TestBasicOps): cum = 0 for i in xrange(100): r = self.gen.randrange(span) - self.assert_(0 <= r < span) + self.assertTrue(0 <= r < span) cum |= r self.assertEqual(cum, span-1) @@ -399,7 +399,7 @@ class MersenneTwister_TestBasicOps(TestBasicOps): stop = self.gen.randrange(2 ** (i-2)) if stop <= start: return - self.assert_(start <= self.gen.randrange(start, stop) < stop) + self.assertTrue(start <= self.gen.randrange(start, stop) < stop) def test_rangelimits(self): for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]: @@ -413,7 +413,7 @@ class MersenneTwister_TestBasicOps(TestBasicOps): 97904845777343510404718956115L) # Verify ranges for k in xrange(1, 1000): - self.assert_(0 <= self.gen.getrandbits(k) < 2**k) + self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k) # Verify all bits active getbits = self.gen.getrandbits @@ -439,24 +439,24 @@ class MersenneTwister_TestBasicOps(TestBasicOps): numbits = i+1 k = int(1.00001 + _log(n, 2)) self.assertEqual(k, numbits) - self.assert_(n == 2**(k-1)) + self.assertTrue(n == 2**(k-1)) n += n - 1 # check 1 below the next power of two k = int(1.00001 + _log(n, 2)) - self.assert_(k in [numbits, numbits+1]) - self.assert_(2**k > n > 2**(k-2)) + self.assertTrue(k in [numbits, numbits+1]) + self.assertTrue(2**k > n > 2**(k-2)) n -= n >> 15 # check a little farther below the next power of two k = int(1.00001 + _log(n, 2)) self.assertEqual(k, numbits) # note the stronger assertion - self.assert_(2**k > n > 2**(k-1)) # note the stronger assertion + self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion def test_randrange_bug_1590891(self): start = 1000000000000 stop = -100000000000000000000 step = -200 x = self.gen.randrange(start, stop, step) - self.assert_(stop < x <= start) + self.assertTrue(stop < x <= start) self.assertEqual((x+stop)%step, 0) def gamma(z, sqrt2pi=(2.0*pi)**0.5): @@ -534,7 +534,7 @@ class TestModule(unittest.TestCase): def test__all__(self): # tests validity but not completeness of the __all__ list - self.failUnless(set(random.__all__) <= set(dir(random))) + self.assertTrue(set(random.__all__) <= set(dir(random))) def test_random_subclass_with_kwargs(self): # SF bug #1486663 -- this used to erroneously raise a TypeError diff --git a/Lib/test/test_re.py b/Lib/test/test_re.py index feb7160..4f543d9 100644 --- a/Lib/test/test_re.py +++ b/Lib/test/test_re.py @@ -609,7 +609,7 @@ class ReTests(unittest.TestCase): unicode except NameError: return # no problem if we have no unicode - self.assert_(re.compile('bug_926075') is not + self.assertTrue(re.compile('bug_926075') is not re.compile(eval("u'bug_926075'"))) def test_bug_931848(self): diff --git a/Lib/test/test_repr.py b/Lib/test/test_repr.py index 1094816..494a7c3 100644 --- a/Lib/test/test_repr.py +++ b/Lib/test/test_repr.py @@ -123,20 +123,20 @@ class ReprTests(unittest.TestCase): eq(r(i3), ("<ClassWithFailingRepr instance at %x>"%id(i3))) s = r(ClassWithFailingRepr) - self.failUnless(s.startswith("<class ")) - self.failUnless(s.endswith(">")) - self.failUnless(s.find("...") == 8) + self.assertTrue(s.startswith("<class ")) + self.assertTrue(s.endswith(">")) + self.assertTrue(s.find("...") == 8) def test_file(self): fp = open(unittest.__file__) - self.failUnless(repr(fp).startswith( + self.assertTrue(repr(fp).startswith( "<open file '%s', mode 'r' at 0x" % unittest.__file__)) fp.close() - self.failUnless(repr(fp).startswith( + self.assertTrue(repr(fp).startswith( "<closed file '%s', mode 'r' at 0x" % unittest.__file__)) def test_lambda(self): - self.failUnless(repr(lambda x: x).startswith( + self.assertTrue(repr(lambda x: x).startswith( "<function <lambda")) # XXX anonymous functions? see func_repr @@ -145,7 +145,7 @@ class ReprTests(unittest.TestCase): # Functions eq(repr(hash), '<built-in function hash>') # Methods - self.failUnless(repr(''.split).startswith( + self.assertTrue(repr(''.split).startswith( '<built-in method split of str object at 0x')) def test_xrange(self): @@ -175,7 +175,7 @@ class ReprTests(unittest.TestCase): # XXX doesn't test buffers with no b_base or read-write buffers (see # bufferobject.c). The test is fairly incomplete too. Sigh. x = buffer('foo') - self.failUnless(repr(x).startswith('<read-only buffer for 0x')) + self.assertTrue(repr(x).startswith('<read-only buffer for 0x')) def test_cell(self): # XXX Hmm? How to get at a cell object? @@ -192,9 +192,9 @@ class ReprTests(unittest.TestCase): class C: def foo(cls): pass x = staticmethod(C.foo) - self.failUnless(repr(x).startswith('<staticmethod object at 0x')) + self.assertTrue(repr(x).startswith('<staticmethod object at 0x')) x = classmethod(C.foo) - self.failUnless(repr(x).startswith('<classmethod object at 0x')) + self.assertTrue(repr(x).startswith('<classmethod object at 0x')) def test_unsortable(self): # Repr.repr() used to call sorted() on sets, frozensets and dicts @@ -272,7 +272,7 @@ class bar: ''') from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar # Module name may be prefixed with "test.", depending on how run. - self.failUnless(repr(bar.bar).startswith( + self.assertTrue(repr(bar.bar).startswith( "<class %s.bar at 0x" % bar.__name__)) def test_instance(self): @@ -282,7 +282,7 @@ class baz: ''') from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz ibaz = baz.baz() - self.failUnless(repr(ibaz).startswith( + self.assertTrue(repr(ibaz).startswith( "<%s.baz instance at 0x" % baz.__name__)) def test_method(self): @@ -297,7 +297,7 @@ class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa '<unbound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod>') # Bound method next iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() - self.failUnless(repr(iqux.amethod).startswith( + self.assertTrue(repr(iqux.amethod).startswith( '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa instance at 0x' \ % (qux.__name__,) )) diff --git a/Lib/test/test_rfc822.py b/Lib/test/test_rfc822.py index afbc984..8c2b2c6 100644 --- a/Lib/test/test_rfc822.py +++ b/Lib/test/test_rfc822.py @@ -16,23 +16,23 @@ class MessageTestCase(unittest.TestCase): def test_get(self): msg = self.create_message( 'To: "last, first" <userid@foo.net>\n\ntest\n') - self.assert_(msg.get("to") == '"last, first" <userid@foo.net>') - self.assert_(msg.get("TO") == '"last, first" <userid@foo.net>') - self.assert_(msg.get("No-Such-Header") is None) - self.assert_(msg.get("No-Such-Header", "No-Such-Value") + self.assertTrue(msg.get("to") == '"last, first" <userid@foo.net>') + self.assertTrue(msg.get("TO") == '"last, first" <userid@foo.net>') + self.assertTrue(msg.get("No-Such-Header") is None) + self.assertTrue(msg.get("No-Such-Header", "No-Such-Value") == "No-Such-Value") def test_setdefault(self): msg = self.create_message( 'To: "last, first" <userid@foo.net>\n\ntest\n') - self.assert_(not msg.has_key("New-Header")) - self.assert_(msg.setdefault("New-Header", "New-Value") == "New-Value") - self.assert_(msg.setdefault("New-Header", "Different-Value") + self.assertTrue(not msg.has_key("New-Header")) + self.assertTrue(msg.setdefault("New-Header", "New-Value") == "New-Value") + self.assertTrue(msg.setdefault("New-Header", "Different-Value") == "New-Value") - self.assert_(msg["new-header"] == "New-Value") + self.assertTrue(msg["new-header"] == "New-Value") - self.assert_(msg.setdefault("Another-Header") == "") - self.assert_(msg["another-header"] == "") + self.assertTrue(msg.setdefault("Another-Header") == "") + self.assertTrue(msg["another-header"] == "") def check(self, msg, results): """Check addresses and the date.""" diff --git a/Lib/test/test_richcmp.py b/Lib/test/test_richcmp.py index ad68386..ed0b497 100644 --- a/Lib/test/test_richcmp.py +++ b/Lib/test/test_richcmp.py @@ -106,7 +106,7 @@ class VectorTest(unittest.TestCase): self.assertEqual(len(realres), len(expres)) for i in xrange(len(realres)): # results are bool, so we can use "is" here - self.assert_(realres[i] is expres[i]) + self.assertTrue(realres[i] is expres[i]) def test_mixed(self): # check that comparisons involving Vector objects @@ -163,7 +163,7 @@ class NumberTest(unittest.TestCase): for op in opmap[opname]: realres = op(ta, tb) realres = getattr(realres, "x", realres) - self.assert_(realres is expres) + self.assertTrue(realres is expres) def test_values(self): # check all operators and all comparison results @@ -239,8 +239,8 @@ class MiscTest(unittest.TestCase): b.append(17) # Even recursive lists of different lengths are different, # but they cannot be ordered - self.assert_(not (a == b)) - self.assert_(a != b) + self.assertTrue(not (a == b)) + self.assertTrue(a != b) self.assertRaises(RuntimeError, operator.lt, a, b) self.assertRaises(RuntimeError, operator.le, a, b) self.assertRaises(RuntimeError, operator.gt, a, b) @@ -250,9 +250,9 @@ class MiscTest(unittest.TestCase): self.assertRaises(RuntimeError, operator.ne, a, b) a.insert(0, 11) b.insert(0, 12) - self.assert_(not (a == b)) - self.assert_(a != b) - self.assert_(a < b) + self.assertTrue(not (a == b)) + self.assertTrue(a != b) + self.assertTrue(a < b) class DictTest(unittest.TestCase): @@ -271,10 +271,10 @@ class DictTest(unittest.TestCase): imag1b[k] = v imag2 = imag1b.copy() imag2[k] = v + 1.0 - self.assert_(imag1a == imag1a) - self.assert_(imag1a == imag1b) - self.assert_(imag2 == imag2) - self.assert_(imag1a != imag2) + self.assertTrue(imag1a == imag1a) + self.assertTrue(imag1a == imag1b) + self.assertTrue(imag2 == imag2) + self.assertTrue(imag1a != imag2) for opname in ("lt", "le", "gt", "ge"): for op in opmap[opname]: self.assertRaises(TypeError, op, imag1a, imag2) @@ -282,7 +282,7 @@ class DictTest(unittest.TestCase): class ListTest(unittest.TestCase): def assertIs(self, a, b): - self.assert_(a is b) + self.assertTrue(a is b) def test_coverage(self): # exercise all comparisons for lists diff --git a/Lib/test/test_robotparser.py b/Lib/test/test_robotparser.py index 431b8ff..26fb290 100644 --- a/Lib/test/test_robotparser.py +++ b/Lib/test/test_robotparser.py @@ -20,9 +20,9 @@ class RobotTestCase(unittest.TestCase): url = self.url agent = self.agent if self.good: - self.failUnless(self.parser.can_fetch(agent, url)) + self.assertTrue(self.parser.can_fetch(agent, url)) else: - self.failIf(self.parser.can_fetch(agent, url)) + self.assertFalse(self.parser.can_fetch(agent, url)) def __str__(self): return self.str diff --git a/Lib/test/test_runpy.py b/Lib/test/test_runpy.py index 165cb63..fa5d9b7 100644 --- a/Lib/test/test_runpy.py +++ b/Lib/test/test_runpy.py @@ -37,14 +37,14 @@ class RunModuleCodeTest(unittest.TestCase): def test_run_code(self): saved_argv0 = sys.argv[0] d = _run_code(self.test_source, {}) - self.failUnless(d["result"] == self.expected_result) - self.failUnless(d["__name__"] is None) - self.failUnless(d["__file__"] is None) - self.failUnless(d["__loader__"] is None) - self.failUnless(d["__package__"] is None) - self.failUnless(d["run_argv0"] is saved_argv0) - self.failUnless("run_name" not in d) - self.failUnless(sys.argv[0] is saved_argv0) + self.assertTrue(d["result"] == self.expected_result) + self.assertTrue(d["__name__"] is None) + self.assertTrue(d["__file__"] is None) + self.assertTrue(d["__loader__"] is None) + self.assertTrue(d["__package__"] is None) + self.assertTrue(d["run_argv0"] is saved_argv0) + self.assertTrue("run_name" not in d) + self.assertTrue(sys.argv[0] is saved_argv0) def test_run_module_code(self): initial = object() @@ -60,19 +60,19 @@ class RunModuleCodeTest(unittest.TestCase): file, loader, package) - self.failUnless("result" not in d1) - self.failUnless(d2["initial"] is initial) - self.failUnless(d2["result"] == self.expected_result) - self.failUnless(d2["nested"]["x"] == 1) - self.failUnless(d2["__name__"] is name) - self.failUnless(d2["run_name_in_sys_modules"]) - self.failUnless(d2["module_in_sys_modules"]) - self.failUnless(d2["__file__"] is file) - self.failUnless(d2["run_argv0"] is file) - self.failUnless(d2["__loader__"] is loader) - self.failUnless(d2["__package__"] is package) - self.failUnless(sys.argv[0] is saved_argv0) - self.failUnless(name not in sys.modules) + self.assertTrue("result" not in d1) + self.assertTrue(d2["initial"] is initial) + self.assertTrue(d2["result"] == self.expected_result) + self.assertTrue(d2["nested"]["x"] == 1) + self.assertTrue(d2["__name__"] is name) + self.assertTrue(d2["run_name_in_sys_modules"]) + self.assertTrue(d2["module_in_sys_modules"]) + self.assertTrue(d2["__file__"] is file) + self.assertTrue(d2["run_argv0"] is file) + self.assertTrue(d2["__loader__"] is loader) + self.assertTrue(d2["__package__"] is package) + self.assertTrue(sys.argv[0] is saved_argv0) + self.assertTrue(name not in sys.modules) class RunModuleTest(unittest.TestCase): @@ -159,15 +159,15 @@ class RunModuleTest(unittest.TestCase): try: if verbose: print "Running from source:", mod_name d1 = run_module(mod_name) # Read from source - self.failUnless("x" in d1) - self.failUnless(d1["x"] == 1) + self.assertTrue("x" in d1) + self.assertTrue(d1["x"] == 1) del d1 # Ensure __loader__ entry doesn't keep file open __import__(mod_name) os.remove(mod_fname) if verbose: print "Running from compiled:", mod_name d2 = run_module(mod_name) # Read from bytecode - self.failUnless("x" in d2) - self.failUnless(d2["x"] == 1) + self.assertTrue("x" in d2) + self.assertTrue(d2["x"] == 1) del d2 # Ensure __loader__ entry doesn't keep file open finally: self._del_pkg(pkg_dir, depth, mod_name) @@ -211,19 +211,19 @@ from ..uncle.cousin import nephew pkg_name = mod_name.rpartition('.')[0] if verbose: print "Running from source:", mod_name d1 = run_module(mod_name, run_name=run_name) # Read from source - self.failUnless("__package__" in d1) - self.failUnless(d1["__package__"] == pkg_name) - self.failUnless("sibling" in d1) - self.failUnless("nephew" in d1) + self.assertTrue("__package__" in d1) + self.assertTrue(d1["__package__"] == pkg_name) + self.assertTrue("sibling" in d1) + self.assertTrue("nephew" in d1) del d1 # Ensure __loader__ entry doesn't keep file open __import__(mod_name) os.remove(mod_fname) if verbose: print "Running from compiled:", mod_name d2 = run_module(mod_name, run_name=run_name) # Read from bytecode - self.failUnless("__package__" in d2) - self.failUnless(d2["__package__"] == pkg_name) - self.failUnless("sibling" in d2) - self.failUnless("nephew" in d2) + self.assertTrue("__package__" in d2) + self.assertTrue(d2["__package__"] == pkg_name) + self.assertTrue("sibling" in d2) + self.assertTrue("nephew" in d2) del d2 # Ensure __loader__ entry doesn't keep file open finally: self._del_pkg(pkg_dir, depth, mod_name) diff --git a/Lib/test/test_scope.py b/Lib/test/test_scope.py index 36177ea..b68e8f5 100644 --- a/Lib/test/test_scope.py +++ b/Lib/test/test_scope.py @@ -467,7 +467,7 @@ class X: locals()['looked_up_by_load_name'] = True passed = looked_up_by_load_name -self.assert_(X.passed) +self.assertTrue(X.passed) """ def testLocalsFunction(self): @@ -482,7 +482,7 @@ self.assert_(X.passed) return g d = f(2)(4) - self.assert_(d.has_key('h')) + self.assertTrue(d.has_key('h')) del d['h'] self.assertEqual(d, {'x': 2, 'y': 7, 'w': 6}) @@ -516,8 +516,8 @@ self.assert_(X.passed) return C varnames = f(1).z - self.assert_("x" not in varnames) - self.assert_("y" in varnames) + self.assertTrue("x" not in varnames) + self.assertTrue("y" in varnames) def testLocalsClass_WithTrace(self): # Issue23728: after the trace function returns, the locals() diff --git a/Lib/test/test_set.py b/Lib/test/test_set.py index 886c4b8..872e9ea 100644 --- a/Lib/test/test_set.py +++ b/Lib/test/test_set.py @@ -64,7 +64,7 @@ class TestJointOps(unittest.TestCase): self.assertEqual(c in self.s, c in self.d) self.assertRaises(TypeError, self.s.__contains__, [[]]) s = self.thetype([frozenset(self.letters)]) - self.assert_(self.thetype(self.letters) in s) + self.assertTrue(self.thetype(self.letters) in s) def test_union(self): u = self.s.union(self.otherword) @@ -124,7 +124,7 @@ class TestJointOps(unittest.TestCase): actual = s1.isdisjoint(s2) expected = f(s1, s2) self.assertEqual(actual, expected) - self.assert_(actual is True or actual is False) + self.assertTrue(actual is True or actual is False) def test_and(self): i = self.s.intersection(self.otherword) @@ -207,19 +207,19 @@ class TestJointOps(unittest.TestCase): def test_sub_and_super(self): p, q, r = map(self.thetype, ['ab', 'abcde', 'def']) - self.assert_(p < q) - self.assert_(p <= q) - self.assert_(q <= q) - self.assert_(q > p) - self.assert_(q >= p) - self.failIf(q < r) - self.failIf(q <= r) - self.failIf(q > r) - self.failIf(q >= r) - self.assert_(set('a').issubset('abc')) - self.assert_(set('abc').issuperset('a')) - self.failIf(set('a').issubset('cbs')) - self.failIf(set('cbs').issuperset('a')) + self.assertTrue(p < q) + self.assertTrue(p <= q) + self.assertTrue(q <= q) + self.assertTrue(q > p) + self.assertTrue(q >= p) + self.assertFalse(q < r) + self.assertFalse(q <= r) + self.assertFalse(q > r) + self.assertFalse(q >= r) + self.assertTrue(set('a').issubset('abc')) + self.assertTrue(set('abc').issuperset('a')) + self.assertFalse(set('a').issubset('cbs')) + self.assertFalse(set('cbs').issuperset('a')) def test_pickling(self): for i in range(pickle.HIGHEST_PROTOCOL + 1): @@ -267,7 +267,7 @@ class TestJointOps(unittest.TestCase): s=H() f=set() f.add(s) - self.assert_(s in f) + self.assertTrue(s in f) f.remove(s) f.add(s) f.discard(s) @@ -333,7 +333,7 @@ class TestJointOps(unittest.TestCase): obj.x = iter(container) del obj, container gc.collect() - self.assert_(ref() is None, "Cycle was not collected") + self.assertTrue(ref() is None, "Cycle was not collected") class TestSet(TestJointOps): thetype = set @@ -367,7 +367,7 @@ class TestSet(TestJointOps): def test_add(self): self.s.add('Q') - self.assert_('Q' in self.s) + self.assertTrue('Q' in self.s) dup = self.s.copy() self.s.add('Q') self.assertEqual(self.s, dup) @@ -375,13 +375,13 @@ class TestSet(TestJointOps): def test_remove(self): self.s.remove('a') - self.assert_('a' not in self.s) + self.assertTrue('a' not in self.s) self.assertRaises(KeyError, self.s.remove, 'Q') self.assertRaises(TypeError, self.s.remove, []) s = self.thetype([frozenset(self.word)]) - self.assert_(self.thetype(self.word) in s) + self.assertTrue(self.thetype(self.word) in s) s.remove(self.thetype(self.word)) - self.assert_(self.thetype(self.word) not in s) + self.assertTrue(self.thetype(self.word) not in s) self.assertRaises(KeyError, self.s.remove, self.thetype(self.word)) def test_remove_keyerror_unpacking(self): @@ -400,7 +400,7 @@ class TestSet(TestJointOps): try: self.s.remove(key) except KeyError as e: - self.assert_(e.args[0] is key, + self.assertTrue(e.args[0] is key, "KeyError should be {0}, not {1}".format(key, e.args[0])) else: @@ -408,26 +408,26 @@ class TestSet(TestJointOps): def test_discard(self): self.s.discard('a') - self.assert_('a' not in self.s) + self.assertTrue('a' not in self.s) self.s.discard('Q') self.assertRaises(TypeError, self.s.discard, []) s = self.thetype([frozenset(self.word)]) - self.assert_(self.thetype(self.word) in s) + self.assertTrue(self.thetype(self.word) in s) s.discard(self.thetype(self.word)) - self.assert_(self.thetype(self.word) not in s) + self.assertTrue(self.thetype(self.word) not in s) s.discard(self.thetype(self.word)) def test_pop(self): for i in xrange(len(self.s)): elem = self.s.pop() - self.assert_(elem not in self.s) + self.assertTrue(elem not in self.s) self.assertRaises(KeyError, self.s.pop) def test_update(self): retval = self.s.update(self.otherword) self.assertEqual(retval, None) for c in (self.word + self.otherword): - self.assert_(c in self.s) + self.assertTrue(c in self.s) self.assertRaises(PassThru, self.s.update, check_pass_thru()) self.assertRaises(TypeError, self.s.update, [[]]) for p, q in (('cdc', 'abcd'), ('efgfe', 'abcefg'), ('ccb', 'abc'), ('ef', 'abcef')): @@ -445,16 +445,16 @@ class TestSet(TestJointOps): def test_ior(self): self.s |= set(self.otherword) for c in (self.word + self.otherword): - self.assert_(c in self.s) + self.assertTrue(c in self.s) def test_intersection_update(self): retval = self.s.intersection_update(self.otherword) self.assertEqual(retval, None) for c in (self.word + self.otherword): if c in self.otherword and c in self.word: - self.assert_(c in self.s) + self.assertTrue(c in self.s) else: - self.assert_(c not in self.s) + self.assertTrue(c not in self.s) self.assertRaises(PassThru, self.s.intersection_update, check_pass_thru()) self.assertRaises(TypeError, self.s.intersection_update, [[]]) for p, q in (('cdc', 'c'), ('efgfe', ''), ('ccb', 'bc'), ('ef', '')): @@ -472,18 +472,18 @@ class TestSet(TestJointOps): self.s &= set(self.otherword) for c in (self.word + self.otherword): if c in self.otherword and c in self.word: - self.assert_(c in self.s) + self.assertTrue(c in self.s) else: - self.assert_(c not in self.s) + self.assertTrue(c not in self.s) def test_difference_update(self): retval = self.s.difference_update(self.otherword) self.assertEqual(retval, None) for c in (self.word + self.otherword): if c in self.word and c not in self.otherword: - self.assert_(c in self.s) + self.assertTrue(c in self.s) else: - self.assert_(c not in self.s) + self.assertTrue(c not in self.s) self.assertRaises(PassThru, self.s.difference_update, check_pass_thru()) self.assertRaises(TypeError, self.s.difference_update, [[]]) self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]]) @@ -509,18 +509,18 @@ class TestSet(TestJointOps): self.s -= set(self.otherword) for c in (self.word + self.otherword): if c in self.word and c not in self.otherword: - self.assert_(c in self.s) + self.assertTrue(c in self.s) else: - self.assert_(c not in self.s) + self.assertTrue(c not in self.s) def test_symmetric_difference_update(self): retval = self.s.symmetric_difference_update(self.otherword) self.assertEqual(retval, None) for c in (self.word + self.otherword): if (c in self.word) ^ (c in self.otherword): - self.assert_(c in self.s) + self.assertTrue(c in self.s) else: - self.assert_(c not in self.s) + self.assertTrue(c not in self.s) self.assertRaises(PassThru, self.s.symmetric_difference_update, check_pass_thru()) self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]]) for p, q in (('cdc', 'abd'), ('efgfe', 'abcefg'), ('ccb', 'a'), ('ef', 'abcef')): @@ -533,9 +533,9 @@ class TestSet(TestJointOps): self.s ^= set(self.otherword) for c in (self.word + self.otherword): if (c in self.word) ^ (c in self.otherword): - self.assert_(c in self.s) + self.assertTrue(c in self.s) else: - self.assert_(c not in self.s) + self.assertTrue(c not in self.s) def test_inplace_on_self(self): t = self.s.copy() @@ -763,7 +763,7 @@ class TestBasicOps(unittest.TestCase): def test_iteration(self): for v in self.set: - self.assert_(v in self.values) + self.assertTrue(v in self.values) setiter = iter(self.set) # note: __length_hint__ is an internal undocumented API, # don't rely on it in your own programs @@ -798,10 +798,10 @@ class TestBasicOpsSingleton(TestBasicOps): self.repr = "set([3])" def test_in(self): - self.failUnless(3 in self.set) + self.assertTrue(3 in self.set) def test_not_in(self): - self.failUnless(2 not in self.set) + self.assertTrue(2 not in self.set) #------------------------------------------------------------------------------ @@ -815,10 +815,10 @@ class TestBasicOpsTuple(TestBasicOps): self.repr = "set([(0, 'zero')])" def test_in(self): - self.failUnless((0, "zero") in self.set) + self.assertTrue((0, "zero") in self.set) def test_not_in(self): - self.failUnless(9 not in self.set) + self.assertTrue(9 not in self.set) #------------------------------------------------------------------------------ @@ -1110,7 +1110,7 @@ class TestMutate(unittest.TestCase): popped[self.set.pop()] = None self.assertEqual(len(popped), len(self.values)) for v in self.values: - self.failUnless(v in popped) + self.assertTrue(v in popped) def test_update_empty_tuple(self): self.set.update(()) @@ -1379,7 +1379,7 @@ class TestCopying(unittest.TestCase): set_list = list(self.set); set_list.sort() self.assertEqual(len(dup_list), len(set_list)) for i in range(len(dup_list)): - self.failUnless(dup_list[i] is set_list[i]) + self.assertTrue(dup_list[i] is set_list[i]) def test_deep_copy(self): dup = copy.deepcopy(self.set) @@ -1429,13 +1429,13 @@ class TestIdentities(unittest.TestCase): def test_binopsVsSubsets(self): a, b = self.a, self.b - self.assert_(a - b < a) - self.assert_(b - a < b) - self.assert_(a & b < a) - self.assert_(a & b < b) - self.assert_(a | b > a) - self.assert_(a | b > b) - self.assert_(a ^ b < a | b) + self.assertTrue(a - b < a) + self.assertTrue(b - a < b) + self.assertTrue(a & b < a) + self.assertTrue(a & b < b) + self.assertTrue(a | b > a) + self.assertTrue(a | b > b) + self.assertTrue(a ^ b < a | b) def test_commutativity(self): a, b = self.a, self.b @@ -1684,7 +1684,7 @@ class TestGraphs(unittest.TestCase): edge = vertex # Cuboctahedron vertices are edges in Cube self.assertEqual(len(edge), 2) # Two cube vertices define an edge for cubevert in edge: - self.assert_(cubevert in g) + self.assertTrue(cubevert in g) #============================================================================== diff --git a/Lib/test/test_sets.py b/Lib/test/test_sets.py index efa388f..9c59836 100644 --- a/Lib/test/test_sets.py +++ b/Lib/test/test_sets.py @@ -76,7 +76,7 @@ class TestBasicOps(unittest.TestCase): def test_iteration(self): for v in self.set: - self.assert_(v in self.values) + self.assertTrue(v in self.values) def test_pickling(self): p = pickle.dumps(self.set) @@ -107,10 +107,10 @@ class TestBasicOpsSingleton(TestBasicOps): self.repr = "Set([3])" def test_in(self): - self.failUnless(3 in self.set) + self.assertTrue(3 in self.set) def test_not_in(self): - self.failUnless(2 not in self.set) + self.assertTrue(2 not in self.set) #------------------------------------------------------------------------------ @@ -124,10 +124,10 @@ class TestBasicOpsTuple(TestBasicOps): self.repr = "Set([(0, 'zero')])" def test_in(self): - self.failUnless((0, "zero") in self.set) + self.assertTrue((0, "zero") in self.set) def test_not_in(self): - self.failUnless(9 not in self.set) + self.assertTrue(9 not in self.set) #------------------------------------------------------------------------------ @@ -406,7 +406,7 @@ class TestMutate(unittest.TestCase): popped[self.set.pop()] = None self.assertEqual(len(popped), len(self.values)) for v in self.values: - self.failUnless(v in popped) + self.assertTrue(v in popped) def test_update_empty_tuple(self): self.set.union_update(()) @@ -683,7 +683,7 @@ class TestCopying(unittest.TestCase): set_list = list(self.set); set_list.sort() self.assertEqual(len(dup_list), len(set_list)) for i in range(len(dup_list)): - self.failUnless(dup_list[i] is set_list[i]) + self.assertTrue(dup_list[i] is set_list[i]) def test_deep_copy(self): dup = copy.deepcopy(self.set) @@ -733,13 +733,13 @@ class TestIdentities(unittest.TestCase): def test_binopsVsSubsets(self): a, b = self.a, self.b - self.assert_(a - b <= a) - self.assert_(b - a <= b) - self.assert_(a & b <= a) - self.assert_(a & b <= b) - self.assert_(a | b >= a) - self.assert_(a | b >= b) - self.assert_(a ^ b <= a | b) + self.assertTrue(a - b <= a) + self.assertTrue(b - a <= b) + self.assertTrue(a & b <= a) + self.assertTrue(a & b <= b) + self.assertTrue(a | b >= a) + self.assertTrue(a | b >= b) + self.assertTrue(a ^ b <= a | b) def test_commutativity(self): a, b = self.a, self.b @@ -755,9 +755,9 @@ class TestIdentities(unittest.TestCase): self.assertEqual(a - a, zero) self.assertEqual(a | a, a) self.assertEqual(a & a, a) - self.assert_(a <= a) - self.assert_(a >= a) - self.assert_(a == a) + self.assertTrue(a <= a) + self.assertTrue(a >= a) + self.assertTrue(a == a) def test_summations(self): # check that sums of parts equal the whole diff --git a/Lib/test/test_sha.py b/Lib/test/test_sha.py index 0647db3..6b38435 100644 --- a/Lib/test/test_sha.py +++ b/Lib/test/test_sha.py @@ -18,19 +18,19 @@ class SHATestCase(unittest.TestCase): # Check digest matches the expected value obj = sha.new(data) computed = obj.hexdigest() - self.assert_(computed == digest) + self.assertTrue(computed == digest) # Verify that the value doesn't change between two consecutive # digest operations. computed_again = obj.hexdigest() - self.assert_(computed == computed_again) + self.assertTrue(computed == computed_again) # Check hexdigest() output matches digest()'s output digest = obj.digest() hexd = "" for c in digest: hexd += '%02x' % ord(c) - self.assert_(computed == hexd) + self.assertTrue(computed == hexd) def test_case_1(self): self.check("abc", diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py index 6226f9b..17d3cab 100644 --- a/Lib/test/test_shutil.py +++ b/Lib/test/test_shutil.py @@ -63,12 +63,12 @@ class TestShutil(unittest.TestCase): self.assertIs(func, os.listdir, "func must be either os.remove or os.listdir") self.assertEqual(arg, TESTFN) - self.failUnless(issubclass(exc[0], OSError)) + self.assertTrue(issubclass(exc[0], OSError)) self.errorState = 1 else: self.assertEqual(func, os.rmdir) self.assertEqual(arg, TESTFN) - self.failUnless(issubclass(exc[0], OSError)) + self.assertTrue(issubclass(exc[0], OSError)) self.errorState = 2 def test_rmtree_dont_delete_file(self): @@ -158,9 +158,9 @@ class TestShutil(unittest.TestCase): patterns = shutil.ignore_patterns('*.tmp', 'test_dir2') shutil.copytree(src_dir, dst_dir, ignore=patterns) # checking the result: some elements should not be copied - self.assert_(exists(join(dst_dir, 'test.txt'))) - self.assert_(not exists(join(dst_dir, 'test.tmp'))) - self.assert_(not exists(join(dst_dir, 'test_dir2'))) + self.assertTrue(exists(join(dst_dir, 'test.txt'))) + self.assertTrue(not exists(join(dst_dir, 'test.tmp'))) + self.assertTrue(not exists(join(dst_dir, 'test_dir2'))) finally: if os.path.exists(dst_dir): shutil.rmtree(dst_dir) @@ -168,9 +168,9 @@ class TestShutil(unittest.TestCase): patterns = shutil.ignore_patterns('*.tmp', 'subdir*') shutil.copytree(src_dir, dst_dir, ignore=patterns) # checking the result: some elements should not be copied - self.assert_(not exists(join(dst_dir, 'test.tmp'))) - self.assert_(not exists(join(dst_dir, 'test_dir2', 'subdir2'))) - self.assert_(not exists(join(dst_dir, 'test_dir2', 'subdir'))) + self.assertTrue(not exists(join(dst_dir, 'test.tmp'))) + self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2'))) + self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir'))) finally: if os.path.exists(dst_dir): shutil.rmtree(dst_dir) @@ -192,9 +192,9 @@ class TestShutil(unittest.TestCase): shutil.copytree(src_dir, dst_dir, ignore=_filter) # checking the result: some elements should not be copied - self.assert_(not exists(join(dst_dir, 'test_dir2', 'subdir2', + self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2', 'test.py'))) - self.assert_(not exists(join(dst_dir, 'test_dir2', 'subdir'))) + self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir'))) finally: if os.path.exists(dst_dir): @@ -393,7 +393,7 @@ class TestMove(unittest.TestCase): for src, dst in [('srcdir', 'srcdir/dest')]: src = os.path.join(TESTFN, src) dst = os.path.join(TESTFN, dst) - self.assert_(shutil._destinsrc(src, dst), + self.assertTrue(shutil._destinsrc(src, dst), msg='_destinsrc() wrongly concluded that ' 'dst (%s) is not in src (%s)' % (dst, src)) finally: @@ -405,7 +405,7 @@ class TestMove(unittest.TestCase): for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]: src = os.path.join(TESTFN, src) dst = os.path.join(TESTFN, dst) - self.failIf(shutil._destinsrc(src, dst), + self.assertFalse(shutil._destinsrc(src, dst), msg='_destinsrc() wrongly concluded that ' 'dst (%s) is in src (%s)' % (dst, src)) finally: diff --git a/Lib/test/test_signal.py b/Lib/test/test_signal.py index 21577db..4368375 100644 --- a/Lib/test/test_signal.py +++ b/Lib/test/test_signal.py @@ -217,10 +217,10 @@ class WakeupSignalTests(unittest.TestCase): # before select is called time.sleep(self.TIMEOUT_FULL) mid_time = time.time() - self.assert_(mid_time - before_time < self.TIMEOUT_HALF) + self.assertTrue(mid_time - before_time < self.TIMEOUT_HALF) select.select([self.read], [], [], self.TIMEOUT_FULL) after_time = time.time() - self.assert_(after_time - mid_time < self.TIMEOUT_HALF) + self.assertTrue(after_time - mid_time < self.TIMEOUT_HALF) def test_wakeup_fd_during(self): import select @@ -231,7 +231,7 @@ class WakeupSignalTests(unittest.TestCase): self.assertRaises(select.error, select.select, [self.read], [], [], self.TIMEOUT_FULL) after_time = time.time() - self.assert_(after_time - before_time < self.TIMEOUT_HALF) + self.assertTrue(after_time - before_time < self.TIMEOUT_HALF) def setUp(self): import fcntl diff --git a/Lib/test/test_site.py b/Lib/test/test_site.py index 03f6d80..2b93d04 100644 --- a/Lib/test/test_site.py +++ b/Lib/test/test_site.py @@ -47,26 +47,26 @@ class HelperFunctionsTests(unittest.TestCase): path_parts = ("Beginning", "End") original_dir = os.path.join(*path_parts) abs_dir, norm_dir = site.makepath(*path_parts) - self.failUnlessEqual(os.path.abspath(original_dir), abs_dir) + self.assertEqual(os.path.abspath(original_dir), abs_dir) if original_dir == os.path.normcase(original_dir): - self.failUnlessEqual(abs_dir, norm_dir) + self.assertEqual(abs_dir, norm_dir) else: - self.failUnlessEqual(os.path.normcase(abs_dir), norm_dir) + self.assertEqual(os.path.normcase(abs_dir), norm_dir) def test_init_pathinfo(self): dir_set = site._init_pathinfo() for entry in [site.makepath(path)[1] for path in sys.path if path and os.path.isdir(path)]: - self.failUnless(entry in dir_set, + self.assertTrue(entry in dir_set, "%s from sys.path not found in set returned " "by _init_pathinfo(): %s" % (entry, dir_set)) def pth_file_tests(self, pth_file): """Contain common code for testing results of reading a .pth file""" - self.failUnless(pth_file.imported in sys.modules, + self.assertTrue(pth_file.imported in sys.modules, "%s not in sys.path" % pth_file.imported) - self.failUnless(site.makepath(pth_file.good_dir_path)[0] in sys.path) - self.failUnless(not os.path.exists(pth_file.bad_dir_path)) + self.assertTrue(site.makepath(pth_file.good_dir_path)[0] in sys.path) + self.assertTrue(not os.path.exists(pth_file.bad_dir_path)) def test_addpackage(self): # Make sure addpackage() imports if the line starts with 'import', @@ -98,7 +98,7 @@ class HelperFunctionsTests(unittest.TestCase): def test_s_option(self): usersite = site.USER_SITE - self.assert_(usersite in sys.path) + self.assertTrue(usersite in sys.path) rc = subprocess.call([sys.executable, '-c', 'import sys; sys.exit(%r in sys.path)' % usersite]) @@ -197,7 +197,7 @@ class ImportSideEffectTests(unittest.TestCase): site.abs__file__() for module in (sys, os, __builtin__): try: - self.failUnless(os.path.isabs(module.__file__), `module`) + self.assertTrue(os.path.isabs(module.__file__), `module`) except AttributeError: continue # We could try everything in sys.modules; however, when regrtest.py @@ -210,7 +210,7 @@ class ImportSideEffectTests(unittest.TestCase): site.removeduppaths() seen_paths = set() for path in sys.path: - self.failUnless(path not in seen_paths) + self.assertTrue(path not in seen_paths) seen_paths.add(path) def test_add_build_dir(self): @@ -221,17 +221,17 @@ class ImportSideEffectTests(unittest.TestCase): def test_setting_quit(self): # 'quit' and 'exit' should be injected into __builtin__ - self.failUnless(hasattr(__builtin__, "quit")) - self.failUnless(hasattr(__builtin__, "exit")) + self.assertTrue(hasattr(__builtin__, "quit")) + self.assertTrue(hasattr(__builtin__, "exit")) def test_setting_copyright(self): # 'copyright' and 'credits' should be in __builtin__ - self.failUnless(hasattr(__builtin__, "copyright")) - self.failUnless(hasattr(__builtin__, "credits")) + self.assertTrue(hasattr(__builtin__, "copyright")) + self.assertTrue(hasattr(__builtin__, "credits")) def test_setting_help(self): # 'help' should be set in __builtin__ - self.failUnless(hasattr(__builtin__, "help")) + self.assertTrue(hasattr(__builtin__, "help")) def test_aliasing_mbcs(self): if sys.platform == "win32": @@ -245,7 +245,7 @@ class ImportSideEffectTests(unittest.TestCase): def test_setdefaultencoding_removed(self): # Make sure sys.setdefaultencoding is gone - self.failUnless(not hasattr(sys, "setdefaultencoding")) + self.assertTrue(not hasattr(sys, "setdefaultencoding")) def test_sitecustomize_executed(self): # If sitecustomize is available, it should have been imported. diff --git a/Lib/test/test_slice.py b/Lib/test/test_slice.py index 854805b..08de8e3 100644 --- a/Lib/test/test_slice.py +++ b/Lib/test/test_slice.py @@ -71,7 +71,7 @@ class SliceTest(unittest.TestCase): obj = AnyClass() s = slice(obj) - self.assert_(s.stop is obj) + self.assertTrue(s.stop is obj) def test_indices(self): self.assertEqual(slice(None ).indices(10), (0, 10, 1)) diff --git a/Lib/test/test_socket.py b/Lib/test/test_socket.py index 5c906d7..a2265de 100644 --- a/Lib/test/test_socket.py +++ b/Lib/test/test_socket.py @@ -237,11 +237,11 @@ class GeneralModuleTests(unittest.TestCase): raise socket.herror def raise_gaierror(*args, **kwargs): raise socket.gaierror - self.failUnlessRaises(socket.error, raise_error, + self.assertRaises(socket.error, raise_error, "Error raising socket exception.") - self.failUnlessRaises(socket.error, raise_herror, + self.assertRaises(socket.error, raise_herror, "Error raising socket exception.") - self.failUnlessRaises(socket.error, raise_gaierror, + self.assertRaises(socket.error, raise_gaierror, "Error raising socket exception.") def testCrucialConstants(self): @@ -263,7 +263,7 @@ class GeneralModuleTests(unittest.TestCase): except socket.error: # Probably name lookup wasn't set up right; skip this test return - self.assert_(ip.find('.') >= 0, "Error resolving host to ip.") + self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.") try: hname, aliases, ipaddrs = socket.gethostbyaddr(ip) except socket.error: @@ -491,7 +491,7 @@ class GeneralModuleTests(unittest.TestCase): # it reasonable to get the host's addr in addition to 0.0.0.0. # At least for eCos. This is required for the S/390 to pass. my_ip_addr = socket.gethostbyname(socket.gethostname()) - self.assert_(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0]) + self.assertTrue(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0]) self.assertEqual(name[1], port) def testGetSockOpt(self): @@ -499,14 +499,14 @@ class GeneralModuleTests(unittest.TestCase): # We know a socket should start without reuse==0 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) - self.failIf(reuse != 0, "initial mode is reuse") + self.assertFalse(reuse != 0, "initial mode is reuse") def testSetSockOpt(self): # Testing setsockopt() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) - self.failIf(reuse == 0, "failed to set reuse mode") + self.assertFalse(reuse == 0, "failed to set reuse mode") def testSendAfterClose(self): # testing send() after close() with timeout @@ -539,10 +539,10 @@ class GeneralModuleTests(unittest.TestCase): def test_sock_ioctl(self): if os.name != "nt": return - self.assert_(hasattr(socket.socket, 'ioctl')) - self.assert_(hasattr(socket, 'SIO_RCVALL')) - self.assert_(hasattr(socket, 'RCVALL_ON')) - self.assert_(hasattr(socket, 'RCVALL_OFF')) + self.assertTrue(hasattr(socket.socket, 'ioctl')) + self.assertTrue(hasattr(socket, 'SIO_RCVALL')) + self.assertTrue(hasattr(socket, 'RCVALL_ON')) + self.assertTrue(hasattr(socket, 'RCVALL_OFF')) class BasicTCPTest(SocketConnectedTest): @@ -701,7 +701,7 @@ class NonBlockingTCPTests(ThreadedTCPSocketTest): except socket.error: pass end = time.time() - self.assert_((end - start) < 1.0, "Error setting non-blocking mode.") + self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.") def _testSetBlocking(self): pass @@ -768,7 +768,7 @@ class FileObjectClassTestCase(SocketConnectedTest): def tearDown(self): self.serv_file.close() - self.assert_(self.serv_file.closed) + self.assertTrue(self.serv_file.closed) self.serv_file = None SocketConnectedTest.tearDown(self) @@ -778,7 +778,7 @@ class FileObjectClassTestCase(SocketConnectedTest): def clientTearDown(self): self.cli_file.close() - self.assert_(self.cli_file.closed) + self.assertTrue(self.cli_file.closed) self.cli_file = None SocketConnectedTest.clientTearDown(self) @@ -853,10 +853,10 @@ class FileObjectClassTestCase(SocketConnectedTest): self.cli_file.write("End Of Line") def testClosedAttr(self): - self.assert_(not self.serv_file.closed) + self.assertTrue(not self.serv_file.closed) def _testClosedAttr(self): - self.assert_(not self.cli_file.closed) + self.assertTrue(not self.cli_file.closed) class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase): @@ -908,7 +908,7 @@ class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest): class NetworkConnectionNoServer(unittest.TestCase): def testWithoutServer(self): port = test_support.find_unused_port() - self.failUnlessRaises( + self.assertRaises( socket.error, lambda: socket.create_connection((HOST, port)) ) @@ -938,7 +938,7 @@ class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest): testTimeoutDefault = _justAccept def _testTimeoutDefault(self): # passing no explicit timeout uses socket's global default - self.assert_(socket.getdefaulttimeout() is None) + self.assertTrue(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(42) try: self.cli = socket.create_connection((HOST, self.port)) @@ -949,7 +949,7 @@ class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest): testTimeoutNone = _justAccept def _testTimeoutNone(self): # None timeout means the same as sock.settimeout(None) - self.assert_(socket.getdefaulttimeout() is None) + self.assertTrue(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(30) try: self.cli = socket.create_connection((HOST, self.port), timeout=None) @@ -994,7 +994,7 @@ class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest): def _testOutsideTimeout(self): self.cli = sock = socket.create_connection((HOST, self.port), timeout=1) - self.failUnlessRaises(socket.timeout, lambda: sock.recv(5)) + self.assertRaises(socket.timeout, lambda: sock.recv(5)) class Urllib2FileobjectTest(unittest.TestCase): @@ -1014,12 +1014,12 @@ class Urllib2FileobjectTest(unittest.TestCase): s = MockSocket() f = socket._fileobject(s) f.close() - self.assert_(not s.closed) + self.assertTrue(not s.closed) s = MockSocket() f = socket._fileobject(s, close=True) f.close() - self.assert_(s.closed) + self.assertTrue(s.closed) class TCPTimeoutTest(SocketTCPTest): @@ -1027,7 +1027,7 @@ class TCPTimeoutTest(SocketTCPTest): def raise_timeout(*args, **kwargs): self.serv.settimeout(1.0) self.serv.accept() - self.failUnlessRaises(socket.timeout, raise_timeout, + self.assertRaises(socket.timeout, raise_timeout, "Error generating a timeout exception (TCP)") def testTimeoutZero(self): @@ -1084,7 +1084,7 @@ class UDPTimeoutTest(SocketTCPTest): def raise_timeout(*args, **kwargs): self.serv.settimeout(1.0) self.serv.recv(1024) - self.failUnlessRaises(socket.timeout, raise_timeout, + self.assertRaises(socket.timeout, raise_timeout, "Error generating a timeout exception (UDP)") def testTimeoutZero(self): @@ -1104,10 +1104,10 @@ class UDPTimeoutTest(SocketTCPTest): class TestExceptions(unittest.TestCase): def testExceptionTree(self): - self.assert_(issubclass(socket.error, Exception)) - self.assert_(issubclass(socket.herror, socket.error)) - self.assert_(issubclass(socket.gaierror, socket.error)) - self.assert_(issubclass(socket.timeout, socket.error)) + self.assertTrue(issubclass(socket.error, Exception)) + self.assertTrue(issubclass(socket.herror, socket.error)) + self.assertTrue(issubclass(socket.gaierror, socket.error)) + self.assertTrue(issubclass(socket.timeout, socket.error)) class TestLinuxAbstractNamespace(unittest.TestCase): diff --git a/Lib/test/test_str.py b/Lib/test/test_str.py index 5341af2..c546154 100644 --- a/Lib/test/test_str.py +++ b/Lib/test/test_str.py @@ -86,7 +86,7 @@ class StrTest( def __unicode__(self): return "not unicode" - self.assert_(str(Foo0()).startswith("<")) # this is different from __unicode__ + self.assertTrue(str(Foo0()).startswith("<")) # this is different from __unicode__ self.assertEqual(str(Foo1()), "foo") self.assertEqual(str(Foo2()), "foo") self.assertEqual(str(Foo3()), "foo") diff --git a/Lib/test/test_string.py b/Lib/test/test_string.py index 20cff0a..35ab117 100644 --- a/Lib/test/test_string.py +++ b/Lib/test/test_string.py @@ -199,13 +199,13 @@ class ModuleTest(unittest.TestCase): class BytesAliasTest(unittest.TestCase): def test_builtin(self): - self.assert_(str is bytes) + self.assertTrue(str is bytes) def test_syntax(self): self.assertEqual(b"spam", "spam") self.assertEqual(br"egg\foo", "egg\\foo") - self.assert_(type(b""), str) - self.assert_(type(br""), str) + self.assertTrue(type(b""), str) + self.assertTrue(type(br""), str) def test_main(): test_support.run_unittest(StringTest, ModuleTest, BytesAliasTest) diff --git a/Lib/test/test_stringprep.py b/Lib/test/test_stringprep.py index 60425dd..15bdf87 100644 --- a/Lib/test/test_stringprep.py +++ b/Lib/test/test_stringprep.py @@ -8,66 +8,66 @@ from stringprep import * class StringprepTests(unittest.TestCase): def test(self): - self.failUnless(in_table_a1(u"\u0221")) - self.failIf(in_table_a1(u"\u0222")) + self.assertTrue(in_table_a1(u"\u0221")) + self.assertFalse(in_table_a1(u"\u0222")) - self.failUnless(in_table_b1(u"\u00ad")) - self.failIf(in_table_b1(u"\u00ae")) + self.assertTrue(in_table_b1(u"\u00ad")) + self.assertFalse(in_table_b1(u"\u00ae")) - self.failUnless(map_table_b2(u"\u0041"), u"\u0061") - self.failUnless(map_table_b2(u"\u0061"), u"\u0061") + self.assertTrue(map_table_b2(u"\u0041"), u"\u0061") + self.assertTrue(map_table_b2(u"\u0061"), u"\u0061") - self.failUnless(map_table_b3(u"\u0041"), u"\u0061") - self.failUnless(map_table_b3(u"\u0061"), u"\u0061") + self.assertTrue(map_table_b3(u"\u0041"), u"\u0061") + self.assertTrue(map_table_b3(u"\u0061"), u"\u0061") - self.failUnless(in_table_c11(u"\u0020")) - self.failIf(in_table_c11(u"\u0021")) + self.assertTrue(in_table_c11(u"\u0020")) + self.assertFalse(in_table_c11(u"\u0021")) - self.failUnless(in_table_c12(u"\u00a0")) - self.failIf(in_table_c12(u"\u00a1")) + self.assertTrue(in_table_c12(u"\u00a0")) + self.assertFalse(in_table_c12(u"\u00a1")) - self.failUnless(in_table_c12(u"\u00a0")) - self.failIf(in_table_c12(u"\u00a1")) + self.assertTrue(in_table_c12(u"\u00a0")) + self.assertFalse(in_table_c12(u"\u00a1")) - self.failUnless(in_table_c11_c12(u"\u00a0")) - self.failIf(in_table_c11_c12(u"\u00a1")) + self.assertTrue(in_table_c11_c12(u"\u00a0")) + self.assertFalse(in_table_c11_c12(u"\u00a1")) - self.failUnless(in_table_c21(u"\u001f")) - self.failIf(in_table_c21(u"\u0020")) + self.assertTrue(in_table_c21(u"\u001f")) + self.assertFalse(in_table_c21(u"\u0020")) - self.failUnless(in_table_c22(u"\u009f")) - self.failIf(in_table_c22(u"\u00a0")) + self.assertTrue(in_table_c22(u"\u009f")) + self.assertFalse(in_table_c22(u"\u00a0")) - self.failUnless(in_table_c21_c22(u"\u009f")) - self.failIf(in_table_c21_c22(u"\u00a0")) + self.assertTrue(in_table_c21_c22(u"\u009f")) + self.assertFalse(in_table_c21_c22(u"\u00a0")) - self.failUnless(in_table_c3(u"\ue000")) - self.failIf(in_table_c3(u"\uf900")) + self.assertTrue(in_table_c3(u"\ue000")) + self.assertFalse(in_table_c3(u"\uf900")) - self.failUnless(in_table_c4(u"\uffff")) - self.failIf(in_table_c4(u"\u0000")) + self.assertTrue(in_table_c4(u"\uffff")) + self.assertFalse(in_table_c4(u"\u0000")) - self.failUnless(in_table_c5(u"\ud800")) - self.failIf(in_table_c5(u"\ud7ff")) + self.assertTrue(in_table_c5(u"\ud800")) + self.assertFalse(in_table_c5(u"\ud7ff")) - self.failUnless(in_table_c6(u"\ufff9")) - self.failIf(in_table_c6(u"\ufffe")) + self.assertTrue(in_table_c6(u"\ufff9")) + self.assertFalse(in_table_c6(u"\ufffe")) - self.failUnless(in_table_c7(u"\u2ff0")) - self.failIf(in_table_c7(u"\u2ffc")) + self.assertTrue(in_table_c7(u"\u2ff0")) + self.assertFalse(in_table_c7(u"\u2ffc")) - self.failUnless(in_table_c8(u"\u0340")) - self.failIf(in_table_c8(u"\u0342")) + self.assertTrue(in_table_c8(u"\u0340")) + self.assertFalse(in_table_c8(u"\u0342")) # C.9 is not in the bmp - # self.failUnless(in_table_c9(u"\U000E0001")) - # self.failIf(in_table_c8(u"\U000E0002")) + # self.assertTrue(in_table_c9(u"\U000E0001")) + # self.assertFalse(in_table_c8(u"\U000E0002")) - self.failUnless(in_table_d1(u"\u05be")) - self.failIf(in_table_d1(u"\u05bf")) + self.assertTrue(in_table_d1(u"\u05be")) + self.assertFalse(in_table_d1(u"\u05bf")) - self.failUnless(in_table_d2(u"\u0041")) - self.failIf(in_table_d2(u"\u0040")) + self.assertTrue(in_table_d2(u"\u0041")) + self.assertFalse(in_table_d2(u"\u0040")) # This would generate a hash of all predicates. However, running # it is quite expensive, and only serves to detect changes in the diff --git a/Lib/test/test_strop.py b/Lib/test/test_strop.py index 7cda83f..0172957 100644 --- a/Lib/test/test_strop.py +++ b/Lib/test/test_strop.py @@ -10,104 +10,104 @@ from test import test_support class StropFunctionTestCase(unittest.TestCase): def test_atoi(self): - self.assert_(strop.atoi(" 1 ") == 1) + self.assertTrue(strop.atoi(" 1 ") == 1) self.assertRaises(ValueError, strop.atoi, " 1x") self.assertRaises(ValueError, strop.atoi, " x1 ") def test_atol(self): - self.assert_(strop.atol(" 1 ") == 1L) + self.assertTrue(strop.atol(" 1 ") == 1L) self.assertRaises(ValueError, strop.atol, " 1x") self.assertRaises(ValueError, strop.atol, " x1 ") def test_atof(self): - self.assert_(strop.atof(" 1 ") == 1.0) + self.assertTrue(strop.atof(" 1 ") == 1.0) self.assertRaises(ValueError, strop.atof, " 1x") self.assertRaises(ValueError, strop.atof, " x1 ") def test_capitalize(self): - self.assert_(strop.capitalize(" hello ") == " hello ") - self.assert_(strop.capitalize("hello ") == "Hello ") + self.assertTrue(strop.capitalize(" hello ") == " hello ") + self.assertTrue(strop.capitalize("hello ") == "Hello ") def test_find(self): - self.assert_(strop.find("abcdefghiabc", "abc") == 0) - self.assert_(strop.find("abcdefghiabc", "abc", 1) == 9) - self.assert_(strop.find("abcdefghiabc", "def", 4) == -1) + self.assertTrue(strop.find("abcdefghiabc", "abc") == 0) + self.assertTrue(strop.find("abcdefghiabc", "abc", 1) == 9) + self.assertTrue(strop.find("abcdefghiabc", "def", 4) == -1) def test_rfind(self): - self.assert_(strop.rfind("abcdefghiabc", "abc") == 9) + self.assertTrue(strop.rfind("abcdefghiabc", "abc") == 9) def test_lower(self): - self.assert_(strop.lower("HeLLo") == "hello") + self.assertTrue(strop.lower("HeLLo") == "hello") def test_upper(self): - self.assert_(strop.upper("HeLLo") == "HELLO") + self.assertTrue(strop.upper("HeLLo") == "HELLO") def test_swapcase(self): - self.assert_(strop.swapcase("HeLLo cOmpUteRs") == "hEllO CoMPuTErS") + self.assertTrue(strop.swapcase("HeLLo cOmpUteRs") == "hEllO CoMPuTErS") def test_strip(self): - self.assert_(strop.strip(" \t\n hello \t\n ") == "hello") + self.assertTrue(strop.strip(" \t\n hello \t\n ") == "hello") def test_lstrip(self): - self.assert_(strop.lstrip(" \t\n hello \t\n ") == "hello \t\n ") + self.assertTrue(strop.lstrip(" \t\n hello \t\n ") == "hello \t\n ") def test_rstrip(self): - self.assert_(strop.rstrip(" \t\n hello \t\n ") == " \t\n hello") + self.assertTrue(strop.rstrip(" \t\n hello \t\n ") == " \t\n hello") def test_replace(self): replace = strop.replace - self.assert_(replace("one!two!three!", '!', '@', 1) + self.assertTrue(replace("one!two!three!", '!', '@', 1) == "one@two!three!") - self.assert_(replace("one!two!three!", '!', '@', 2) + self.assertTrue(replace("one!two!three!", '!', '@', 2) == "one@two@three!") - self.assert_(replace("one!two!three!", '!', '@', 3) + self.assertTrue(replace("one!two!three!", '!', '@', 3) == "one@two@three@") - self.assert_(replace("one!two!three!", '!', '@', 4) + self.assertTrue(replace("one!two!three!", '!', '@', 4) == "one@two@three@") # CAUTION: a replace count of 0 means infinity only to strop, # not to the string .replace() method or to the # string.replace() function. - self.assert_(replace("one!two!three!", '!', '@', 0) + self.assertTrue(replace("one!two!three!", '!', '@', 0) == "one@two@three@") - self.assert_(replace("one!two!three!", '!', '@') + self.assertTrue(replace("one!two!three!", '!', '@') == "one@two@three@") - self.assert_(replace("one!two!three!", 'x', '@') + self.assertTrue(replace("one!two!three!", 'x', '@') == "one!two!three!") - self.assert_(replace("one!two!three!", 'x', '@', 2) + self.assertTrue(replace("one!two!three!", 'x', '@', 2) == "one!two!three!") def test_split(self): split = strop.split - self.assert_(split("this is the split function") + self.assertTrue(split("this is the split function") == ['this', 'is', 'the', 'split', 'function']) - self.assert_(split("a|b|c|d", '|') == ['a', 'b', 'c', 'd']) - self.assert_(split("a|b|c|d", '|', 2) == ['a', 'b', 'c|d']) - self.assert_(split("a b c d", None, 1) == ['a', 'b c d']) - self.assert_(split("a b c d", None, 2) == ['a', 'b', 'c d']) - self.assert_(split("a b c d", None, 3) == ['a', 'b', 'c', 'd']) - self.assert_(split("a b c d", None, 4) == ['a', 'b', 'c', 'd']) - self.assert_(split("a b c d", None, 0) == ['a', 'b', 'c', 'd']) - self.assert_(split("a b c d", None, 2) == ['a', 'b', 'c d']) + self.assertTrue(split("a|b|c|d", '|') == ['a', 'b', 'c', 'd']) + self.assertTrue(split("a|b|c|d", '|', 2) == ['a', 'b', 'c|d']) + self.assertTrue(split("a b c d", None, 1) == ['a', 'b c d']) + self.assertTrue(split("a b c d", None, 2) == ['a', 'b', 'c d']) + self.assertTrue(split("a b c d", None, 3) == ['a', 'b', 'c', 'd']) + self.assertTrue(split("a b c d", None, 4) == ['a', 'b', 'c', 'd']) + self.assertTrue(split("a b c d", None, 0) == ['a', 'b', 'c', 'd']) + self.assertTrue(split("a b c d", None, 2) == ['a', 'b', 'c d']) def test_join(self): - self.assert_(strop.join(['a', 'b', 'c', 'd']) == 'a b c d') - self.assert_(strop.join(('a', 'b', 'c', 'd'), '') == 'abcd') - self.assert_(strop.join(Sequence()) == 'w x y z') + self.assertTrue(strop.join(['a', 'b', 'c', 'd']) == 'a b c d') + self.assertTrue(strop.join(('a', 'b', 'c', 'd'), '') == 'abcd') + self.assertTrue(strop.join(Sequence()) == 'w x y z') # try a few long ones - self.assert_(strop.join(['x' * 100] * 100, ':') + self.assertTrue(strop.join(['x' * 100] * 100, ':') == (('x' * 100) + ":") * 99 + "x" * 100) - self.assert_(strop.join(('x' * 100,) * 100, ':') + self.assertTrue(strop.join(('x' * 100,) * 100, ':') == (('x' * 100) + ":") * 99 + "x" * 100) def test_maketrans(self): - self.assert_(strop.maketrans("abc", "xyz") == transtable) + self.assertTrue(strop.maketrans("abc", "xyz") == transtable) self.assertRaises(ValueError, strop.maketrans, "abc", "xyzq") def test_translate(self): - self.assert_(strop.translate("xyzabcdef", transtable, "def") + self.assertTrue(strop.translate("xyzabcdef", transtable, "def") == "xyzxyz") def test_data_attributes(self): diff --git a/Lib/test/test_strptime.py b/Lib/test/test_strptime.py index 2aa4bc9..168263a 100644 --- a/Lib/test/test_strptime.py +++ b/Lib/test/test_strptime.py @@ -13,7 +13,7 @@ import _strptime class getlang_Tests(unittest.TestCase): """Test _getlang""" def test_basic(self): - self.failUnlessEqual(_strptime._getlang(), locale.getlocale(locale.LC_TIME)) + self.assertEqual(_strptime._getlang(), locale.getlocale(locale.LC_TIME)) class LocaleTime_Tests(unittest.TestCase): """Tests for _strptime.LocaleTime. @@ -36,9 +36,9 @@ class LocaleTime_Tests(unittest.TestCase): """ strftime_output = time.strftime(directive, self.time_tuple).lower() comparison = testing[self.time_tuple[tuple_position]] - self.failUnless(strftime_output in testing, "%s: not found in tuple" % + self.assertTrue(strftime_output in testing, "%s: not found in tuple" % error_msg) - self.failUnless(comparison == strftime_output, + self.assertTrue(comparison == strftime_output, "%s: position within tuple incorrect; %s != %s" % (error_msg, comparison, strftime_output)) @@ -61,18 +61,18 @@ class LocaleTime_Tests(unittest.TestCase): def test_am_pm(self): # Make sure AM/PM representation done properly strftime_output = time.strftime("%p", self.time_tuple).lower() - self.failUnless(strftime_output in self.LT_ins.am_pm, + self.assertTrue(strftime_output in self.LT_ins.am_pm, "AM/PM representation not in tuple") if self.time_tuple[3] < 12: position = 0 else: position = 1 - self.failUnless(strftime_output == self.LT_ins.am_pm[position], + self.assertTrue(strftime_output == self.LT_ins.am_pm[position], "AM/PM representation in the wrong position within the tuple") def test_timezone(self): # Make sure timezone is correct timezone = time.strftime("%Z", self.time_tuple).lower() if timezone: - self.failUnless(timezone in self.LT_ins.timezone[0] or \ + self.assertTrue(timezone in self.LT_ins.timezone[0] or \ timezone in self.LT_ins.timezone[1], "timezone %s not found in %s" % (timezone, self.LT_ins.timezone)) @@ -86,26 +86,26 @@ class LocaleTime_Tests(unittest.TestCase): # output. magic_date = (1999, 3, 17, 22, 44, 55, 2, 76, 0) strftime_output = time.strftime("%c", magic_date) - self.failUnless(strftime_output == time.strftime(self.LT_ins.LC_date_time, + self.assertTrue(strftime_output == time.strftime(self.LT_ins.LC_date_time, magic_date), "LC_date_time incorrect") strftime_output = time.strftime("%x", magic_date) - self.failUnless(strftime_output == time.strftime(self.LT_ins.LC_date, + self.assertTrue(strftime_output == time.strftime(self.LT_ins.LC_date, magic_date), "LC_date incorrect") strftime_output = time.strftime("%X", magic_date) - self.failUnless(strftime_output == time.strftime(self.LT_ins.LC_time, + self.assertTrue(strftime_output == time.strftime(self.LT_ins.LC_time, magic_date), "LC_time incorrect") LT = _strptime.LocaleTime() LT.am_pm = ('', '') - self.failUnless(LT.LC_time, "LocaleTime's LC directives cannot handle " + self.assertTrue(LT.LC_time, "LocaleTime's LC directives cannot handle " "empty strings") def test_lang(self): # Make sure lang is set to what _getlang() returns # Assuming locale has not changed between now and when self.LT_ins was created - self.failUnlessEqual(self.LT_ins.lang, _strptime._getlang()) + self.assertEqual(self.LT_ins.lang, _strptime._getlang()) class TimeRETests(unittest.TestCase): @@ -119,13 +119,13 @@ class TimeRETests(unittest.TestCase): def test_pattern(self): # Test TimeRE.pattern pattern_string = self.time_re.pattern(r"%a %A %d") - self.failUnless(pattern_string.find(self.locale_time.a_weekday[2]) != -1, + self.assertTrue(pattern_string.find(self.locale_time.a_weekday[2]) != -1, "did not find abbreviated weekday in pattern string '%s'" % pattern_string) - self.failUnless(pattern_string.find(self.locale_time.f_weekday[4]) != -1, + self.assertTrue(pattern_string.find(self.locale_time.f_weekday[4]) != -1, "did not find full weekday in pattern string '%s'" % pattern_string) - self.failUnless(pattern_string.find(self.time_re['d']) != -1, + self.assertTrue(pattern_string.find(self.time_re['d']) != -1, "did not find 'd' directive pattern string '%s'" % pattern_string) @@ -133,23 +133,23 @@ class TimeRETests(unittest.TestCase): # Make sure any characters in the format string that might be taken as # regex syntax is escaped. pattern_string = self.time_re.pattern("\d+") - self.failUnless(r"\\d\+" in pattern_string, + self.assertTrue(r"\\d\+" in pattern_string, "%s does not have re characters escaped properly" % pattern_string) def test_compile(self): # Check that compiled regex is correct found = self.time_re.compile(r"%A").match(self.locale_time.f_weekday[6]) - self.failUnless(found and found.group('A') == self.locale_time.f_weekday[6], + self.assertTrue(found and found.group('A') == self.locale_time.f_weekday[6], "re object for '%A' failed") compiled = self.time_re.compile(r"%a %b") found = compiled.match("%s %s" % (self.locale_time.a_weekday[4], self.locale_time.a_month[4])) - self.failUnless(found, + self.assertTrue(found, "Match failed with '%s' regex and '%s' string" % (compiled.pattern, "%s %s" % (self.locale_time.a_weekday[4], self.locale_time.a_month[4]))) - self.failUnless(found.group('a') == self.locale_time.a_weekday[4] and + self.assertTrue(found.group('a') == self.locale_time.a_weekday[4] and found.group('b') == self.locale_time.a_month[4], "re object couldn't find the abbreviated weekday month in " "'%s' using '%s'; group 'a' = '%s', group 'b' = %s'" % @@ -159,7 +159,7 @@ class TimeRETests(unittest.TestCase): 'U','w','W','x','X','y','Y','Z','%'): compiled = self.time_re.compile("%" + directive) found = compiled.match(time.strftime("%" + directive)) - self.failUnless(found, "Matching failed on '%s' using '%s' regex" % + self.assertTrue(found, "Matching failed on '%s' using '%s' regex" % (time.strftime("%" + directive), compiled.pattern)) @@ -168,14 +168,14 @@ class TimeRETests(unittest.TestCase): # Fixes bug #661354 test_locale = _strptime.LocaleTime() test_locale.timezone = (frozenset(), frozenset()) - self.failUnless(_strptime.TimeRE(test_locale).pattern("%Z") == '', + self.assertTrue(_strptime.TimeRE(test_locale).pattern("%Z") == '', "with timezone == ('',''), TimeRE().pattern('%Z') != ''") def test_matching_with_escapes(self): # Make sure a format that requires escaping of characters works compiled_re = self.time_re.compile("\w+ %m") found = compiled_re.match("\w+ 10") - self.failUnless(found, "Escaping failed of format '\w+ 10'") + self.assertTrue(found, "Escaping failed of format '\w+ 10'") def test_locale_data_w_regex_metacharacters(self): # Check that if locale data contains regex metacharacters they are @@ -186,7 +186,7 @@ class TimeRETests(unittest.TestCase): "Tokyo (standard time)")), frozenset("Tokyo (daylight time)")) time_re = _strptime.TimeRE(locale_time) - self.failUnless(time_re.compile("%Z").match("Tokyo (standard time)"), + self.assertTrue(time_re.compile("%Z").match("Tokyo (standard time)"), "locale data that contains regex metacharacters is not" " properly escaped") @@ -195,8 +195,8 @@ class TimeRETests(unittest.TestCase): # so as to not allow to subpatterns to end up next to each other and # "steal" characters from each other. pattern = self.time_re.pattern('%j %H') - self.failUnless(not re.match(pattern, "180")) - self.failUnless(re.match(pattern, "18 0")) + self.assertTrue(not re.match(pattern, "180")) + self.assertTrue(re.match(pattern, "18 0")) class StrptimeTests(unittest.TestCase): @@ -229,7 +229,7 @@ class StrptimeTests(unittest.TestCase): """Helper fxn in testing.""" strf_output = time.strftime("%" + directive, self.time_tuple) strp_output = _strptime._strptime_time(strf_output, "%" + directive) - self.failUnless(strp_output[position] == self.time_tuple[position], + self.assertTrue(strp_output[position] == self.time_tuple[position], "testing of '%s' directive failed; '%s' -> %s != %s" % (directive, strf_output, strp_output[position], self.time_tuple[position])) @@ -243,7 +243,7 @@ class StrptimeTests(unittest.TestCase): for bound in bounds: strp_output = _strptime._strptime_time(bound, '%y') expected_result = century + int(bound) - self.failUnless(strp_output[0] == expected_result, + self.assertTrue(strp_output[0] == expected_result, "'y' test failed; passed in '%s' " "and returned '%s'" % (bound, strp_output[0])) @@ -261,7 +261,7 @@ class StrptimeTests(unittest.TestCase): self.helper('H', 3) strf_output = time.strftime("%I %p", self.time_tuple) strp_output = _strptime._strptime_time(strf_output, "%I %p") - self.failUnless(strp_output[3] == self.time_tuple[3], + self.assertTrue(strp_output[3] == self.time_tuple[3], "testing of '%%I %%p' directive failed; '%s' -> %s != %s" % (strf_output, strp_output[3], self.time_tuple[3])) @@ -294,9 +294,9 @@ class StrptimeTests(unittest.TestCase): # Check for equal timezone names deals with bad locale info when this # occurs; first found in FreeBSD 4.4. strp_output = _strptime._strptime_time("UTC", "%Z") - self.failUnlessEqual(strp_output.tm_isdst, 0) + self.assertEqual(strp_output.tm_isdst, 0) strp_output = _strptime._strptime_time("GMT", "%Z") - self.failUnlessEqual(strp_output.tm_isdst, 0) + self.assertEqual(strp_output.tm_isdst, 0) if sys.platform == "mac": # Timezones don't really work on MacOS9 return @@ -305,11 +305,11 @@ class StrptimeTests(unittest.TestCase): strp_output = _strptime._strptime_time(strf_output, "%Z") locale_time = _strptime.LocaleTime() if time.tzname[0] != time.tzname[1] or not time.daylight: - self.failUnless(strp_output[8] == time_tuple[8], + self.assertTrue(strp_output[8] == time_tuple[8], "timezone check failed; '%s' -> %s != %s" % (strf_output, strp_output[8], time_tuple[8])) else: - self.failUnless(strp_output[8] == -1, + self.assertTrue(strp_output[8] == -1, "LocaleTime().timezone has duplicate values and " "time.daylight but timezone value not set to -1") @@ -327,7 +327,7 @@ class StrptimeTests(unittest.TestCase): time.tzname = (tz_name, tz_name) time.daylight = 1 tz_value = _strptime._strptime_time(tz_name, "%Z")[8] - self.failUnlessEqual(tz_value, -1, + self.assertEqual(tz_value, -1, "%s lead to a timezone value of %s instead of -1 when " "time.daylight set to %s and passing in %s" % (time.tzname, tz_value, time.daylight, tz_name)) @@ -354,25 +354,25 @@ class StrptimeTests(unittest.TestCase): # Make sure % signs are handled properly strf_output = time.strftime("%m %% %Y", self.time_tuple) strp_output = _strptime._strptime_time(strf_output, "%m %% %Y") - self.failUnless(strp_output[0] == self.time_tuple[0] and + self.assertTrue(strp_output[0] == self.time_tuple[0] and strp_output[1] == self.time_tuple[1], "handling of percent sign failed") def test_caseinsensitive(self): # Should handle names case-insensitively. strf_output = time.strftime("%B", self.time_tuple) - self.failUnless(_strptime._strptime_time(strf_output.upper(), "%B"), + self.assertTrue(_strptime._strptime_time(strf_output.upper(), "%B"), "strptime does not handle ALL-CAPS names properly") - self.failUnless(_strptime._strptime_time(strf_output.lower(), "%B"), + self.assertTrue(_strptime._strptime_time(strf_output.lower(), "%B"), "strptime does not handle lowercase names properly") - self.failUnless(_strptime._strptime_time(strf_output.capitalize(), "%B"), + self.assertTrue(_strptime._strptime_time(strf_output.capitalize(), "%B"), "strptime does not handle capword names properly") def test_defaults(self): # Default return value should be (1900, 1, 1, 0, 0, 0, 0, 1, 0) defaults = (1900, 1, 1, 0, 0, 0, 0, 1, -1) strp_output = _strptime._strptime_time('1', '%m') - self.failUnless(strp_output == defaults, + self.assertTrue(strp_output == defaults, "Default values for strptime() are incorrect;" " %s != %s" % (strp_output, defaults)) @@ -383,7 +383,7 @@ class StrptimeTests(unittest.TestCase): # escaped. # Test instigated by bug #796149 . need_escaping = ".^$*+?{}\[]|)(" - self.failUnless(_strptime._strptime_time(need_escaping, need_escaping)) + self.assertTrue(_strptime._strptime_time(need_escaping, need_escaping)) class Strptime12AMPMTests(unittest.TestCase): """Test a _strptime regression in '%I %p' at 12 noon (12 PM)""" @@ -416,7 +416,7 @@ class CalculationTests(unittest.TestCase): format_string = "%Y %m %d %H %M %S %w %Z" result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple), format_string) - self.failUnless(result.tm_yday == self.time_tuple.tm_yday, + self.assertTrue(result.tm_yday == self.time_tuple.tm_yday, "Calculation of tm_yday failed; %s != %s" % (result.tm_yday, self.time_tuple.tm_yday)) @@ -425,7 +425,7 @@ class CalculationTests(unittest.TestCase): format_string = "%Y %H %M %S %w %j %Z" result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple), format_string) - self.failUnless(result.tm_year == self.time_tuple.tm_year and + self.assertTrue(result.tm_year == self.time_tuple.tm_year and result.tm_mon == self.time_tuple.tm_mon and result.tm_mday == self.time_tuple.tm_mday, "Calculation of Gregorian date failed;" @@ -439,7 +439,7 @@ class CalculationTests(unittest.TestCase): format_string = "%Y %m %d %H %S %j %Z" result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple), format_string) - self.failUnless(result.tm_wday == self.time_tuple.tm_wday, + self.assertTrue(result.tm_wday == self.time_tuple.tm_wday, "Calculation of day of the week failed;" "%s != %s" % (result.tm_wday, self.time_tuple.tm_wday)) @@ -452,7 +452,7 @@ class CalculationTests(unittest.TestCase): dt_date = datetime_date(*ymd_tuple) strp_input = dt_date.strftime(format_string) strp_output = _strptime._strptime_time(strp_input, format_string) - self.failUnless(strp_output[:3] == ymd_tuple, + self.assertTrue(strp_output[:3] == ymd_tuple, "%s(%s) test failed w/ '%s': %s != %s (%s != %s)" % (test_reason, directive, strp_input, strp_output[:3], ymd_tuple, @@ -495,8 +495,8 @@ class CacheTests(unittest.TestCase): _strptime._TimeRE_cache.locale_time.lang = "Ni" original_time_re = id(_strptime._TimeRE_cache) _strptime._strptime_time("10", "%d") - self.failIfEqual(original_time_re, id(_strptime._TimeRE_cache)) - self.failUnlessEqual(len(_strptime._regex_cache), 1) + self.assertNotEqual(original_time_re, id(_strptime._TimeRE_cache)) + self.assertEqual(len(_strptime._regex_cache), 1) def test_regex_cleanup(self): # Make sure cached regexes are discarded when cache becomes "full". @@ -509,7 +509,7 @@ class CacheTests(unittest.TestCase): _strptime._regex_cache[bogus_key] = None bogus_key += 1 _strptime._strptime_time("10", "%d") - self.failUnlessEqual(len(_strptime._regex_cache), 1) + self.assertEqual(len(_strptime._regex_cache), 1) def test_new_localetime(self): # A new LocaleTime instance should be created when a new TimeRE object @@ -517,7 +517,7 @@ class CacheTests(unittest.TestCase): locale_time_id = id(_strptime._TimeRE_cache.locale_time) _strptime._TimeRE_cache.locale_time.lang = "Ni" _strptime._strptime_time("10", "%d") - self.failIfEqual(locale_time_id, + self.assertNotEqual(locale_time_id, id(_strptime._TimeRE_cache.locale_time)) def test_TimeRE_recreation(self): @@ -538,7 +538,7 @@ class CacheTests(unittest.TestCase): # Get the new cache object's id. second_time_re_id = id(_strptime._TimeRE_cache) # They should not be equal. - self.failIfEqual(first_time_re_id, second_time_re_id) + self.assertNotEqual(first_time_re_id, second_time_re_id) # Possible test locale is not supported while initial locale is. # If this is the case just suppress the exception and fall-through # to the reseting to the original locale. diff --git a/Lib/test/test_struct.py b/Lib/test/test_struct.py index 1cf3484..ef05e3c 100644 --- a/Lib/test/test_struct.py +++ b/Lib/test/test_struct.py @@ -181,7 +181,7 @@ class StructTest(unittest.TestCase): self.assertEqual(struct.calcsize(xfmt), len(res)) rev = struct.unpack(xfmt, res)[0] if rev != arg: - self.assert_(asy) + self.assertTrue(asy) def test_native_qQ(self): # can't pack -1 as unsigned regardless @@ -252,7 +252,7 @@ class StructTest(unittest.TestCase): expected = long(x) if x < 0: expected += 1L << self.bitsize - self.assert_(expected > 0) + self.assertTrue(expected > 0) expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' if len(expected) & 1: expected = "0" + expected diff --git a/Lib/test/test_structseq.py b/Lib/test/test_structseq.py index 83c7ccf..5783ccb 100644 --- a/Lib/test/test_structseq.py +++ b/Lib/test/test_structseq.py @@ -28,7 +28,7 @@ class StructSeqTest(unittest.TestCase): def test_repr(self): t = time.gmtime() - self.assert_(repr(t)) + self.assertTrue(repr(t)) t = time.gmtime(0) self.assertEqual(repr(t), "time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, " @@ -50,8 +50,8 @@ class StructSeqTest(unittest.TestCase): def test_contains(self): t1 = time.gmtime() for item in t1: - self.assert_(item in t1) - self.assert_(-42 not in t1) + self.assertTrue(item in t1) + self.assertTrue(-42 not in t1) def test_hash(self): t1 = time.gmtime() @@ -61,11 +61,11 @@ class StructSeqTest(unittest.TestCase): t1 = time.gmtime() t2 = type(t1)(t1) self.assertEqual(t1, t2) - self.assert_(not (t1 < t2)) - self.assert_(t1 <= t2) - self.assert_(not (t1 > t2)) - self.assert_(t1 >= t2) - self.assert_(not (t1 != t2)) + self.assertTrue(not (t1 < t2)) + self.assertTrue(t1 <= t2) + self.assertTrue(not (t1 > t2)) + self.assertTrue(t1 >= t2) + self.assertTrue(not (t1 != t2)) def test_fields(self): t = time.gmtime() diff --git a/Lib/test/test_subprocess.py b/Lib/test/test_subprocess.py index 0ddac3d..c441cdc 100644 --- a/Lib/test/test_subprocess.py +++ b/Lib/test/test_subprocess.py @@ -497,7 +497,7 @@ class ProcessTestCase(unittest.TestCase): # but, based on system scheduling we can't control, it's possible # poll() never returned None. It "should be" very rare that it # didn't go around at least twice. - self.assert_(count >= 2) + self.assertTrue(count >= 2) # Subsequent invocations should just return the returncode self.assertEqual(p.poll(), 0) @@ -652,7 +652,7 @@ class ProcessTestCase(unittest.TestCase): p = subprocess.Popen([sys.executable, "-c", "input()"]) - self.assert_(p.poll() is None, p.poll()) + self.assertTrue(p.poll() is None, p.poll()) p.send_signal(signal.SIGINT) self.assertNotEqual(p.wait(), 0) @@ -660,7 +660,7 @@ class ProcessTestCase(unittest.TestCase): p = subprocess.Popen([sys.executable, "-c", "input()"]) - self.assert_(p.poll() is None, p.poll()) + self.assertTrue(p.poll() is None, p.poll()) p.kill() self.assertEqual(p.wait(), -signal.SIGKILL) @@ -668,7 +668,7 @@ class ProcessTestCase(unittest.TestCase): p = subprocess.Popen([sys.executable, "-c", "input()"]) - self.assert_(p.poll() is None, p.poll()) + self.assertTrue(p.poll() is None, p.poll()) p.terminate() self.assertEqual(p.wait(), -signal.SIGTERM) @@ -746,7 +746,7 @@ class ProcessTestCase(unittest.TestCase): p = subprocess.Popen([sys.executable, "-c", "input()"]) - self.assert_(p.poll() is None, p.poll()) + self.assertTrue(p.poll() is None, p.poll()) p.send_signal(signal.SIGTERM) self.assertNotEqual(p.wait(), 0) @@ -754,7 +754,7 @@ class ProcessTestCase(unittest.TestCase): p = subprocess.Popen([sys.executable, "-c", "input()"]) - self.assert_(p.poll() is None, p.poll()) + self.assertTrue(p.poll() is None, p.poll()) p.kill() self.assertNotEqual(p.wait(), 0) @@ -762,7 +762,7 @@ class ProcessTestCase(unittest.TestCase): p = subprocess.Popen([sys.executable, "-c", "input()"]) - self.assert_(p.poll() is None, p.poll()) + self.assertTrue(p.poll() is None, p.poll()) p.terminate() self.assertNotEqual(p.wait(), 0) diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py index dd1f005..4b14c3b 100644 --- a/Lib/test/test_support.py +++ b/Lib/test/test_support.py @@ -741,7 +741,7 @@ def bigmemtest(minsize, memuse, overhead=5*_1M): # to make sure they work. We still want to avoid using # too much memory, though, but we do that noisily. maxsize = 5147 - self.failIf(maxsize * memuse + overhead > 20 * _1M) + self.assertFalse(maxsize * memuse + overhead > 20 * _1M) else: maxsize = int((max_memuse - overhead) / memuse) if maxsize < minsize: diff --git a/Lib/test/test_symtable.py b/Lib/test/test_symtable.py index 2de30ae..c9d2054 100644 --- a/Lib/test/test_symtable.py +++ b/Lib/test/test_symtable.py @@ -132,7 +132,7 @@ class SymtableTest(unittest.TestCase): self.assertTrue(self.top.lookup("namespace_test").is_namespace()) self.assertFalse(self.spam.lookup("x").is_namespace()) - self.assert_(self.top.lookup("spam").get_namespace() is self.spam) + self.assertTrue(self.top.lookup("spam").get_namespace() is self.spam) ns_test = self.top.lookup("namespace_test") self.assertEqual(len(ns_test.get_namespaces()), 2) self.assertRaises(ValueError, ns_test.get_namespace) diff --git a/Lib/test/test_sys.py b/Lib/test/test_sys.py index 3493fd1..0e364af 100644 --- a/Lib/test/test_sys.py +++ b/Lib/test/test_sys.py @@ -19,7 +19,7 @@ class SysModuleTest(unittest.TestCase): dh(None) self.assertEqual(out.getvalue(), "") - self.assert_(not hasattr(__builtin__, "_")) + self.assertTrue(not hasattr(__builtin__, "_")) dh(42) self.assertEqual(out.getvalue(), "42\n") self.assertEqual(__builtin__._, 42) @@ -59,7 +59,7 @@ class SysModuleTest(unittest.TestCase): eh(*sys.exc_info()) sys.stderr = savestderr - self.assert_(err.getvalue().endswith("ValueError: 42\n")) + self.assertTrue(err.getvalue().endswith("ValueError: 42\n")) # FIXME: testing the code for a lost or replaced excepthook in # Python/pythonrun.c::PyErr_PrintEx() is tricky. @@ -71,16 +71,16 @@ class SysModuleTest(unittest.TestCase): # check that it worked. def clear_check(exc): typ, value, traceback = sys.exc_info() - self.assert_(typ is not None) - self.assert_(value is exc) - self.assert_(traceback is not None) + self.assertTrue(typ is not None) + self.assertTrue(value is exc) + self.assertTrue(traceback is not None) sys.exc_clear() typ, value, traceback = sys.exc_info() - self.assert_(typ is None) - self.assert_(value is None) - self.assert_(traceback is None) + self.assertTrue(typ is None) + self.assertTrue(value is None) + self.assertTrue(traceback is None) def clear(): try: @@ -100,10 +100,10 @@ class SysModuleTest(unittest.TestCase): clear() typ2, value2, traceback2 = sys.exc_info() - self.assert_(typ1 is typ2) - self.assert_(value1 is exc) - self.assert_(value1 is value2) - self.assert_(traceback1 is traceback2) + self.assertTrue(typ1 is typ2) + self.assertTrue(value1 is exc) + self.assertTrue(value1 is value2) + self.assertTrue(traceback1 is traceback2) # Check that an exception can be cleared outside of an except block clear_check(exc) @@ -178,7 +178,7 @@ class SysModuleTest(unittest.TestCase): if test.test_support.have_unicode: self.assertRaises(TypeError, sys.getdefaultencoding, 42) # can't check more than the type, as the user might have changed it - self.assert_(isinstance(sys.getdefaultencoding(), str)) + self.assertTrue(isinstance(sys.getdefaultencoding(), str)) # testing sys.settrace() is done in test_trace.py # testing sys.setprofile() is done in test_profile.py @@ -202,17 +202,17 @@ class SysModuleTest(unittest.TestCase): def test_getwindowsversion(self): if hasattr(sys, "getwindowsversion"): v = sys.getwindowsversion() - self.assert_(isinstance(v, tuple)) + self.assertTrue(isinstance(v, tuple)) self.assertEqual(len(v), 5) - self.assert_(isinstance(v[0], int)) - self.assert_(isinstance(v[1], int)) - self.assert_(isinstance(v[2], int)) - self.assert_(isinstance(v[3], int)) - self.assert_(isinstance(v[4], str)) + self.assertTrue(isinstance(v[0], int)) + self.assertTrue(isinstance(v[1], int)) + self.assertTrue(isinstance(v[2], int)) + self.assertTrue(isinstance(v[3], int)) + self.assertTrue(isinstance(v[4], str)) def test_dlopenflags(self): if hasattr(sys, "setdlopenflags"): - self.assert_(hasattr(sys, "getdlopenflags")) + self.assertTrue(hasattr(sys, "getdlopenflags")) self.assertRaises(TypeError, sys.getdlopenflags, 42) oldflags = sys.getdlopenflags() self.assertRaises(TypeError, sys.setdlopenflags) @@ -233,12 +233,12 @@ class SysModuleTest(unittest.TestCase): del n self.assertEqual(sys.getrefcount(None), c) if hasattr(sys, "gettotalrefcount"): - self.assert_(isinstance(sys.gettotalrefcount(), int)) + self.assertTrue(isinstance(sys.gettotalrefcount(), int)) def test_getframe(self): self.assertRaises(TypeError, sys._getframe, 42, 42) self.assertRaises(ValueError, sys._getframe, 2000000000) - self.assert_( + self.assertTrue( SysModuleTest.test_getframe.im_func.func_code \ is sys._getframe().f_code ) @@ -289,12 +289,12 @@ class SysModuleTest(unittest.TestCase): d = sys._current_frames() main_id = thread.get_ident() - self.assert_(main_id in d) - self.assert_(thread_id in d) + self.assertTrue(main_id in d) + self.assertTrue(thread_id in d) # Verify that the captured main-thread frame is _this_ frame. frame = d.pop(main_id) - self.assert_(frame is sys._getframe()) + self.assertTrue(frame is sys._getframe()) # Verify that the captured thread frame is blocked in g456, called # from f123. This is a litte tricky, since various bits of @@ -312,7 +312,7 @@ class SysModuleTest(unittest.TestCase): # And the next record must be for g456(). filename, lineno, funcname, sourceline = stack[i+1] self.assertEqual(funcname, "g456") - self.assert_(sourceline in ["leave_g.wait()", "entered_g.set()"]) + self.assertTrue(sourceline in ["leave_g.wait()", "entered_g.set()"]) # Reap the spawned thread. leave_g.set() @@ -324,67 +324,67 @@ class SysModuleTest(unittest.TestCase): # "thread id" 0. d = sys._current_frames() self.assertEqual(len(d), 1) - self.assert_(0 in d) - self.assert_(d[0] is sys._getframe()) + self.assertTrue(0 in d) + self.assertTrue(d[0] is sys._getframe()) def test_attributes(self): - self.assert_(isinstance(sys.api_version, int)) - self.assert_(isinstance(sys.argv, list)) - self.assert_(sys.byteorder in ("little", "big")) - self.assert_(isinstance(sys.builtin_module_names, tuple)) - self.assert_(isinstance(sys.copyright, basestring)) - self.assert_(isinstance(sys.exec_prefix, basestring)) - self.assert_(isinstance(sys.executable, basestring)) + self.assertTrue(isinstance(sys.api_version, int)) + self.assertTrue(isinstance(sys.argv, list)) + self.assertTrue(sys.byteorder in ("little", "big")) + self.assertTrue(isinstance(sys.builtin_module_names, tuple)) + self.assertTrue(isinstance(sys.copyright, basestring)) + self.assertTrue(isinstance(sys.exec_prefix, basestring)) + self.assertTrue(isinstance(sys.executable, basestring)) self.assertEqual(len(sys.float_info), 11) self.assertEqual(sys.float_info.radix, 2) self.assertEqual(len(sys.long_info), 2) - self.assert_(sys.long_info.bits_per_digit % 5 == 0) - self.assert_(sys.long_info.sizeof_digit >= 1) + self.assertTrue(sys.long_info.bits_per_digit % 5 == 0) + self.assertTrue(sys.long_info.sizeof_digit >= 1) self.assertEqual(type(sys.long_info.bits_per_digit), int) self.assertEqual(type(sys.long_info.sizeof_digit), int) - self.assert_(isinstance(sys.hexversion, int)) - self.assert_(isinstance(sys.maxint, int)) + self.assertTrue(isinstance(sys.hexversion, int)) + self.assertTrue(isinstance(sys.maxint, int)) if test.test_support.have_unicode: - self.assert_(isinstance(sys.maxunicode, int)) - self.assert_(isinstance(sys.platform, basestring)) - self.assert_(isinstance(sys.prefix, basestring)) - self.assert_(isinstance(sys.version, basestring)) + self.assertTrue(isinstance(sys.maxunicode, int)) + self.assertTrue(isinstance(sys.platform, basestring)) + self.assertTrue(isinstance(sys.prefix, basestring)) + self.assertTrue(isinstance(sys.version, basestring)) vi = sys.version_info - self.assert_(isinstance(vi[:], tuple)) + self.assertTrue(isinstance(vi[:], tuple)) self.assertEqual(len(vi), 5) - self.assert_(isinstance(vi[0], int)) - self.assert_(isinstance(vi[1], int)) - self.assert_(isinstance(vi[2], int)) - self.assert_(vi[3] in ("alpha", "beta", "candidate", "final")) - self.assert_(isinstance(vi[4], int)) - self.assert_(isinstance(vi.major, int)) - self.assert_(isinstance(vi.minor, int)) - self.assert_(isinstance(vi.micro, int)) - self.assert_(vi.releaselevel in + self.assertTrue(isinstance(vi[0], int)) + self.assertTrue(isinstance(vi[1], int)) + self.assertTrue(isinstance(vi[2], int)) + self.assertTrue(vi[3] in ("alpha", "beta", "candidate", "final")) + self.assertTrue(isinstance(vi[4], int)) + self.assertTrue(isinstance(vi.major, int)) + self.assertTrue(isinstance(vi.minor, int)) + self.assertTrue(isinstance(vi.micro, int)) + self.assertTrue(vi.releaselevel in ("alpha", "beta", "candidate", "final")) - self.assert_(isinstance(vi.serial, int)) + self.assertTrue(isinstance(vi.serial, int)) self.assertEqual(vi[0], vi.major) self.assertEqual(vi[1], vi.minor) self.assertEqual(vi[2], vi.micro) self.assertEqual(vi[3], vi.releaselevel) self.assertEqual(vi[4], vi.serial) - self.assert_(vi > (1,0,0)) + self.assertTrue(vi > (1,0,0)) def test_43581(self): # Can't use sys.stdout, as this is a cStringIO object when # the test runs under regrtest. - self.assert_(sys.__stdout__.encoding == sys.__stderr__.encoding) + self.assertTrue(sys.__stdout__.encoding == sys.__stderr__.encoding) def test_sys_flags(self): - self.failUnless(sys.flags) + self.assertTrue(sys.flags) attrs = ("debug", "py3k_warning", "division_warning", "division_new", "inspect", "interactive", "optimize", "dont_write_bytecode", "no_site", "ignore_environment", "tabcheck", "verbose", "unicode", "bytes_warning") for attr in attrs: - self.assert_(hasattr(sys.flags, attr), attr) + self.assertTrue(hasattr(sys.flags, attr), attr) self.assertEqual(type(getattr(sys.flags, attr)), int, attr) - self.assert_(repr(sys.flags)) + self.assertTrue(repr(sys.flags)) def test_clear_type_cache(self): sys._clear_type_cache() diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py index ee68118..aba218d 100644 --- a/Lib/test/test_tarfile.py +++ b/Lib/test/test_tarfile.py @@ -58,7 +58,7 @@ class UstarReadTest(ReadTest): tarinfo = self.tar.getmember("ustar/regtype") fobj = self.tar.extractfile(tarinfo) data = fobj.read() - self.assert_((len(data), md5sum(data)) == (tarinfo.size, md5_regtype), + self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype), "regular file extraction failed") def test_fileobj_readlines(self): @@ -69,11 +69,11 @@ class UstarReadTest(ReadTest): lines1 = fobj1.readlines() lines2 = fobj2.readlines() - self.assert_(lines1 == lines2, + self.assertTrue(lines1 == lines2, "fileobj.readlines() failed") - self.assert_(len(lines2) == 114, + self.assertTrue(len(lines2) == 114, "fileobj.readlines() failed") - self.assert_(lines2[83] == \ + self.assertTrue(lines2[83] == \ "I will gladly admit that Python is not the fastest running scripting language.\n", "fileobj.readlines() failed") @@ -84,7 +84,7 @@ class UstarReadTest(ReadTest): fobj2 = self.tar.extractfile(tarinfo) lines1 = fobj1.readlines() lines2 = [line for line in fobj2] - self.assert_(lines1 == lines2, + self.assertTrue(lines1 == lines2, "fileobj.__iter__() failed") def test_fileobj_seek(self): @@ -98,43 +98,43 @@ class UstarReadTest(ReadTest): text = fobj.read() fobj.seek(0) - self.assert_(0 == fobj.tell(), + self.assertTrue(0 == fobj.tell(), "seek() to file's start failed") fobj.seek(2048, 0) - self.assert_(2048 == fobj.tell(), + self.assertTrue(2048 == fobj.tell(), "seek() to absolute position failed") fobj.seek(-1024, 1) - self.assert_(1024 == fobj.tell(), + self.assertTrue(1024 == fobj.tell(), "seek() to negative relative position failed") fobj.seek(1024, 1) - self.assert_(2048 == fobj.tell(), + self.assertTrue(2048 == fobj.tell(), "seek() to positive relative position failed") s = fobj.read(10) - self.assert_(s == data[2048:2058], + self.assertTrue(s == data[2048:2058], "read() after seek failed") fobj.seek(0, 2) - self.assert_(tarinfo.size == fobj.tell(), + self.assertTrue(tarinfo.size == fobj.tell(), "seek() to file's end failed") - self.assert_(fobj.read() == "", + self.assertTrue(fobj.read() == "", "read() at file's end did not return empty string") fobj.seek(-tarinfo.size, 2) - self.assert_(0 == fobj.tell(), + self.assertTrue(0 == fobj.tell(), "relative seek() to file's start failed") fobj.seek(512) s1 = fobj.readlines() fobj.seek(512) s2 = fobj.readlines() - self.assert_(s1 == s2, + self.assertTrue(s1 == s2, "readlines() after seek failed") fobj.seek(0) - self.assert_(len(fobj.readline()) == fobj.tell(), + self.assertTrue(len(fobj.readline()) == fobj.tell(), "tell() after readline() failed") fobj.seek(512) - self.assert_(len(fobj.readline()) + 512 == fobj.tell(), + self.assertTrue(len(fobj.readline()) + 512 == fobj.tell(), "tell() after seek() and readline() failed") fobj.seek(0) line = fobj.readline() - self.assert_(fobj.read() == data[len(line):], + self.assertTrue(fobj.read() == data[len(line):], "read() after readline() failed") fobj.close() @@ -205,7 +205,7 @@ class MiscReadTest(ReadTest): # Old V7 tars create directory members using an AREGTYPE # header with a "/" appended to the filename field. tarinfo = self.tar.getmember("misc/dirtype-old-v7") - self.assert_(tarinfo.type == tarfile.DIRTYPE, + self.assertTrue(tarinfo.type == tarfile.DIRTYPE, "v7 dirtype failed") def test_xstar_type(self): @@ -219,15 +219,15 @@ class MiscReadTest(ReadTest): def test_check_members(self): for tarinfo in self.tar: - self.assert_(int(tarinfo.mtime) == 07606136617, + self.assertTrue(int(tarinfo.mtime) == 07606136617, "wrong mtime for %s" % tarinfo.name) if not tarinfo.name.startswith("ustar/"): continue - self.assert_(tarinfo.uname == "tarfile", + self.assertTrue(tarinfo.uname == "tarfile", "wrong uname for %s" % tarinfo.name) def test_find_members(self): - self.assert_(self.tar.getmembers()[-1].name == "misc/eof", + self.assertTrue(self.tar.getmembers()[-1].name == "misc/eof", "could not find all members") def test_extract_hardlink(self): @@ -276,7 +276,7 @@ class StreamReadTest(ReadTest): tarinfo = self.tar.next() # get "regtype" (can't use getmember) fobj = self.tar.extractfile(tarinfo) data = fobj.read() - self.assert_((len(data), md5sum(data)) == (tarinfo.size, md5_regtype), + self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype), "regular file extraction failed") def test_provoke_stream_error(self): @@ -293,7 +293,7 @@ class StreamReadTest(ReadTest): t2 = tar2.next() if t1 is None: break - self.assert_(t2 is not None, "stream.next() failed.") + self.assertTrue(t2 is not None, "stream.next() failed.") if t2.islnk() or t2.issym(): self.assertRaises(tarfile.StreamError, tar2.extractfile, t2) @@ -303,8 +303,8 @@ class StreamReadTest(ReadTest): v2 = tar2.extractfile(t2) if v1 is None: continue - self.assert_(v2 is not None, "stream.extractfile() failed") - self.assert_(v1.read() == v2.read(), "stream extraction failed") + self.assertTrue(v2 is not None, "stream.extractfile() failed") + self.assertTrue(v1.read() == v2.read(), "stream extraction failed") tar1.close() @@ -365,7 +365,7 @@ class MemberReadTest(ReadTest): def _test_member(self, tarinfo, chksum=None, **kwargs): if chksum is not None: - self.assert_(md5sum(self.tar.extractfile(tarinfo).read()) == chksum, + self.assertTrue(md5sum(self.tar.extractfile(tarinfo).read()) == chksum, "wrong md5sum for %s" % tarinfo.name) kwargs["mtime"] = 07606136617 @@ -376,7 +376,7 @@ class MemberReadTest(ReadTest): kwargs["uname"] = "tarfile" kwargs["gname"] = "tarfile" for k, v in kwargs.iteritems(): - self.assert_(getattr(tarinfo, k) == v, + self.assertTrue(getattr(tarinfo, k) == v, "wrong value in %s field of %s" % (k, tarinfo.name)) def test_find_regtype(self): @@ -425,7 +425,7 @@ class MemberReadTest(ReadTest): def test_find_ustar_longname(self): name = "ustar/" + "12345/" * 39 + "1234567/longname" - self.assert_(name in self.tar.getnames()) + self.assertTrue(name in self.tar.getnames()) def test_find_regtype_oldv7(self): tarinfo = self.tar.getmember("misc/regtype-old-v7") @@ -446,7 +446,7 @@ class LongnameTest(ReadTest): tarinfo = self.tar.getmember(longname) except KeyError: self.fail("longname not found") - self.assert_(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype") + self.assertTrue(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype") def test_read_longlink(self): longname = self.subdir + "/" + "123/" * 125 + "longname" @@ -455,7 +455,7 @@ class LongnameTest(ReadTest): tarinfo = self.tar.getmember(longlink) except KeyError: self.fail("longlink not found") - self.assert_(tarinfo.linkname == longname, "linkname wrong") + self.assertTrue(tarinfo.linkname == longname, "linkname wrong") def test_truncated_longname(self): longname = self.subdir + "/" + "123/" * 125 + "longname" @@ -486,7 +486,7 @@ class GNUReadTest(LongnameTest): fobj1 = self.tar.extractfile(tarinfo1) tarinfo2 = self.tar.getmember("gnu/sparse") fobj2 = self.tar.extractfile(tarinfo2) - self.assert_(fobj1.read() == fobj2.read(), + self.assertTrue(fobj1.read() == fobj2.read(), "sparse file extraction failed") @@ -535,7 +535,7 @@ class WriteTestBase(unittest.TestCase): tar = tarfile.open(fileobj=fobj, mode=self.mode) tar.addfile(tarfile.TarInfo("foo")) tar.close() - self.assert_(fobj.closed is False, "external fileobjs must never closed") + self.assertTrue(fobj.closed is False, "external fileobjs must never closed") class WriteTest(WriteTestBase): @@ -554,7 +554,7 @@ class WriteTest(WriteTestBase): tar.close() tar = tarfile.open(tmpname) - self.assert_(tar.getnames()[0] == name, + self.assertTrue(tar.getnames()[0] == name, "failed to store 100 char filename") tar.close() @@ -567,7 +567,7 @@ class WriteTest(WriteTestBase): fobj.close() tar.add(path) tar.close() - self.assert_(os.path.getsize(tmpname) > 0, + self.assertTrue(os.path.getsize(tmpname) > 0, "tarfile is empty") # The test_*_size tests test for bug #1167128. @@ -628,16 +628,16 @@ class WriteTest(WriteTestBase): dstname = os.path.abspath(tmpname) tar = tarfile.open(tmpname, self.mode) - self.assert_(tar.name == dstname, "archive name must be absolute") + self.assertTrue(tar.name == dstname, "archive name must be absolute") tar.add(dstname) - self.assert_(tar.getnames() == [], "added the archive to itself") + self.assertTrue(tar.getnames() == [], "added the archive to itself") cwd = os.getcwd() os.chdir(TEMPDIR) tar.add(dstname) os.chdir(cwd) - self.assert_(tar.getnames() == [], "added the archive to itself") + self.assertTrue(tar.getnames() == [], "added the archive to itself") def test_exclude(self): tempdir = os.path.join(TEMPDIR, "exclude") @@ -678,14 +678,14 @@ class StreamWriteTest(WriteTestBase): dec = bz2.BZ2Decompressor() data = open(tmpname, "rb").read() data = dec.decompress(data) - self.assert_(len(dec.unused_data) == 0, + self.assertTrue(len(dec.unused_data) == 0, "found trailing data") else: fobj = open(tmpname, "rb") data = fobj.read() fobj.close() - self.assert_(data.count("\0") == tarfile.RECORDSIZE, + self.assertTrue(data.count("\0") == tarfile.RECORDSIZE, "incorrect zero padding") @@ -725,14 +725,14 @@ class GNUWriteTest(unittest.TestCase): v1 = self._calc_size(name, link) v2 = tar.offset - self.assert_(v1 == v2, "GNU longname/longlink creation failed") + self.assertTrue(v1 == v2, "GNU longname/longlink creation failed") tar.close() tar = tarfile.open(tmpname) member = tar.next() - self.failIf(member is None, "unable to read longname member") - self.assert_(tarinfo.name == member.name and \ + self.assertFalse(member is None, "unable to read longname member") + self.assertTrue(tarinfo.name == member.name and \ tarinfo.linkname == member.linkname, \ "unable to read longname member") @@ -792,18 +792,18 @@ class HardlinkTest(unittest.TestCase): # The same name will be added as a REGTYPE every # time regardless of st_nlink. tarinfo = self.tar.gettarinfo(self.foo) - self.assert_(tarinfo.type == tarfile.REGTYPE, + self.assertTrue(tarinfo.type == tarfile.REGTYPE, "add file as regular failed") def test_add_hardlink(self): tarinfo = self.tar.gettarinfo(self.bar) - self.assert_(tarinfo.type == tarfile.LNKTYPE, + self.assertTrue(tarinfo.type == tarfile.LNKTYPE, "add file as hardlink failed") def test_dereference_hardlink(self): self.tar.dereference = True tarinfo = self.tar.gettarinfo(self.bar) - self.assert_(tarinfo.type == tarfile.REGTYPE, + self.assertTrue(tarinfo.type == tarfile.REGTYPE, "dereferencing hardlink failed") @@ -823,10 +823,10 @@ class PaxWriteTest(GNUWriteTest): tar = tarfile.open(tmpname) if link: l = tar.getmembers()[0].linkname - self.assert_(link == l, "PAX longlink creation failed") + self.assertTrue(link == l, "PAX longlink creation failed") else: n = tar.getmembers()[0].name - self.assert_(name == n, "PAX longname creation failed") + self.assertTrue(name == n, "PAX longname creation failed") def test_pax_global_header(self): pax_headers = { @@ -848,8 +848,8 @@ class PaxWriteTest(GNUWriteTest): # Test if all the fields are unicode. for key, val in tar.pax_headers.iteritems(): - self.assert_(type(key) is unicode) - self.assert_(type(val) is unicode) + self.assertTrue(type(key) is unicode) + self.assertTrue(type(val) is unicode) if key in tarfile.PAX_NUMBER_FIELDS: try: tarfile.PAX_NUMBER_FIELDS[key](val) @@ -897,7 +897,7 @@ class UstarUnicodeTest(unittest.TestCase): tar.close() tar = tarfile.open(tmpname, encoding=encoding) - self.assert_(type(tar.getnames()[0]) is not unicode) + self.assertTrue(type(tar.getnames()[0]) is not unicode) self.assertEqual(tar.getmembers()[0].name, name.encode(encoding)) tar.close() @@ -921,10 +921,10 @@ class UstarUnicodeTest(unittest.TestCase): def test_unicode_argument(self): tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict") for t in tar: - self.assert_(type(t.name) is str) - self.assert_(type(t.linkname) is str) - self.assert_(type(t.uname) is str) - self.assert_(type(t.gname) is str) + self.assertTrue(type(t.name) is str) + self.assertTrue(type(t.linkname) is str) + self.assertTrue(type(t.uname) is str) + self.assertTrue(type(t.gname) is str) tar.close() def test_uname_unicode(self): diff --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py index 8b883b0..7f0b8b3 100644 --- a/Lib/test/test_tempfile.py +++ b/Lib/test/test_tempfile.py @@ -59,7 +59,7 @@ class TC(unittest.TestCase): "file '%s' does not end with '%s'" % (nbase, suf)) nbase = nbase[len(pre):len(nbase)-len(suf)] - self.assert_(self.str_check.match(nbase), + self.assertTrue(self.str_check.match(nbase), "random string '%s' does not match /^[a-zA-Z0-9_-]{6}$/" % nbase) @@ -88,7 +88,7 @@ class test_exports(TC): for key in dict: if key[0] != '_' and key not in expected: unexp.append(key) - self.failUnless(len(unexp) == 0, + self.assertTrue(len(unexp) == 0, "unexpected keys: %s" % unexp) test_classes.append(test_exports) @@ -113,7 +113,7 @@ class test__RandomNameSequence(TC): for i in xrange(TEST_FILES): s = r.next() self.nameCheck(s, '', '', '') - self.failIf(s in dict) + self.assertFalse(s in dict) dict[s] = 1 def test_supports_iter(self): @@ -140,9 +140,9 @@ class test__candidate_tempdir_list(TC): cand = tempfile._candidate_tempdir_list() - self.failIf(len(cand) == 0) + self.assertFalse(len(cand) == 0) for c in cand: - self.assert_(isinstance(c, basestring), + self.assertTrue(isinstance(c, basestring), "%s is not a string" % c) def test_wanted_dirs(self): @@ -160,14 +160,14 @@ class test__candidate_tempdir_list(TC): for envname in 'TMPDIR', 'TEMP', 'TMP': dirname = os.getenv(envname) if not dirname: raise ValueError - self.assert_(dirname in cand) + self.assertTrue(dirname in cand) try: dirname = os.getcwd() except (AttributeError, os.error): dirname = os.curdir - self.assert_(dirname in cand) + self.assertTrue(dirname in cand) # Not practical to try to verify the presence of OS-specific # paths in this list. @@ -184,14 +184,14 @@ class test__get_candidate_names(TC): def test_retval(self): # _get_candidate_names returns a _RandomNameSequence object obj = tempfile._get_candidate_names() - self.assert_(isinstance(obj, tempfile._RandomNameSequence)) + self.assertTrue(isinstance(obj, tempfile._RandomNameSequence)) def test_same_thing(self): # _get_candidate_names always returns the same object a = tempfile._get_candidate_names() b = tempfile._get_candidate_names() - self.assert_(a is b) + self.assertTrue(a is b) test_classes.append(test__get_candidate_names) @@ -300,9 +300,9 @@ class test__mkstemp_inner(TC): decorated = sys.executable retval = os.spawnl(os.P_WAIT, sys.executable, decorated, tester, v, fd) - self.failIf(retval < 0, + self.assertFalse(retval < 0, "child process caught fatal signal %d" % -retval) - self.failIf(retval > 0, "child process reports failure %d"%retval) + self.assertFalse(retval > 0, "child process reports failure %d"%retval) def test_textmode(self): # _mkstemp_inner can create files in text mode @@ -322,8 +322,8 @@ class test_gettempprefix(TC): # gettempprefix returns a nonempty prefix string p = tempfile.gettempprefix() - self.assert_(isinstance(p, basestring)) - self.assert_(len(p) > 0) + self.assertTrue(isinstance(p, basestring)) + self.assertTrue(len(p) > 0) def test_usable_template(self): # gettempprefix returns a usable prefix string @@ -354,9 +354,9 @@ class test_gettempdir(TC): # gettempdir returns a directory which exists dir = tempfile.gettempdir() - self.assert_(os.path.isabs(dir) or dir == os.curdir, + self.assertTrue(os.path.isabs(dir) or dir == os.curdir, "%s is not an absolute path" % dir) - self.assert_(os.path.isdir(dir), + self.assertTrue(os.path.isdir(dir), "%s is not a directory" % dir) def test_directory_writable(self): @@ -377,7 +377,7 @@ class test_gettempdir(TC): a = tempfile.gettempdir() b = tempfile.gettempdir() - self.assert_(a is b) + self.assertTrue(a is b) test_classes.append(test_gettempdir) @@ -580,7 +580,7 @@ class test_NamedTemporaryFile(TC): def test_creates_named(self): # NamedTemporaryFile creates files with names f = tempfile.NamedTemporaryFile() - self.failUnless(os.path.exists(f.name), + self.assertTrue(os.path.exists(f.name), "NamedTemporaryFile %s does not exist" % f.name) def test_del_on_close(self): @@ -590,7 +590,7 @@ class test_NamedTemporaryFile(TC): f = tempfile.NamedTemporaryFile(dir=dir) f.write('blat') f.close() - self.failIf(os.path.exists(f.name), + self.assertFalse(os.path.exists(f.name), "NamedTemporaryFile %s exists after close" % f.name) finally: os.rmdir(dir) @@ -604,7 +604,7 @@ class test_NamedTemporaryFile(TC): tmp = f.name f.write('blat') f.close() - self.failUnless(os.path.exists(f.name), + self.assertTrue(os.path.exists(f.name), "NamedTemporaryFile %s missing after close" % f.name) finally: if tmp is not None: @@ -625,12 +625,12 @@ class test_NamedTemporaryFile(TC): def test_context_manager(self): # A NamedTemporaryFile can be used as a context manager with tempfile.NamedTemporaryFile() as f: - self.failUnless(os.path.exists(f.name)) - self.failIf(os.path.exists(f.name)) + self.assertTrue(os.path.exists(f.name)) + self.assertFalse(os.path.exists(f.name)) def use_closed(): with f: pass - self.failUnlessRaises(ValueError, use_closed) + self.assertRaises(ValueError, use_closed) # How to test the mode and bufsize parameters? @@ -653,21 +653,21 @@ class test_SpooledTemporaryFile(TC): def test_basic(self): # SpooledTemporaryFile can create files f = self.do_create() - self.failIf(f._rolled) + self.assertFalse(f._rolled) f = self.do_create(max_size=100, pre="a", suf=".txt") - self.failIf(f._rolled) + self.assertFalse(f._rolled) def test_del_on_close(self): # A SpooledTemporaryFile is deleted when closed dir = tempfile.mkdtemp() try: f = tempfile.SpooledTemporaryFile(max_size=10, dir=dir) - self.failIf(f._rolled) + self.assertFalse(f._rolled) f.write('blat ' * 5) - self.failUnless(f._rolled) + self.assertTrue(f._rolled) filename = f.name f.close() - self.failIf(os.path.exists(filename), + self.assertFalse(os.path.exists(filename), "SpooledTemporaryFile %s exists after close" % filename) finally: os.rmdir(dir) @@ -675,46 +675,46 @@ class test_SpooledTemporaryFile(TC): def test_rewrite_small(self): # A SpooledTemporaryFile can be written to multiple within the max_size f = self.do_create(max_size=30) - self.failIf(f._rolled) + self.assertFalse(f._rolled) for i in range(5): f.seek(0, 0) f.write('x' * 20) - self.failIf(f._rolled) + self.assertFalse(f._rolled) def test_write_sequential(self): # A SpooledTemporaryFile should hold exactly max_size bytes, and roll # over afterward f = self.do_create(max_size=30) - self.failIf(f._rolled) + self.assertFalse(f._rolled) f.write('x' * 20) - self.failIf(f._rolled) + self.assertFalse(f._rolled) f.write('x' * 10) - self.failIf(f._rolled) + self.assertFalse(f._rolled) f.write('x') - self.failUnless(f._rolled) + self.assertTrue(f._rolled) def test_sparse(self): # A SpooledTemporaryFile that is written late in the file will extend # when that occurs f = self.do_create(max_size=30) - self.failIf(f._rolled) + self.assertFalse(f._rolled) f.seek(100, 0) - self.failIf(f._rolled) + self.assertFalse(f._rolled) f.write('x') - self.failUnless(f._rolled) + self.assertTrue(f._rolled) def test_fileno(self): # A SpooledTemporaryFile should roll over to a real file on fileno() f = self.do_create(max_size=30) - self.failIf(f._rolled) - self.failUnless(f.fileno() > 0) - self.failUnless(f._rolled) + self.assertFalse(f._rolled) + self.assertTrue(f.fileno() > 0) + self.assertTrue(f._rolled) def test_multiple_close_before_rollover(self): # A SpooledTemporaryFile can be closed many times without error f = tempfile.SpooledTemporaryFile() f.write('abc\n') - self.failIf(f._rolled) + self.assertFalse(f._rolled) f.close() try: f.close() @@ -726,7 +726,7 @@ class test_SpooledTemporaryFile(TC): # A SpooledTemporaryFile can be closed many times without error f = tempfile.SpooledTemporaryFile(max_size=1) f.write('abc\n') - self.failUnless(f._rolled) + self.assertTrue(f._rolled) f.close() try: f.close() @@ -746,46 +746,46 @@ class test_SpooledTemporaryFile(TC): write("a" * 35) write("b" * 35) seek(0, 0) - self.failUnless(read(70) == 'a'*35 + 'b'*35) + self.assertTrue(read(70) == 'a'*35 + 'b'*35) def test_context_manager_before_rollover(self): # A SpooledTemporaryFile can be used as a context manager with tempfile.SpooledTemporaryFile(max_size=1) as f: - self.failIf(f._rolled) - self.failIf(f.closed) - self.failUnless(f.closed) + self.assertFalse(f._rolled) + self.assertFalse(f.closed) + self.assertTrue(f.closed) def use_closed(): with f: pass - self.failUnlessRaises(ValueError, use_closed) + self.assertRaises(ValueError, use_closed) def test_context_manager_during_rollover(self): # A SpooledTemporaryFile can be used as a context manager with tempfile.SpooledTemporaryFile(max_size=1) as f: - self.failIf(f._rolled) + self.assertFalse(f._rolled) f.write('abc\n') f.flush() - self.failUnless(f._rolled) - self.failIf(f.closed) - self.failUnless(f.closed) + self.assertTrue(f._rolled) + self.assertFalse(f.closed) + self.assertTrue(f.closed) def use_closed(): with f: pass - self.failUnlessRaises(ValueError, use_closed) + self.assertRaises(ValueError, use_closed) def test_context_manager_after_rollover(self): # A SpooledTemporaryFile can be used as a context manager f = tempfile.SpooledTemporaryFile(max_size=1) f.write('abc\n') f.flush() - self.failUnless(f._rolled) + self.assertTrue(f._rolled) with f: - self.failIf(f.closed) - self.failUnless(f.closed) + self.assertFalse(f.closed) + self.assertTrue(f.closed) def use_closed(): with f: pass - self.failUnlessRaises(ValueError, use_closed) + self.assertRaises(ValueError, use_closed) test_classes.append(test_SpooledTemporaryFile) diff --git a/Lib/test/test_threading.py b/Lib/test/test_threading.py index 463d0d8..233ccf6 100644 --- a/Lib/test/test_threading.py +++ b/Lib/test/test_threading.py @@ -41,7 +41,7 @@ class TestThread(threading.Thread): self.nrunning.inc() if verbose: print self.nrunning.get(), 'tasks are running' - self.testcase.assert_(self.nrunning.get() <= 3) + self.testcase.assertTrue(self.nrunning.get() <= 3) time.sleep(delay) if verbose: @@ -49,7 +49,7 @@ class TestThread(threading.Thread): with self.mutex: self.nrunning.dec() - self.testcase.assert_(self.nrunning.get() >= 0) + self.testcase.assertTrue(self.nrunning.get() >= 0) if verbose: print '%s is finished. %d tasks are running' % ( self.name, self.nrunning.get()) @@ -73,18 +73,18 @@ class ThreadTests(unittest.TestCase): for i in range(NUMTASKS): t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning) threads.append(t) - self.failUnlessEqual(t.ident, None) - self.assert_(re.match('<TestThread\(.*, initial\)>', repr(t))) + self.assertEqual(t.ident, None) + self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t))) t.start() if verbose: print 'waiting for all tasks to complete' for t in threads: t.join(NUMTASKS) - self.assert_(not t.is_alive()) - self.failIfEqual(t.ident, 0) + self.assertTrue(not t.is_alive()) + self.assertNotEqual(t.ident, 0) self.assertFalse(t.ident is None) - self.assert_(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t))) + self.assertTrue(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t))) if verbose: print 'all tasks done' self.assertEqual(numrunning.get(), 0) @@ -142,8 +142,8 @@ class ThreadTests(unittest.TestCase): tid = thread.start_new_thread(f, (mutex,)) # Wait for the thread to finish. mutex.acquire() - self.assert_(tid in threading._active) - self.assert_(isinstance(threading._active[tid], + self.assertTrue(tid in threading._active) + self.assertTrue(isinstance(threading._active[tid], threading._DummyThread)) del threading._active[tid] @@ -203,7 +203,7 @@ class ThreadTests(unittest.TestCase): self.assertTrue(ret) if verbose: print " verifying worker hasn't exited" - self.assert_(not t.finished) + self.assertTrue(not t.finished) if verbose: print " attempting to raise asynch exception in worker" result = set_async_exc(ctypes.c_long(t.id), exception) @@ -211,7 +211,7 @@ class ThreadTests(unittest.TestCase): if verbose: print " waiting for worker to say it caught the exception" worker_saw_exception.wait(timeout=10) - self.assert_(t.finished) + self.assertTrue(t.finished) if verbose: print " all OK -- joining worker" if t.finished: @@ -282,8 +282,8 @@ class ThreadTests(unittest.TestCase): sys.settrace(func) """]) - self.failIf(rc == 2, "interpreted was blocked") - self.failUnless(rc == 0, "Unexpected error") + self.assertFalse(rc == 2, "interpreted was blocked") + self.assertTrue(rc == 0, "Unexpected error") def test_enumerate_after_join(self): @@ -354,8 +354,8 @@ class ThreadJoinOnShutdown(unittest.TestCase): rc = p.wait() data = p.stdout.read().replace('\r', '') self.assertEqual(data, "end of main\nend of thread\n") - self.failIf(rc == 2, "interpreter was blocked") - self.failUnless(rc == 0, "Unexpected error") + self.assertFalse(rc == 2, "interpreter was blocked") + self.assertTrue(rc == 0, "Unexpected error") def test_1_join_on_shutdown(self): # The usual case: on exit, wait for a non-daemon thread diff --git a/Lib/test/test_threading_local.py b/Lib/test/test_threading_local.py index 8642141..fc2c341 100644 --- a/Lib/test/test_threading_local.py +++ b/Lib/test/test_threading_local.py @@ -40,7 +40,7 @@ class ThreadingLocalTest(unittest.TestCase): local.someothervar = None gc.collect() deadlist = [weak for weak in weaklist if weak() is None] - self.assert_(len(deadlist) in (n-1, n), (n, len(deadlist))) + self.assertTrue(len(deadlist) in (n-1, n), (n, len(deadlist))) def test_derived(self): # Issue 3088: if there is a threads switch inside the __init__ diff --git a/Lib/test/test_time.py b/Lib/test/test_time.py index b5155b4..965f7e2 100644 --- a/Lib/test/test_time.py +++ b/Lib/test/test_time.py @@ -18,9 +18,9 @@ class TimeTestCase(unittest.TestCase): time.clock() def test_conversions(self): - self.assert_(time.ctime(self.t) + self.assertTrue(time.ctime(self.t) == time.asctime(time.localtime(self.t))) - self.assert_(long(time.mktime(time.localtime(self.t))) + self.assertTrue(long(time.mktime(time.localtime(self.t))) == long(self.t)) def test_sleep(self): @@ -148,36 +148,36 @@ class TimeTestCase(unittest.TestCase): time.tzset() environ['TZ'] = utc time.tzset() - self.failUnlessEqual( + self.assertEqual( time.gmtime(xmas2002), time.localtime(xmas2002) ) - self.failUnlessEqual(time.daylight, 0) - self.failUnlessEqual(time.timezone, 0) - self.failUnlessEqual(time.localtime(xmas2002).tm_isdst, 0) + self.assertEqual(time.daylight, 0) + self.assertEqual(time.timezone, 0) + self.assertEqual(time.localtime(xmas2002).tm_isdst, 0) # Make sure we can switch to US/Eastern environ['TZ'] = eastern time.tzset() - self.failIfEqual(time.gmtime(xmas2002), time.localtime(xmas2002)) - self.failUnlessEqual(time.tzname, ('EST', 'EDT')) - self.failUnlessEqual(len(time.tzname), 2) - self.failUnlessEqual(time.daylight, 1) - self.failUnlessEqual(time.timezone, 18000) - self.failUnlessEqual(time.altzone, 14400) - self.failUnlessEqual(time.localtime(xmas2002).tm_isdst, 0) - self.failUnlessEqual(len(time.tzname), 2) + self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002)) + self.assertEqual(time.tzname, ('EST', 'EDT')) + self.assertEqual(len(time.tzname), 2) + self.assertEqual(time.daylight, 1) + self.assertEqual(time.timezone, 18000) + self.assertEqual(time.altzone, 14400) + self.assertEqual(time.localtime(xmas2002).tm_isdst, 0) + self.assertEqual(len(time.tzname), 2) # Now go to the southern hemisphere. environ['TZ'] = victoria time.tzset() - self.failIfEqual(time.gmtime(xmas2002), time.localtime(xmas2002)) - self.failUnless(time.tzname[0] == 'AEST', str(time.tzname[0])) - self.failUnless(time.tzname[1] == 'AEDT', str(time.tzname[1])) - self.failUnlessEqual(len(time.tzname), 2) - self.failUnlessEqual(time.daylight, 1) - self.failUnlessEqual(time.timezone, -36000) - self.failUnlessEqual(time.altzone, -39600) - self.failUnlessEqual(time.localtime(xmas2002).tm_isdst, 1) + self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002)) + self.assertTrue(time.tzname[0] == 'AEST', str(time.tzname[0])) + self.assertTrue(time.tzname[1] == 'AEDT', str(time.tzname[1])) + self.assertEqual(len(time.tzname), 2) + self.assertEqual(time.daylight, 1) + self.assertEqual(time.timezone, -36000) + self.assertEqual(time.altzone, -39600) + self.assertEqual(time.localtime(xmas2002).tm_isdst, 1) finally: # Repair TZ environment variable in case any other tests @@ -209,14 +209,14 @@ class TimeTestCase(unittest.TestCase): gt1 = time.gmtime(None) t0 = time.mktime(gt0) t1 = time.mktime(gt1) - self.assert_(0 <= (t1-t0) < 0.2) + self.assertTrue(0 <= (t1-t0) < 0.2) def test_localtime_without_arg(self): lt0 = time.localtime() lt1 = time.localtime(None) t0 = time.mktime(lt0) t1 = time.mktime(lt1) - self.assert_(0 <= (t1-t0) < 0.2) + self.assertTrue(0 <= (t1-t0) < 0.2) def test_main(): test_support.run_unittest(TimeTestCase) diff --git a/Lib/test/test_timeout.py b/Lib/test/test_timeout.py index 02687b0..04cfbe7 100644 --- a/Lib/test/test_timeout.py +++ b/Lib/test/test_timeout.py @@ -119,11 +119,11 @@ class TimeoutTestCase(unittest.TestCase): self.sock.settimeout(_timeout) _t1 = time.time() - self.failUnlessRaises(socket.error, self.sock.connect, addr) + self.assertRaises(socket.error, self.sock.connect, addr) _t2 = time.time() _delta = abs(_t1 - _t2) - self.assert_(_delta < _timeout + self.fuzz, + self.assertTrue(_delta < _timeout + self.fuzz, "timeout (%g) is more than %g seconds more than expected (%g)" %(_delta, self.fuzz, _timeout)) @@ -134,11 +134,11 @@ class TimeoutTestCase(unittest.TestCase): self.sock.settimeout(_timeout) _t1 = time.time() - self.failUnlessRaises(socket.error, self.sock.recv, 1024) + self.assertRaises(socket.error, self.sock.recv, 1024) _t2 = time.time() _delta = abs(_t1 - _t2) - self.assert_(_delta < _timeout + self.fuzz, + self.assertTrue(_delta < _timeout + self.fuzz, "timeout (%g) is %g seconds more than expected (%g)" %(_delta, self.fuzz, _timeout)) @@ -150,11 +150,11 @@ class TimeoutTestCase(unittest.TestCase): self.sock.listen(5) _t1 = time.time() - self.failUnlessRaises(socket.error, self.sock.accept) + self.assertRaises(socket.error, self.sock.accept) _t2 = time.time() _delta = abs(_t1 - _t2) - self.assert_(_delta < _timeout + self.fuzz, + self.assertTrue(_delta < _timeout + self.fuzz, "timeout (%g) is %g seconds more than expected (%g)" %(_delta, self.fuzz, _timeout)) @@ -166,11 +166,11 @@ class TimeoutTestCase(unittest.TestCase): self.sock.bind(self.addr_local) _t1 = time.time() - self.failUnlessRaises(socket.error, self.sock.recvfrom, 8192) + self.assertRaises(socket.error, self.sock.recvfrom, 8192) _t2 = time.time() _delta = abs(_t1 - _t2) - self.assert_(_delta < _timeout + self.fuzz, + self.assertTrue(_delta < _timeout + self.fuzz, "timeout (%g) is %g seconds more than expected (%g)" %(_delta, self.fuzz, _timeout)) diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py index 1140a94..b29869a 100644 --- a/Lib/test/test_traceback.py +++ b/Lib/test/test_traceback.py @@ -37,16 +37,16 @@ class TracebackCases(unittest.TestCase): def test_caret(self): err = self.get_exception_format(self.syntax_error_with_caret, SyntaxError) - self.assert_(len(err) == 4) - self.assert_(err[1].strip() == "return x!") - self.assert_("^" in err[2]) # third line has caret - self.assert_(err[1].find("!") == err[2].find("^")) # in the right place + self.assertTrue(len(err) == 4) + self.assertTrue(err[1].strip() == "return x!") + self.assertTrue("^" in err[2]) # third line has caret + self.assertTrue(err[1].find("!") == err[2].find("^")) # in the right place err = self.get_exception_format(self.syntax_error_with_caret_2, SyntaxError) - self.assert_("^" in err[2]) # third line has caret - self.assert_(err[2].count('\n') == 1) # and no additional newline - self.assert_(err[1].find("+") == err[2].find("^")) # in the right place + self.assertTrue("^" in err[2]) # third line has caret + self.assertTrue(err[2].count('\n') == 1) # and no additional newline + self.assertTrue(err[1].find("+") == err[2].find("^")) # in the right place def test_nocaret(self): if is_jython: @@ -54,16 +54,16 @@ class TracebackCases(unittest.TestCase): return err = self.get_exception_format(self.syntax_error_without_caret, SyntaxError) - self.assert_(len(err) == 3) - self.assert_(err[1].strip() == "[x for x in x] = x") + self.assertTrue(len(err) == 3) + self.assertTrue(err[1].strip() == "[x for x in x] = x") def test_bad_indentation(self): err = self.get_exception_format(self.syntax_error_bad_indentation, IndentationError) - self.assert_(len(err) == 4) - self.assert_(err[1].strip() == "print 2") - self.assert_("^" in err[2]) - self.assert_(err[1].find("2") == err[2].find("^")) + self.assertTrue(len(err) == 4) + self.assertTrue(err[1].strip() == "print 2") + self.assertTrue("^" in err[2]) + self.assertTrue(err[1].find("2") == err[2].find("^")) def test_bug737473(self): import sys, os, tempfile, time @@ -103,7 +103,7 @@ def test(): test_bug737473.test() except NotImplementedError: src = traceback.extract_tb(sys.exc_traceback)[-1][-1] - self.failUnlessEqual(src, 'raise NotImplementedError') + self.assertEqual(src, 'raise NotImplementedError') finally: sys.path[:] = savedpath for f in os.listdir(testdir): @@ -181,9 +181,9 @@ class TracebackFormatTests(unittest.TestCase): tb_lines = python_fmt.splitlines() self.assertEquals(len(tb_lines), 3) banner, location, source_line = tb_lines - self.assert_(banner.startswith('Traceback')) - self.assert_(location.startswith(' File')) - self.assert_(source_line.startswith(' raise')) + self.assertTrue(banner.startswith('Traceback')) + self.assertTrue(location.startswith(' File')) + self.assertTrue(source_line.startswith(' raise')) def test_main(): diff --git a/Lib/test/test_tuple.py b/Lib/test/test_tuple.py index 89cbe1d..6436412 100644 --- a/Lib/test/test_tuple.py +++ b/Lib/test/test_tuple.py @@ -11,7 +11,7 @@ class TupleTest(seq_tests.CommonTest): self.assertEqual(tuple(), ()) t0_3 = (0, 1, 2, 3) t0_3_bis = tuple(t0_3) - self.assert_(t0_3 is t0_3_bis) + self.assertTrue(t0_3 is t0_3_bis) self.assertEqual(tuple([]), ()) self.assertEqual(tuple([0, 1, 2, 3]), (0, 1, 2, 3)) self.assertEqual(tuple(''), ()) @@ -19,8 +19,8 @@ class TupleTest(seq_tests.CommonTest): def test_truth(self): super(TupleTest, self).test_truth() - self.assert_(not ()) - self.assert_((42, )) + self.assertTrue(not ()) + self.assertTrue((42, )) def test_len(self): super(TupleTest, self).test_len() @@ -33,14 +33,14 @@ class TupleTest(seq_tests.CommonTest): u = (0, 1) u2 = u u += (2, 3) - self.assert_(u is not u2) + self.assertTrue(u is not u2) def test_imul(self): super(TupleTest, self).test_imul() u = (0, 1) u2 = u u *= 3 - self.assert_(u is not u2) + self.assertTrue(u is not u2) def test_tupleresizebug(self): # Check that a specific bug in _PyTuple_Resize() is squashed. @@ -71,7 +71,7 @@ class TupleTest(seq_tests.CommonTest): inps = base + [(i, j) for i in base for j in xp] + \ [(i, j) for i in xp for j in base] + xp + zip(base) collisions = len(inps) - len(set(map(hash, inps))) - self.assert_(collisions <= 15) + self.assertTrue(collisions <= 15) def test_repr(self): l0 = tuple() diff --git a/Lib/test/test_unary.py b/Lib/test/test_unary.py index 9854f64..598fca8 100644 --- a/Lib/test/test_unary.py +++ b/Lib/test/test_unary.py @@ -6,32 +6,32 @@ from test.test_support import run_unittest, have_unicode class UnaryOpTestCase(unittest.TestCase): def test_negative(self): - self.assert_(-2 == 0 - 2) - self.assert_(-0 == 0) - self.assert_(--2 == 2) - self.assert_(-2L == 0 - 2L) - self.assert_(-2.0 == 0 - 2.0) - self.assert_(-2j == 0 - 2j) + self.assertTrue(-2 == 0 - 2) + self.assertTrue(-0 == 0) + self.assertTrue(--2 == 2) + self.assertTrue(-2L == 0 - 2L) + self.assertTrue(-2.0 == 0 - 2.0) + self.assertTrue(-2j == 0 - 2j) def test_positive(self): - self.assert_(+2 == 2) - self.assert_(+0 == 0) - self.assert_(++2 == 2) - self.assert_(+2L == 2L) - self.assert_(+2.0 == 2.0) - self.assert_(+2j == 2j) + self.assertTrue(+2 == 2) + self.assertTrue(+0 == 0) + self.assertTrue(++2 == 2) + self.assertTrue(+2L == 2L) + self.assertTrue(+2.0 == 2.0) + self.assertTrue(+2j == 2j) def test_invert(self): - self.assert_(-2 == 0 - 2) - self.assert_(-0 == 0) - self.assert_(--2 == 2) - self.assert_(-2L == 0 - 2L) + self.assertTrue(-2 == 0 - 2) + self.assertTrue(-0 == 0) + self.assertTrue(--2 == 2) + self.assertTrue(-2L == 0 - 2L) def test_no_overflow(self): nines = "9" * 32 - self.assert_(eval("+" + nines) == eval("+" + nines + "L")) - self.assert_(eval("-" + nines) == eval("-" + nines + "L")) - self.assert_(eval("~" + nines) == eval("~" + nines + "L")) + self.assertTrue(eval("+" + nines) == eval("+" + nines + "L")) + self.assertTrue(eval("-" + nines) == eval("-" + nines + "L")) + self.assertTrue(eval("~" + nines) == eval("~" + nines + "L")) def test_negation_of_exponentiation(self): # Make sure '**' does the right thing; these form a diff --git a/Lib/test/test_unicode.py b/Lib/test/test_unicode.py index 99155ec..43830b2 100644 --- a/Lib/test/test_unicode.py +++ b/Lib/test/test_unicode.py @@ -38,7 +38,7 @@ class UnicodeTest( method = getattr(object, methodname) realresult = method(*args) self.assertEqual(realresult, result) - self.assert_(type(realresult) is type(result)) + self.assertTrue(type(realresult) is type(result)) # if the original is returned make sure that # this doesn't happen with subclasses @@ -50,7 +50,7 @@ class UnicodeTest( method = getattr(object, methodname) realresult = method(*args) self.assertEqual(realresult, result) - self.assert_(object is not realresult) + self.assertTrue(object is not realresult) def test_literals(self): self.assertEqual(u'\xff', u'\u00ff') @@ -200,25 +200,25 @@ class UnicodeTest( self.assertEqual(u'abc', 'abc') self.assertEqual('abc', u'abc') self.assertEqual(u'abc', u'abc') - self.assert_(u'abcd' > 'abc') - self.assert_('abcd' > u'abc') - self.assert_(u'abcd' > u'abc') - self.assert_(u'abc' < 'abcd') - self.assert_('abc' < u'abcd') - self.assert_(u'abc' < u'abcd') + self.assertTrue(u'abcd' > 'abc') + self.assertTrue('abcd' > u'abc') + self.assertTrue(u'abcd' > u'abc') + self.assertTrue(u'abc' < 'abcd') + self.assertTrue('abc' < u'abcd') + self.assertTrue(u'abc' < u'abcd') if 0: # Move these tests to a Unicode collation module test... # Testing UTF-16 code point order comparisons... # No surrogates, no fixup required. - self.assert_(u'\u0061' < u'\u20ac') + self.assertTrue(u'\u0061' < u'\u20ac') # Non surrogate below surrogate value, no fixup required - self.assert_(u'\u0061' < u'\ud800\udc02') + self.assertTrue(u'\u0061' < u'\ud800\udc02') # Non surrogate above surrogate value, fixup required def test_lecmp(s, s2): - self.assert_(s < s2) + self.assertTrue(s < s2) def test_fixup(s): s2 = u'\ud800\udc01' @@ -258,7 +258,7 @@ class UnicodeTest( test_fixup(u'\uff61') # Surrogates on both sides, no fixup required - self.assert_(u'\ud800\udc02' < u'\ud84d\udc56') + self.assertTrue(u'\ud800\udc02' < u'\ud84d\udc56') def test_islower(self): string_tests.MixinStrUnicodeUserStringTest.test_islower(self) @@ -316,63 +316,63 @@ class UnicodeTest( def test_contains(self): # Testing Unicode contains method - self.assert_('a' in u'abdb') - self.assert_('a' in u'bdab') - self.assert_('a' in u'bdaba') - self.assert_('a' in u'bdba') - self.assert_('a' in u'bdba') - self.assert_(u'a' in u'bdba') - self.assert_(u'a' not in u'bdb') - self.assert_(u'a' not in 'bdb') - self.assert_(u'a' in 'bdba') - self.assert_(u'a' in ('a',1,None)) - self.assert_(u'a' in (1,None,'a')) - self.assert_(u'a' in (1,None,u'a')) - self.assert_('a' in ('a',1,None)) - self.assert_('a' in (1,None,'a')) - self.assert_('a' in (1,None,u'a')) - self.assert_('a' not in ('x',1,u'y')) - self.assert_('a' not in ('x',1,None)) - self.assert_(u'abcd' not in u'abcxxxx') - self.assert_(u'ab' in u'abcd') - self.assert_('ab' in u'abc') - self.assert_(u'ab' in 'abc') - self.assert_(u'ab' in (1,None,u'ab')) - self.assert_(u'' in u'abc') - self.assert_('' in u'abc') + self.assertTrue('a' in u'abdb') + self.assertTrue('a' in u'bdab') + self.assertTrue('a' in u'bdaba') + self.assertTrue('a' in u'bdba') + self.assertTrue('a' in u'bdba') + self.assertTrue(u'a' in u'bdba') + self.assertTrue(u'a' not in u'bdb') + self.assertTrue(u'a' not in 'bdb') + self.assertTrue(u'a' in 'bdba') + self.assertTrue(u'a' in ('a',1,None)) + self.assertTrue(u'a' in (1,None,'a')) + self.assertTrue(u'a' in (1,None,u'a')) + self.assertTrue('a' in ('a',1,None)) + self.assertTrue('a' in (1,None,'a')) + self.assertTrue('a' in (1,None,u'a')) + self.assertTrue('a' not in ('x',1,u'y')) + self.assertTrue('a' not in ('x',1,None)) + self.assertTrue(u'abcd' not in u'abcxxxx') + self.assertTrue(u'ab' in u'abcd') + self.assertTrue('ab' in u'abc') + self.assertTrue(u'ab' in 'abc') + self.assertTrue(u'ab' in (1,None,u'ab')) + self.assertTrue(u'' in u'abc') + self.assertTrue('' in u'abc') # If the following fails either # the contains operator does not propagate UnicodeErrors or # someone has changed the default encoding self.assertRaises(UnicodeError, 'g\xe2teau'.__contains__, u'\xe2') - self.assert_(u'' in '') - self.assert_('' in u'') - self.assert_(u'' in u'') - self.assert_(u'' in 'abc') - self.assert_('' in u'abc') - self.assert_(u'' in u'abc') - self.assert_(u'\0' not in 'abc') - self.assert_('\0' not in u'abc') - self.assert_(u'\0' not in u'abc') - self.assert_(u'\0' in '\0abc') - self.assert_('\0' in u'\0abc') - self.assert_(u'\0' in u'\0abc') - self.assert_(u'\0' in 'abc\0') - self.assert_('\0' in u'abc\0') - self.assert_(u'\0' in u'abc\0') - self.assert_(u'a' in '\0abc') - self.assert_('a' in u'\0abc') - self.assert_(u'a' in u'\0abc') - self.assert_(u'asdf' in 'asdf') - self.assert_('asdf' in u'asdf') - self.assert_(u'asdf' in u'asdf') - self.assert_(u'asdf' not in 'asd') - self.assert_('asdf' not in u'asd') - self.assert_(u'asdf' not in u'asd') - self.assert_(u'asdf' not in '') - self.assert_('asdf' not in u'') - self.assert_(u'asdf' not in u'') + self.assertTrue(u'' in '') + self.assertTrue('' in u'') + self.assertTrue(u'' in u'') + self.assertTrue(u'' in 'abc') + self.assertTrue('' in u'abc') + self.assertTrue(u'' in u'abc') + self.assertTrue(u'\0' not in 'abc') + self.assertTrue('\0' not in u'abc') + self.assertTrue(u'\0' not in u'abc') + self.assertTrue(u'\0' in '\0abc') + self.assertTrue('\0' in u'\0abc') + self.assertTrue(u'\0' in u'\0abc') + self.assertTrue(u'\0' in 'abc\0') + self.assertTrue('\0' in u'abc\0') + self.assertTrue(u'\0' in u'abc\0') + self.assertTrue(u'a' in '\0abc') + self.assertTrue('a' in u'\0abc') + self.assertTrue(u'a' in u'\0abc') + self.assertTrue(u'asdf' in 'asdf') + self.assertTrue('asdf' in u'asdf') + self.assertTrue(u'asdf' in u'asdf') + self.assertTrue(u'asdf' not in 'asd') + self.assertTrue('asdf' not in u'asd') + self.assertTrue(u'asdf' not in u'asd') + self.assertTrue(u'asdf' not in '') + self.assertTrue('asdf' not in u'') + self.assertTrue(u'asdf' not in u'') self.assertRaises(TypeError, u"abc".__contains__) diff --git a/Lib/test/test_unicode_file.py b/Lib/test/test_unicode_file.py index 5c1f45b..326200b 100644 --- a/Lib/test/test_unicode_file.py +++ b/Lib/test/test_unicode_file.py @@ -42,19 +42,19 @@ class TestUnicodeFiles(unittest.TestCase): # Do all the tests we can given only a single filename. The file should # exist. def _do_single(self, filename): - self.failUnless(os.path.exists(filename)) - self.failUnless(os.path.isfile(filename)) - self.failUnless(os.access(filename, os.R_OK)) - self.failUnless(os.path.exists(os.path.abspath(filename))) - self.failUnless(os.path.isfile(os.path.abspath(filename))) - self.failUnless(os.access(os.path.abspath(filename), os.R_OK)) + self.assertTrue(os.path.exists(filename)) + self.assertTrue(os.path.isfile(filename)) + self.assertTrue(os.access(filename, os.R_OK)) + self.assertTrue(os.path.exists(os.path.abspath(filename))) + self.assertTrue(os.path.isfile(os.path.abspath(filename))) + self.assertTrue(os.access(os.path.abspath(filename), os.R_OK)) os.chmod(filename, 0777) os.utime(filename, None) os.utime(filename, (time.time(), time.time())) # Copy/rename etc tests using the same filename self._do_copyish(filename, filename) # Filename should appear in glob output - self.failUnless( + self.assertTrue( os.path.abspath(filename)==os.path.abspath(glob.glob(filename)[0])) # basename should appear in listdir. path, base = os.path.split(os.path.abspath(filename)) @@ -71,7 +71,7 @@ class TestUnicodeFiles(unittest.TestCase): base = unicodedata.normalize("NFD", base) file_list = [unicodedata.normalize("NFD", f) for f in file_list] - self.failUnless(base in file_list) + self.assertTrue(base in file_list) # Do as many "equivalancy' tests as we can - ie, check that although we # have different types for the filename, they refer to the same file. @@ -79,12 +79,12 @@ class TestUnicodeFiles(unittest.TestCase): # Note we only check "filename1 against filename2" - we don't bother # checking "filename2 against 1", as we assume we are called again with # the args reversed. - self.failUnless(type(filename1)!=type(filename2), + self.assertTrue(type(filename1)!=type(filename2), "No point checking equivalent filenames of the same type") # stat and lstat should return the same results. - self.failUnlessEqual(os.stat(filename1), + self.assertEqual(os.stat(filename1), os.stat(filename2)) - self.failUnlessEqual(os.lstat(filename1), + self.assertEqual(os.lstat(filename1), os.lstat(filename2)) # Copy/rename etc tests using equivalent filename self._do_copyish(filename1, filename2) @@ -92,19 +92,19 @@ class TestUnicodeFiles(unittest.TestCase): # Tests that copy, move, etc one file to another. def _do_copyish(self, filename1, filename2): # Should be able to rename the file using either name. - self.failUnless(os.path.isfile(filename1)) # must exist. + self.assertTrue(os.path.isfile(filename1)) # must exist. os.rename(filename1, filename2 + ".new") - self.failUnless(os.path.isfile(filename1+".new")) + self.assertTrue(os.path.isfile(filename1+".new")) os.rename(filename1 + ".new", filename2) - self.failUnless(os.path.isfile(filename2)) + self.assertTrue(os.path.isfile(filename2)) shutil.copy(filename1, filename2 + ".new") os.unlink(filename1 + ".new") # remove using equiv name. # And a couple of moves, one using each name. shutil.move(filename1, filename2 + ".new") - self.failUnless(not os.path.exists(filename2)) + self.assertTrue(not os.path.exists(filename2)) shutil.move(filename1 + ".new", filename2) - self.failUnless(os.path.exists(filename1)) + self.assertTrue(os.path.exists(filename1)) # Note - due to the implementation of shutil.move, # it tries a rename first. This only fails on Windows when on # different file systems - and this test can't ensure that. @@ -131,7 +131,7 @@ class TestUnicodeFiles(unittest.TestCase): cwd_result = unicodedata.normalize("NFD", cwd_result) name_result = unicodedata.normalize("NFD", name_result) - self.failUnlessEqual(os.path.basename(cwd_result),name_result) + self.assertEqual(os.path.basename(cwd_result),name_result) finally: os.chdir(cwd) finally: @@ -147,7 +147,7 @@ class TestUnicodeFiles(unittest.TestCase): self._do_single(filename) finally: os.unlink(filename) - self.failUnless(not os.path.exists(filename)) + self.assertTrue(not os.path.exists(filename)) # and again with os.open. f = os.open(filename, os.O_CREAT) os.close(f) @@ -158,7 +158,7 @@ class TestUnicodeFiles(unittest.TestCase): def _test_equivalent(self, filename1, filename2): remove_if_exists(filename1) - self.failUnless(not os.path.exists(filename2)) + self.assertTrue(not os.path.exists(filename2)) f = file(filename1, "w") f.close() try: diff --git a/Lib/test/test_unicodedata.py b/Lib/test/test_unicodedata.py index baa36cb..9d7133b 100644 --- a/Lib/test/test_unicodedata.py +++ b/Lib/test/test_unicodedata.py @@ -230,7 +230,7 @@ class UnicodeMiscTest(UnicodeDatabaseTest): if dec != -1: self.assertEqual(dec, self.db.numeric(c)) count += 1 - self.assert_(count >= 10) # should have tested at least the ASCII digits + self.assertTrue(count >= 10) # should have tested at least the ASCII digits def test_digit_numeric_consistent(self): # Test that digit and numeric are consistent, @@ -243,7 +243,7 @@ class UnicodeMiscTest(UnicodeDatabaseTest): if dec != -1: self.assertEqual(dec, self.db.numeric(c)) count += 1 - self.assert_(count >= 10) # should have tested at least the ASCII digits + self.assertTrue(count >= 10) # should have tested at least the ASCII digits def test_bug_1704793(self): self.assertEquals(self.db.lookup("GOTHIC LETTER FAIHU"), u'\U00010346') @@ -251,13 +251,13 @@ class UnicodeMiscTest(UnicodeDatabaseTest): def test_ucd_510(self): import unicodedata # In UCD 5.1.0, a mirrored property changed wrt. UCD 3.2.0 - self.assert_(unicodedata.mirrored(u"\u0f3a")) - self.assert_(not unicodedata.ucd_3_2_0.mirrored(u"\u0f3a")) + self.assertTrue(unicodedata.mirrored(u"\u0f3a")) + self.assertTrue(not unicodedata.ucd_3_2_0.mirrored(u"\u0f3a")) # Also, we now have two ways of representing # the upper-case mapping: as delta, or as absolute value - self.assert_(u"a".upper()==u'A') - self.assert_(u"\u1d79".upper()==u'\ua77d') - self.assert_(u".".upper()==u".") + self.assertTrue(u"a".upper()==u'A') + self.assertTrue(u"\u1d79".upper()==u'\ua77d') + self.assertTrue(u".".upper()==u".") def test_bug_5828(self): self.assertEqual(u"\u1d79".lower(), u"\u1d79") diff --git a/Lib/test/test_urllib.py b/Lib/test/test_urllib.py index ffc2f31..9320c62 100644 --- a/Lib/test/test_urllib.py +++ b/Lib/test/test_urllib.py @@ -44,7 +44,7 @@ class urlopen_FileTests(unittest.TestCase): # Make sure object returned by urlopen() has the specified methods for attr in ("read", "readline", "readlines", "fileno", "close", "info", "geturl", "getcode", "__iter__"): - self.assert_(hasattr(self.returned_obj, attr), + self.assertTrue(hasattr(self.returned_obj, attr), "object returned by urlopen() lacks %s attribute" % attr) @@ -66,7 +66,7 @@ class urlopen_FileTests(unittest.TestCase): def test_fileno(self): file_num = self.returned_obj.fileno() - self.assert_(isinstance(file_num, int), + self.assertTrue(isinstance(file_num, int), "fileno() did not return an int") self.assertEqual(os.read(file_num, len(self.text)), self.text, "Reading on the file descriptor returned by fileno() " @@ -78,7 +78,7 @@ class urlopen_FileTests(unittest.TestCase): self.returned_obj.close() def test_info(self): - self.assert_(isinstance(self.returned_obj.info(), mimetools.Message)) + self.assertTrue(isinstance(self.returned_obj.info(), mimetools.Message)) def test_geturl(self): self.assertEqual(self.returned_obj.geturl(), self.pathname) @@ -229,7 +229,7 @@ class urlretrieve_FileTests(unittest.TestCase): # a headers value is returned. result = urllib.urlretrieve("file:%s" % test_support.TESTFN) self.assertEqual(result[0], test_support.TESTFN) - self.assert_(isinstance(result[1], mimetools.Message), + self.assertTrue(isinstance(result[1], mimetools.Message), "did not get a mimetools.Message instance as second " "returned value") @@ -240,7 +240,7 @@ class urlretrieve_FileTests(unittest.TestCase): result = urllib.urlretrieve(self.constructLocalFileUrl( test_support.TESTFN), second_temp) self.assertEqual(second_temp, result[0]) - self.assert_(os.path.exists(second_temp), "copy of the file was not " + self.assertTrue(os.path.exists(second_temp), "copy of the file was not " "made") FILE = file(second_temp, 'rb') try: @@ -254,9 +254,9 @@ class urlretrieve_FileTests(unittest.TestCase): def test_reporthook(self): # Make sure that the reporthook works. def hooktester(count, block_size, total_size, count_holder=[0]): - self.assert_(isinstance(count, int)) - self.assert_(isinstance(block_size, int)) - self.assert_(isinstance(total_size, int)) + self.assertTrue(isinstance(count, int)) + self.assertTrue(isinstance(block_size, int)) + self.assertTrue(isinstance(total_size, int)) self.assertEqual(count, count_holder[0]) count_holder[0] = count_holder[0] + 1 second_temp = "%s.2" % test_support.TESTFN @@ -487,7 +487,7 @@ class urlencode_Tests(unittest.TestCase): expect_somewhere = ["1st=1", "2nd=2", "3rd=3"] result = urllib.urlencode(given) for expected in expect_somewhere: - self.assert_(expected in result, + self.assertTrue(expected in result, "testing %s: %s not found in %s" % (test_type, expected, result)) self.assertEqual(result.count('&'), 2, @@ -496,7 +496,7 @@ class urlencode_Tests(unittest.TestCase): amp_location = result.index('&') on_amp_left = result[amp_location - 1] on_amp_right = result[amp_location + 1] - self.assert_(on_amp_left.isdigit() and on_amp_right.isdigit(), + self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(), "testing %s: '&' not located in proper place in %s" % (test_type, result)) self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps @@ -534,7 +534,7 @@ class urlencode_Tests(unittest.TestCase): result = urllib.urlencode(given, True) for value in given["sequence"]: expect = "sequence=%s" % value - self.assert_(expect in result, + self.assertTrue(expect in result, "%s not found in %s" % (expect, result)) self.assertEqual(result.count('&'), 2, "Expected 2 '&'s, got %s" % result.count('&')) @@ -661,7 +661,7 @@ class URLopener_Tests(unittest.TestCase): # def testTimeoutNone(self): # # global default timeout is ignored # import socket -# self.assert_(socket.getdefaulttimeout() is None) +# self.assertTrue(socket.getdefaulttimeout() is None) # socket.setdefaulttimeout(30) # try: # ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, []) @@ -673,7 +673,7 @@ class URLopener_Tests(unittest.TestCase): # def testTimeoutDefault(self): # # global default timeout is used # import socket -# self.assert_(socket.getdefaulttimeout() is None) +# self.assertTrue(socket.getdefaulttimeout() is None) # socket.setdefaulttimeout(30) # try: # ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, []) diff --git a/Lib/test/test_urllib2.py b/Lib/test/test_urllib2.py index 9edd7c2..1dcd616 100644 --- a/Lib/test/test_urllib2.py +++ b/Lib/test/test_urllib2.py @@ -521,15 +521,15 @@ class OpenerDirectorTests(unittest.TestCase): # *_request self.assertEqual((handler, name), calls[i]) self.assertEqual(len(args), 1) - self.assert_(isinstance(args[0], Request)) + self.assertTrue(isinstance(args[0], Request)) else: # *_response self.assertEqual((handler, name), calls[i]) self.assertEqual(len(args), 2) - self.assert_(isinstance(args[0], Request)) + self.assertTrue(isinstance(args[0], Request)) # response from opener.open is None, because there's no # handler that defines http_open to handle it - self.assert_(args[1] is None or + self.assertTrue(args[1] is None or isinstance(args[1], MockResponse)) @@ -580,7 +580,7 @@ class HandlerTests(unittest.TestCase): req.timeout = None r = h.ftp_open(req) # ftp authentication not yet implemented by FTPHandler - self.assert_(h.user == h.passwd == "") + self.assertTrue(h.user == h.passwd == "") self.assertEqual(h.host, socket.gethostbyname(host)) self.assertEqual(h.port, port) self.assertEqual(h.dirs, dirs) @@ -674,9 +674,9 @@ class HandlerTests(unittest.TestCase): h.file_open(req) # XXXX remove OSError when bug fixed except (urllib2.URLError, OSError): - self.assert_(not ftp) + self.assertTrue(not ftp) else: - self.assert_(o.req is req) + self.assertTrue(o.req is req) self.assertEqual(req.type, "ftp") def test_http(self): @@ -751,8 +751,8 @@ class HandlerTests(unittest.TestCase): r = MockResponse(200, "OK", {}, "") newreq = h.do_request_(req) if data is None: # GET - self.assert_("Content-length" not in req.unredirected_hdrs) - self.assert_("Content-type" not in req.unredirected_hdrs) + self.assertTrue("Content-length" not in req.unredirected_hdrs) + self.assertTrue("Content-type" not in req.unredirected_hdrs) else: # POST self.assertEqual(req.unredirected_hdrs["Content-length"], "0") self.assertEqual(req.unredirected_hdrs["Content-type"], @@ -807,19 +807,19 @@ class HandlerTests(unittest.TestCase): # all 2xx are passed through r = MockResponse(200, "OK", {}, "", url) newr = h.http_response(req, r) - self.assert_(r is newr) - self.assert_(not hasattr(o, "proto")) # o.error not called + self.assertTrue(r is newr) + self.assertTrue(not hasattr(o, "proto")) # o.error not called r = MockResponse(202, "Accepted", {}, "", url) newr = h.http_response(req, r) - self.assert_(r is newr) - self.assert_(not hasattr(o, "proto")) # o.error not called + self.assertTrue(r is newr) + self.assertTrue(not hasattr(o, "proto")) # o.error not called r = MockResponse(206, "Partial content", {}, "", url) newr = h.http_response(req, r) - self.assert_(r is newr) - self.assert_(not hasattr(o, "proto")) # o.error not called + self.assertTrue(r is newr) + self.assertTrue(not hasattr(o, "proto")) # o.error not called # anything else calls o.error (and MockOpener returns None, here) r = MockResponse(502, "Bad gateway", {}, "", url) - self.assert_(h.http_response(req, r) is None) + self.assertTrue(h.http_response(req, r) is None) self.assertEqual(o.proto, "http") # o.error called self.assertEqual(o.args, (req, r, 502, "Bad gateway", {})) @@ -831,12 +831,12 @@ class HandlerTests(unittest.TestCase): req = Request("http://example.com/") r = MockResponse(200, "OK", {}, "") newreq = h.http_request(req) - self.assert_(cj.ach_req is req is newreq) + self.assertTrue(cj.ach_req is req is newreq) self.assertEquals(req.get_origin_req_host(), "example.com") - self.assert_(not req.is_unverifiable()) + self.assertTrue(not req.is_unverifiable()) newr = h.http_response(req, r) - self.assert_(cj.ec_req is req) - self.assert_(cj.ec_r is r is newr) + self.assertTrue(cj.ec_req is req) + self.assertTrue(cj.ec_r is r is newr) def test_redirect(self): from_url = "http://example.com/a.html" @@ -858,12 +858,12 @@ class HandlerTests(unittest.TestCase): MockHeaders({"location": to_url})) except urllib2.HTTPError: # 307 in response to POST requires user OK - self.assert_(code == 307 and data is not None) + self.assertTrue(code == 307 and data is not None) self.assertEqual(o.req.get_full_url(), to_url) try: self.assertEqual(o.req.get_method(), "GET") except AttributeError: - self.assert_(not o.req.has_data()) + self.assertTrue(not o.req.has_data()) # now it's a GET, there should not be headers regarding content # (possibly dragged from before being a POST) @@ -873,8 +873,8 @@ class HandlerTests(unittest.TestCase): self.assertEqual(o.req.headers["Nonsense"], "viking=withhold") - self.assert_("Spam" not in o.req.headers) - self.assert_("Spam" not in o.req.unredirected_hdrs) + self.assertTrue("Spam" not in o.req.headers) + self.assertTrue("Spam" not in o.req.unredirected_hdrs) # loop detection req = Request(from_url) @@ -920,7 +920,7 @@ class HandlerTests(unittest.TestCase): cp = urllib2.HTTPCookieProcessor(cj) o = build_test_opener(hh, hdeh, hrh, cp) o.open("http://www.example.com/") - self.assert_(not hh.req.has_header("Cookie")) + self.assertTrue(not hh.req.has_header("Cookie")) def test_proxy(self): o = OpenerDirector() @@ -1117,7 +1117,7 @@ class MiscTests(unittest.TestCase): if h.__class__ == handler_class: break else: - self.assert_(False) + self.assertTrue(False) class RequestTests(unittest.TestCase): @@ -1132,10 +1132,10 @@ class RequestTests(unittest.TestCase): self.assertEqual("GET", self.get.get_method()) def test_add_data(self): - self.assert_(not self.get.has_data()) + self.assertTrue(not self.get.has_data()) self.assertEqual("GET", self.get.get_method()) self.get.add_data("spam") - self.assert_(self.get.has_data()) + self.assertTrue(self.get.has_data()) self.assertEqual("POST", self.get.get_method()) def test_get_full_url(self): @@ -1158,9 +1158,9 @@ class RequestTests(unittest.TestCase): self.assertEqual("www.python.org", req.get_host()) def test_proxy(self): - self.assert_(not self.get.has_proxy()) + self.assertTrue(not self.get.has_proxy()) self.get.set_proxy("www.perl.org", "http") - self.assert_(self.get.has_proxy()) + self.assertTrue(self.get.has_proxy()) self.assertEqual("www.python.org", self.get.get_origin_req_host()) self.assertEqual("www.perl.org", self.get.get_host()) diff --git a/Lib/test/test_urllib2_localnet.py b/Lib/test/test_urllib2_localnet.py index 00498ec..1729d5f 100644 --- a/Lib/test/test_urllib2_localnet.py +++ b/Lib/test/test_urllib2_localnet.py @@ -434,10 +434,10 @@ class TestUrlopen(unittest.TestCase): try: open_url = urllib2.urlopen("http://localhost:%s" % handler.port) for attr in ("read", "close", "info", "geturl"): - self.assert_(hasattr(open_url, attr), "object returned from " + self.assertTrue(hasattr(open_url, attr), "object returned from " "urlopen lacks the %s attribute" % attr) try: - self.assert_(open_url.read(), "calling 'read' failed") + self.assertTrue(open_url.read(), "calling 'read' failed") finally: open_url.close() finally: @@ -449,7 +449,7 @@ class TestUrlopen(unittest.TestCase): try: open_url = urllib2.urlopen("http://localhost:%s" % handler.port) info_obj = open_url.info() - self.assert_(isinstance(info_obj, mimetools.Message), + self.assertTrue(isinstance(info_obj, mimetools.Message), "object returned by 'info' is not an instance of " "mimetools.Message") self.assertEqual(info_obj.getsubtype(), "plain") diff --git a/Lib/test/test_urllib2net.py b/Lib/test/test_urllib2net.py index b4e6ae5..9788675 100644 --- a/Lib/test/test_urllib2net.py +++ b/Lib/test/test_urllib2net.py @@ -81,15 +81,15 @@ class CloseSocketTest(unittest.TestCase): # delve deep into response to fetch socket._socketobject response = _urlopen_with_retry("http://www.python.org/") abused_fileobject = response.fp - self.assert_(abused_fileobject.__class__ is socket._fileobject) + self.assertTrue(abused_fileobject.__class__ is socket._fileobject) httpresponse = abused_fileobject._sock - self.assert_(httpresponse.__class__ is httplib.HTTPResponse) + self.assertTrue(httpresponse.__class__ is httplib.HTTPResponse) fileobject = httpresponse.fp - self.assert_(fileobject.__class__ is socket._fileobject) + self.assertTrue(fileobject.__class__ is socket._fileobject) - self.assert_(not fileobject.closed) + self.assertTrue(not fileobject.closed) response.close() - self.assert_(fileobject.closed) + self.assertTrue(fileobject.closed) class OtherNetworkTests(unittest.TestCase): def setUp(self): @@ -176,7 +176,7 @@ class OtherNetworkTests(unittest.TestCase): if expected_err: msg = ("Didn't get expected error(s) %s for %s %s, got %s: %s" % (expected_err, url, req, type(err), err)) - self.assert_(isinstance(err, expected_err), msg) + self.assertTrue(isinstance(err, expected_err), msg) else: with test_support.transient_internet(): buf = f.read() diff --git a/Lib/test/test_urllibnet.py b/Lib/test/test_urllibnet.py index ffb8b98..7ab2aa2 100644 --- a/Lib/test/test_urllibnet.py +++ b/Lib/test/test_urllibnet.py @@ -60,10 +60,10 @@ class urlopenNetworkTests(unittest.TestCase): open_url = self.urlopen("http://www.python.org/") for attr in ("read", "readline", "readlines", "fileno", "close", "info", "geturl"): - self.assert_(hasattr(open_url, attr), "object returned from " + self.assertTrue(hasattr(open_url, attr), "object returned from " "urlopen lacks the %s attribute" % attr) try: - self.assert_(open_url.read(), "calling 'read' failed") + self.assertTrue(open_url.read(), "calling 'read' failed") finally: open_url.close() @@ -71,9 +71,9 @@ class urlopenNetworkTests(unittest.TestCase): # Test both readline and readlines. open_url = self.urlopen("http://www.python.org/") try: - self.assert_(isinstance(open_url.readline(), basestring), + self.assertTrue(isinstance(open_url.readline(), basestring), "readline did not return a string") - self.assert_(isinstance(open_url.readlines(), list), + self.assertTrue(isinstance(open_url.readlines(), list), "readlines did not return a list") finally: open_url.close() @@ -85,7 +85,7 @@ class urlopenNetworkTests(unittest.TestCase): info_obj = open_url.info() finally: open_url.close() - self.assert_(isinstance(info_obj, mimetools.Message), + self.assertTrue(isinstance(info_obj, mimetools.Message), "object returned by 'info' is not an instance of " "mimetools.Message") self.assertEqual(info_obj.getsubtype(), "html") @@ -121,7 +121,7 @@ class urlopenNetworkTests(unittest.TestCase): fd = open_url.fileno() FILE = os.fdopen(fd) try: - self.assert_(FILE.read(), "reading from file created using fd " + self.assertTrue(FILE.read(), "reading from file created using fd " "returned by fileno failed") finally: FILE.close() @@ -148,11 +148,11 @@ class urlretrieveNetworkTests(unittest.TestCase): def test_basic(self): # Test basic functionality. file_location,info = self.urlretrieve("http://www.python.org/") - self.assert_(os.path.exists(file_location), "file location returned by" + self.assertTrue(os.path.exists(file_location), "file location returned by" " urlretrieve is not a valid path") FILE = file(file_location) try: - self.assert_(FILE.read(), "reading from the file location returned" + self.assertTrue(FILE.read(), "reading from the file location returned" " by urlretrieve failed") finally: FILE.close() @@ -163,10 +163,10 @@ class urlretrieveNetworkTests(unittest.TestCase): file_location,info = self.urlretrieve("http://www.python.org/", test_support.TESTFN) self.assertEqual(file_location, test_support.TESTFN) - self.assert_(os.path.exists(file_location)) + self.assertTrue(os.path.exists(file_location)) FILE = file(file_location) try: - self.assert_(FILE.read(), "reading from temporary file failed") + self.assertTrue(FILE.read(), "reading from temporary file failed") finally: FILE.close() os.unlink(file_location) @@ -175,7 +175,7 @@ class urlretrieveNetworkTests(unittest.TestCase): # Make sure header returned as 2nd value from urlretrieve is good. file_location, header = self.urlretrieve("http://www.python.org/") os.unlink(file_location) - self.assert_(isinstance(header, mimetools.Message), + self.assertTrue(isinstance(header, mimetools.Message), "header is not an instance of mimetools.Message") diff --git a/Lib/test/test_userdict.py b/Lib/test/test_userdict.py index 0818e98..c86a773 100644 --- a/Lib/test/test_userdict.py +++ b/Lib/test/test_userdict.py @@ -38,9 +38,9 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol): self.assertEqual(UserDict.UserDict().fromkeys('one two'.split()), d4) self.assertEqual(UserDict.UserDict.fromkeys('one two'.split(), 1), d5) self.assertEqual(UserDict.UserDict().fromkeys('one two'.split(), 1), d5) - self.assert_(u1.fromkeys('one two'.split()) is not u1) - self.assert_(isinstance(u1.fromkeys('one two'.split()), UserDict.UserDict)) - self.assert_(isinstance(u2.fromkeys('one two'.split()), UserDict.IterableUserDict)) + self.assertTrue(u1.fromkeys('one two'.split()) is not u1) + self.assertTrue(isinstance(u1.fromkeys('one two'.split()), UserDict.UserDict)) + self.assertTrue(isinstance(u2.fromkeys('one two'.split()), UserDict.IterableUserDict)) # Test __repr__ self.assertEqual(str(u0), str(d0)) @@ -95,8 +95,8 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol): # Test has_key and "in". for i in u2.keys(): - self.assert_(u2.has_key(i)) - self.assert_(i in u2) + self.assertTrue(u2.has_key(i)) + 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(u0.has_key(i), d0.has_key(i)) @@ -131,7 +131,7 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol): # Test setdefault t = UserDict.UserDict() self.assertEqual(t.setdefault("x", 42), 42) - self.assert_(t.has_key("x")) + self.assertTrue(t.has_key("x")) self.assertEqual(t.setdefault("x", 23), 42) # Test pop @@ -161,8 +161,8 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol): d = D({1: 2, 3: 4}) self.assertEqual(d[1], 2) self.assertEqual(d[3], 4) - self.assert_(2 not in d) - self.assert_(2 not in d.keys()) + self.assertTrue(2 not in d) + self.assertTrue(2 not in d.keys()) self.assertEqual(d[2], 42) class E(UserDict.UserDict): def __missing__(self, key): @@ -269,12 +269,12 @@ class UserDictMixinTest(mapping_tests.TestMappingProtocol): ## Now, test the DictMixin methods one by one # has_key - self.assert_(s.has_key(10)) - self.assert_(not s.has_key(20)) + self.assertTrue(s.has_key(10)) + self.assertTrue(not s.has_key(20)) # __contains__ - self.assert_(10 in s) - self.assert_(20 not in s) + self.assertTrue(10 in s) + self.assertTrue(20 not in s) # __iter__ self.assertEqual([k for k in s], [10, 30]) @@ -309,7 +309,7 @@ class UserDictMixinTest(mapping_tests.TestMappingProtocol): # pop self.assertEqual(s.pop(10), 'ten') - self.assert_(10 not in s) + self.assertTrue(10 not in s) s[10] = 'ten' self.assertEqual(s.pop("x", 1), 1) s["x"] = 42 @@ -317,7 +317,7 @@ class UserDictMixinTest(mapping_tests.TestMappingProtocol): # popitem k, v = s.popitem() - self.assert_(k not in s) + self.assertTrue(k not in s) s[k] = v # clear diff --git a/Lib/test/test_userstring.py b/Lib/test/test_userstring.py index 4bb0c45..b99581d 100755 --- a/Lib/test/test_userstring.py +++ b/Lib/test/test_userstring.py @@ -114,7 +114,7 @@ class MutableStringTest(UserStringTest): s = self.type2test("foobar") s2 = s.immutable() self.assertEqual(s, s2) - self.assert_(isinstance(s2, UserString)) + self.assertTrue(isinstance(s2, UserString)) def test_iadd(self): s = self.type2test("foo") diff --git a/Lib/test/test_uuid.py b/Lib/test/test_uuid.py index ab926ae..dc28b1e 100644 --- a/Lib/test/test_uuid.py +++ b/Lib/test/test_uuid.py @@ -288,8 +288,8 @@ class TestUUID(TestCase): self.assertEqual(universal_local_bit, 0, message) self.assertNotEqual(node, 0, message) self.assertNotEqual(node, 0xffffffffffffL, message) - self.assert_(0 <= node, message) - self.assert_(node < (1L << 48), message) + self.assertTrue(0 <= node, message) + self.assertTrue(node < (1L << 48), message) TestUUID.source2node[source] = node if TestUUID.last_node: @@ -331,8 +331,8 @@ class TestUUID(TestCase): def test_random_getnode(self): node = uuid._random_getnode() - self.assert_(0 <= node) - self.assert_(node < (1L <<48)) + self.assertTrue(0 <= node) + self.assertTrue(node < (1L <<48)) def test_unixdll_getnode(self): import sys diff --git a/Lib/test/test_warnings.py b/Lib/test/test_warnings.py index 9764783..ca27519 100644 --- a/Lib/test/test_warnings.py +++ b/Lib/test/test_warnings.py @@ -83,9 +83,9 @@ class FilterTests(object): self.module.filterwarnings("always", category=UserWarning) message = "FilterTests.test_always" self.module.warn(message, UserWarning) - self.assert_(message, w[-1].message) + self.assertTrue(message, w[-1].message) self.module.warn(message, UserWarning) - self.assert_(w[-1].message, message) + self.assertTrue(w[-1].message, message) def test_default(self): with original_warnings.catch_warnings(record=True, @@ -165,7 +165,7 @@ class FilterTests(object): text = 'handle normally' self.module.warn(text) self.assertEqual(str(w[-1].message), text) - self.assert_(w[-1].category is UserWarning) + self.assertTrue(w[-1].category is UserWarning) self.module.filterwarnings("ignore", "", Warning, "", 0) text = 'filtered out' @@ -178,7 +178,7 @@ class FilterTests(object): text = 'nonmatching text' self.module.warn(text) self.assertEqual(str(w[-1].message), text) - self.assert_(w[-1].category is UserWarning) + self.assertTrue(w[-1].category is UserWarning) class CFilterTests(BaseTest, FilterTests): module = c_warnings @@ -198,7 +198,7 @@ class WarnTests(unittest.TestCase): text = 'multi %d' %i # Different text on each call. self.module.warn(text) self.assertEqual(str(w[-1].message), text) - self.assert_(w[-1].category is UserWarning) + self.assertTrue(w[-1].category is UserWarning) def test_filename(self): with warnings_state(self.module): @@ -397,7 +397,7 @@ class _WarningsTests(BaseTest): self.module.resetwarnings() self.module.filterwarnings("once", category=UserWarning) self.module.warn_explicit(message, UserWarning, "file", 42) - self.failUnlessEqual(w[-1].message, message) + self.assertEqual(w[-1].message, message) del w[:] self.module.warn_explicit(message, UserWarning, "file", 42) self.assertEquals(len(w), 0) @@ -405,7 +405,7 @@ class _WarningsTests(BaseTest): self.module.onceregistry = {} __warningregistry__ = {} self.module.warn('onceregistry test') - self.failUnlessEqual(w[-1].message.args, message.args) + self.assertEqual(w[-1].message.args, message.args) # Removal of onceregistry is okay. del w[:] del self.module.onceregistry @@ -459,7 +459,7 @@ class _WarningsTests(BaseTest): with test_support.captured_output('stderr') as stream: self.module.warn(text) result = stream.getvalue() - self.failUnless(text in result) + self.assertTrue(text in result) def test_showwarning_not_callable(self): with original_warnings.catch_warnings(module=self.module): @@ -480,19 +480,19 @@ class _WarningsTests(BaseTest): with test_support.captured_output('stderr') as stream: warning_tests.inner(text) result = stream.getvalue() - self.failUnlessEqual(result.count('\n'), 2, + self.assertEqual(result.count('\n'), 2, "Too many newlines in %r" % result) first_line, second_line = result.split('\n', 1) expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py' first_line_parts = first_line.rsplit(':', 3) path, line, warning_class, message = first_line_parts line = int(line) - self.failUnlessEqual(expected_file, path) - self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__) - self.failUnlessEqual(message, ' ' + text) + self.assertEqual(expected_file, path) + self.assertEqual(warning_class, ' ' + UserWarning.__name__) + self.assertEqual(message, ' ' + text) expected_line = ' ' + linecache.getline(path, line).strip() + '\n' assert expected_line - self.failUnlessEqual(second_line, expected_line) + self.assertEqual(second_line, expected_line) class WarningsDisplayTests(unittest.TestCase): @@ -509,13 +509,13 @@ class WarningsDisplayTests(unittest.TestCase): format = "%s:%s: %s: %s\n %s\n" expect = format % (file_name, line_num, category.__name__, message, file_line) - self.failUnlessEqual(expect, self.module.formatwarning(message, + self.assertEqual(expect, self.module.formatwarning(message, category, file_name, line_num)) # Test the 'line' argument. file_line += " for the win!" expect = format % (file_name, line_num, category.__name__, message, file_line) - self.failUnlessEqual(expect, self.module.formatwarning(message, + self.assertEqual(expect, self.module.formatwarning(message, category, file_name, line_num, file_line)) def test_showwarning(self): @@ -529,7 +529,7 @@ class WarningsDisplayTests(unittest.TestCase): line_num) self.module.showwarning(message, category, file_name, line_num, file_object) - self.failUnlessEqual(file_object.getvalue(), expect) + self.assertEqual(file_object.getvalue(), expect) # Test 'line' argument. expected_file_line += "for the win!" expect = self.module.formatwarning(message, category, file_name, @@ -537,7 +537,7 @@ class WarningsDisplayTests(unittest.TestCase): file_object = StringIO.StringIO() self.module.showwarning(message, category, file_name, line_num, file_object, expected_file_line) - self.failUnlessEqual(expect, file_object.getvalue()) + self.assertEqual(expect, file_object.getvalue()) class CWarningsDisplayTests(BaseTest, WarningsDisplayTests): module = c_warnings @@ -557,20 +557,20 @@ class CatchWarningTests(BaseTest): # Ensure both showwarning and filters are restored when recording with wmod.catch_warnings(module=wmod, record=True): wmod.filters = wmod.showwarning = object() - self.assert_(wmod.filters is orig_filters) - self.assert_(wmod.showwarning is orig_showwarning) + self.assertTrue(wmod.filters is orig_filters) + self.assertTrue(wmod.showwarning is orig_showwarning) # Same test, but with recording disabled with wmod.catch_warnings(module=wmod, record=False): wmod.filters = wmod.showwarning = object() - self.assert_(wmod.filters is orig_filters) - self.assert_(wmod.showwarning is orig_showwarning) + self.assertTrue(wmod.filters is orig_filters) + self.assertTrue(wmod.showwarning is orig_showwarning) def test_catch_warnings_recording(self): wmod = self.module # Ensure warnings are recorded when requested with wmod.catch_warnings(module=wmod, record=True) as w: self.assertEqual(w, []) - self.assert_(type(w) is list) + self.assertTrue(type(w) is list) wmod.simplefilter("always") wmod.warn("foo") self.assertEqual(str(w[-1].message), "foo") @@ -583,8 +583,8 @@ class CatchWarningTests(BaseTest): # Ensure warnings are not recorded when not requested orig_showwarning = wmod.showwarning with wmod.catch_warnings(module=wmod, record=False) as w: - self.assert_(w is None) - self.assert_(wmod.showwarning is orig_showwarning) + self.assertTrue(w is None) + self.assertTrue(wmod.showwarning is orig_showwarning) def test_catch_warnings_reentry_guard(self): wmod = self.module @@ -605,17 +605,17 @@ class CatchWarningTests(BaseTest): orig_showwarning = wmod.showwarning # Ensure default behaviour is not to record warnings with wmod.catch_warnings(module=wmod) as w: - self.assert_(w is None) - self.assert_(wmod.showwarning is orig_showwarning) - self.assert_(wmod.filters is not orig_filters) - self.assert_(wmod.filters is orig_filters) + self.assertTrue(w is None) + self.assertTrue(wmod.showwarning is orig_showwarning) + self.assertTrue(wmod.filters is not orig_filters) + self.assertTrue(wmod.filters is orig_filters) if wmod is sys.modules['warnings']: # Ensure the default module is this one with wmod.catch_warnings() as w: - self.assert_(w is None) - self.assert_(wmod.showwarning is orig_showwarning) - self.assert_(wmod.filters is not orig_filters) - self.assert_(wmod.filters is orig_filters) + self.assertTrue(w is None) + self.assertTrue(wmod.showwarning is orig_showwarning) + self.assertTrue(wmod.filters is not orig_filters) + self.assertTrue(wmod.filters is orig_filters) def test_check_warnings(self): # Explicit tests for the test_support convenience wrapper diff --git a/Lib/test/test_weakref.py b/Lib/test/test_weakref.py index aeafdda..ed63147 100644 --- a/Lib/test/test_weakref.py +++ b/Lib/test/test_weakref.py @@ -70,11 +70,11 @@ class ReferencesTestCase(TestBase): ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del o - self.assert_(ref1() is None, + self.assertTrue(ref1() is None, "expected reference to be invalidated") - self.assert_(ref2() is None, + self.assertTrue(ref2() is None, "expected reference to be invalidated") - self.assert_(self.cbcalled == 2, + self.assertTrue(self.cbcalled == 2, "callback not called the right number of times") def test_multiple_selfref_callbacks(self): @@ -108,15 +108,15 @@ class ReferencesTestCase(TestBase): self.assertRaises(weakref.ReferenceError, check, ref1) self.assertRaises(weakref.ReferenceError, check, ref2) self.assertRaises(weakref.ReferenceError, bool, weakref.proxy(C())) - self.assert_(self.cbcalled == 2) + self.assertTrue(self.cbcalled == 2) def check_basic_ref(self, factory): o = factory() ref = weakref.ref(o) - self.assert_(ref() is not None, + self.assertTrue(ref() is not None, "weak reference to live object should be live") o2 = ref() - self.assert_(o is o2, + self.assertTrue(o is o2, "<ref>() should return original object if live") def check_basic_callback(self, factory): @@ -124,9 +124,9 @@ class ReferencesTestCase(TestBase): o = factory() ref = weakref.ref(o, self.callback) del o - self.assert_(self.cbcalled == 1, + self.assertTrue(self.cbcalled == 1, "callback did not properly set 'cbcalled'") - self.assert_(ref() is None, + self.assertTrue(ref() is None, "ref2 should be dead after deleting object reference") def test_ref_reuse(self): @@ -136,19 +136,19 @@ class ReferencesTestCase(TestBase): # between these two; it should make no difference proxy = weakref.proxy(o) ref2 = weakref.ref(o) - self.assert_(ref1 is ref2, + self.assertTrue(ref1 is ref2, "reference object w/out callback should be re-used") o = C() proxy = weakref.proxy(o) ref1 = weakref.ref(o) ref2 = weakref.ref(o) - self.assert_(ref1 is ref2, + self.assertTrue(ref1 is ref2, "reference object w/out callback should be re-used") - self.assert_(weakref.getweakrefcount(o) == 2, + self.assertTrue(weakref.getweakrefcount(o) == 2, "wrong weak ref count for object") del proxy - self.assert_(weakref.getweakrefcount(o) == 1, + self.assertTrue(weakref.getweakrefcount(o) == 1, "wrong weak ref count for object after deleting proxy") def test_proxy_reuse(self): @@ -156,7 +156,7 @@ class ReferencesTestCase(TestBase): proxy1 = weakref.proxy(o) ref = weakref.ref(o) proxy2 = weakref.proxy(o) - self.assert_(proxy1 is proxy2, + self.assertTrue(proxy1 is proxy2, "proxy object w/out callback should have been re-used") def test_basic_proxy(self): @@ -165,14 +165,14 @@ class ReferencesTestCase(TestBase): L = UserList.UserList() p = weakref.proxy(L) - self.failIf(p, "proxy for empty UserList should be false") + self.assertFalse(p, "proxy for empty UserList should be false") p.append(12) self.assertEqual(len(L), 1) - self.failUnless(p, "proxy for non-empty UserList should be true") + self.assertTrue(p, "proxy for non-empty UserList should be true") p[:] = [2, 3] self.assertEqual(len(L), 2) self.assertEqual(len(p), 2) - self.failUnless(3 in p, + self.assertTrue(3 in p, "proxy didn't support __contains__() properly") p[1] = 5 self.assertEqual(L[1], 5) @@ -226,19 +226,19 @@ class ReferencesTestCase(TestBase): o = Object(1) p1 = makeref(o, None) p2 = makeref(o, None) - self.assert_(p1 is p2, "both callbacks were None in the C API") + self.assertTrue(p1 is p2, "both callbacks were None in the C API") del p1, p2 p1 = makeref(o) p2 = makeref(o, None) - self.assert_(p1 is p2, "callbacks were NULL, None in the C API") + self.assertTrue(p1 is p2, "callbacks were NULL, None in the C API") del p1, p2 p1 = makeref(o) p2 = makeref(o) - self.assert_(p1 is p2, "both callbacks were NULL in the C API") + self.assertTrue(p1 is p2, "both callbacks were NULL in the C API") del p1, p2 p1 = makeref(o, None) p2 = makeref(o) - self.assert_(p1 is p2, "callbacks were None, NULL in the C API") + self.assertTrue(p1 is p2, "callbacks were None, NULL in the C API") def test_callable_proxy(self): o = Callable() @@ -246,13 +246,13 @@ class ReferencesTestCase(TestBase): self.check_proxy(o, ref1) - self.assert_(type(ref1) is weakref.CallableProxyType, + self.assertTrue(type(ref1) is weakref.CallableProxyType, "proxy is not of callable type") ref1('twinkies!') - self.assert_(o.bar == 'twinkies!', + self.assertTrue(o.bar == 'twinkies!', "call through proxy not passed through to original") ref1(x='Splat.') - self.assert_(o.bar == 'Splat.', + self.assertTrue(o.bar == 'Splat.', "call through proxy not passed through to original") # expect due to too few args @@ -263,24 +263,24 @@ class ReferencesTestCase(TestBase): def check_proxy(self, o, proxy): o.foo = 1 - self.assert_(proxy.foo == 1, + self.assertTrue(proxy.foo == 1, "proxy does not reflect attribute addition") o.foo = 2 - self.assert_(proxy.foo == 2, + self.assertTrue(proxy.foo == 2, "proxy does not reflect attribute modification") del o.foo - self.assert_(not hasattr(proxy, 'foo'), + self.assertTrue(not hasattr(proxy, 'foo'), "proxy does not reflect attribute removal") proxy.foo = 1 - self.assert_(o.foo == 1, + self.assertTrue(o.foo == 1, "object does not reflect attribute addition via proxy") proxy.foo = 2 - self.assert_( + self.assertTrue( o.foo == 2, "object does not reflect attribute modification via proxy") del proxy.foo - self.assert_(not hasattr(o, 'foo'), + self.assertTrue(not hasattr(o, 'foo'), "object does not reflect attribute removal via proxy") def test_proxy_deletion(self): @@ -304,21 +304,21 @@ class ReferencesTestCase(TestBase): o = C() ref1 = weakref.ref(o) ref2 = weakref.ref(o, self.callback) - self.assert_(weakref.getweakrefcount(o) == 2, + self.assertTrue(weakref.getweakrefcount(o) == 2, "got wrong number of weak reference objects") proxy1 = weakref.proxy(o) proxy2 = weakref.proxy(o, self.callback) - self.assert_(weakref.getweakrefcount(o) == 4, + self.assertTrue(weakref.getweakrefcount(o) == 4, "got wrong number of weak reference objects") del ref1, ref2, proxy1, proxy2 - self.assert_(weakref.getweakrefcount(o) == 0, + self.assertTrue(weakref.getweakrefcount(o) == 0, "weak reference objects not unlinked from" " referent when discarded.") # assumes ints do not support weakrefs - self.assert_(weakref.getweakrefcount(1) == 0, + self.assertTrue(weakref.getweakrefcount(1) == 0, "got wrong number of weak reference objects for int") def test_getweakrefs(self): @@ -326,22 +326,22 @@ class ReferencesTestCase(TestBase): ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref1 - self.assert_(weakref.getweakrefs(o) == [ref2], + self.assertTrue(weakref.getweakrefs(o) == [ref2], "list of refs does not match") o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref2 - self.assert_(weakref.getweakrefs(o) == [ref1], + self.assertTrue(weakref.getweakrefs(o) == [ref1], "list of refs does not match") del ref1 - self.assert_(weakref.getweakrefs(o) == [], + self.assertTrue(weakref.getweakrefs(o) == [], "list of refs not cleared") # assumes ints do not support weakrefs - self.assert_(weakref.getweakrefs(1) == [], + self.assertTrue(weakref.getweakrefs(1) == [], "list of refs does not match for int") def test_newstyle_number_ops(self): @@ -349,8 +349,8 @@ class ReferencesTestCase(TestBase): pass f = F(2.0) p = weakref.proxy(f) - self.assert_(p + 1.0 == 3.0) - self.assert_(1.0 + p == 3.0) # this used to SEGV + self.assertTrue(p + 1.0 == 3.0) + self.assertTrue(1.0 + p == 3.0) # this used to SEGV def test_callbacks_protected(self): # Callbacks protected from already-set exceptions? @@ -603,7 +603,7 @@ class ReferencesTestCase(TestBase): c.wr = weakref.ref(d, callback) # this won't trigger d.wr = weakref.ref(callback, d.cb) # ditto external_wr = weakref.ref(callback, safe_callback) # but this will - self.assert_(external_wr() is callback) + self.assertTrue(external_wr() is callback) # The weakrefs attached to c and d should get cleared, so that # C.cb is never called. But external_wr isn't part of the cyclic @@ -686,12 +686,12 @@ class SubclassableWeakrefTestCase(TestBase): return super(MyRef, self).__call__() o = Object("foo") mr = MyRef(o, value=24) - self.assert_(mr() is o) - self.assert_(mr.called) + self.assertTrue(mr() is o) + self.assertTrue(mr.called) self.assertEqual(mr.value, 24) del o - self.assert_(mr() is None) - self.assert_(mr.called) + self.assertTrue(mr() is None) + self.assertTrue(mr.called) def test_subclass_refs_dont_replace_standard_refs(self): class MyRef(weakref.ref): @@ -699,16 +699,16 @@ class SubclassableWeakrefTestCase(TestBase): o = Object(42) r1 = MyRef(o) r2 = weakref.ref(o) - self.assert_(r1 is not r2) + self.assertTrue(r1 is not r2) self.assertEqual(weakref.getweakrefs(o), [r2, r1]) self.assertEqual(weakref.getweakrefcount(o), 2) r3 = MyRef(o) self.assertEqual(weakref.getweakrefcount(o), 3) refs = weakref.getweakrefs(o) self.assertEqual(len(refs), 3) - self.assert_(r2 is refs[0]) - self.assert_(r1 in refs[1:]) - self.assert_(r3 in refs[1:]) + self.assertTrue(r2 is refs[0]) + self.assertTrue(r1 in refs[1:]) + self.assertTrue(r3 in refs[1:]) def test_subclass_refs_dont_conflate_callbacks(self): class MyRef(weakref.ref): @@ -716,10 +716,10 @@ class SubclassableWeakrefTestCase(TestBase): o = Object(42) r1 = MyRef(o, id) r2 = MyRef(o, str) - self.assert_(r1 is not r2) + self.assertTrue(r1 is not r2) refs = weakref.getweakrefs(o) - self.assert_(r1 in refs) - self.assert_(r2 in refs) + self.assertTrue(r1 in refs) + self.assertTrue(r2 in refs) def test_subclass_refs_with_slots(self): class MyRef(weakref.ref): @@ -736,7 +736,7 @@ class SubclassableWeakrefTestCase(TestBase): self.assertEqual(r.slot1, "abc") self.assertEqual(r.slot2, "def") self.assertEqual(r.meth(), "abcdef") - self.failIf(hasattr(r, "__dict__")) + self.assertFalse(hasattr(r, "__dict__")) def test_subclass_refs_with_cycle(self): # Bug #3110 @@ -794,23 +794,23 @@ class MappingTestCase(TestBase): # dict, objects = self.make_weak_valued_dict() for o in objects: - self.assert_(weakref.getweakrefcount(o) == 1, + self.assertTrue(weakref.getweakrefcount(o) == 1, "wrong number of weak references to %r!" % o) - self.assert_(o is dict[o.arg], + self.assertTrue(o is dict[o.arg], "wrong object returned by weak dict!") items1 = dict.items() items2 = dict.copy().items() items1.sort() items2.sort() - self.assert_(items1 == items2, + self.assertTrue(items1 == items2, "cloning of weak-valued dictionary did not work!") del items1, items2 - self.assert_(len(dict) == self.COUNT) + self.assertTrue(len(dict) == self.COUNT) del objects[0] - self.assert_(len(dict) == (self.COUNT - 1), + self.assertTrue(len(dict) == (self.COUNT - 1), "deleting object did not cause dictionary update") del objects, o - self.assert_(len(dict) == 0, + self.assertTrue(len(dict) == 0, "deleting the values did not clear the dictionary") # regression on SF bug #447152: dict = weakref.WeakValueDictionary() @@ -825,26 +825,26 @@ class MappingTestCase(TestBase): # dict, objects = self.make_weak_keyed_dict() for o in objects: - self.assert_(weakref.getweakrefcount(o) == 1, + self.assertTrue(weakref.getweakrefcount(o) == 1, "wrong number of weak references to %r!" % o) - self.assert_(o.arg is dict[o], + self.assertTrue(o.arg is dict[o], "wrong object returned by weak dict!") items1 = dict.items() items2 = dict.copy().items() - self.assert_(set(items1) == set(items2), + self.assertTrue(set(items1) == set(items2), "cloning of weak-keyed dictionary did not work!") del items1, items2 - self.assert_(len(dict) == self.COUNT) + self.assertTrue(len(dict) == self.COUNT) del objects[0] - self.assert_(len(dict) == (self.COUNT - 1), + self.assertTrue(len(dict) == (self.COUNT - 1), "deleting object did not cause dictionary update") del objects, o - self.assert_(len(dict) == 0, + self.assertTrue(len(dict) == 0, "deleting the keys did not clear the dictionary") o = Object(42) dict[o] = "What is the meaning of the universe?" - self.assert_(dict.has_key(o)) - self.assert_(not dict.has_key(34)) + self.assertTrue(dict.has_key(o)) + self.assertTrue(not dict.has_key(34)) def test_weak_keyed_iters(self): dict, objects = self.make_weak_keyed_dict() @@ -856,8 +856,8 @@ class MappingTestCase(TestBase): objects2 = list(objects) for wr in refs: ob = wr() - self.assert_(dict.has_key(ob)) - self.assert_(ob in dict) + self.assertTrue(dict.has_key(ob)) + self.assertTrue(ob in dict) self.assertEqual(ob.arg, dict[ob]) objects2.remove(ob) self.assertEqual(len(objects2), 0) @@ -867,8 +867,8 @@ class MappingTestCase(TestBase): self.assertEqual(len(list(dict.iterkeyrefs())), len(objects)) for wr in dict.iterkeyrefs(): ob = wr() - self.assert_(dict.has_key(ob)) - self.assert_(ob in dict) + self.assertTrue(dict.has_key(ob)) + self.assertTrue(ob in dict) self.assertEqual(ob.arg, dict[ob]) objects2.remove(ob) self.assertEqual(len(objects2), 0) @@ -903,37 +903,37 @@ class MappingTestCase(TestBase): items = dict.items() for item in dict.iteritems(): items.remove(item) - self.assert_(len(items) == 0, "iteritems() did not touch all items") + self.assertTrue(len(items) == 0, "iteritems() did not touch all items") # key iterator, via __iter__(): keys = dict.keys() for k in dict: keys.remove(k) - self.assert_(len(keys) == 0, "__iter__() did not touch all keys") + self.assertTrue(len(keys) == 0, "__iter__() did not touch all keys") # key iterator, via iterkeys(): keys = dict.keys() for k in dict.iterkeys(): keys.remove(k) - self.assert_(len(keys) == 0, "iterkeys() did not touch all keys") + self.assertTrue(len(keys) == 0, "iterkeys() did not touch all keys") # value iterator: values = dict.values() for v in dict.itervalues(): values.remove(v) - self.assert_(len(values) == 0, + self.assertTrue(len(values) == 0, "itervalues() did not touch all values") def test_make_weak_keyed_dict_from_dict(self): o = Object(3) dict = weakref.WeakKeyDictionary({o:364}) - self.assert_(dict[o] == 364) + self.assertTrue(dict[o] == 364) def test_make_weak_keyed_dict_from_weak_keyed_dict(self): o = Object(3) dict = weakref.WeakKeyDictionary({o:364}) dict2 = weakref.WeakKeyDictionary(dict) - self.assert_(dict[o] == 364) + self.assertTrue(dict[o] == 364) def make_weak_keyed_dict(self): dict = weakref.WeakKeyDictionary() @@ -953,19 +953,19 @@ class MappingTestCase(TestBase): weakdict = klass() weakdict[key1] = value1 weakdict[key2] = value2 - self.assert_(len(weakdict) == 2) + self.assertTrue(len(weakdict) == 2) k, v = weakdict.popitem() - self.assert_(len(weakdict) == 1) + self.assertTrue(len(weakdict) == 1) if k is key1: - self.assert_(v is value1) + self.assertTrue(v is value1) else: - self.assert_(v is value2) + self.assertTrue(v is value2) k, v = weakdict.popitem() - self.assert_(len(weakdict) == 0) + self.assertTrue(len(weakdict) == 0) if k is key1: - self.assert_(v is value1) + self.assertTrue(v is value1) else: - self.assert_(v is value2) + self.assertTrue(v is value2) def test_weak_valued_dict_popitem(self): self.check_popitem(weakref.WeakValueDictionary, @@ -976,21 +976,21 @@ class MappingTestCase(TestBase): C(), "value 1", C(), "value 2") def check_setdefault(self, klass, key, value1, value2): - self.assert_(value1 is not value2, + self.assertTrue(value1 is not value2, "invalid test" " -- value parameters must be distinct objects") weakdict = klass() o = weakdict.setdefault(key, value1) - self.assert_(o is value1) - self.assert_(weakdict.has_key(key)) - self.assert_(weakdict.get(key) is value1) - self.assert_(weakdict[key] is value1) + self.assertTrue(o is value1) + self.assertTrue(weakdict.has_key(key)) + self.assertTrue(weakdict.get(key) is value1) + self.assertTrue(weakdict[key] is value1) o = weakdict.setdefault(key, value2) - self.assert_(o is value1) - self.assert_(weakdict.has_key(key)) - self.assert_(weakdict.get(key) is value1) - self.assert_(weakdict[key] is value1) + self.assertTrue(o is value1) + self.assertTrue(weakdict.has_key(key)) + self.assertTrue(weakdict.get(key) is value1) + self.assertTrue(weakdict[key] is value1) def test_weak_valued_dict_setdefault(self): self.check_setdefault(weakref.WeakValueDictionary, @@ -1007,19 +1007,19 @@ class MappingTestCase(TestBase): # weakdict = klass() weakdict.update(dict) - self.assert_(len(weakdict) == len(dict)) + self.assertTrue(len(weakdict) == len(dict)) for k in weakdict.keys(): - self.assert_(dict.has_key(k), + self.assertTrue(dict.has_key(k), "mysterious new key appeared in weak dict") v = dict.get(k) - self.assert_(v is weakdict[k]) - self.assert_(v is weakdict.get(k)) + self.assertTrue(v is weakdict[k]) + self.assertTrue(v is weakdict.get(k)) for k in dict.keys(): - self.assert_(weakdict.has_key(k), + self.assertTrue(weakdict.has_key(k), "original key disappeared in weak dict") v = dict[k] - self.assert_(v is weakdict[k]) - self.assert_(v is weakdict.get(k)) + self.assertTrue(v is weakdict[k]) + self.assertTrue(v is weakdict.get(k)) def test_weak_valued_dict_update(self): self.check_update(weakref.WeakValueDictionary, @@ -1035,10 +1035,10 @@ class MappingTestCase(TestBase): o2 = Object('2') d[o1] = 'something' d[o2] = 'something' - self.assert_(len(d) == 2) + self.assertTrue(len(d) == 2) del d[o1] - self.assert_(len(d) == 1) - self.assert_(d.keys() == [o2]) + self.assertTrue(len(d) == 1) + self.assertTrue(d.keys() == [o2]) def test_weak_valued_delitem(self): d = weakref.WeakValueDictionary() @@ -1046,10 +1046,10 @@ class MappingTestCase(TestBase): o2 = Object('2') d['something'] = o1 d['something else'] = o2 - self.assert_(len(d) == 2) + self.assertTrue(len(d) == 2) del d['something'] - self.assert_(len(d) == 1) - self.assert_(d.items() == [('something else', o2)]) + self.assertTrue(len(d) == 1) + self.assertTrue(d.items() == [('something else', o2)]) def test_weak_keyed_bad_delitem(self): d = weakref.WeakKeyDictionary() diff --git a/Lib/test/test_wsgiref.py b/Lib/test/test_wsgiref.py index b6d994b..db82139 100755 --- a/Lib/test/test_wsgiref.py +++ b/Lib/test/test_wsgiref.py @@ -149,7 +149,7 @@ class IntegrationTests(TestCase): start_response("200 OK", ('Content-Type','text/plain')) return ["Hello, world!"] out, err = run_amock(validator(bad_app)) - self.failUnless(out.endswith( + self.assertTrue(out.endswith( "A server error occurred. Please contact the administrator." )) self.assertEqual( @@ -178,14 +178,14 @@ class UtilityTests(TestCase): env = {} util.setup_testing_defaults(env) if isinstance(value,StringIO): - self.failUnless(isinstance(env[key],StringIO)) + self.assertTrue(isinstance(env[key],StringIO)) else: self.assertEqual(env[key],value) # Check existing value env = {key:alt} util.setup_testing_defaults(env) - self.failUnless(env[key] is alt) + self.assertTrue(env[key] is alt) def checkCrossDefault(self,key,value,**kw): util.setup_testing_defaults(kw) @@ -212,15 +212,15 @@ class UtilityTests(TestCase): compare_generic_iter(make_it,match) it = make_it() - self.failIf(it.filelike.closed) + self.assertFalse(it.filelike.closed) for item in it: pass - self.failIf(it.filelike.closed) + self.assertFalse(it.filelike.closed) it.close() - self.failUnless(it.filelike.closed) + self.assertTrue(it.filelike.closed) def testSimpleShifts(self): @@ -318,14 +318,14 @@ class UtilityTests(TestCase): "TE Trailers Transfer-Encoding Upgrade" ).split(): for alt in hop, hop.title(), hop.upper(), hop.lower(): - self.failUnless(util.is_hop_by_hop(alt)) + self.assertTrue(util.is_hop_by_hop(alt)) # Not comprehensive, just a few random header names for hop in ( "Accept Cache-Control Date Pragma Trailer Via Warning" ).split(): for alt in hop, hop.title(), hop.upper(), hop.lower(): - self.failIf(util.is_hop_by_hop(alt)) + self.assertFalse(util.is_hop_by_hop(alt)) class HeaderTests(TestCase): @@ -336,17 +336,17 @@ class HeaderTests(TestCase): self.assertEqual(Headers(test[:]).keys(), ['x']) self.assertEqual(Headers(test[:]).values(), ['y']) self.assertEqual(Headers(test[:]).items(), test) - self.failIf(Headers(test).items() is test) # must be copy! + self.assertFalse(Headers(test).items() is test) # must be copy! h=Headers([]) del h['foo'] # should not raise an error h['Foo'] = 'bar' for m in h.has_key, h.__contains__, h.get, h.get_all, h.__getitem__: - self.failUnless(m('foo')) - self.failUnless(m('Foo')) - self.failUnless(m('FOO')) - self.failIf(m('bar')) + self.assertTrue(m('foo')) + self.assertTrue(m('Foo')) + self.assertTrue(m('FOO')) + self.assertFalse(m('bar')) self.assertEqual(h['foo'],'bar') h['foo'] = 'baz' @@ -428,7 +428,7 @@ class HandlerTests(TestCase): if not empty.has_key(k): self.assertEqual(env[k],v) for k,v in empty.items(): - self.failUnless(env.has_key(k)) + self.assertTrue(env.has_key(k)) def testEnviron(self): h = TestHandler(X="Y") @@ -441,7 +441,7 @@ class HandlerTests(TestCase): h = BaseCGIHandler(None,None,None,{}) h.setup_environ() for key in 'wsgi.url_scheme', 'wsgi.input', 'wsgi.errors': - self.assert_(h.environ.has_key(key)) + self.assertTrue(h.environ.has_key(key)) def testScheme(self): h=TestHandler(HTTPS="on"); h.setup_environ() @@ -516,7 +516,7 @@ class HandlerTests(TestCase): "Content-Length: %d\r\n" "\r\n%s" % (h.error_status,len(h.error_body),h.error_body)) - self.failUnless(h.stderr.getvalue().find("AssertionError")<>-1) + self.assertTrue(h.stderr.getvalue().find("AssertionError")<>-1) def testErrorAfterOutput(self): MSG = "Some output has been sent" @@ -529,7 +529,7 @@ class HandlerTests(TestCase): self.assertEqual(h.stdout.getvalue(), "Status: 200 OK\r\n" "\r\n"+MSG) - self.failUnless(h.stderr.getvalue().find("AssertionError")<>-1) + self.assertTrue(h.stderr.getvalue().find("AssertionError")<>-1) def testHeaderFormats(self): @@ -568,7 +568,7 @@ class HandlerTests(TestCase): if proto=="HTTP/0.9": self.assertEqual(h.stdout.getvalue(),"") else: - self.failUnless( + self.assertTrue( re.match(stdpat%(version,sw), h.stdout.getvalue()), (stdpat%(version,sw), h.stdout.getvalue()) ) diff --git a/Lib/test/test_xdrlib.py b/Lib/test/test_xdrlib.py index 8fc88a5..ab6e460 100644 --- a/Lib/test/test_xdrlib.py +++ b/Lib/test/test_xdrlib.py @@ -30,15 +30,15 @@ class XDRTest(unittest.TestCase): self.assertEqual(up.unpack_int(), 42) self.assertEqual(up.unpack_uint(), 9) - self.assert_(up.unpack_bool() is True) + self.assertTrue(up.unpack_bool() is True) # remember position pos = up.get_position() - self.assert_(up.unpack_bool() is False) + self.assertTrue(up.unpack_bool() is False) # rewind and unpack again up.set_position(pos) - self.assert_(up.unpack_bool() is False) + self.assertTrue(up.unpack_bool() is False) self.assertEqual(up.unpack_uhyper(), 45L) self.assertAlmostEqual(up.unpack_float(), 1.9) diff --git a/Lib/test/test_xmlrpc.py b/Lib/test/test_xmlrpc.py index ce561f4..ff0dec9 100644 --- a/Lib/test/test_xmlrpc.py +++ b/Lib/test/test_xmlrpc.py @@ -71,21 +71,21 @@ class XMLRPCTestCase(unittest.TestCase): def test_cmp_datetime_DateTime(self): now = datetime.datetime.now() dt = xmlrpclib.DateTime(now.timetuple()) - self.assert_(dt == now) - self.assert_(now == dt) + self.assertTrue(dt == now) + self.assertTrue(now == dt) then = now + datetime.timedelta(seconds=4) - self.assert_(then >= dt) - self.assert_(dt < then) + self.assertTrue(then >= dt) + self.assertTrue(dt < then) def test_bug_1164912 (self): d = xmlrpclib.DateTime() ((new_d,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((d,), methodresponse=True)) - self.assert_(isinstance(new_d.value, str)) + self.assertTrue(isinstance(new_d.value, str)) # Check that the output of dumps() is still an 8-bit string s = xmlrpclib.dumps((new_d,), methodresponse=True) - self.assert_(isinstance(s, str)) + self.assertTrue(isinstance(s, str)) def test_newstyle_class(self): class T(object): @@ -175,10 +175,10 @@ class XMLRPCTestCase(unittest.TestCase): items = d.items() if have_unicode: self.assertEquals(s, u"abc \x95") - self.assert_(isinstance(s, unicode)) + self.assertTrue(isinstance(s, unicode)) self.assertEquals(items, [(u"def \x96", u"ghi \x97")]) - self.assert_(isinstance(items[0][0], unicode)) - self.assert_(isinstance(items[0][1], unicode)) + self.assertTrue(isinstance(items[0][0], unicode)) + self.assertTrue(isinstance(items[0][1], unicode)) else: self.assertEquals(s, "abc \xc2\x95") self.assertEquals(items, [("def \xc2\x96", "ghi \xc2\x97")]) @@ -511,7 +511,7 @@ class SimpleServerTestCase(BaseServerTestCase): self.assertRaises(AttributeError, SimpleXMLRPCServer.resolve_dotted_attribute, str, '__add') - self.assert_(SimpleXMLRPCServer.resolve_dotted_attribute(str, 'title')) + self.assertTrue(SimpleXMLRPCServer.resolve_dotted_attribute(str, 'title')) # Get the test to run faster by sending a request with test_simple1. # This avoids waiting for the socket timeout. self.test_simple1() @@ -838,7 +838,7 @@ class TransportSubclassTestCase(unittest.TestCase): conn.putheader("X-Test", "test_custom_user_agent") req = self.issue_request(TestTransport) - self.assert_("X-Test: test_custom_user_agent\r\n" in req) + self.assertTrue("X-Test: test_custom_user_agent\r\n" in req) def test_send_host(self): class TestTransport(FakeTransport): @@ -848,7 +848,7 @@ class TransportSubclassTestCase(unittest.TestCase): conn.putheader("X-Test", "test_send_host") req = self.issue_request(TestTransport) - self.assert_("X-Test: test_send_host\r\n" in req) + self.assertTrue("X-Test: test_send_host\r\n" in req) def test_send_request(self): class TestTransport(FakeTransport): @@ -858,7 +858,7 @@ class TransportSubclassTestCase(unittest.TestCase): conn.putheader("X-Test", "test_send_request") req = self.issue_request(TestTransport) - self.assert_("X-Test: test_send_request\r\n" in req) + self.assertTrue("X-Test: test_send_request\r\n" in req) def test_send_content(self): class TestTransport(FakeTransport): @@ -868,7 +868,7 @@ class TransportSubclassTestCase(unittest.TestCase): xmlrpclib.Transport.send_content(self, conn, body) req = self.issue_request(TestTransport) - self.assert_("X-Test: test_send_content\r\n" in req) + self.assertTrue("X-Test: test_send_content\r\n" in req) def test_main(): xmlrpc_tests = [XMLRPCTestCase, HelperTestCase, DateTimeTestCase, diff --git a/Lib/test/test_xrange.py b/Lib/test/test_xrange.py index 7e2a1a3..a0b94fa 100644 --- a/Lib/test/test_xrange.py +++ b/Lib/test/test_xrange.py @@ -26,18 +26,18 @@ class XrangeTest(unittest.TestCase): self.assertEqual(list(xrange(a+4, a, -2)), [a+4, a+2]) seq = list(xrange(a, b, c)) - self.assert_(a in seq) - self.assert_(b not in seq) + self.assertTrue(a in seq) + self.assertTrue(b not in seq) self.assertEqual(len(seq), 2) seq = list(xrange(b, a, -c)) - self.assert_(b in seq) - self.assert_(a not in seq) + self.assertTrue(b in seq) + self.assertTrue(a not in seq) self.assertEqual(len(seq), 2) seq = list(xrange(-a, -b, -c)) - self.assert_(-a in seq) - self.assert_(-b not in seq) + self.assertTrue(-a in seq) + self.assertTrue(-b not in seq) self.assertEqual(len(seq), 2) self.assertRaises(TypeError, xrange) diff --git a/Lib/test/test_zipfile.py b/Lib/test/test_zipfile.py index cb8ba10..0b0727d 100644 --- a/Lib/test/test_zipfile.py +++ b/Lib/test/test_zipfile.py @@ -64,9 +64,9 @@ class TestsWithSourceFile(unittest.TestCase): lines = directory.splitlines() self.assertEquals(len(lines), 4) # Number of files + header - self.assert_('File Name' in lines[0]) - self.assert_('Modified' in lines[0]) - self.assert_('Size' in lines[0]) + self.assertTrue('File Name' in lines[0]) + self.assertTrue('Modified' in lines[0]) + self.assertTrue('Size' in lines[0]) fn, date, time, size = lines[1].split() self.assertEquals(fn, 'another.name') @@ -76,17 +76,17 @@ class TestsWithSourceFile(unittest.TestCase): # Check the namelist names = zipfp.namelist() self.assertEquals(len(names), 3) - self.assert_(TESTFN in names) - self.assert_("another"+os.extsep+"name" in names) - self.assert_("strfile" in names) + self.assertTrue(TESTFN in names) + self.assertTrue("another"+os.extsep+"name" in names) + self.assertTrue("strfile" in names) # Check infolist infos = zipfp.infolist() names = [ i.filename for i in infos ] self.assertEquals(len(names), 3) - self.assert_(TESTFN in names) - self.assert_("another"+os.extsep+"name" in names) - self.assert_("strfile" in names) + self.assertTrue(TESTFN in names) + self.assertTrue("another"+os.extsep+"name" in names) + self.assertTrue("strfile" in names) for i in infos: self.assertEquals(i.file_size, len(self.data)) @@ -145,11 +145,11 @@ class TestsWithSourceFile(unittest.TestCase): data = "" for info in infos: data += zipfp.open(info).read() - self.assert_(data == "foobar" or data == "barfoo") + self.assertTrue(data == "foobar" or data == "barfoo") data = "" for info in infos: data += zipfp.read(info) - self.assert_(data == "foobar" or data == "barfoo") + self.assertTrue(data == "foobar" or data == "barfoo") zipfp.close() def zipRandomOpenTest(self, f, compression): @@ -451,9 +451,9 @@ class TestZip64InSmallFiles(unittest.TestCase): lines = directory.splitlines() self.assertEquals(len(lines), 4) # Number of files + header - self.assert_('File Name' in lines[0]) - self.assert_('Modified' in lines[0]) - self.assert_('Size' in lines[0]) + self.assertTrue('File Name' in lines[0]) + self.assertTrue('Modified' in lines[0]) + self.assertTrue('Size' in lines[0]) fn, date, time, size = lines[1].split() self.assertEquals(fn, 'another.name') @@ -463,17 +463,17 @@ class TestZip64InSmallFiles(unittest.TestCase): # Check the namelist names = zipfp.namelist() self.assertEquals(len(names), 3) - self.assert_(TESTFN in names) - self.assert_("another"+os.extsep+"name" in names) - self.assert_("strfile" in names) + self.assertTrue(TESTFN in names) + self.assertTrue("another"+os.extsep+"name" in names) + self.assertTrue("strfile" in names) # Check infolist infos = zipfp.infolist() names = [ i.filename for i in infos ] self.assertEquals(len(names), 3) - self.assert_(TESTFN in names) - self.assert_("another"+os.extsep+"name" in names) - self.assert_("strfile" in names) + self.assertTrue(TESTFN in names) + self.assertTrue("another"+os.extsep+"name" in names) + self.assertTrue("strfile" in names) for i in infos: self.assertEquals(i.file_size, len(self.data)) @@ -523,8 +523,8 @@ class PyZipFileTests(unittest.TestCase): zipfp.writepy(fn) bn = os.path.basename(fn) - self.assert_(bn not in zipfp.namelist()) - self.assert_(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist()) + self.assertTrue(bn not in zipfp.namelist()) + self.assertTrue(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist()) zipfp.close() @@ -536,8 +536,8 @@ class PyZipFileTests(unittest.TestCase): zipfp.writepy(fn, "testpackage") bn = "%s/%s"%("testpackage", os.path.basename(fn)) - self.assert_(bn not in zipfp.namelist()) - self.assert_(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist()) + self.assertTrue(bn not in zipfp.namelist()) + self.assertTrue(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist()) zipfp.close() def testWritePythonPackage(self): @@ -549,8 +549,8 @@ class PyZipFileTests(unittest.TestCase): # Check for a couple of modules at different levels of the hieararchy names = zipfp.namelist() - self.assert_('email/__init__.pyo' in names or 'email/__init__.pyc' in names) - self.assert_('email/mime/text.pyo' in names or 'email/mime/text.pyc' in names) + self.assertTrue('email/__init__.pyo' in names or 'email/__init__.pyc' in names) + self.assertTrue('email/mime/text.pyo' in names or 'email/mime/text.pyc' in names) def testWritePythonDirectory(self): os.mkdir(TESTFN2) @@ -571,9 +571,9 @@ class PyZipFileTests(unittest.TestCase): zipfp.writepy(TESTFN2) names = zipfp.namelist() - self.assert_('mod1.pyc' in names or 'mod1.pyo' in names) - self.assert_('mod2.pyc' in names or 'mod2.pyo' in names) - self.assert_('mod2.txt' not in names) + self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names) + self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names) + self.assertTrue('mod2.txt' not in names) finally: shutil.rmtree(TESTFN2) @@ -611,7 +611,7 @@ class OtherTests(unittest.TestCase): except IOError, (errno, errmsg): self.fail('Could not append data to a non-existent zip file.') - self.assert_(os.path.exists(TESTFN)) + self.assertTrue(os.path.exists(TESTFN)) zf = zipfile.ZipFile(TESTFN, 'r') self.assertEqual(zf.read(filename), content) @@ -640,19 +640,19 @@ class OtherTests(unittest.TestCase): with open(TESTFN, "w") as fp: fp.write("this is not a legal zip file\n") chk = zipfile.is_zipfile(TESTFN) - self.assert_(not chk) + self.assertTrue(not chk) # - passing a file object with open(TESTFN, "rb") as fp: chk = zipfile.is_zipfile(fp) - self.assert_(not chk) + self.assertTrue(not chk) # - passing a file-like object fp = StringIO() fp.write("this is not a legal zip file\n") chk = zipfile.is_zipfile(fp) - self.assert_(not chk) + self.assertTrue(not chk) fp.seek(0,0) chk = zipfile.is_zipfile(fp) - self.assert_(not chk) + self.assertTrue(not chk) def testIsZipValidFile(self): # This test checks that the is_zipfile function correctly identifies @@ -663,21 +663,21 @@ class OtherTests(unittest.TestCase): zipf.writestr("foo.txt", "O, for a Muse of Fire!") zipf.close() chk = zipfile.is_zipfile(TESTFN) - self.assert_(chk) + self.assertTrue(chk) # - passing a file object with open(TESTFN, "rb") as fp: chk = zipfile.is_zipfile(fp) - self.assert_(chk) + self.assertTrue(chk) fp.seek(0,0) zip_contents = fp.read() # - passing a file-like object fp = StringIO() fp.write(zip_contents) chk = zipfile.is_zipfile(fp) - self.assert_(chk) + self.assertTrue(chk) fp.seek(0,0) chk = zipfile.is_zipfile(fp) - self.assert_(chk) + self.assertTrue(chk) def testNonExistentFileRaisesIOError(self): # make sure we don't raise an AttributeError when a partially-constructed diff --git a/Lib/test/test_zipimport.py b/Lib/test/test_zipimport.py index 1543b3b..3072230 100644 --- a/Lib/test/test_zipimport.py +++ b/Lib/test/test_zipimport.py @@ -290,7 +290,7 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase): z.close() zi = zipimport.zipimporter(TEMP_ZIP) self.assertEquals(data, zi.get_data(name)) - self.assert_('zipimporter object' in repr(zi)) + self.assertTrue('zipimporter object' in repr(zi)) finally: z.close() os.remove(TEMP_ZIP) @@ -372,7 +372,7 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase): s = StringIO.StringIO() print_tb(tb, 1, s) - self.failUnless(s.getvalue().endswith(raise_src)) + self.assertTrue(s.getvalue().endswith(raise_src)) else: raise AssertionError("This ought to be impossible") diff --git a/Lib/test/test_zipimport_support.py b/Lib/test/test_zipimport_support.py index b416b81..1f02787 100644 --- a/Lib/test/test_zipimport_support.py +++ b/Lib/test/test_zipimport_support.py @@ -191,7 +191,7 @@ class ZipSupportTests(ImportHooksBaseTestCase): print "Expected line", expected print "Got stdout:" print data - self.assert_(expected in data) + self.assertTrue(expected in data) zip_name, run_name = _make_test_zip(d, "test_zip", script_name, '__main__.py') exit_code, data = _run_python(zip_name) @@ -200,7 +200,7 @@ class ZipSupportTests(ImportHooksBaseTestCase): print "Expected line", expected print "Got stdout:" print data - self.assert_(expected in data) + self.assertTrue(expected in data) def test_pdb_issue4201(self): test_src = textwrap.dedent("""\ @@ -215,13 +215,13 @@ class ZipSupportTests(ImportHooksBaseTestCase): p = _spawn_python(script_name) p.stdin.write('l\n') data = _kill_python(p) - self.assert_(script_name in data) + self.assertTrue(script_name in data) zip_name, run_name = _make_test_zip(d, "test_zip", script_name, '__main__.py') p = _spawn_python(zip_name) p.stdin.write('l\n') data = _kill_python(p) - self.assert_(run_name in data) + self.assertTrue(run_name in data) def test_main(): diff --git a/Lib/test/test_zlib.py b/Lib/test/test_zlib.py index cbf844f..f1f9d38 100644 --- a/Lib/test/test_zlib.py +++ b/Lib/test/test_zlib.py @@ -10,7 +10,7 @@ class ChecksumTestCase(unittest.TestCase): # checksum test cases def test_crc32start(self): self.assertEqual(zlib.crc32(""), zlib.crc32("", 0)) - self.assert_(zlib.crc32("abc", 0xffffffff)) + self.assertTrue(zlib.crc32("abc", 0xffffffff)) def test_crc32empty(self): self.assertEqual(zlib.crc32("", 0), 0) @@ -19,7 +19,7 @@ class ChecksumTestCase(unittest.TestCase): def test_adler32start(self): self.assertEqual(zlib.adler32(""), zlib.adler32("", 1)) - self.assert_(zlib.adler32("abc", 0xffffffff)) + self.assertTrue(zlib.adler32("abc", 0xffffffff)) def test_adler32empty(self): self.assertEqual(zlib.adler32("", 0), 0) @@ -208,7 +208,7 @@ class CompressObjectTestCase(unittest.TestCase): while cb: #max_length = 1 + len(cb)//10 chunk = dco.decompress(cb, dcx) - self.failIf(len(chunk) > dcx, + self.assertFalse(len(chunk) > dcx, 'chunk too big (%d>%d)' % (len(chunk), dcx)) bufs.append(chunk) cb = dco.unconsumed_tail @@ -233,7 +233,7 @@ class CompressObjectTestCase(unittest.TestCase): while cb: max_length = 1 + len(cb)//10 chunk = dco.decompress(cb, max_length) - self.failIf(len(chunk) > max_length, + self.assertFalse(len(chunk) > max_length, 'chunk too big (%d>%d)' % (len(chunk),max_length)) bufs.append(chunk) cb = dco.unconsumed_tail @@ -242,7 +242,7 @@ class CompressObjectTestCase(unittest.TestCase): else: while chunk: chunk = dco.decompress('', max_length) - self.failIf(len(chunk) > max_length, + self.assertFalse(len(chunk) > max_length, 'chunk too big (%d>%d)' % (len(chunk),max_length)) bufs.append(chunk) self.assertEqual(data, ''.join(bufs), 'Wrong data retrieved') @@ -316,7 +316,7 @@ class CompressObjectTestCase(unittest.TestCase): # caused a core dump.) co = zlib.compressobj(zlib.Z_BEST_COMPRESSION) - self.failUnless(co.flush()) # Returns a zlib header + self.assertTrue(co.flush()) # Returns a zlib header dco = zlib.decompressobj() self.assertEqual(dco.flush(), "") # Returns nothing |