diff options
275 files changed, 4545 insertions, 4545 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 6bed1f1..ca1edcf 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 8b5476d..c0cdfd5 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 = list(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], b"a") - self.failUnlessEqual(ca[1], b"b") - self.failUnlessEqual(ca[2], b"c") - self.failUnlessEqual(ca[-3], b"a") - self.failUnlessEqual(ca[-2], b"b") - self.failUnlessEqual(ca[-1], b"c") + self.assertEqual(ca[0], b"a") + self.assertEqual(ca[1], b"b") + self.assertEqual(ca[2], b"c") + self.assertEqual(ca[-3], b"a") + self.assertEqual(ca[-2], b"b") + self.assertEqual(ca[-1], b"c") - self.failUnlessEqual(len(ca), 3) + self.assertEqual(len(ca), 3) # cannot delete items from operator import delitem @@ -69,34 +69,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[:], b"foo") - self.failUnlessEqual(sz[::], b"foo") - self.failUnlessEqual(sz[::-1], b"oof") - self.failUnlessEqual(sz[::3], b"f") - self.failUnlessEqual(sz[1:4:2], b"o") - self.failUnlessEqual(sz.value, b"foo") + self.assertEqual(sz[:], b"foo") + self.assertEqual(sz[::], b"foo") + self.assertEqual(sz[::-1], b"oof") + self.assertEqual(sz[::3], b"f") + self.assertEqual(sz[1:4:2], b"o") + self.assertEqual(sz.value, b"foo") try: create_unicode_buffer @@ -106,12 +106,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, @@ -125,7 +125,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 884361c..835398f 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("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)) + self.assertTrue(isinstance(value, int)) 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 de1c619..4eb9571 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 1f4091e..3f8a587 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 bytes) + self.assertEqual(len(b), 32) + self.assertEqual(sizeof(b), 32 * sizeof(c_char)) + self.assertTrue(type(b[0]) is bytes) 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 bytes) - self.failUnlessEqual(b[0], b"a") - self.failUnlessEqual(b[:], b"abc\0") - self.failUnlessEqual(b[::], b"abc\0") - self.failUnlessEqual(b[::-1], b"\0cba") - self.failUnlessEqual(b[::2], b"ac") - self.failUnlessEqual(b[::5], b"a") + self.assertEqual(len(b), 4) # trailing nul char + self.assertEqual(sizeof(b), 4 * sizeof(c_char)) + self.assertTrue(type(b[0]) is bytes) + self.assertEqual(b[0], b"a") + self.assertEqual(b[:], b"abc\0") + self.assertEqual(b[::], b"abc\0") + self.assertEqual(b[::-1], b"\0cba") + self.assertEqual(b[::2], b"ac") + self.assertEqual(b[::5], b"a") def test_string_conversion(self): 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 bytes) - self.failUnlessEqual(b[0], b"a") - self.failUnlessEqual(b[:], b"abc\0") - self.failUnlessEqual(b[::], b"abc\0") - self.failUnlessEqual(b[::-1], b"\0cba") - self.failUnlessEqual(b[::2], b"ac") - self.failUnlessEqual(b[::5], b"a") + self.assertEqual(len(b), 4) # trailing nul char + self.assertEqual(sizeof(b), 4 * sizeof(c_char)) + self.assertTrue(type(b[0]) is bytes) + self.assertEqual(b[0], b"a") + self.assertEqual(b[:], b"abc\0") + self.assertEqual(b[::], b"abc\0") + self.assertEqual(b[::-1], b"\0cba") + self.assertEqual(b[::2], b"ac") + self.assertEqual(b[::5], b"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 str) + self.assertEqual(len(b), 32) + self.assertEqual(sizeof(b), 32 * sizeof(c_wchar)) + self.assertTrue(type(b[0]) is str) 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 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_wchar)) + 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_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 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_wchar)) + 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") if __name__ == "__main__": unittest.main() diff --git a/Lib/ctypes/test/test_byteswap.py b/Lib/ctypes/test/test_byteswap.py index 67fa44b..83cb667 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, places=6) + self.assertAlmostEqual(s.value, math.pi, places=6) s = c_float.__ctype_le__(math.pi) - self.failUnlessAlmostEqual(s.value, math.pi, places=6) - self.failUnlessEqual(bin(struct.pack("<f", math.pi)), bin(s)) + self.assertAlmostEqual(s.value, math.pi, places=6) + self.assertEqual(bin(struct.pack("<f", math.pi)), bin(s)) s = c_float.__ctype_be__(math.pi) - self.failUnlessAlmostEqual(s.value, math.pi, places=6) - self.failUnlessEqual(bin(struct.pack(">f", math.pi)), bin(s)) + self.assertAlmostEqual(s.value, math.pi, places=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 bf580ae..1bef33f 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.__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.__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 cb7524e..04ed5ca 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': b"foo bar"}) + self.assertEqual(array._objects, {'0': b"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': b"foo bar", id(array): array}) + self.assertTrue(p._objects is array._objects) + self.assertEqual(array._objects, {'0': b"foo bar", id(array): array}) p[0] = "spam spam" - self.failUnlessEqual(p._objects, {'0': b"spam spam", id(array): array}) - self.failUnless(array._objects is p._objects) + self.assertEqual(p._objects, {'0': b"spam spam", id(array): array}) + self.assertTrue(array._objects is p._objects) p[1] = "foo bar" - self.failUnlessEqual(p._objects, {'1': b'foo bar', '0': b"spam spam", id(array): array}) - self.failUnless(array._objects is p._objects) + self.assertEqual(p._objects, {'1': b'foo bar', '0': b"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 dc05093..c54b69b 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 23e2dcb..92d6158 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[:], list(range(16))) diff --git a/Lib/ctypes/test/test_funcptr.py b/Lib/ctypes/test/test_funcptr.py index 56099cc..1b29317 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, b"\n"), "a") - self.failUnlessEqual(strtok(None, b"\n"), "b") - self.failUnlessEqual(strtok(None, b"\n"), "c") - self.failUnlessEqual(strtok(None, b"\n"), None) + self.assertEqual(strtok(b, b"\n"), "a") + self.assertEqual(strtok(None, b"\n"), "b") + self.assertEqual(strtok(None, b"\n"), "c") + self.assertEqual(strtok(None, b"\n"), None) if __name__ == '__main__': unittest.main() diff --git a/Lib/ctypes/test/test_functions.py b/Lib/ctypes/test/test_functions.py index 3af11cc..303ce07 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, "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, '\x00') + self.assertEqual(result, '\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(b"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)) + self.assertTrue(isinstance(value, int)) 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 e4dfe36..94928c8 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 c6a51a7..f7d9a1b 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 rc = grc(i) ci = c_int(i) - self.failUnlessEqual(rc, grc(i)) - self.failUnlessEqual(ci._objects, None) + self.assertEqual(rc, grc(i)) + self.assertEqual(ci._objects, None) def test_c_char_p(self): s = b"Hello, World" rc = grc(s) cs = c_char_p(s) - self.failUnlessEqual(rc + 1, grc(s)) - self.failUnlessSame(cs._objects, s) + self.assertEqual(rc + 1, 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,12 +76,12 @@ class ObjectsTestCase(unittest.TestCase): x = X() x.a = s1 x.b = s2 - self.failUnlessEqual(x._objects, {"0": bytes(s1, "ascii"), + self.assertEqual(x._objects, {"0": bytes(s1, "ascii"), "1": bytes(s2, "ascii")}) y = Y() y.x = x - self.failUnlessEqual(y._objects, {"0": {"0": bytes(s1, "ascii"), + self.assertEqual(y._objects, {"0": {"0": bytes(s1, "ascii"), "1": bytes(s2, "ascii")}}) ## x = y.x ## del y @@ -93,7 +93,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 75e227c..b90765a 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 fa4c0c9..cce409f 100644 --- a/Lib/ctypes/test/test_libc.py +++ b/Lib/ctypes/test/test_libc.py @@ -13,9 +13,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)) @@ -27,7 +27,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, b" ,,aaaadmmmnpppsss\x00") + self.assertEqual(chars.raw, b" ,,aaaadmmmnpppsss\x00") if __name__ == "__main__": unittest.main() diff --git a/Lib/ctypes/test/test_loading.py b/Lib/ctypes/test/test_loading.py index b83828a..07b69ec 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 4bee77f..7082b55 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 = b"Hello, World" result = memmove(a, p, len(p)) - self.failUnlessEqual(a.value, b"Hello, World") + self.assertEqual(a.value, b"Hello, World") - self.failUnlessEqual(string_at(result), b"Hello, World") - self.failUnlessEqual(string_at(result, 5), b"Hello") - self.failUnlessEqual(string_at(result, 16), b"Hello, World\0\0\0\0") - self.failUnlessEqual(string_at(result, 0), b"") + self.assertEqual(string_at(result), b"Hello, World") + self.assertEqual(string_at(result, 5), b"Hello") + self.assertEqual(string_at(result, 16), b"Hello, World\0\0\0\0") + self.assertEqual(string_at(result, 0), b"") def test_memset(self): a = create_string_buffer(1000000) result = memset(a, ord('x'), 16) - self.failUnlessEqual(a.value, b"xxxxxxxxxxxxxxxx") + self.assertEqual(a.value, b"xxxxxxxxxxxxxxxx") - self.failUnlessEqual(string_at(result), b"xxxxxxxxxxxxxxxx") - self.failUnlessEqual(string_at(a), b"xxxxxxxxxxxxxxxx") - self.failUnlessEqual(string_at(a, 20), b"xxxxxxxxxxxxxxxx\0\0\0\0") + self.assertEqual(string_at(result), b"xxxxxxxxxxxxxxxx") + self.assertEqual(string_at(a), b"xxxxxxxxxxxxxxxx") + self.assertEqual(string_at(a, 20), b"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(b"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(b"foo bar", 7), b"foo bar") - self.failUnlessEqual(string_at(b"foo bar", 3), b"foo") + self.assertEqual(string_at(b"foo bar", 7), b"foo bar") + self.assertEqual(string_at(b"foo bar", 3), b"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 c0732de..24d7293 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(2).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(2).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 @@ -193,11 +193,11 @@ class NumberTestCase(unittest.TestCase): a = array('b', [0]) a[0] = ord('x') v = c_char.from_address(a.buffer_info()[0]) - self.failUnlessEqual(v.value, b'x') - self.failUnless(type(v) is c_char) + self.assertEqual(v.value, b'x') + self.assertTrue(type(v) is c_char) a[0] = ord('?') - self.failUnlessEqual(v.value, b'?') + self.assertEqual(v.value, b'?') # array does not support c_bool / 't' # def test_bool_from_address(self): @@ -205,11 +205,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 4c80bdf..10eddd4 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 = b"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("123")._obj, b"123") + self.assertEqual(c_char_p.from_param("123")._obj, b"123") self.assertRaises(UnicodeEncodeError, c_char_p.from_param, "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 = "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, "123") + self.assertEqual(c_wchar_p.from_param("123")._obj, "123") self.assertRaises(UnicodeDecodeError, c_wchar_p.from_param, b"123\377") pa = c_wchar_p.from_param(c_wchar_p("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 b839ac2..fa6461f 100644 --- a/Lib/ctypes/test/test_pep3118.py +++ b/Lib/ctypes/test/test_pep3118.py @@ -24,23 +24,23 @@ class Test(unittest.TestCase): ob = tp() v = memoryview(ob) try: - self.failUnlessEqual(normalize(v.format), normalize(fmt)) + self.assertEqual(normalize(v.format), normalize(fmt)) if shape is not None: - self.failUnlessEqual(len(v), shape[0]) + self.assertEqual(len(v), shape[0]) else: - self.failUnlessEqual(len(v) * sizeof(itemtp), sizeof(ob)) - self.failUnlessEqual(v.itemsize, sizeof(itemtp)) - self.failUnlessEqual(v.shape, shape) + self.assertEqual(len(v) * sizeof(itemtp), 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(n * v.itemsize, len(v.tobytes())) + self.assertEqual(n * v.itemsize, len(v.tobytes())) except: # so that we can see the failing type print(tp) @@ -51,23 +51,23 @@ class Test(unittest.TestCase): ob = tp() v = memoryview(ob) try: - self.failUnlessEqual(v.format, fmt) + self.assertEqual(v.format, fmt) if shape is not None: - self.failUnlessEqual(len(v), shape[0]) + self.assertEqual(len(v), shape[0]) else: - self.failUnlessEqual(len(v) * sizeof(itemtp), sizeof(ob)) - self.failUnlessEqual(v.itemsize, sizeof(itemtp)) - self.failUnlessEqual(v.shape, shape) + self.assertEqual(len(v) * sizeof(itemtp), 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(n, len(v)) + self.assertEqual(n, len(v)) 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 d88f08b..8c91222 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(memoryview(src).tobytes(), + self.assertEqual(src.__dict__, dst.__dict__) + self.assertEqual(memoryview(src).tobytes(), memoryview(dst).tobytes()) 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(memoryview(y).tobytes(), + self.assertEqual(y.__dict__, x.__dict__) + self.assertEqual(memoryview(y).tobytes(), memoryview(x).tobytes()) def test_unpickable(self): diff --git a/Lib/ctypes/test/test_pointers.py b/Lib/ctypes/test/test_pointers.py index 86429c0..6e61d30 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(0xFFFFFFFF).value, + self.assertEqual(c_void_p(0xFFFFFFFF).value, c_void_p(-1).value) - self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFF).value, + self.assertEqual(c_void_p(0xFFFFFFFFFFFFFFFF).value, c_void_p(-1).value) elif sizeof(c_void_p) == 8: - self.failUnlessEqual(c_void_p(0xFFFFFFFF).value, + self.assertEqual(c_void_p(0xFFFFFFFF).value, 0xFFFFFFFF) - self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFF).value, + self.assertEqual(c_void_p(0xFFFFFFFFFFFFFFFF).value, c_void_p(-1).value) - self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFFFFFFFFFF).value, + self.assertEqual(c_void_p(0xFFFFFFFFFFFFFFFFFFFFFFFF).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 e098e7b..9041750 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 as 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(b"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(b"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("123", func(c_wchar_p("123"))) + self.assertEqual(None, func(c_wchar_p(None))) + self.assertEqual("123", func(c_wchar_p("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("123", func("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("123")) + self.assertEqual(None, func(c_wchar_p(None))) + self.assertEqual("123", func(c_wchar_p("123"))) - 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]) def test_c_wchar_p_arg(self): func = testdll._testfunc_p_p @@ -191,16 +191,16 @@ else: c_wchar_p.from_param("123") - self.failUnlessEqual(None, func(None)) - self.failUnlessEqual("123", func("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("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 674f9ab..b74767a 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): PyBytes_FromStringAndSize.restype = py_object PyBytes_FromStringAndSize.argtypes = c_char_p, c_py_ssize_t - self.failUnlessEqual(PyBytes_FromStringAndSize(b"abcdefghi", 3), b"abc") + self.assertEqual(PyBytes_FromStringAndSize(b"abcdefghi", 3), b"abc") def test_PyString_FromString(self): pythonapi.PyBytes_FromString.restype = py_object @@ -32,10 +32,10 @@ class PythonAPITestCase(unittest.TestCase): s = b"abc" refcnt = grc(s) pyob = pythonapi.PyBytes_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_PyLong_Long(self): ref42 = grc(42) pythonapi.PyLong_FromLong.restype = py_object - self.failUnlessEqual(pythonapi.PyLong_FromLong(42), 42) + self.assertEqual(pythonapi.PyLong_FromLong(42), 42) - self.failUnlessEqual(grc(42), ref42) + self.assertEqual(grc(42), ref42) pythonapi.PyLong_AsLong.argtypes = (py_object,) pythonapi.PyLong_AsLong.restype = c_long res = pythonapi.PyLong_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", b"ctypes") - self.failUnlessEqual(buf.value, b"Hello from ctypes") + self.assertEqual(buf.value, b"Hello from ctypes") PyOS_snprintf(buf, sizeof(buf), "Hello from %s (%d, %d, %d)", b"ctypes", 1, 2, 3) - self.failUnlessEqual(buf.value, b"Hello from ctypes (1, 2, 3)") + self.assertEqual(buf.value, b"Hello from ctypes (1, 2, 3)") # 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 6b2c1b1..2520a5e 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(b"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 3f1e819..9a1e238 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(b'x')", repr(c_char('x'))) - self.failUnlessEqual("<X object at", repr(X('x'))[:12]) + self.assertEqual("c_char(b'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 cd451a2..ae8c26a 100644 --- a/Lib/ctypes/test/test_returnfuncptrs.py +++ b/Lib/ctypes/test/test_returnfuncptrs.py @@ -12,10 +12,10 @@ 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.failUnlessEqual(strchr("abcdef", 98), "bcdef") - self.failUnlessEqual(strchr("abcdef", 107), None) + self.assertEqual(strchr("abcdef", "b"), "bcdef") + self.assertEqual(strchr("abcdef", "x"), None) + self.assertEqual(strchr("abcdef", 98), "bcdef") + self.assertEqual(strchr("abcdef", 107), None) self.assertRaises(ArgumentError, strchr, "abcdef", 3.0) self.assertRaises(TypeError, strchr, "abcdef") @@ -28,8 +28,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.0) self.assertRaises(TypeError, strchr, "abcdef") diff --git a/Lib/ctypes/test/test_simplesubclasses.py b/Lib/ctypes/test/test_simplesubclasses.py index 420c0a0..3da2794 100644 --- a/Lib/ctypes/test/test_simplesubclasses.py +++ b/Lib/ctypes/test/test_simplesubclasses.py @@ -10,8 +10,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 @@ -21,7 +21,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): @@ -32,24 +32,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 7c863c1..5343917 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)(*range(1100, 1200)) b = list(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], list(range(5, 10))) - self.failUnlessEqual(a[0:5:], list(range(5, 10))) - self.failUnlessEqual(a[4::-1], list(range(9, 4, -1))) + self.assertEqual(a[0:5], list(range(5, 10))) + self.assertEqual(a[0:5:], list(range(5, 10))) + self.assertEqual(a[4::-1], list(range(9, 4, -1))) def test_setslice_cint(self): a = (c_int * 100)(*range(1100, 1200)) b = list(range(1100, 1200)) a[32:47] = list(range(32, 47)) - self.failUnlessEqual(a[32:47], list(range(32, 47))) + self.assertEqual(a[32:47], list(range(32, 47))) a[32:47] = range(132, 147) - self.failUnlessEqual(a[32:47:], list(range(132, 147))) + self.assertEqual(a[32:47:], list(range(132, 147))) a[46:31:-1] = range(232, 247) - self.failUnlessEqual(a[32:47:1], list(range(246, 231, -1))) + self.assertEqual(a[32:47:1], list(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 setitem @@ -65,12 +65,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, @@ -88,8 +88,8 @@ class SlicesTestCase(unittest.TestCase): dll.my_strdup.restype = POINTER(c_byte) res = dll.my_strdup(s) - self.failUnlessEqual(res[:len(s)], list(range(ord("a"), ord("z")+1))) - self.failUnlessEqual(res[:len(s):], list(range(ord("a"), ord("z")+1))) + self.assertEqual(res[:len(s)], list(range(ord("a"), ord("z")+1))) + self.assertEqual(res[:len(s):], list(range(ord("a"), ord("z")+1))) dll.my_free(res) def test_char_ptr_with_free(self): @@ -109,7 +109,7 @@ class SlicesTestCase(unittest.TestCase): dll.my_strdup.errcheck = errcheck try: res = dll.my_strdup(s) - self.failUnlessEqual(res, s.decode()) + self.assertEqual(res, s.decode()) finally: del dll.my_strdup.errcheck @@ -118,11 +118,11 @@ class SlicesTestCase(unittest.TestCase): s = b"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: @@ -138,10 +138,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.setitem, @@ -158,10 +158,10 @@ class SlicesTestCase(unittest.TestCase): return res = dll.my_wcsdup(s) tmpl = list(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 a5a471c..84126f5 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, (b"c", b"d", b"e", b"f", b"\000")) + self.assertEqual(x, (b"c", b"d", b"e", b"f", b"\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 ef1cfcf..3cd1f84 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, b"abc") - self.failUnlessEqual(buf.raw, b"abc\000") + self.assertEqual(buf.value, b"abc") + self.assertEqual(buf.raw, b"abc\000") buf.value = "ABCD" - self.failUnlessEqual(buf.value, b"ABCD") - self.failUnlessEqual(buf.raw, b"ABCD") + self.assertEqual(buf.value, b"ABCD") + self.assertEqual(buf.raw, b"ABCD") buf.value = "x" - self.failUnlessEqual(buf.value, b"x") - self.failUnlessEqual(buf.raw, b"x\000CD") + self.assertEqual(buf.value, b"x") + self.assertEqual(buf.raw, b"x\000CD") buf[1] = "Z" - self.failUnlessEqual(buf.value, b"xZCD") - self.failUnlessEqual(buf.raw, b"xZCD") + self.assertEqual(buf.value, b"xZCD") + self.assertEqual(buf.raw, b"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 = b"Hello, World" - self.failUnlessEqual(buf.value, b"Hello, World") + self.assertEqual(buf.value, b"Hello, World") - self.failUnlessRaises(TypeError, setattr, buf, "value", memoryview(b"Hello, World")) + self.assertRaises(TypeError, setattr, buf, "value", memoryview(b"Hello, World")) self.assertRaises(TypeError, setattr, buf, "value", memoryview(b"abc")) self.assertRaises(ValueError, setattr, buf, "raw", memoryview(b"x" * 100)) @@ -38,7 +38,7 @@ class StringArrayTestCase(unittest.TestCase): buf = c_buffer(32) buf.raw = memoryview(b"Hello, World") - self.failUnlessEqual(buf.value, b"Hello, World") + self.assertEqual(buf.value, b"Hello, World") self.assertRaises(TypeError, setattr, buf, "value", memoryview(b"abc")) self.assertRaises(ValueError, setattr, buf, "raw", memoryview(b"x" * 100)) @@ -63,16 +63,16 @@ else: BUF = c_wchar * 4 buf = BUF("a", "b", "c") - self.failUnlessEqual(buf.value, "abc") + self.assertEqual(buf.value, "abc") buf.value = "ABCD" - self.failUnlessEqual(buf.value, "ABCD") + self.assertEqual(buf.value, "ABCD") buf.value = "x" - self.failUnlessEqual(buf.value, "x") + self.assertEqual(buf.value, "x") buf[1] = "Z" - self.failUnlessEqual(buf.value, "xZCD") + self.assertEqual(buf.value, "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, "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 == "abcdef") - self.failUnless(c_wstring("abc\000def").value == "abc") + self.assertTrue(cs.value == "abcdef") + self.assertTrue(c_wstring("abc\000def").value == "abc") - self.failUnless(c_wstring("abc\000def").value == "abc") + self.assertTrue(c_wstring("abc\000def").value == "abc") # The raw property is the total buffer contents: - self.failUnless(cs.raw == "abcdef\000") - self.failUnless(c_wstring("abc\000def").raw == "abc\000def\000") + self.assertTrue(cs.raw == "abcdef\000") + self.assertTrue(c_wstring("abc\000def").raw == "abc\000def\000") # We can change the value: cs.value = "ab" - self.failUnless(cs.value == "ab") - self.failUnless(cs.raw == "ab\000\000\000\000\000") + self.assertTrue(cs.value == "ab") + self.assertTrue(cs.raw == "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 3587f0f..23468dc 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("Someone") - self.failUnlessEqual(p.name, "Someone") + self.assertEqual(p.name, "Someone") - self.failUnlessEqual(PersonW("1234567890").name, "1234567890") - self.failUnlessEqual(PersonW("12345678901").name, "12345678901") + self.assertEqual(PersonW("1234567890").name, "1234567890") + self.assertEqual(PersonW("12345678901").name, "12345678901") # exact fit - self.failUnlessEqual(PersonW("123456789012").name, "123456789012") + self.assertEqual(PersonW("123456789012").name, "123456789012") #too long self.assertRaises(ValueError, PersonW, "1234567890123") @@ -305,18 +305,18 @@ class StructureTestCase(unittest.TestCase): ("age", c_int)] cls, msg = self.get_except(Person, "Someone", (1, 2)) - self.failUnlessEqual(cls, RuntimeError) - self.failUnlessEqual(msg, + self.assertEqual(cls, RuntimeError) + self.assertEqual(msg, "(Phone) <class 'TypeError'>: " "expected string, 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) <class 'TypeError'>: too many initializers") else: - self.failUnlessEqual(msg, "(Phone) TypeError: too many initializers") + self.assertEqual(msg, "(Phone) TypeError: too many initializers") def get_except(self, func, *args): @@ -331,7 +331,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): @@ -339,15 +339,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): @@ -360,7 +360,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. @@ -371,14 +371,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): @@ -388,7 +388,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): @@ -398,7 +398,7 @@ class TestRecursiveStructure(unittest.TestCase): try: Recursive._fields_ = [("next", Recursive)] except AttributeError as 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") @@ -415,7 +415,7 @@ class TestRecursiveStructure(unittest.TestCase): try: Second._fields_ = [("first", First)] except AttributeError as 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 0eae59b..7d628f2 100644 --- a/Lib/ctypes/test/test_unicode.py +++ b/Lib/ctypes/test/test_unicode.py @@ -22,55 +22,55 @@ else: def test_ascii_strict(self): ctypes.set_conversion_mode("ascii", "strict") # no conversions take place with unicode arguments - self.failUnlessEqual(wcslen("abc"), 3) - self.failUnlessEqual(wcslen("ab\u2070"), 3) + self.assertEqual(wcslen("abc"), 3) + self.assertEqual(wcslen("ab\u2070"), 3) # string args are converted - self.failUnlessEqual(wcslen("abc"), 3) - self.failUnlessRaises(ctypes.ArgumentError, wcslen, b"ab\xe4") + self.assertEqual(wcslen("abc"), 3) + self.assertRaises(ctypes.ArgumentError, wcslen, b"ab\xe4") def test_ascii_replace(self): ctypes.set_conversion_mode("ascii", "replace") - self.failUnlessEqual(wcslen("abc"), 3) - self.failUnlessEqual(wcslen("ab\u2070"), 3) - self.failUnlessEqual(wcslen("abc"), 3) - self.failUnlessEqual(wcslen("ab\xe4"), 3) + self.assertEqual(wcslen("abc"), 3) + self.assertEqual(wcslen("ab\u2070"), 3) + self.assertEqual(wcslen("abc"), 3) + self.assertEqual(wcslen("ab\xe4"), 3) def test_ascii_ignore(self): ctypes.set_conversion_mode("ascii", "ignore") - self.failUnlessEqual(wcslen("abc"), 3) - self.failUnlessEqual(wcslen("ab\u2070"), 3) + self.assertEqual(wcslen("abc"), 3) + self.assertEqual(wcslen("ab\u2070"), 3) # ignore error mode skips non-ascii characters - self.failUnlessEqual(wcslen("abc"), 3) - self.failUnlessEqual(wcslen(b"\xe4\xf6\xfc\xdf"), 0) + self.assertEqual(wcslen("abc"), 3) + self.assertEqual(wcslen(b"\xe4\xf6\xfc\xdf"), 0) def test_latin1_strict(self): ctypes.set_conversion_mode("latin-1", "strict") - self.failUnlessEqual(wcslen("abc"), 3) - self.failUnlessEqual(wcslen("ab\u2070"), 3) - self.failUnlessEqual(wcslen("abc"), 3) - self.failUnlessEqual(wcslen("\xe4\xf6\xfc\xdf"), 4) + self.assertEqual(wcslen("abc"), 3) + self.assertEqual(wcslen("ab\u2070"), 3) + self.assertEqual(wcslen("abc"), 3) + self.assertEqual(wcslen("\xe4\xf6\xfc\xdf"), 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(b"ab\xe4\xf6\xfc") - self.failUnlessEqual(buf[:], "ab\uFFFD\uFFFD\uFFFD\0") - self.failUnlessEqual(buf[::], "ab\uFFFD\uFFFD\uFFFD\0") - self.failUnlessEqual(buf[::-1], "\0\uFFFD\uFFFD\uFFFDba") - self.failUnlessEqual(buf[::2], "a\uFFFD\uFFFD") - self.failUnlessEqual(buf[6:5:-1], "") + self.assertEqual(buf[:], "ab\uFFFD\uFFFD\uFFFD\0") + self.assertEqual(buf[::], "ab\uFFFD\uFFFD\uFFFD\0") + self.assertEqual(buf[::-1], "\0\uFFFD\uFFFD\uFFFDba") + self.assertEqual(buf[::2], "a\uFFFD\uFFFD") + self.assertEqual(buf[6:5:-1], "") ctypes.set_conversion_mode("ascii", "ignore") buf = ctypes.create_unicode_buffer(b"ab\xe4\xf6\xfc") # 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.failUnlessEqual(buf[::2], "a\0\0") - self.failUnlessEqual(buf[6:5:-1], "") + self.assertEqual(buf[:], "ab\0\0\0\0") + self.assertEqual(buf[::], "ab\0\0\0\0") + self.assertEqual(buf[::-1], "\0\0\0\0ba") + self.assertEqual(buf[::2], "a\0\0") + self.assertEqual(buf[6:5:-1], "") import _ctypes_test func = ctypes.CDLL(_ctypes_test.__file__)._testfunc_p_p @@ -88,41 +88,41 @@ else: def test_ascii_replace(self): ctypes.set_conversion_mode("ascii", "strict") - self.failUnlessEqual(func("abc"), "abc") - self.failUnlessEqual(func("abc"), "abc") + self.assertEqual(func("abc"), "abc") + self.assertEqual(func("abc"), "abc") self.assertRaises(ctypes.ArgumentError, func, "ab\xe4") def test_ascii_ignore(self): ctypes.set_conversion_mode("ascii", "ignore") - self.failUnlessEqual(func("abc"), "abc") - self.failUnlessEqual(func("abc"), "abc") - self.failUnlessEqual(func("\xe4\xf6\xfc\xdf"), "") + self.assertEqual(func("abc"), "abc") + self.assertEqual(func("abc"), "abc") + self.assertEqual(func("\xe4\xf6\xfc\xdf"), "") def test_ascii_replace(self): ctypes.set_conversion_mode("ascii", "replace") - self.failUnlessEqual(func("abc"), "abc") - self.failUnlessEqual(func("abc"), "abc") - self.failUnlessEqual(func("\xe4\xf6\xfc\xdf"), "????") + self.assertEqual(func("abc"), "abc") + self.assertEqual(func("abc"), "abc") + self.assertEqual(func("\xe4\xf6\xfc\xdf"), "????") def test_buffers(self): ctypes.set_conversion_mode("ascii", "strict") buf = ctypes.create_string_buffer("abc") - self.failUnlessEqual(len(buf), 3+1) + self.assertEqual(len(buf), 3+1) ctypes.set_conversion_mode("ascii", "replace") buf = ctypes.create_string_buffer("ab\xe4\xf6\xfc") - self.failUnlessEqual(buf[:], b"ab???\0") - self.failUnlessEqual(buf[::], b"ab???\0") - self.failUnlessEqual(buf[::-1], b"\0???ba") - self.failUnlessEqual(buf[::2], b"a??") - self.failUnlessEqual(buf[6:5:-1], b"") + self.assertEqual(buf[:], b"ab???\0") + self.assertEqual(buf[::], b"ab???\0") + self.assertEqual(buf[::-1], b"\0???ba") + self.assertEqual(buf[::2], b"a??") + self.assertEqual(buf[6:5:-1], b"") ctypes.set_conversion_mode("ascii", "ignore") buf = ctypes.create_string_buffer("ab\xe4\xf6\xfc") # is that correct? not sure. But with 'ignore', you get what you pay for.. - self.failUnlessEqual(buf[:], b"ab\0\0\0\0") - self.failUnlessEqual(buf[::], b"ab\0\0\0\0") - self.failUnlessEqual(buf[::-1], b"\0\0\0\0ba") + self.assertEqual(buf[:], b"ab\0\0\0\0") + self.assertEqual(buf[::], b"ab\0\0\0\0") + self.assertEqual(buf[::-1], b"\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 476b7b7..e464102 100644 --- a/Lib/ctypes/test/test_values.py +++ b/Lib/ctypes/test/test_values.py @@ -15,13 +15,13 @@ 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()) # To avoid test failures when this test is repeated several # times the original value must be restored an_integer.value = x - self.failUnlessEqual(x, ctdll.get_an_integer()) + self.assertEqual(x, ctdll.get_an_integer()) def test_undefined(self): ctdll = CDLL(_ctypes_test.__file__) @@ -40,11 +40,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 @@ -76,7 +76,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 663b335..d88e0b3 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 fe6009b..08e3e1f 100644 --- a/Lib/distutils/tests/test_build_ext.py +++ b/Lib/distutils/tests/test_build_ext.py @@ -74,15 +74,15 @@ class BuildExtTestCase(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(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(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(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(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(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(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(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(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 75b6624..8ad3bbc 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 0f97cf7..879689d 100644 --- a/Lib/distutils/tests/test_config.py +++ b/Lib/distutils/tests/test_config.py @@ -102,9 +102,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 16ef68e..c031cb8 100644 --- a/Lib/distutils/tests/test_dist.py +++ b/Lib/distutils/tests/test_dist.py @@ -72,7 +72,7 @@ class DistributionTestCase(support.LoggingSilencer, 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): @@ -175,10 +175,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", @@ -190,9 +190,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, @@ -210,11 +210,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, @@ -232,11 +232,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, @@ -270,14 +270,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) @@ -303,7 +303,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 11e5a47..7382798 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, "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 d9ff3ec..c03ad10 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 input and getpass.getpass # so register gets happy @@ -115,7 +115,7 @@ class RegisterTestCase(PyPIRCCommandTestCase): del register_module.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_((b'xxx') in self.conn.reqs[1].data) + self.assertTrue((b'xxx') in self.conn.reqs[1].data) def test_password_not_in_file(self): @@ -165,11 +165,11 @@ class RegisterTestCase(PyPIRCCommandTestCase): del register_module.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_((b'tarek') in req.data) + self.assertTrue((b'tarek') in req.data) def test_password_reset(self): # this test runs choice 3 @@ -183,11 +183,11 @@ class RegisterTestCase(PyPIRCCommandTestCase): del register_module.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_((b'tarek') in req.data) + self.assertTrue((b'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 2d8fa27..eb36204 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 aaeaffd..9281885 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'], '2087') - 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_(b'xxx' in self.last_open.req.data) + self.assertTrue(b'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 86e3537..25885c7 100644 --- a/Lib/email/test/test_email.py +++ b/Lib/email/test/test_email.py @@ -53,7 +53,7 @@ def openfile(filename, *args, **kws): # 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) @@ -222,12 +222,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.ndiffAssertEqual @@ -237,7 +237,7 @@ class TestMessageAPI(TestEmailBase): eq(text, str(msg)) fullrepr = msg.as_string(unixfrom=True) 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): @@ -307,12 +307,12 @@ class TestMessageAPI(TestEmailBase): '"Jim&&Jill"') def test_field_containment(self): - unless = self.failUnless + unless = self.assertTrue msg = email.message_from_string('Header: exists') unless('header' in msg) unless('Header' in msg) unless('HEADER' in msg) - self.failIf('headerx' in msg) + self.assertFalse('headerx' in msg) def test_set_param(self): eq = self.assertEqual @@ -952,7 +952,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'], @@ -992,7 +992,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'], @@ -1036,7 +1036,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 = [] @@ -1046,7 +1046,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 @@ -1097,7 +1097,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 @@ -1411,7 +1411,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) @@ -1441,7 +1441,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) @@ -1451,7 +1451,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) @@ -1509,7 +1509,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) @@ -1529,7 +1529,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): @@ -1539,7 +1539,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') @@ -1607,7 +1607,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 @@ -1651,20 +1651,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') @@ -2002,7 +2002,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') @@ -2024,7 +2024,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) @@ -2034,7 +2034,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') @@ -2044,9 +2044,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') @@ -2077,7 +2077,7 @@ class TestMiscellaneous(TestEmailBase): self.assertEqual(text, s.getvalue()) def test_message_from_string_with_class(self): - unless = self.failUnless + unless = self.assertTrue with openfile('msg_01.txt') as fp: text = fp.read() @@ -2095,7 +2095,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 @@ -2217,7 +2217,7 @@ Foo def test_charset_richcomparisons(self): eq = self.assertEqual - ne = self.failIfEqual + ne = self.assertNotEqual cset1 = Charset() cset2 = Charset() eq(cset1, 'us-ascii') @@ -2410,8 +2410,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 @@ -2613,18 +2613,18 @@ class TestQuopri(unittest.TestCase): def test_quopri_header_check(self): for c in self.hlit: - self.failIf(quoprimime.header_check(c), + self.assertFalse(quoprimime.header_check(c), 'Should not be header quopri encoded: %s' % chr(c)) for c in self.hnon: - self.failUnless(quoprimime.header_check(c), + self.assertTrue(quoprimime.header_check(c), 'Should be header quopri encoded: %s' % chr(c)) def test_quopri_body_check(self): for c in self.blit: - self.failIf(quoprimime.body_check(c), + self.assertFalse(quoprimime.body_check(c), 'Should not be body quopri encoded: %s' % chr(c)) for c in self.bnon: - self.failUnless(quoprimime.body_check(c), + self.assertTrue(quoprimime.body_check(c), 'Should be body quopri encoded: %s' % chr(c)) def test_header_quopri_len(self): @@ -2789,7 +2789,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 @@ -3166,7 +3166,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') @@ -3319,7 +3319,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): @@ -3343,7 +3343,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/importlib/test/builtin/test_finder.py b/Lib/importlib/test/builtin/test_finder.py index ef8e8fe..40f690e 100644 --- a/Lib/importlib/test/builtin/test_finder.py +++ b/Lib/importlib/test/builtin/test_finder.py @@ -14,7 +14,7 @@ class FinderTests(abc.FinderTests): # Common case. with util.uncache(builtin_util.NAME): found = machinery.BuiltinImporter.find_module(builtin_util.NAME) - self.assert_(found) + self.assertTrue(found) def test_package(self): # Built-in modules cannot be a package. @@ -35,14 +35,14 @@ class FinderTests(abc.FinderTests): def test_failure(self): assert 'importlib' not in sys.builtin_module_names loader = machinery.BuiltinImporter.find_module('importlib') - self.assert_(loader is None) + self.assertTrue(loader is None) def test_ignore_path(self): # The value for 'path' should always trigger a failed import. with util.uncache(builtin_util.NAME): loader = machinery.BuiltinImporter.find_module(builtin_util.NAME, ['pkg']) - self.assert_(loader is None) + self.assertTrue(loader is None) diff --git a/Lib/importlib/test/builtin/test_loader.py b/Lib/importlib/test/builtin/test_loader.py index cfedb5d..dff00ce 100644 --- a/Lib/importlib/test/builtin/test_loader.py +++ b/Lib/importlib/test/builtin/test_loader.py @@ -18,10 +18,10 @@ class LoaderTests(abc.LoaderTests): def verify(self, module): """Verify that the module matches against what it should have.""" - self.assert_(isinstance(module, types.ModuleType)) + self.assertTrue(isinstance(module, types.ModuleType)) for attr, value in self.verification.items(): self.assertEqual(getattr(module, attr), value) - self.assert_(module.__name__ in sys.modules) + self.assertTrue(module.__name__ in sys.modules) load_module = staticmethod(lambda name: machinery.BuiltinImporter.load_module(name)) @@ -49,7 +49,7 @@ class LoaderTests(abc.LoaderTests): with util.uncache(builtin_util.NAME): module1 = self.load_module(builtin_util.NAME) module2 = self.load_module(builtin_util.NAME) - self.assert_(module1 is module2) + self.assertTrue(module1 is module2) def test_unloadable(self): name = 'dssdsdfff' @@ -70,17 +70,17 @@ class InspectLoaderTests(unittest.TestCase): def test_get_code(self): # There is no code object. result = machinery.BuiltinImporter.get_code(builtin_util.NAME) - self.assert_(result is None) + self.assertTrue(result is None) def test_get_source(self): # There is no source. result = machinery.BuiltinImporter.get_source(builtin_util.NAME) - self.assert_(result is None) + self.assertTrue(result is None) def test_is_package(self): # Cannot be a package. result = machinery.BuiltinImporter.is_package(builtin_util.NAME) - self.assert_(not result) + self.assertTrue(not result) def test_not_builtin(self): # Modules not built-in should raise ImportError. diff --git a/Lib/importlib/test/extension/test_finder.py b/Lib/importlib/test/extension/test_finder.py index 39e26a7..546a176 100644 --- a/Lib/importlib/test/extension/test_finder.py +++ b/Lib/importlib/test/extension/test_finder.py @@ -13,7 +13,7 @@ class FinderTests(abc.FinderTests): return importer.find_module(fullname) def test_module(self): - self.assert_(self.find_module(util.NAME)) + self.assertTrue(self.find_module(util.NAME)) def test_package(self): # Extension modules cannot be an __init__ for a package. @@ -32,7 +32,7 @@ class FinderTests(abc.FinderTests): pass def test_failure(self): - self.assert_(self.find_module('asdfjkl;') is None) + self.assertTrue(self.find_module('asdfjkl;') is None) # XXX Raise an exception if someone tries to use the 'path' argument? diff --git a/Lib/importlib/test/extension/test_loader.py b/Lib/importlib/test/extension/test_loader.py index 157a3b6..71841c6 100644 --- a/Lib/importlib/test/extension/test_loader.py +++ b/Lib/importlib/test/extension/test_loader.py @@ -23,8 +23,8 @@ class LoaderTests(abc.LoaderTests): ('__file__', ext_util.FILEPATH), ('__package__', '')]: self.assertEqual(getattr(module, attr), value) - self.assert_(ext_util.NAME in sys.modules) - self.assert_(isinstance(module.__loader__, + self.assertTrue(ext_util.NAME in sys.modules) + self.assertTrue(isinstance(module.__loader__, _bootstrap._ExtensionFileLoader)) def test_package(self): @@ -39,7 +39,7 @@ class LoaderTests(abc.LoaderTests): with util.uncache(ext_util.NAME): module1 = self.load_module(ext_util.NAME) module2 = self.load_module(ext_util.NAME) - self.assert_(module1 is module2) + self.assertTrue(module1 is module2) def test_state_after_failure(self): # No easy way to trigger a failure after a successful import. diff --git a/Lib/importlib/test/extension/test_path_hook.py b/Lib/importlib/test/extension/test_path_hook.py index 8532956..bf2f411 100644 --- a/Lib/importlib/test/extension/test_path_hook.py +++ b/Lib/importlib/test/extension/test_path_hook.py @@ -19,7 +19,7 @@ class PathHookTests(unittest.TestCase): def test_success(self): # Path hook should handle a directory where a known extension module # exists. - self.assert_(hasattr(self.hook(util.PATH), 'find_module')) + self.assertTrue(hasattr(self.hook(util.PATH), 'find_module')) def test_main(): diff --git a/Lib/importlib/test/frozen/test_finder.py b/Lib/importlib/test/frozen/test_finder.py index 8caac48..db88379 100644 --- a/Lib/importlib/test/frozen/test_finder.py +++ b/Lib/importlib/test/frozen/test_finder.py @@ -15,15 +15,15 @@ class FinderTests(abc.FinderTests): def test_module(self): name = '__hello__' loader = self.find(name) - self.assert_(hasattr(loader, 'load_module')) + self.assertTrue(hasattr(loader, 'load_module')) def test_package(self): loader = self.find('__phello__') - self.assert_(hasattr(loader, 'load_module')) + self.assertTrue(hasattr(loader, 'load_module')) def test_module_in_package(self): loader = self.find('__phello__.spam', ['__phello__']) - self.assert_(hasattr(loader, 'load_module')) + self.assertTrue(hasattr(loader, 'load_module')) def test_package_in_package(self): # No frozen package within another package to test with. @@ -35,7 +35,7 @@ class FinderTests(abc.FinderTests): def test_failure(self): loader = self.find('<not real>') - self.assert_(loader is None) + self.assertTrue(loader is None) def test_main(): diff --git a/Lib/importlib/test/frozen/test_loader.py b/Lib/importlib/test/frozen/test_loader.py index 472d6ec..fa64f30 100644 --- a/Lib/importlib/test/frozen/test_loader.py +++ b/Lib/importlib/test/frozen/test_loader.py @@ -43,7 +43,7 @@ class LoaderTests(abc.LoaderTests): with util.uncache('__hello__'): module1 = machinery.FrozenImporter.load_module('__hello__') module2 = machinery.FrozenImporter.load_module('__hello__') - self.assert_(module1 is module2) + self.assertTrue(module1 is module2) def test_state_after_failure(self): # No way to trigger an error in a frozen module. @@ -65,12 +65,12 @@ class InspectLoaderTests(unittest.TestCase): code = machinery.FrozenImporter.get_code(name) mod = imp.new_module(name) exec(code, mod.__dict__) - self.assert_(hasattr(mod, 'initialized')) + self.assertTrue(hasattr(mod, 'initialized')) def test_get_source(self): # Should always return None. result = machinery.FrozenImporter.get_source('__hello__') - self.assert_(result is None) + self.assertTrue(result is None) def test_is_package(self): # Should be able to tell what is a package. @@ -78,7 +78,7 @@ class InspectLoaderTests(unittest.TestCase): ('__phello__.spam', False)) for name, is_package in test_for: result = machinery.FrozenImporter.is_package(name) - self.assert_(bool(result) == is_package) + self.assertTrue(bool(result) == is_package) def test_failure(self): # Raise ImportError for modules that are not frozen. diff --git a/Lib/importlib/test/import_/test_caching.py b/Lib/importlib/test/import_/test_caching.py index e37c69a..cf65b23 100644 --- a/Lib/importlib/test/import_/test_caching.py +++ b/Lib/importlib/test/import_/test_caching.py @@ -53,8 +53,8 @@ class UseCache(unittest.TestCase): with self.create_mock('pkg.__init__', 'pkg.module') as importer: with util.import_state(meta_path=[importer]): module = import_util.import_('pkg.module') - self.assert_(hasattr(module, 'module')) - self.assert_(id(module.module), id(sys.modules['pkg.module'])) + self.assertTrue(hasattr(module, 'module')) + self.assertTrue(id(module.module), id(sys.modules['pkg.module'])) # See test_using_cache_after_loader() for reasoning. @import_util.importlib_only @@ -63,7 +63,7 @@ class UseCache(unittest.TestCase): with self.create_mock('pkg.__init__', 'pkg.module') as importer: with util.import_state(meta_path=[importer]): module = import_util.import_('pkg', fromlist=['module']) - self.assert_(hasattr(module, 'module')) + self.assertTrue(hasattr(module, 'module')) self.assertEquals(id(module.module), id(sys.modules['pkg.module'])) diff --git a/Lib/importlib/test/import_/test_fromlist.py b/Lib/importlib/test/import_/test_fromlist.py index 266a495..340235b 100644 --- a/Lib/importlib/test/import_/test_fromlist.py +++ b/Lib/importlib/test/import_/test_fromlist.py @@ -59,7 +59,7 @@ class HandlingFromlist(unittest.TestCase): with util.import_state(meta_path=[importer]): module = import_util.import_('module', fromlist=['non_existent']) self.assertEquals(module.__name__, 'module') - self.assert_(not hasattr(module, 'non_existent')) + self.assertTrue(not hasattr(module, 'non_existent')) def test_module_from_package(self): # [module] @@ -67,7 +67,7 @@ class HandlingFromlist(unittest.TestCase): with util.import_state(meta_path=[importer]): module = import_util.import_('pkg', fromlist=['module']) self.assertEquals(module.__name__, 'pkg') - self.assert_(hasattr(module, 'module')) + self.assertTrue(hasattr(module, 'module')) self.assertEquals(module.module.__name__, 'pkg.module') def test_no_module_from_package(self): @@ -76,7 +76,7 @@ class HandlingFromlist(unittest.TestCase): with util.import_state(meta_path=[importer]): module = import_util.import_('pkg', fromlist='non_existent') self.assertEquals(module.__name__, 'pkg') - self.assert_(not hasattr(module, 'non_existent')) + self.assertTrue(not hasattr(module, 'non_existent')) def test_empty_string(self): with util.mock_modules('pkg.__init__', 'pkg.mod') as importer: @@ -91,7 +91,7 @@ class HandlingFromlist(unittest.TestCase): mock['pkg'].__all__ = ['module'] module = import_util.import_('pkg', fromlist=['*']) self.assertEquals(module.__name__, 'pkg') - self.assert_(hasattr(module, 'module')) + self.assertTrue(hasattr(module, 'module')) self.assertEqual(module.module.__name__, 'pkg.module') def test_star_with_others(self): @@ -102,8 +102,8 @@ class HandlingFromlist(unittest.TestCase): mock['pkg'].__all__ = ['module1'] module = import_util.import_('pkg', fromlist=['module2', '*']) self.assertEquals(module.__name__, 'pkg') - self.assert_(hasattr(module, 'module1')) - self.assert_(hasattr(module, 'module2')) + self.assertTrue(hasattr(module, 'module1')) + self.assertTrue(hasattr(module, 'module2')) self.assertEquals(module.module1.__name__, 'pkg.module1') self.assertEquals(module.module2.__name__, 'pkg.module2') diff --git a/Lib/importlib/test/import_/test_meta_path.py b/Lib/importlib/test/import_/test_meta_path.py index 69859b1..5486694 100644 --- a/Lib/importlib/test/import_/test_meta_path.py +++ b/Lib/importlib/test/import_/test_meta_path.py @@ -64,7 +64,7 @@ class CallSignature(unittest.TestCase): self.assertEquals(len(args), 2) self.assertEquals(len(kwargs), 0) self.assertEquals(args[0], mod_name) - self.assert_(args[1] is None) + self.assertTrue(args[1] is None) def test_with_path(self): # [path set] @@ -82,9 +82,9 @@ class CallSignature(unittest.TestCase): args = log[1][0] kwargs = log[1][1] # Assuming all arguments are positional. - self.assert_(not kwargs) + self.assertTrue(not kwargs) self.assertEquals(args[0], mod_name) - self.assert_(args[1] is path) + self.assertTrue(args[1] is path) diff --git a/Lib/importlib/test/import_/test_packages.py b/Lib/importlib/test/import_/test_packages.py index 5912c1f..b41c36f 100644 --- a/Lib/importlib/test/import_/test_packages.py +++ b/Lib/importlib/test/import_/test_packages.py @@ -13,7 +13,7 @@ class ParentModuleTests(unittest.TestCase): with util.mock_modules('pkg.__init__', 'pkg.module') as mock: with util.import_state(meta_path=[mock]): module = import_util.import_('pkg.module') - self.assert_('pkg' in sys.modules) + self.assertTrue('pkg' in sys.modules) def test_bad_parent(self): with util.mock_modules('pkg.module') as mock: diff --git a/Lib/importlib/test/import_/test_path.py b/Lib/importlib/test/import_/test_path.py index ede9b5f..0e055b1 100644 --- a/Lib/importlib/test/import_/test_path.py +++ b/Lib/importlib/test/import_/test_path.py @@ -19,7 +19,7 @@ class FinderTests(unittest.TestCase): # Test None returned upon not finding a suitable finder. module = '<test module>' with util.import_state(): - self.assert_(machinery.PathFinder.find_module(module) is None) + self.assertTrue(machinery.PathFinder.find_module(module) is None) def test_sys_path(self): # Test that sys.path is used when 'path' is None. @@ -30,7 +30,7 @@ class FinderTests(unittest.TestCase): with util.import_state(path_importer_cache={path: importer}, path=[path]): loader = machinery.PathFinder.find_module(module) - self.assert_(loader is importer) + self.assertTrue(loader is importer) def test_path(self): # Test that 'path' is used when set. @@ -40,7 +40,7 @@ class FinderTests(unittest.TestCase): importer = util.mock_modules(module) with util.import_state(path_importer_cache={path: importer}): loader = machinery.PathFinder.find_module(module, [path]) - self.assert_(loader is importer) + self.assertTrue(loader is importer) def test_path_hooks(self): # Test that sys.path_hooks is used. @@ -51,16 +51,16 @@ class FinderTests(unittest.TestCase): hook = import_util.mock_path_hook(path, importer=importer) with util.import_state(path_hooks=[hook]): loader = machinery.PathFinder.find_module(module, [path]) - self.assert_(loader is importer) - self.assert_(path in sys.path_importer_cache) - self.assert_(sys.path_importer_cache[path] is importer) + self.assertTrue(loader is importer) + self.assertTrue(path in sys.path_importer_cache) + self.assertTrue(sys.path_importer_cache[path] is importer) def test_path_importer_cache_has_None(self): # Test that if sys.path_importer_cache has None that None is returned. clear_cache = {path: None for path in sys.path} with util.import_state(path_importer_cache=clear_cache): for name in ('asynchat', 'sys', '<test module>'): - self.assert_(machinery.PathFinder.find_module(name) is None) + self.assertTrue(machinery.PathFinder.find_module(name) is None) def test_path_importer_cache_has_None_continues(self): # Test that having None in sys.path_importer_cache causes the search to @@ -71,7 +71,7 @@ class FinderTests(unittest.TestCase): with util.import_state(path=['1', '2'], path_importer_cache={'1': None, '2': importer}): loader = machinery.PathFinder.find_module(module) - self.assert_(loader is importer) + self.assertTrue(loader is importer) @@ -88,15 +88,15 @@ class DefaultPathFinderTests(unittest.TestCase): with util.import_state(): nothing = _bootstrap._DefaultPathFinder.find_module(module, path=[existing_path]) - self.assert_(nothing is None) - self.assert_(existing_path in sys.path_importer_cache) - self.assert_(not isinstance(sys.path_importer_cache[existing_path], + self.assertTrue(nothing is None) + self.assertTrue(existing_path in sys.path_importer_cache) + self.assertTrue(not isinstance(sys.path_importer_cache[existing_path], imp.NullImporter)) nothing = _bootstrap._DefaultPathFinder.find_module(module, path=[bad_path]) - self.assert_(nothing is None) - self.assert_(bad_path in sys.path_importer_cache) - self.assert_(isinstance(sys.path_importer_cache[bad_path], + self.assertTrue(nothing is None) + self.assertTrue(bad_path in sys.path_importer_cache) + self.assertTrue(isinstance(sys.path_importer_cache[bad_path], imp.NullImporter)) def test_path_importer_cache_has_None(self): @@ -113,7 +113,7 @@ class DefaultPathFinderTests(unittest.TestCase): with util.import_state(path_importer_cache={path: None}): loader = _bootstrap._DefaultPathFinder.find_module(module, path=[path]) - self.assert_(loader is importer) + self.assertTrue(loader is importer) finally: _bootstrap._DEFAULT_PATH_HOOK = original_hook diff --git a/Lib/importlib/test/import_/test_relative_imports.py b/Lib/importlib/test/import_/test_relative_imports.py index dca0699..5547d4c 100644 --- a/Lib/importlib/test/import_/test_relative_imports.py +++ b/Lib/importlib/test/import_/test_relative_imports.py @@ -79,7 +79,7 @@ class RelativeImports(unittest.TestCase): import_util.import_('pkg') # For __import__(). module = import_util.import_('', global_, fromlist=['mod2'], level=1) self.assertEqual(module.__name__, 'pkg') - self.assert_(hasattr(module, 'mod2')) + self.assertTrue(hasattr(module, 'mod2')) self.assertEqual(module.mod2.attr, 'pkg.mod2') self.relative_import_test(create, globals_, callback) @@ -105,7 +105,7 @@ class RelativeImports(unittest.TestCase): module = import_util.import_('', global_, fromlist=['module'], level=1) self.assertEqual(module.__name__, 'pkg') - self.assert_(hasattr(module, 'module')) + self.assertTrue(hasattr(module, 'module')) self.assertEqual(module.module.attr, 'pkg.module') self.relative_import_test(create, globals_, callback) @@ -129,7 +129,7 @@ class RelativeImports(unittest.TestCase): module = import_util.import_('', global_, fromlist=['subpkg2'], level=2) self.assertEqual(module.__name__, 'pkg') - self.assert_(hasattr(module, 'subpkg2')) + self.assertTrue(hasattr(module, 'subpkg2')) self.assertEqual(module.subpkg2.attr, 'pkg.subpkg2.__init__') def test_deep_import(self): diff --git a/Lib/importlib/test/source/test_abc_loader.py b/Lib/importlib/test/source/test_abc_loader.py index b95db04..6848527 100644 --- a/Lib/importlib/test/source/test_abc_loader.py +++ b/Lib/importlib/test/source/test_abc_loader.py @@ -133,10 +133,10 @@ class PyLoaderTests(testing_abc.LoaderTests): mock = self.mocker({name: path}) with util.uncache(name): module = mock.load_module(name) - self.assert_(name in sys.modules) + self.assertTrue(name in sys.modules) self.eq_attrs(module, __name__=name, __file__=path, __package__='', __loader__=mock) - self.assert_(not hasattr(module, '__path__')) + self.assertTrue(not hasattr(module, '__path__')) return mock, name def test_package(self): @@ -145,7 +145,7 @@ class PyLoaderTests(testing_abc.LoaderTests): mock = self.mocker({name: path}) with util.uncache(name): module = mock.load_module(name) - self.assert_(name in sys.modules) + self.assertTrue(name in sys.modules) self.eq_attrs(module, __name__=name, __file__=path, __path__=[os.path.dirname(path)], __package__=name, __loader__=mock) @@ -171,8 +171,8 @@ class PyLoaderTests(testing_abc.LoaderTests): with util.uncache(name): sys.modules[name] = module loaded_module = mock.load_module(name) - self.assert_(loaded_module is module) - self.assert_(sys.modules[name] is module) + self.assertTrue(loaded_module is module) + self.assertTrue(sys.modules[name] is module) return mock, name def test_state_after_failure(self): @@ -184,8 +184,8 @@ class PyLoaderTests(testing_abc.LoaderTests): with util.uncache(name): sys.modules[name] = module self.assertRaises(ZeroDivisionError, mock.load_module, name) - self.assert_(sys.modules[name] is module) - self.assert_(hasattr(module, 'blah')) + self.assertTrue(sys.modules[name] is module) + self.assertTrue(hasattr(module, 'blah')) return mock def test_unloadable(self): @@ -194,7 +194,7 @@ class PyLoaderTests(testing_abc.LoaderTests): mock.source = b"1/0" with util.uncache(name): self.assertRaises(ZeroDivisionError, mock.load_module, name) - self.assert_(name not in sys.modules) + self.assertTrue(name not in sys.modules) return mock @@ -293,7 +293,7 @@ class SkipWritingBytecodeTests(unittest.TestCase): sys.dont_write_bytecode = dont_write_bytecode with util.uncache(name): mock.load_module(name) - self.assert_((name in mock.module_bytecode) is not + self.assertTrue((name in mock.module_bytecode) is not dont_write_bytecode) def test_no_bytecode_written(self): @@ -319,7 +319,7 @@ class RegeneratedBytecodeTests(unittest.TestCase): 'magic': bad_magic}}) with util.uncache(name): mock.load_module(name) - self.assert_(name in mock.module_bytecode) + self.assertTrue(name in mock.module_bytecode) magic = mock.module_bytecode[name][:4] self.assertEqual(magic, imp.get_magic()) @@ -332,7 +332,7 @@ class RegeneratedBytecodeTests(unittest.TestCase): {name: {'path': 'path/to/mod.bytecode', 'mtime': old_mtime}}) with util.uncache(name): mock.load_module(name) - self.assert_(name in mock.module_bytecode) + self.assertTrue(name in mock.module_bytecode) mtime = importlib._r_long(mock.module_bytecode[name][4:8]) self.assertEqual(mtime, PyPycLoaderMock.default_mtime) diff --git a/Lib/importlib/test/source/test_file_loader.py b/Lib/importlib/test/source/test_file_loader.py index d01a2a7..0384e7d 100644 --- a/Lib/importlib/test/source/test_file_loader.py +++ b/Lib/importlib/test/source/test_file_loader.py @@ -23,7 +23,7 @@ class SimpleTest(unittest.TestCase): loader = _bootstrap._PyPycFileLoader('_temp', mapping['_temp'], False) module = loader.load_module('_temp') - self.assert_('_temp' in sys.modules) + self.assertTrue('_temp' in sys.modules) check = {'__name__': '_temp', '__file__': mapping['_temp'], '__package__': ''} for attr, value in check.items(): @@ -35,7 +35,7 @@ class SimpleTest(unittest.TestCase): mapping['_pkg.__init__'], True) module = loader.load_module('_pkg') - self.assert_('_pkg' in sys.modules) + self.assertTrue('_pkg' in sys.modules) check = {'__name__': '_pkg', '__file__': mapping['_pkg.__init__'], '__path__': [os.path.dirname(mapping['_pkg.__init__'])], '__package__': '_pkg'} @@ -48,7 +48,7 @@ class SimpleTest(unittest.TestCase): loader = _bootstrap._PyPycFileLoader('_pkg.mod', mapping['_pkg.mod'], False) module = loader.load_module('_pkg.mod') - self.assert_('_pkg.mod' in sys.modules) + self.assertTrue('_pkg.mod' in sys.modules) check = {'__name__': '_pkg.mod', '__file__': mapping['_pkg.mod'], '__package__': '_pkg'} for attr, value in check.items(): @@ -73,7 +73,7 @@ class SimpleTest(unittest.TestCase): # than the original mtime. loader.source_mtime = self.fake_mtime(loader.source_mtime) module = loader.load_module('_temp') - self.assert_('testing_var' in module.__dict__, + self.assertTrue('testing_var' in module.__dict__, "'testing_var' not in " "{0}".format(list(module.__dict__.keys()))) self.assertEqual(module, sys.modules['_temp']) @@ -105,7 +105,7 @@ class SimpleTest(unittest.TestCase): loader = _bootstrap._PyPycFileLoader('_temp', mapping['_temp'], False) self.assertRaises(SyntaxError, loader.load_module, '_temp') - self.assert_('_temp' not in sys.modules) + self.assertTrue('_temp' not in sys.modules) class BadBytecodeTest(unittest.TestCase): @@ -124,7 +124,7 @@ class BadBytecodeTest(unittest.TestCase): def import_(self, file, module_name): loader = _bootstrap._PyPycFileLoader(module_name, file, False) module = loader.load_module(module_name) - self.assert_(module_name in sys.modules) + self.assertTrue(module_name in sys.modules) # [bad magic] @source_util.writes_bytecode_files @@ -168,7 +168,7 @@ class BadBytecodeTest(unittest.TestCase): bytecode_file.write(b'AAAA') self.assertRaises(ValueError, self.import_, mapping['_temp'], '_temp') - self.assert_('_temp' not in sys.modules) + self.assertTrue('_temp' not in sys.modules) def test_main(): diff --git a/Lib/importlib/test/source/test_finder.py b/Lib/importlib/test/source/test_finder.py index dd56429..c495c5a 100644 --- a/Lib/importlib/test/source/test_finder.py +++ b/Lib/importlib/test/source/test_finder.py @@ -53,7 +53,7 @@ class FinderTests(abc.FinderTests): for name in unlink: os.unlink(mapping[name]) loader = self.import_(mapping['.root'], test) - self.assert_(hasattr(loader, 'load_module')) + self.assertTrue(hasattr(loader, 'load_module')) return loader def test_module(self): @@ -79,7 +79,7 @@ class FinderTests(abc.FinderTests): with source_util.create_modules('pkg.__init__', 'pkg.sub') as mapping: pkg_dir = os.path.dirname(mapping['pkg.__init__']) loader = self.import_(pkg_dir, 'pkg.sub') - self.assert_(hasattr(loader, 'load_module')) + self.assertTrue(hasattr(loader, 'load_module')) # [sub package] def test_package_in_package(self): @@ -87,7 +87,7 @@ class FinderTests(abc.FinderTests): with context as mapping: pkg_dir = os.path.dirname(mapping['pkg.__init__']) loader = self.import_(pkg_dir, 'pkg.sub') - self.assert_(hasattr(loader, 'load_module')) + self.assertTrue(hasattr(loader, 'load_module')) # [sub empty] def test_empty_sub_directory(self): @@ -105,13 +105,13 @@ class FinderTests(abc.FinderTests): # XXX This is not a blackbox test! name = '_temp' loader = self.run_test(name, {'{0}.__init__'.format(name), name}) - self.assert_('__init__' in loader._base_path) + self.assertTrue('__init__' in loader._base_path) def test_failure(self): with source_util.create_modules('blah') as mapping: nothing = self.import_(mapping['.root'], 'sdfsadsadf') - self.assert_(nothing is None) + self.assertTrue(nothing is None) # [empty dir] def test_empty_dir(self): diff --git a/Lib/importlib/test/source/test_path_hook.py b/Lib/importlib/test/source/test_path_hook.py index 71ca508..3efb3be 100644 --- a/Lib/importlib/test/source/test_path_hook.py +++ b/Lib/importlib/test/source/test_path_hook.py @@ -10,7 +10,7 @@ class PathHookTest(unittest.TestCase): def test_success(self): # XXX Only work on existing directories? with source_util.create_modules('dummy') as mapping: - self.assert_(hasattr(_bootstrap._FileFinder(mapping['.root']), + self.assertTrue(hasattr(_bootstrap._FileFinder(mapping['.root']), 'find_module')) diff --git a/Lib/importlib/test/test_abc.py b/Lib/importlib/test/test_abc.py index a54adb9..c5a5908 100644 --- a/Lib/importlib/test/test_abc.py +++ b/Lib/importlib/test/test_abc.py @@ -11,7 +11,7 @@ class SubclassTests(unittest.TestCase): def verify(self, ABC, *classes): """Verify the classes are subclasses of the ABC.""" for cls in classes: - self.assert_(issubclass(cls, ABC)) + self.assertTrue(issubclass(cls, ABC)) def test_Finder(self): self.verify(abc.Finder, machinery.BuiltinImporter, diff --git a/Lib/importlib/test/test_util.py b/Lib/importlib/test/test_util.py index 706128a..406477d 100644 --- a/Lib/importlib/test/test_util.py +++ b/Lib/importlib/test/test_util.py @@ -29,8 +29,8 @@ class ModuleForLoaderTests(unittest.TestCase): module_name = 'a.b.c' with test_util.uncache(module_name): module = self.return_module(module_name) - self.assert_(module_name in sys.modules) - self.assert_(isinstance(module, types.ModuleType)) + self.assertTrue(module_name in sys.modules) + self.assertTrue(isinstance(module, types.ModuleType)) self.assertEqual(module.__name__, module_name) def test_reload(self): @@ -40,7 +40,7 @@ class ModuleForLoaderTests(unittest.TestCase): with test_util.uncache(name): sys.modules[name] = module returned_module = self.return_module(name) - self.assert_(sys.modules[name] is returned_module) + self.assertTrue(sys.modules[name] is returned_module) def test_new_module_failure(self): # Test that a module is removed from sys.modules if added but an @@ -48,7 +48,7 @@ class ModuleForLoaderTests(unittest.TestCase): name = 'a.b.c' with test_util.uncache(name): self.raise_exception(name) - self.assert_(name not in sys.modules) + self.assertTrue(name not in sys.modules) def test_reload_failure(self): # Test that a failure on reload leaves the module in-place. @@ -57,7 +57,7 @@ class ModuleForLoaderTests(unittest.TestCase): with test_util.uncache(name): sys.modules[name] = module self.raise_exception(name) - self.assert_(sys.modules[name] is module) + self.assertTrue(sys.modules[name] is module) class SetPackageTests(unittest.TestCase): @@ -71,7 +71,7 @@ class SetPackageTests(unittest.TestCase): fxn = lambda: module wrapped = util.set_package(fxn) wrapped() - self.assert_(hasattr(module, '__package__')) + self.assertTrue(hasattr(module, '__package__')) self.assertEqual(expect, module.__package__) def test_top_level(self): diff --git a/Lib/json/tests/test_decode.py b/Lib/json/tests/test_decode.py index 78e7e07..4610c6c 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_object_pairs_hook(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/test/mapping_tests.py b/Lib/test/mapping_tests.py index b8bbc9a..c34bd59 100644 --- a/Lib/test/mapping_tests.py +++ b/Lib/test/mapping_tests.py @@ -50,15 +50,15 @@ class BasicTestMappingProtocol(unittest.TestCase): for key, value in self.reference.items(): self.assertEqual(d[key], value) knownkey = list(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)) #__contains__ for k in self.reference: - self.assert_(k in d) + self.assertTrue(k in d) for k in self.other: - self.failIf(k in d) + self.assertFalse(k in d) #cmp self.assertEqual(p, p) self.assertEqual(d, d) @@ -69,10 +69,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(iter(d.keys()), list(d.keys()), self.reference.keys()) check_iterandlist(iter(d), list(d.keys()), self.reference.keys()) @@ -85,7 +85,7 @@ class BasicTestMappingProtocol(unittest.TestCase): knownkey, knownvalue = next(iter(self.other.items())) 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 @@ -96,7 +96,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) @@ -115,16 +115,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) @@ -133,17 +133,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(list(d.keys()), []) d = self.reference - self.assert_(list(self.inmapping.keys())[0] in d.keys()) - self.assert_(list(self.other.keys())[0] not in d.keys()) + self.assertTrue(list(self.inmapping.keys())[0] in d.keys()) + self.assertTrue(list(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(list(self.other.keys())[0]) is None) + self.assertTrue(d.get(list(self.other.keys())[0]) is None) self.assertEqual(d.get(list(self.other.keys())[0], 3), 3) d = self.reference - self.assert_(d.get(list(self.other.keys())[0]) is None) + self.assertTrue(d.get(list(self.other.keys())[0]) is None) self.assertEqual(d.get(list(self.other.keys())[0], 3), 3) self.assertEqual(d.get(list(self.inmapping.keys())[0]), list(self.inmapping.values())[0]) @@ -304,15 +304,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) @@ -320,9 +320,9 @@ class TestMappingProtocol(BasicTestMappingProtocol): self.assertEqual(list(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) @@ -337,12 +337,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__) @@ -421,7 +421,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([]), {}) @@ -432,17 +432,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 collections.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, collections.UserDict)) + # self.assertTrue(isinstance(ud, collections.UserDict)) self.assertRaises(TypeError, dict.fromkeys) class Exc(Exception): pass @@ -472,16 +472,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) @@ -489,9 +489,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) @@ -517,9 +517,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) @@ -577,7 +577,7 @@ class TestHashMappingProtocol(TestMappingProtocol): return collections.UserDict() ud = mydict.fromkeys('ab') self.assertEqual(ud, {'a':None, 'b':None}) - self.assert_(isinstance(ud, collections.UserDict)) + self.assertTrue(isinstance(ud, collections.UserDict)) def test_pop(self): TestMappingProtocol.test_pop(self) diff --git a/Lib/test/pickletester.py b/Lib/test/pickletester.py index 3ed26b8..19704ae 100644 --- a/Lib/test/pickletester.py +++ b/Lib/test/pickletester.py @@ -449,7 +449,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 = ([],) @@ -459,7 +459,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 = {} @@ -468,7 +468,7 @@ class AbstractPickleTests(unittest.TestCase): s = self.dumps(d, proto) x = self.loads(s) self.assertEqual(list(x.keys()), [1]) - self.assert_(x[1] is x) + self.assertTrue(x[1] is x) def test_recursive_inst(self): i = C() @@ -477,7 +477,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 = [] @@ -491,7 +491,7 @@ class AbstractPickleTests(unittest.TestCase): self.assertEqual(len(x), 1) self.assertEqual(dir(x[0]), dir(i)) self.assertEqual(list(x[0].attr.keys()), [1]) - self.assert_(x[0].attr[1] is x) + self.assertTrue(x[0].attr[1] is x) def test_get(self): self.assertRaises(KeyError, self.loads, b'g0\np0') @@ -639,7 +639,7 @@ class AbstractPickleTests(unittest.TestCase): try: self.loads(badpickle) except ValueError as detail: - self.failUnless(str(detail).startswith( + self.assertTrue(str(detail).startswith( "unsupported pickle protocol")) else: self.fail("expected bad protocol number to raise ValueError") @@ -720,7 +720,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) @@ -770,8 +770,8 @@ class AbstractPickleTests(unittest.TestCase): # Dump using protocol 1 for comparison. s1 = self.dumps(x, 1) - self.assert_(__name__.encode("utf-8") in s1) - self.assert_(b"MyList" in s1) + self.assertTrue(__name__.encode("utf-8") in s1) + self.assertTrue(b"MyList" in s1) self.assertEqual(opcode_in_pickle(opcode, s1), False) y = self.loads(s1) @@ -780,8 +780,8 @@ class AbstractPickleTests(unittest.TestCase): # Dump using protocol 2 for test. s2 = self.dumps(x, 2) - self.assert_(__name__.encode("utf-8") not in s2) - self.assert_(b"MyList" not in s2) + self.assertTrue(__name__.encode("utf-8") not in s2) + self.assertTrue(b"MyList" not in s2) self.assertEqual(opcode_in_pickle(opcode, s2), True, repr(s2)) y = self.loads(s2) @@ -825,7 +825,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 @@ -848,7 +848,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___all__.py b/Lib/test/test___all__.py index 4b56749..8ebe568 100644 --- a/Lib/test/test___all__.py +++ b/Lib/test/test___all__.py @@ -17,7 +17,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, names) diff --git a/Lib/test/test___future__.py b/Lib/test/test___future__.py index 77006e1..ef81788 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 4965c42..c3482d6 100644 --- a/Lib/test/test_abc.py +++ b/Lib/test/test_abc.py @@ -42,23 +42,23 @@ class TestABC(unittest.TestCase): def bar(self): pass # concrete self.assertEqual(C.__abstractmethods__, {"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__, {"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__, {"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: @@ -142,41 +142,41 @@ class TestABC(unittest.TestCase): def test_registration_transitiveness(self): class A(metaclass=abc.ABCMeta): pass - 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): pass - 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): pass 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(metaclass=abc.ABCMeta): diff --git a/Lib/test/test_abstract_numbers.py b/Lib/test/test_abstract_numbers.py index e20f2d4..d0164c0 100644 --- a/Lib/test/test_abstract_numbers.py +++ b/Lib/test/test_abstract_numbers.py @@ -9,8 +9,8 @@ from test import 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,16 +19,16 @@ class TestNumbers(unittest.TestCase): self.assertEqual(1, int(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 8e22839..7ae34a9 100755 --- a/Lib/test/test_array.py +++ b/Lib/test/test_array.py @@ -49,7 +49,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): @@ -64,10 +64,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)) - self.assert_(isinstance(bi[1], int)) + self.assertTrue(isinstance(bi[0], int)) + self.assertTrue(isinstance(bi[1], int)) self.assertEqual(bi[1], len(a)) def test_byteswap(self): @@ -216,39 +216,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) \ @@ -267,7 +267,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) @@ -310,22 +310,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 021ae95..63e9763 100644 --- a/Lib/test/test_ast.py +++ b/Lib/test/test_ast.py @@ -116,20 +116,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"), @@ -138,7 +138,7 @@ class AST_Tests(unittest.TestCase): for i, o in zip(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 e03b4d4..8567821 100644 --- a/Lib/test/test_augassign.py +++ b/Lib/test/test_augassign.py @@ -60,7 +60,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): @@ -85,23 +85,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_base64.py b/Lib/test/test_base64.py index 149ac8a..fadee6d 100644 --- a/Lib/test/test_base64.py +++ b/Lib/test/test_base64.py @@ -204,7 +204,7 @@ class BaseXYTestCase(unittest.TestCase): self.assertRaises(TypeError, base64.b16decode, "") def test_ErrorHeritage(self): - self.assert_(issubclass(binascii.Error, ValueError)) + self.assertTrue(issubclass(binascii.Error, ValueError)) diff --git a/Lib/test/test_bigmem.py b/Lib/test/test_bigmem.py index 091893e..030ada5 100644 --- a/Lib/test/test_bigmem.py +++ b/Lib/test/test_bigmem.py @@ -80,12 +80,12 @@ class BaseStrTest: _ = self.from_latin1 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): @@ -139,27 +139,27 @@ class BaseStrTest: _ = self.from_latin1 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): _ = self.from_latin1 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): _ = self.from_latin1 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): @@ -168,9 +168,9 @@ class BaseStrTest: 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): @@ -178,20 +178,20 @@ class BaseStrTest: 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): _ = self.from_latin1 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): @@ -200,9 +200,9 @@ class BaseStrTest: 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): @@ -211,15 +211,15 @@ class BaseStrTest: 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): _ = self.from_latin1 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()) @@ -244,7 +244,7 @@ class BaseStrTest: # Type-specific optimization if isinstance(s, (str, bytes)): stripped = s.lstrip() - self.failUnless(stripped is s) + self.assertTrue(stripped is s) @bigmemtest(minsize=_2G + 10, memuse=2) def test_replace(self, size): @@ -299,7 +299,7 @@ class BaseStrTest: _ = self.from_latin1 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()) @@ -316,7 +316,7 @@ class BaseStrTest: # Type-specific optimization if isinstance(s, (str, bytes)): 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 @@ -378,9 +378,9 @@ class BaseStrTest: _ = self.from_latin1 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): @@ -412,8 +412,8 @@ class BaseStrTest: 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): @@ -451,8 +451,8 @@ class BaseStrTest: _ = self.from_latin1 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)) @@ -519,12 +519,12 @@ class BaseStrTest: 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): @@ -534,10 +534,10 @@ class BaseStrTest: self.assertEqual(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): @@ -552,7 +552,7 @@ class BaseStrTest: h1 = hash(s) del s s = _('\x00') * (size + 1) - self.failIf(h1 == hash(s)) + self.assertFalse(h1 == hash(s)) class StrTest(unittest.TestCase, BaseStrTest): @@ -623,7 +623,7 @@ class StrTest(unittest.TestCase, BaseStrTest): except MemoryError: pass # acceptable on 32-bit else: - self.failUnless(s == eval(r)) + self.assertTrue(s == eval(r)) @bigmemtest(minsize=_2G + 10, memuse=character_size * 2) def test_format(self, size): @@ -633,8 +633,8 @@ class StrTest(unittest.TestCase, BaseStrTest): 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 @@ -682,8 +682,8 @@ class StrTest(unittest.TestCase, BaseStrTest): s = "\uAAAA" * size for f in (repr, ascii): r = f(s) - self.failUnless(len(r) > size) - self.failUnless(r.endswith(r"\uaaaa'"), r[-10:]) + self.assertTrue(len(r) > size) + self.assertTrue(r.endswith(r"\uaaaa'"), r[-10:]) del r # The character takes 4 bytes even in UCS-2 builds because it will @@ -693,8 +693,8 @@ class StrTest(unittest.TestCase, BaseStrTest): s = "\U0001AAAA" * size for f in (repr, ascii): r = f(s) - self.failUnless(len(r) > size) - self.failUnless(r.endswith(r"\U0001aaaa'"), r[-12:]) + self.assertTrue(len(r) > size) + self.assertTrue(r.endswith(r"\U0001aaaa'"), r[-12:]) del r @@ -740,10 +740,10 @@ class TupleTest(unittest.TestCase): self.assertEqual(t1, t2) del t2 t2 = ('',) * (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 @@ -768,9 +768,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): @@ -778,7 +778,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): @@ -874,10 +874,10 @@ class ListTest(unittest.TestCase): self.assertEqual(l1, l2) del l2 l2 = [''] * (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 @@ -902,8 +902,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): @@ -917,14 +917,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): @@ -984,7 +984,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 @@ -1002,13 +1002,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): @@ -1042,8 +1042,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): @@ -1055,8 +1055,8 @@ class ListTest(unittest.TestCase): l = [object] * 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 d4ab6bf..65de81b 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_(hasattr(getattr(binascii, name), '__call__')) + self.assertTrue(hasattr(getattr(binascii, name), '__call__')) self.assertRaises(TypeError, getattr(binascii, name)) for name in ("hexlify", "unhexlify"): - self.assert_(hasattr(getattr(binascii, name), '__call__')) + self.assertTrue(hasattr(getattr(binascii, name), '__call__')) 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 0dc18dd..5d77f23 100644 --- a/Lib/test/test_binop.py +++ b/Lib/test/test_binop.py @@ -210,10 +210,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 df2f8b1..93b8613 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 range(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 80229aa..3a68dfc 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: @@ -221,15 +221,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_bufio.py b/Lib/test/test_bufio.py index 7d617d3..5ab6f5a 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 fdb0ea2..28fd938 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -176,24 +176,24 @@ class BuiltinTest(unittest.TestCase): def test_neg(self): x = -sys.maxsize-1 - self.assert_(isinstance(x, int)) + self.assertTrue(isinstance(x, int)) self.assertEqual(-x, sys.maxsize+1) # XXX(nnorwitz): This test case for callable should probably be removed. def test_callable(self): - self.assert_(hasattr(len, '__call__')) + self.assertTrue(hasattr(len, '__call__')) def f(): pass - self.assert_(hasattr(f, '__call__')) + self.assertTrue(hasattr(f, '__call__')) class C: def meth(self): pass - self.assert_(hasattr(C, '__call__')) + self.assertTrue(hasattr(C, '__call__')) x = C() - self.assert_(hasattr(x.meth, '__call__')) - self.assert_(not hasattr(x, '__call__')) + self.assertTrue(hasattr(x.meth, '__call__')) + self.assertTrue(not hasattr(x, '__call__')) class D(C): def __call__(self): pass y = D() - self.assert_(hasattr(y, '__call__')) + self.assertTrue(hasattr(y, '__call__')) y() def test_chr(self): @@ -220,7 +220,7 @@ class BuiltinTest(unittest.TestCase): self.assertRaises((OverflowError, ValueError), chr, 2**32) def test_cmp(self): - self.assert_(not hasattr(builtins, "cmp")) + self.assertTrue(not hasattr(builtins, "cmp")) def test_compile(self): compile('print(1)\n', '', 'exec') @@ -252,11 +252,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 @@ -266,8 +266,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): @@ -276,13 +276,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) @@ -291,15 +291,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): @@ -334,10 +334,10 @@ class BuiltinTest(unittest.TestCase): self.assertEqual(divmod(-sys.maxsize-1, -1), (sys.maxsize+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) @@ -489,7 +489,7 @@ class BuiltinTest(unittest.TestCase): 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) @@ -497,7 +497,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) self.assertEqual(False, hasattr(sys, chr(sys.maxunicode))) @@ -575,11 +575,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) @@ -593,9 +593,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) @@ -958,18 +958,18 @@ class BuiltinTest(unittest.TestCase): self.assertEqual(list(range(a+4, a, -2)), [a+4, a+2]) seq = list(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 = list(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 = list(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) diff --git a/Lib/test/test_bytes.py b/Lib/test/test_bytes.py index 992f3d2..caea909 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: "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) @@ -626,7 +626,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: @@ -642,7 +642,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") @@ -650,17 +650,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) @@ -759,7 +759,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") @@ -769,7 +769,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") @@ -860,10 +860,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") @@ -920,7 +920,7 @@ class AssortedBytesTest(unittest.TestCase): def test_return_self(self): # bytearray.replace must always return a new bytearray b = bytearray() - self.failIf(b.replace(b'', b'') is b) + self.assertFalse(b.replace(b'', b'') is b) def test_compare(self): if sys.flags.bytes_warning: @@ -997,20 +997,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) @@ -1018,7 +1018,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 @@ -1026,12 +1026,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 d3d2226..0460679 100644 --- a/Lib/test/test_capi.py +++ b/Lib/test/test_capi.py @@ -24,7 +24,7 @@ class CAPITest(unittest.TestCase): def test_instancemethod(self): inst = InstanceMethod() self.assertEqual(id(inst), inst.id()) - self.assert_(inst.testfunction() is inst) + self.assertTrue(inst.testfunction() is inst) self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__) self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__) @@ -64,7 +64,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 support.verbose: print("(%i)"%(len(l),)) diff --git a/Lib/test/test_cfgparser.py b/Lib/test/test_cfgparser.py index 12fd00c..a3d2640 100644 --- a/Lib/test/test_cfgparser.py +++ b/Lib/test/test_cfgparser.py @@ -76,16 +76,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") @@ -107,10 +107,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"]) @@ -127,7 +127,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): @@ -163,7 +163,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") @@ -202,8 +202,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 87028b5..ef7dfa5 100644 --- a/Lib/test/test_cgi.py +++ b/Lib/test/test_cgi.py @@ -143,7 +143,7 @@ class CgiTests(unittest.TestCase): # test individual fields for key in expect.keys(): expect_val = expect[key] - self.assert_(key in fs) + self.assertTrue(key in fs) if len(expect_val) > 1: self.assertEqual(fs.getvalue(key), expect_val) else: @@ -194,7 +194,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 17cb566..2d2deff 100755 --- a/Lib/test/test_cmath.py +++ b/Lib/test/test_cmath.py @@ -412,7 +412,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 @@ -425,18 +425,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"): @@ -455,26 +455,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.py b/Lib/test/test_cmd_line.py index ef3c109..87ae2b6 100644 --- a/Lib/test/test_cmd_line.py +++ b/Lib/test/test_cmd_line.py @@ -169,7 +169,7 @@ class CmdLineTest(unittest.TestCase): p.stdin.flush() data, rc = _kill_python_and_exit_code(p) self.assertEqual(rc, 0) - self.assert_(data.startswith(b'x'), data) + self.assertTrue(data.startswith(b'x'), data) def test_large_PYTHONPATH(self): with test.support.EnvironmentVarGuard() as env: @@ -178,8 +178,8 @@ class CmdLineTest(unittest.TestCase): env['PYTHONPATH'] = path1 + os.pathsep + path2 p = _spawn_python('-S', '-c', 'import sys; print(sys.path)') stdout, _ = p.communicate() - self.assert_(path1.encode('ascii') in stdout) - self.assert_(path2.encode('ascii') in stdout) + self.assertTrue(path1.encode('ascii') in stdout) + self.assertTrue(path2.encode('ascii') in stdout) def test_main(): diff --git a/Lib/test/test_cmd_line_script.py b/Lib/test/test_cmd_line_script.py index e060ec1..7114681 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 e060471..9f73453 100644 --- a/Lib/test/test_codecs.py +++ b/Lib/test/test_codecs.py @@ -29,14 +29,14 @@ class MixInCheckStateHandling: d = codecs.getincrementaldecoder(encoding)() part1 = d.decode(s[:i]) state = d.getstate() - self.assert_(isinstance(state[1], int)) + self.assertTrue(isinstance(state[1], int)) # Check that the condition stated in the documentation for # IncrementalDecoder.getstate() holds if not state[1]: # reset decoder to the default state without anything buffered d.setstate((state[0][:0], 0)) # Feeding the previous input may not produce any output - self.assert_(not d.decode(state[0])) + self.assertTrue(not d.decode(state[0])) # The decoder must return to the same state self.assertEqual(state, d.getstate()) # Create a new decoder and set it to the state @@ -296,7 +296,7 @@ class UTF32Test(ReadTest): f.write("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 = io.BytesIO(d) f = reader(s) @@ -429,7 +429,7 @@ class UTF16Test(ReadTest): f.write("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 = io.BytesIO(d) f = reader(s) @@ -1335,7 +1335,7 @@ class BasicUnicodeTest(unittest.TestCase, MixInCheckStateHandling): for c in s: writer.write(c) chunk = q.read() - self.assert_(type(chunk) is bytes, type(chunk)) + self.assertTrue(type(chunk) is bytes, type(chunk)) encodedresult += chunk q = Queue(b"") reader = codecs.getreader(encoding)(q) diff --git a/Lib/test/test_codeop.py b/Lib/test/test_codeop.py index 224a314..d845e20 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_collections.py b/Lib/test/test_collections.py index 8387564..ded8b70 100644 --- a/Lib/test/test_collections.py +++ b/Lib/test/test_collections.py @@ -44,9 +44,9 @@ class TestNamedTuple(unittest.TestCase): namedtuple('_', 'a b c') # Test leading underscores in a typename nt = namedtuple('nt', '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', ('the', '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 @@ -75,8 +75,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 @@ -103,7 +103,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 @@ -236,8 +236,8 @@ class TestOneTrickPonyABCs(ABCTestCase): # Check some non-hashables non_samples = [bytearray(), 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(), @@ -246,23 +246,23 @@ class TestOneTrickPonyABCs(ABCTestCase): int, list, object, type, bytes() ] 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): def __hash__(self): return super().__hash__() 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 = [bytes(), str(), tuple(), list(), set(), frozenset(), dict(), @@ -271,21 +271,21 @@ 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().__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, b"", "", (), [], {}, 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(bytes()), iter(str()), iter(tuple()), iter(list()), iter(dict()), iter(set()), iter(frozenset()), @@ -295,8 +295,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): @@ -305,15 +305,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 = [bytes(), 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): @@ -322,15 +322,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 = [bytes(), 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): @@ -340,32 +340,32 @@ 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: __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,46 +457,46 @@ 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, bytes, str]: - self.failUnless(isinstance(sample(), Sequence)) - self.failUnless(issubclass(sample, Sequence)) - self.failUnless(isinstance(range(10), Sequence)) - self.failUnless(issubclass(range, Sequence)) - self.failUnless(issubclass(str, Sequence)) + self.assertTrue(isinstance(sample(), Sequence)) + self.assertTrue(issubclass(sample, Sequence)) + self.assertTrue(isinstance(range(10), Sequence)) + self.assertTrue(issubclass(range, Sequence)) + self.assertTrue(issubclass(str, Sequence)) self.validate_abstract_methods(Sequence, '__contains__', '__iter__', '__len__', '__getitem__') def test_ByteString(self): for sample in [bytes, bytearray]: - self.failUnless(isinstance(sample(), ByteString)) - self.failUnless(issubclass(sample, ByteString)) + self.assertTrue(isinstance(sample(), ByteString)) + self.assertTrue(issubclass(sample, ByteString)) for sample in [str, list, tuple]: - self.failIf(isinstance(sample(), ByteString)) - self.failIf(issubclass(sample, ByteString)) - self.failIf(isinstance(memoryview(b""), ByteString)) - self.failIf(issubclass(memoryview, ByteString)) + self.assertFalse(isinstance(sample(), ByteString)) + self.assertFalse(issubclass(sample, ByteString)) + self.assertFalse(isinstance(memoryview(b""), ByteString)) + self.assertFalse(issubclass(memoryview, ByteString)) def test_MutableSequence(self): for sample in [tuple, str, bytes]: - self.failIf(isinstance(sample(), MutableSequence)) - self.failIf(issubclass(sample, MutableSequence)) + self.assertFalse(isinstance(sample(), MutableSequence)) + self.assertFalse(issubclass(sample, MutableSequence)) for sample in [list, bytearray]: - self.failUnless(isinstance(sample(), MutableSequence)) - self.failUnless(issubclass(sample, MutableSequence)) - self.failIf(issubclass(str, MutableSequence)) + self.assertTrue(isinstance(sample(), MutableSequence)) + self.assertTrue(issubclass(sample, MutableSequence)) + self.assertFalse(issubclass(str, MutableSequence)) self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__', '__len__', '__getitem__', '__setitem__', '__delitem__', 'insert') @@ -506,10 +506,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]) @@ -581,7 +581,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)) @@ -597,7 +597,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 @@ -622,7 +622,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): @@ -697,7 +697,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:]) @@ -778,7 +778,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)) @@ -791,7 +791,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_compile.py b/Lib/test/test_compile.py index ae8a648..32dd656 100644 --- a/Lib/test/test_compile.py +++ b/Lib/test/test_compile.py @@ -376,10 +376,10 @@ if 1: import __mangled_mod import __package__.module - self.assert_("_A__mangled" in A.f.__code__.co_varnames) - self.assert_("__not_mangled__" in A.f.__code__.co_varnames) - self.assert_("_A__mangled_mod" in A.f.__code__.co_varnames) - self.assert_("__package__" in A.f.__code__.co_varnames) + self.assertTrue("_A__mangled" in A.f.__code__.co_varnames) + self.assertTrue("__not_mangled__" in A.f.__code__.co_varnames) + self.assertTrue("_A__mangled_mod" in A.f.__code__.co_varnames) + self.assertTrue("__package__" in A.f.__code__.co_varnames) def test_compile_ast(self): fname = __file__ @@ -398,7 +398,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_complex.py b/Lib/test/test_complex.py index f621186..faa7e1f 100644 --- a/Lib/test/test_complex.py +++ b/Lib/test/test_complex.py @@ -35,7 +35,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: @@ -66,7 +66,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.""" @@ -174,8 +174,8 @@ class ComplexTest(unittest.TestCase): def test_boolcontext(self): for i in range(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) @@ -257,7 +257,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 3f0b234..622dfd4 100644 --- a/Lib/test/test_contains.py +++ b/Lib/test/test_contains.py @@ -20,19 +20,19 @@ class TestContains(unittest.TestCase): a = base_set(1) b = myset(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') @@ -40,15 +40,15 @@ class TestContains(unittest.TestCase): # 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 @@ -64,7 +64,7 @@ class TestContains(unittest.TestCase): self.aList.remove(14) return 0 - self.assert_(Deviant1() not in Deviant1.aList) + self.assertTrue(Deviant1() not in Deviant1.aList) def test_nonreflexive(self): # containment and equality tests involving elements that are @@ -81,9 +81,9 @@ class TestContains(unittest.TestCase): for constructor in constructors: container = constructor(values) for elem in container: - self.assert_(elem in container) - self.assert_(container == constructor(values)) - self.assert_(container == container) + self.assertTrue(elem in container) + self.assertTrue(container == constructor(values)) + self.assertTrue(container == container) def test_main(): diff --git a/Lib/test/test_contextlib.py b/Lib/test/test_contextlib.py index f97cd81..015a0c5 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_copy.py b/Lib/test/test_copy.py index 502bf3f..2af2109 100644 --- a/Lib/test/test_copy.py +++ b/Lib/test/test_copy.py @@ -17,8 +17,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 @@ -59,7 +59,7 @@ class TestCopy(unittest.TestCase): raise 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): @@ -67,7 +67,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): @@ -91,7 +91,7 @@ class TestCopy(unittest.TestCase): "hello", "hello\u1234", f.__code__, NewStyle, range(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] @@ -185,9 +185,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 @@ -232,7 +232,7 @@ class TestCopy(unittest.TestCase): raise 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): @@ -240,7 +240,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): @@ -264,14 +264,14 @@ class TestCopy(unittest.TestCase): "hello", "hello\u1234", f.__code__, NewStyle, range(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 = [] @@ -279,16 +279,16 @@ class TestCopy(unittest.TestCase): y = copy.deepcopy(x) for op in comparisons: self.assertRaises(RuntimeError, op, 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 = ([],) @@ -296,16 +296,16 @@ class TestCopy(unittest.TestCase): y = copy.deepcopy(x) for op in comparisons: self.assertRaises(RuntimeError, op, 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 = {} @@ -315,15 +315,15 @@ class TestCopy(unittest.TestCase): self.assertRaises(TypeError, op, y, x) for op in equality_comparisons: self.assertRaises(RuntimeError, op, 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: @@ -334,7 +334,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: @@ -347,8 +347,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: @@ -361,8 +361,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: @@ -375,8 +375,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: @@ -389,8 +389,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: @@ -405,8 +405,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: @@ -414,8 +414,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() @@ -425,9 +425,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): @@ -436,9 +436,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): @@ -452,7 +452,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): @@ -468,7 +468,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): @@ -476,8 +476,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 @@ -491,12 +491,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): @@ -508,12 +508,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): @@ -521,7 +521,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): @@ -530,7 +530,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): @@ -540,8 +540,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): @@ -551,8 +551,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): @@ -569,8 +569,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_copyreg.py b/Lib/test/test_copyreg.py index 48e58ea..4fb89d0 100644 --- a/Lib/test/test_copyreg.py +++ b/Lib/test/test_copyreg.py @@ -51,10 +51,10 @@ class CopyRegTestCase(unittest.TestCase): mod, func, code) copyreg.add_extension(mod, func, code) # Should be in the registry. - self.assert_(copyreg._extension_registry[mod, func] == code) - self.assert_(copyreg._inverted_registry[code] == (mod, func)) + self.assertTrue(copyreg._extension_registry[mod, func] == code) + self.assertTrue(copyreg._inverted_registry[code] == (mod, func)) # Shouldn't be in the cache. - self.assert_(code not in copyreg._extension_cache) + self.assertTrue(code not in copyreg._extension_cache) # Redundant registration should be OK. copyreg.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 copyreg._extension_registry) + self.assertTrue((mod, func) not in copyreg._extension_registry) # The code *may* be in copyreg._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 7eb3a7f..95105be 100644 --- a/Lib/test/test_csv.py +++ b/Lib/test/test_csv.py @@ -315,7 +315,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) @@ -326,8 +326,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) @@ -811,7 +811,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 b9d5959..8bf8420 100644 --- a/Lib/test/test_datetime.py +++ b/Lib/test/test_datetime.py @@ -77,9 +77,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) @@ -88,7 +88,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") @@ -99,25 +99,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') @@ -134,16 +134,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, 20, [], me]) - self.failIf(me not in [1, 20, [], me]) + self.assertTrue(me in [1, 20, [], me]) + self.assertFalse(me not in [1, 20, [], me]) - self.failUnless([] in [me, 1, 20, []]) - self.failIf([] not in [me, 1, 20, []]) + self.assertTrue([] in [me, 1, 20, []]) + self.assertFalse([] not in [me, 1, 20, []]) def test_harmful_mixed_comparison(self): me = self.theclass(1, 1, 1) @@ -303,26 +303,26 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): t1 = timedelta(2, 3, 4) t2 = timedelta(2, 3, 4) self.assertEqual(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(not t1 != t2) + self.assertTrue(not t1 < t2) + self.assertTrue(not t1 > t2) 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) for badarg in OTHERSTUFF: self.assertEqual(t1 == badarg, False) @@ -368,7 +368,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) @@ -378,10 +378,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)) @@ -428,11 +428,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): @@ -448,17 +448,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) @@ -521,7 +521,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) @@ -755,7 +755,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): @@ -891,10 +891,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 @@ -943,26 +943,26 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): t1 = self.theclass(2, 3, 4) t2 = self.theclass(2, 3, 4) self.assertEqual(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(not t1 != t2) + self.assertTrue(not t1 < t2) + self.assertTrue(not t1 > t2) 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) for badarg in OTHERSTUFF: self.assertEqual(t1 == badarg, False) @@ -1031,8 +1031,8 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): 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. @@ -1155,7 +1155,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) @@ -1228,7 +1228,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 @@ -1239,7 +1239,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 @@ -1420,28 +1420,28 @@ class TestDateTime(TestDate): t1 = self.theclass(*args) t2 = self.theclass(*args) self.assertEqual(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(not t1 != t2) + self.assertTrue(not t1 < t2) + self.assertTrue(not t1 > t2) for i in range(len(args)): 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) # A helper for timestamp constructor tests. @@ -1520,7 +1520,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 @@ -1689,7 +1689,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) @@ -1704,28 +1704,28 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase): t1 = self.theclass(*args) t2 = self.theclass(*args) self.assertEqual(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(not t1 != t2) + self.assertTrue(not t1 < t2) + self.assertTrue(not t1 > t2) for i in range(len(args)): 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) for badarg in OTHERSTUFF: self.assertEqual(t1 == badarg, False) @@ -1876,10 +1876,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 @@ -1899,12 +1899,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 @@ -2001,7 +2001,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): @@ -2040,9 +2040,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) @@ -2137,7 +2137,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) @@ -2152,25 +2152,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)) @@ -2246,7 +2246,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') @@ -2255,20 +2255,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, "")) @@ -2302,13 +2302,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) @@ -2345,7 +2345,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): @@ -2401,9 +2401,9 @@ 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.assertEqual(t1, t1) self.assertEqual(t2, t2) @@ -2415,21 +2415,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 @@ -2473,7 +2473,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') @@ -2544,7 +2544,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. @@ -2563,15 +2563,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) @@ -2580,7 +2580,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) - @@ -2607,7 +2607,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) @@ -2624,7 +2624,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): @@ -2645,7 +2645,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) @@ -2840,13 +2840,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) @@ -2859,20 +2859,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 @@ -2880,7 +2880,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): @@ -2955,7 +2955,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): @@ -3306,10 +3306,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) diff --git a/Lib/test/test_dbm.py b/Lib/test/test_dbm.py index 35d12e4..818be45 100644 --- a/Lib/test/test_dbm.py +++ b/Lib/test/test_dbm.py @@ -57,7 +57,7 @@ class AnyDBMTestCase(unittest.TestCase): return keys def test_error(self): - self.assert_(issubclass(self.module.error, IOError)) + self.assertTrue(issubclass(self.module.error, IOError)) def test_anydbm_not_existing(self): self.assertRaises(dbm.error, dbm.open, _fname) @@ -154,9 +154,9 @@ class WhichDBTestCase(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_(b'xxx' not in self.d) + self.assertTrue(b'xxx' not in self.d) self.assertRaises(KeyError, lambda: self.d[b'xxx']) self.d.close() diff --git a/Lib/test/test_dbm_dumb.py b/Lib/test/test_dbm_dumb.py index e2964aa..956eec6 100644 --- a/Lib/test/test_dbm_dumb.py +++ b/Lib/test/test_dbm_dumb.py @@ -118,7 +118,7 @@ class DumbDBMTestCase(unittest.TestCase): f['1'] = 'a' f.close() f = dumbdbm.open(_fname, 'r') - self.assert_('\u00fc' in f) + self.assertTrue('\u00fc' in f) self.assertEqual(f['\u00fc'.encode('utf-8')], self._dict['\u00fc'.encode('utf-8')]) self.assertEqual(f[b'1'], b'a') diff --git a/Lib/test/test_dbm_gnu.py b/Lib/test/test_dbm_gnu.py index 857aeb1..2173b92 100755 --- a/Lib/test/test_dbm_gnu.py +++ b/Lib/test/test_dbm_gnu.py @@ -24,11 +24,11 @@ class TestGdbm(unittest.TestCase): self.g[b'bytes'] = b'data' key_set = set(self.g.keys()) self.assertEqual(key_set, set([b'a', b'bytes', b'12345678910'])) - self.assert_(b'a' in self.g) + self.assertTrue(b'a' in self.g) self.assertEqual(self.g[b'bytes'], b'data') 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']) @@ -66,7 +66,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. @@ -74,7 +74,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_dbm_ndbm.py b/Lib/test/test_dbm_ndbm.py index c5e968f..141d4b3 100755 --- a/Lib/test/test_dbm_ndbm.py +++ b/Lib/test/test_dbm_ndbm.py @@ -19,12 +19,12 @@ class DbmTestCase(unittest.TestCase): def test_keys(self): self.d = dbm.ndbm.open(self.filename, 'c') - self.assert_(self.d.keys() == []) + self.assertTrue(self.d.keys() == []) self.d['a'] = 'b' self.d[b'bytes'] = b'data' self.d['12345678910'] = '019237410982340912840198242' self.d.keys() - self.assert_(b'a' in self.d) + self.assertTrue(b'a' in self.d) self.assertEqual(self.d[b'bytes'], b'data') self.d.close() diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py index ceca186..43f2a08 100644 --- a/Lib/test/test_decimal.py +++ b/Lib/test/test_decimal.py @@ -507,7 +507,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')) @@ -1050,12 +1050,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 @@ -1128,18 +1128,18 @@ 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.assertTrue(dc > da) + self.assertTrue(dc >= da) + self.assertTrue(da < dc) + self.assertTrue(da <= dc) self.assertEqual(da, db) - self.failUnless(da != dc) - self.failUnless(da <= db) - self.failUnless(da >= db) + self.assertTrue(da != dc) + self.assertTrue(da <= db) + self.assertTrue(da >= db) #a Decimal and an int - self.failUnless(dc > 23) - self.failUnless(23 < dc) + self.assertTrue(dc > 23) + self.assertTrue(23 < dc) self.assertEqual(dc, 45) #a Decimal and uncomparable @@ -1200,8 +1200,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) @@ -1228,22 +1228,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. @@ -1513,10 +1513,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') @@ -1555,9 +1555,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'))), @@ -1604,8 +1604,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 @@ -1625,9 +1625,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 @@ -1636,10 +1636,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 00bd9dc..35468b4 100644 --- a/Lib/test/test_defaultdict.py +++ b/Lib/test/test_defaultdict.py @@ -25,21 +25,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: @@ -68,7 +68,7 @@ class TestDefaultDict(unittest.TestCase): self.assertEqual(repr(d2), "defaultdict(<class '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)) @@ -127,7 +127,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) @@ -150,7 +150,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 fab5a7c..1a03188 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(range(200)) @@ -461,7 +461,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 ac5ab68..e447d5a 100644 --- a/Lib/test/test_descr.py +++ b/Lib/test/test_descr.py @@ -387,12 +387,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): @@ -405,13 +405,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) @@ -504,7 +504,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) @@ -569,7 +569,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) @@ -960,7 +960,7 @@ order (MRO) for bases """ x = C() x.foo = 5 self.assertEqual(x.foo, 5) - self.assert_(type(slots[0]) is str) + self.assertTrue(type(slots[0]) is str) # this used to leak references try: class C(object): @@ -1049,7 +1049,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}) @@ -1057,7 +1057,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 @@ -1069,16 +1069,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}) @@ -1094,7 +1094,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) @@ -1350,7 +1350,7 @@ order (MRO) for bases """ class E: # *not* subclassing from C foo = C.foo self.assertEqual(E().foo.__func__, 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... @@ -1537,7 +1537,7 @@ order (MRO) for bases """ class E(object): foo = C.foo self.assertEqual(E().foo.__func__, 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 @@ -1648,21 +1648,21 @@ 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(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): @@ -1671,21 +1671,21 @@ 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(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 class Proxy(object): @@ -1717,22 +1717,22 @@ 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.assert_(p0 < p1) - self.assert_(p0 <= p1) - self.assert_(p1 > p0) - self.assert_(p1 >= p0) + self.assertTrue(p0 < p1) + self.assertTrue(p0 <= p1) + self.assertTrue(p1 > p0) + self.assertTrue(p1 >= p0) self.assertEqual(str(p0), "Proxy:0") self.assertEqual(repr(p0), "Proxy(0)") 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) def test_weakrefs(self): @@ -1753,7 +1753,7 @@ order (MRO) for bases """ try: weakref.ref(no) except TypeError as 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): @@ -1790,18 +1790,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: @@ -1863,7 +1863,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 @@ -2021,12 +2021,12 @@ order (MRO) for bases """ c = C() self.assertEqual(interesting(dir(c)), cstuff) - ## self.assert_('__self__' in dir(C.Cmethod)) + ## self.assertTrue('__self__' in dir(C.Cmethod)) c.cdata = 2 c.cmethod = lambda self: 0 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod']) - ## self.assert_('__self__' in dir(c.Cmethod)) + ## self.assertTrue('__self__' in dir(c.Cmethod)) class A(C): Adata = 1 @@ -2034,13 +2034,13 @@ order (MRO) for bases """ astuff = ['Adata', 'Amethod'] + cstuff self.assertEqual(interesting(dir(A)), astuff) - ## self.assert_('__self__' in dir(A.Amethod)) + ## self.assertTrue('__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_('__self__' in dir(a.Amethod)) + ## self.assertTrue('__self__' in dir(a.Amethod)) # Try a module subclass. import sys @@ -2224,13 +2224,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(int): __slots__ = [] @@ -2250,36 +2250,36 @@ order (MRO) for bases """ self.assertEqual(a, 12345) self.assertEqual(int(a), 12345) self.assertEqual(hash(a), hash(12345)) - self.assert_(int(a).__class__ is int) - self.assert_((+a).__class__ is int) - self.assert_((-a).__class__ is int) - self.assert_((-octlong(0)).__class__ is int) - self.assert_((a >> 0).__class__ is int) - self.assert_((a << 0).__class__ is int) - self.assert_((a - 0).__class__ is int) - self.assert_((a * 1).__class__ is int) - self.assert_((a ** 1).__class__ is int) - self.assert_((a // 1).__class__ is int) - self.assert_((1 * a).__class__ is int) - self.assert_((a | 0).__class__ is int) - self.assert_((a ^ 0).__class__ is int) - self.assert_((a & -1).__class__ is int) - self.assert_((octlong(0) << 12).__class__ is int) - self.assert_((octlong(0) >> 12).__class__ is int) - self.assert_(abs(octlong(0)).__class__ is int) + self.assertTrue(int(a).__class__ is int) + self.assertTrue((+a).__class__ is int) + self.assertTrue((-a).__class__ is int) + self.assertTrue((-octlong(0)).__class__ is int) + self.assertTrue((a >> 0).__class__ is int) + self.assertTrue((a << 0).__class__ is int) + self.assertTrue((a - 0).__class__ is int) + self.assertTrue((a * 1).__class__ is int) + self.assertTrue((a ** 1).__class__ is int) + self.assertTrue((a // 1).__class__ is int) + self.assertTrue((1 * a).__class__ is int) + self.assertTrue((a | 0).__class__ is int) + self.assertTrue((a ^ 0).__class__ is int) + self.assertTrue((a & -1).__class__ is int) + self.assertTrue((octlong(0) << 12).__class__ is int) + self.assertTrue((octlong(0) >> 12).__class__ is int) + self.assertTrue(abs(octlong(0)).__class__ is int) # Because octlong overrides __add__, we can't check the absence of +0 # optimizations using octlong. class longclone(int): pass a = longclone(1) - self.assert_((a + 0).__class__ is int) - self.assert_((0 + a).__class__ is int) + self.assertTrue((a + 0).__class__ is int) + self.assertTrue((0 + a).__class__ is int) # Check that negative clones don't segfault a = longclone(-1) self.assertEqual(a.__dict__, {}) - self.assertEqual(int(a), -1) # self.assert_ PyNumber_Long() copies the sign bit + self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit class precfloat(float): __slots__ = ['prec'] @@ -2291,9 +2291,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): @@ -2341,20 +2341,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 @@ -2376,48 +2376,48 @@ 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 = {} - 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.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(str): @@ -2436,47 +2436,47 @@ order (MRO) for bases """ base = "12345" u = madunicode(base) self.assertEqual(str(u), base) - self.assert_(str(u).__class__ is str) + self.assertTrue(str(u).__class__ is str) self.assertEqual(hash(u), hash(base)) self.assertEqual({u: 1}[base], 1) self.assertEqual({base: 1}[u], 1) - self.assert_(u.strip().__class__ is str) + self.assertTrue(u.strip().__class__ is str) self.assertEqual(u.strip(), base) - self.assert_(u.lstrip().__class__ is str) + self.assertTrue(u.lstrip().__class__ is str) self.assertEqual(u.lstrip(), base) - self.assert_(u.rstrip().__class__ is str) + self.assertTrue(u.rstrip().__class__ is str) self.assertEqual(u.rstrip(), base) - self.assert_(u.replace("x", "x").__class__ is str) + self.assertTrue(u.replace("x", "x").__class__ is str) self.assertEqual(u.replace("x", "x"), base) - self.assert_(u.replace("xy", "xy").__class__ is str) + self.assertTrue(u.replace("xy", "xy").__class__ is str) self.assertEqual(u.replace("xy", "xy"), base) - self.assert_(u.center(len(u)).__class__ is str) + self.assertTrue(u.center(len(u)).__class__ is str) self.assertEqual(u.center(len(u)), base) - self.assert_(u.ljust(len(u)).__class__ is str) + self.assertTrue(u.ljust(len(u)).__class__ is str) self.assertEqual(u.ljust(len(u)), base) - self.assert_(u.rjust(len(u)).__class__ is str) + self.assertTrue(u.rjust(len(u)).__class__ is str) self.assertEqual(u.rjust(len(u)), base) - self.assert_(u.lower().__class__ is str) + self.assertTrue(u.lower().__class__ is str) self.assertEqual(u.lower(), base) - self.assert_(u.upper().__class__ is str) + self.assertTrue(u.upper().__class__ is str) self.assertEqual(u.upper(), base) - self.assert_(u.capitalize().__class__ is str) + self.assertTrue(u.capitalize().__class__ is str) self.assertEqual(u.capitalize(), base) - self.assert_(u.title().__class__ is str) + self.assertTrue(u.title().__class__ is str) self.assertEqual(u.title(), base) - self.assert_((u + "").__class__ is str) + self.assertTrue((u + "").__class__ is str) self.assertEqual(u + "", base) - self.assert_(("" + u).__class__ is str) + self.assertTrue(("" + u).__class__ is str) self.assertEqual("" + u, base) - self.assert_((u * 0).__class__ is str) + self.assertTrue((u * 0).__class__ is str) self.assertEqual(u * 0, "") - self.assert_((u * 1).__class__ is str) + self.assertTrue((u * 1).__class__ is str) self.assertEqual(u * 1, base) - self.assert_((u * 2).__class__ is str) + self.assertTrue((u * 2).__class__ is str) self.assertEqual(u * 2, base + base) - self.assert_(u[:].__class__ is str) + self.assertTrue(u[:].__class__ is str) self.assertEqual(u[:], base) - self.assert_(u[0:0].__class__ is str) + self.assertTrue(u[0:0].__class__ is str) self.assertEqual(u[0:0], "") class sublist(list): @@ -2595,7 +2595,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): @@ -2652,13 +2652,13 @@ 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) == + 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) == + 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) == + self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y)) @@ -2731,11 +2731,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_descrdoc(self): @@ -2775,9 +2775,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 @@ -2833,11 +2833,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: @@ -3006,7 +3006,7 @@ order (MRO) for bases """ for cls in C, C1, C2: s = pickle.dumps(cls, bin) cls2 = pickle.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) @@ -3036,7 +3036,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) @@ -3579,8 +3579,8 @@ order (MRO) for bases """ __slots__=() if 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): @@ -3914,29 +3914,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... @@ -4065,17 +4065,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 1c9bca8..1519689 100644 --- a/Lib/test/test_dict.py +++ b/Lib/test/test_dict.py @@ -10,7 +10,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 @@ -24,18 +24,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(set(d.keys()), set()) d = {'a': 1, 'b': 2} k = d.keys() - self.assert_('a' in d) - self.assert_('b' in d) + self.assertTrue('a' in d) + self.assertTrue('b' in d) self.assertRaises(TypeError, d.keys, None) self.assertEqual(repr(dict(a=1).keys()), "dict_keys(['a'])") @@ -58,12 +58,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__) @@ -197,7 +197,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([]), {}) @@ -208,14 +208,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 collections.UserDict() ud = mydict.fromkeys('ab') self.assertEqual(ud, {'a':None, 'b':None}) - self.assert_(isinstance(ud, collections.UserDict)) + self.assertTrue(isinstance(ud, collections.UserDict)) self.assertRaises(TypeError, dict.fromkeys) class Exc(Exception): pass @@ -252,10 +252,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) @@ -265,9 +265,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) @@ -309,9 +309,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) @@ -525,8 +525,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): @@ -663,7 +663,7 @@ class DictTest(unittest.TestCase): obj.x = iter(obj.v) 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_dictviews.py b/Lib/test/test_dictviews.py index 34883d2..4fee755 100644 --- a/Lib/test/test_dictviews.py +++ b/Lib/test/test_dictviews.py @@ -24,10 +24,10 @@ class DictSetTest(unittest.TestCase): self.assertNotEqual(keys, {1, "b"}) self.assertNotEqual(keys, {1}) self.assertNotEqual(keys, 42) - self.assert_(1 in keys) - self.assert_("a" in keys) - self.assert_(10 not in keys) - self.assert_("Z" not in keys) + self.assertTrue(1 in keys) + self.assertTrue("a" in keys) + self.assertTrue(10 not in keys) + self.assertTrue("Z" not in keys) self.assertEqual(d.keys(), d.keys()) e = {1: 11, "a": "def"} self.assertEqual(d.keys(), e.keys()) @@ -44,13 +44,13 @@ class DictSetTest(unittest.TestCase): self.assertNotEqual(items, {(1, 10), ("a", "def")}) self.assertNotEqual(items, {(1, 10)}) self.assertNotEqual(items, 42) - self.assert_((1, 10) in items) - self.assert_(("a", "ABC") in items) - self.assert_((1, 11) not in items) - self.assert_(1 not in items) - self.assert_(() not in items) - self.assert_((1,) not in items) - self.assert_((1, 2, 3) not in items) + self.assertTrue((1, 10) in items) + self.assertTrue(("a", "ABC") in items) + self.assertTrue((1, 11) not in items) + self.assertTrue(1 not in items) + self.assertTrue(() not in items) + self.assertTrue((1,) not in items) + self.assertTrue((1, 2, 3) not in items) self.assertEqual(d.items(), d.items()) e = d.copy() self.assertEqual(d.items(), e.items()) diff --git a/Lib/test/test_docxmlrpc.py b/Lib/test/test_docxmlrpc.py index bd96e23..7bffa48 100644 --- a/Lib/test/test_docxmlrpc.py +++ b/Lib/test/test_docxmlrpc.py @@ -104,7 +104,7 @@ class DocXMLRPCHTTPGETServer(unittest.TestCase): self.client.request("GET", "/") response = self.client.getresponse() - self.assert_( + self.assertTrue( b"""<dl><dt><a name="-<lambda>"><strong><lambda></strong></a>(x, y)</dt></dl>""" in response.read()) @@ -118,7 +118,7 @@ b"""<dl><dt><a name="-<lambda>"><strong><lambda></strong></a>(x, y)< self.client.request("GET", "/") response = self.client.getresponse().read() - self.assert_( # This is ugly ... how can it be made better? + self.assertTrue( # This is ugly ... how can it be made better? b"""<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, response) @@ -131,7 +131,7 @@ b"""<dl><dt><a name="-add"><strong>add</strong></a>(x, y)</dt><dd><tt>Add t self.client.request("GET", "/") response = self.client.getresponse().read() - self.assert_( + self.assertTrue( b"""<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>\n<dl><dt><a name="-test_method"><strong>test_method</strong></a>(arg)</dt><dd><tt>Test method\'s docs. This method truly does very little.</tt></dd></dl>""" in response) def test_autolink_dotted_methods(self): @@ -140,7 +140,7 @@ b"""<dl><dt><a name="-system.methodHelp"><strong>system.methodHelp</strong></a>( self.client.request("GET", "/") response = self.client.getresponse() - self.assert_(b"""Try self.<strong>add</strong>, too.""" in + self.assertTrue(b"""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 ecac3ee..240b61a 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 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 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 ab6bf0b..847b991 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 as 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 as 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(b"Hello!") server.send(b"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 28425e2..80edcc6 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.values(): - 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__.keys(): 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 8bb2079..89e6ebb 100644 --- a/Lib/test/test_exceptions.py +++ b/Lib/test/test_exceptions.py @@ -155,7 +155,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.py')) + self.assertTrue(co.co_filename.endswith('test_exceptions.py')) else: self.fail("Expected exception") @@ -167,7 +167,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.py')) + self.assertTrue(co.co_filename.endswith('test_exceptions.py')) co2 = tb.tb_frame.f_back.f_code self.assertEquals(co2.co_name, "test_capi2") else: @@ -189,12 +189,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 @@ -319,25 +319,25 @@ class ExceptionTests(unittest.TestCase): tb = sys.exc_info()[2] e = BaseException().with_traceback(tb) - self.failUnless(isinstance(e, BaseException)) + self.assertTrue(isinstance(e, BaseException)) self.assertEqual(e.__traceback__, tb) e = IndexError(5).with_traceback(tb) - self.failUnless(isinstance(e, IndexError)) + self.assertTrue(isinstance(e, IndexError)) self.assertEqual(e.__traceback__, tb) class MyException(Exception): pass e = MyException().with_traceback(tb) - self.failUnless(isinstance(e, MyException)) + self.assertTrue(isinstance(e, MyException)) self.assertEqual(e.__traceback__, tb) def testInvalidTraceback(self): try: Exception().__traceback__ = 5 except TypeError as e: - self.failUnless("__traceback__ must be a traceback" in str(e)) + self.assertTrue("__traceback__ must be a traceback" in str(e)) else: self.fail("No exception raised") @@ -402,10 +402,10 @@ 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(str(Exception)) - self.failUnless(str(Exception('a'))) - self.failUnless(str(Exception('a'))) + self.assertTrue(str(Exception)) + self.assertTrue(str(Exception)) + self.assertTrue(str(Exception('a'))) + self.assertTrue(str(Exception('a'))) def testExceptionCleanupNames(self): # Make sure the local variable bound to the exception instance by @@ -413,9 +413,9 @@ class ExceptionTests(unittest.TestCase): try: raise Exception() except Exception as e: - self.failUnless(e) + self.assertTrue(e) del e - self.failIf('e' in locals()) + self.assertFalse('e' in locals()) def testExceptionCleanupState(self): # Make sure exception state is cleaned up as soon as the except @@ -441,7 +441,7 @@ class ExceptionTests(unittest.TestCase): pass obj = None obj = wr() - self.failUnless(obj is None, "%s" % obj) + self.assertTrue(obj is None, "%s" % obj) # Qualified "except" without "as" obj = MyObj() @@ -452,7 +452,7 @@ class ExceptionTests(unittest.TestCase): pass obj = None obj = wr() - self.failUnless(obj is None, "%s" % obj) + self.assertTrue(obj is None, "%s" % obj) # Bare "except" obj = MyObj() @@ -463,7 +463,7 @@ class ExceptionTests(unittest.TestCase): pass obj = None obj = wr() - self.failUnless(obj is None, "%s" % obj) + self.assertTrue(obj is None, "%s" % obj) # "except" with premature block leave obj = MyObj() @@ -475,7 +475,7 @@ class ExceptionTests(unittest.TestCase): break obj = None obj = wr() - self.failUnless(obj is None, "%s" % obj) + self.assertTrue(obj is None, "%s" % obj) # "except" block raising another exception obj = MyObj() @@ -493,7 +493,7 @@ class ExceptionTests(unittest.TestCase): e.__context__ = None obj = None obj = wr() - self.failUnless(obj is None, "%s" % obj) + self.assertTrue(obj is None, "%s" % obj) # Some complicated construct obj = MyObj() @@ -510,7 +510,7 @@ class ExceptionTests(unittest.TestCase): pass obj = None obj = wr() - self.failUnless(obj is None, "%s" % obj) + self.assertTrue(obj is None, "%s" % obj) # Inside an exception-silencing "with" block class Context: @@ -524,7 +524,7 @@ class ExceptionTests(unittest.TestCase): inner_raising_func() obj = None obj = wr() - self.failUnless(obj is None, "%s" % obj) + self.assertTrue(obj is None, "%s" % obj) def test_generator_leaking(self): # Test that generator exception state doesn't leak into the calling @@ -598,8 +598,8 @@ class ExceptionTests(unittest.TestCase): except RuntimeError: return sys.exc_info() e, v, tb = g() - self.assert_(isinstance(v, RuntimeError), type(v)) - self.assert_("maximum recursion depth exceeded" in str(v), str(v)) + self.assertTrue(isinstance(v, RuntimeError), type(v)) + self.assertTrue("maximum recursion depth exceeded" in str(v), str(v)) def test_MemoryError(self): diff --git a/Lib/test/test_file.py b/Lib/test/test_file.py index 3360121..bd2d7c0 100644 --- a/Lib/test/test_file.py +++ b/Lib/test/test_file.py @@ -83,13 +83,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', ()), @@ -111,7 +111,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_filecmp.py b/Lib/test/test_filecmp.py index 22f0be7..c71a27a 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") @@ -104,14 +104,14 @@ class DirCompareTestCase(unittest.TestCase): else: self.assertEqual([d.left_list, d.right_list],[['file'], ['file']]) self.assertEqual(d.common, ['file']) - self.failUnless(d.left_only == d.right_only == []) + self.assertTrue(d.left_only == d.right_only == []) self.assertEqual(d.same_files, ['file']) self.assertEqual(d.diff_files, []) # Check attributes for comparison of two different directories d = filecmp.dircmp(self.dir, self.dir_diff) self.assertEqual(d.left_list, ['file']) - self.failUnless(d.right_list == ['file', 'file2']) + self.assertTrue(d.right_list == ['file', 'file2']) self.assertEqual(d.common, ['file']) self.assertEqual(d.left_only, []) self.assertEqual(d.right_only, ['file2']) diff --git a/Lib/test/test_fileinput.py b/Lib/test/test_fileinput.py index a4d59e1..aae16ea 100644 --- a/Lib/test/test_fileinput.py +++ b/Lib/test/test_fileinput.py @@ -68,8 +68,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)) @@ -138,7 +138,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 657401e..679ed08 100644 --- a/Lib/test/test_fileio.py +++ b/Lib/test/test_fileio.py @@ -80,17 +80,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', @@ -100,7 +100,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 e74e892..af5e13c 100644 --- a/Lib/test/test_float.py +++ b/Lib/test/test_float.py @@ -136,27 +136,27 @@ class GeneralFloatCases(unittest.TestCase): def test_float_containment(self): floats = (INF, -INF, 0.0, 1.0, NAN) for f in floats: - self.assert_(f in [f], "'%r' not in []" % f) - self.assert_(f in (f,), "'%r' not in ()" % f) - self.assert_(f in {f}, "'%r' not in set()" % f) - self.assert_(f in {f: None}, "'%r' not in {}" % f) + self.assertTrue(f in [f], "'%r' not in []" % f) + self.assertTrue(f in (f,), "'%r' not in ()" % f) + self.assertTrue(f in {f}, "'%r' not in set()" % f) + self.assertTrue(f in {f: None}, "'%r' not in {}" % f) self.assertEqual([f].count(f), 1, "[].count('%r') != 1" % f) - self.assert_(f in floats, "'%r' not in container" % f) + self.assertTrue(f in floats, "'%r' not in container" % f) for f in floats: # nonidentical containers, same type, same contents - self.assert_([f] == [f], "[%r] != [%r]" % (f, f)) - self.assert_((f,) == (f,), "(%r,) != (%r,)" % (f, f)) - self.assert_({f} == {f}, "{%r} != {%r}" % (f, f)) - self.assert_({f : None} == {f: None}, "{%r : None} != " + self.assertTrue([f] == [f], "[%r] != [%r]" % (f, f)) + self.assertTrue((f,) == (f,), "(%r,) != (%r,)" % (f, f)) + self.assertTrue({f} == {f}, "{%r} != {%r}" % (f, f)) + self.assertTrue({f : None} == {f: None}, "{%r : None} != " "{%r : None}" % (f, f)) # identical containers l, t, s, d = [f], (f,), {f}, {f: None} - self.assert_(l == l, "[%r] not equal to itself" % f) - self.assert_(t == t, "(%r,) not equal to itself" % f) - self.assert_(s == s, "{%r} not equal to itself" % f) - self.assert_(d == d, "{%r : None} not equal to itself" % f) + self.assertTrue(l == l, "[%r] not equal to itself" % f) + self.assertTrue(t == t, "(%r,) not equal to itself" % f) + self.assertTrue(s == s, "{%r} not equal to itself" % f) + self.assertTrue(d == d, "{%r : None} not equal to itself" % f) @@ -171,9 +171,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) @@ -493,12 +493,12 @@ class RoundTestCase(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") @@ -545,9 +545,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") @@ -581,14 +581,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 30ccf69..2f701ca 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 afc8fda..b83cba0 100644 --- a/Lib/test/test_ftplib.py +++ b/Lib/test/test_ftplib.py @@ -444,7 +444,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") @@ -456,7 +456,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 b42f6cc..5765b4e 100644 --- a/Lib/test/test_funcattrs.py +++ b/Lib/test/test_funcattrs.py @@ -35,11 +35,11 @@ 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.known_attr = 7 - self.assert_('known_attr' in dir(self.fi.a), "set attribute on function " + self.assertTrue('known_attr' in dir(self.fi.a), "set attribute on function " "implementations, should show up in next dir") def test_duplicate_function_equality(self): @@ -248,11 +248,11 @@ class CellTest(unittest.TestCase): # their presence should not be interpreted as providing any # guarantees about the semantics (or even existence) of cell # comparisons in future versions of CPython. - self.assert_(cell(2) < cell(3)) - self.assert_(empty_cell() < cell('saturday')) - self.assert_(empty_cell() == empty_cell()) - self.assert_(cell(-36) == cell(-36.0)) - self.assert_(cell(True) > empty_cell()) + self.assertTrue(cell(2) < cell(3)) + self.assertTrue(empty_cell() < cell('saturday')) + self.assertTrue(empty_cell() == empty_cell()) + self.assertTrue(cell(-36) == cell(-36.0)) + self.assertTrue(cell(True) > empty_cell()) class StaticMethodAttrsTest(unittest.TestCase): def test_func_attribute(self): @@ -260,10 +260,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 dedfb1e..eff31e0 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_genericpath.py b/Lib/test/test_genericpath.py index 9d0baeb..3be9c89 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, b"foobar") - self.assert_( + self.assertTrue( genericpath.getctime(support.TESTFN) <= genericpath.getmtime(support.TESTFN) ) diff --git a/Lib/test/test_getargs2.py b/Lib/test/test_getargs2.py index 34d8ee0..3ffc1cc 100644 --- a/Lib/test/test_getargs2.py +++ b/Lib/test/test_getargs2.py @@ -68,68 +68,68 @@ class Unsigned_TestCase(unittest.TestCase): from _testcapi import getargs_b # b returns 'unsigned char', and does range checking (0 ... UCHAR_MAX) self.assertRaises(TypeError, getargs_b, 3.14) - self.failUnlessEqual(99, getargs_b(Long())) - self.failUnlessEqual(99, getargs_b(Int())) + 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(42)) + self.assertEqual(42, getargs_b(42)) + self.assertEqual(42, getargs_b(42)) self.assertRaises(OverflowError, getargs_b, VERY_LARGE) def test_B(self): from _testcapi import getargs_B # B returns 'unsigned char', no range checking self.assertRaises(TypeError, getargs_B, 3.14) - self.failUnlessEqual(99, getargs_B(Long())) - self.failUnlessEqual(99, getargs_B(Int())) + 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(-1)) - 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(-1)) + 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(42)) - self.failUnlessEqual(UCHAR_MAX & VERY_LARGE, getargs_B(VERY_LARGE)) + self.assertEqual(42, getargs_B(42)) + self.assertEqual(42, getargs_B(42)) + 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.assertRaises(TypeError, getargs_H, 3.14) - self.failUnlessEqual(99, getargs_H(Long())) - self.failUnlessEqual(99, getargs_H(Int())) + 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(42)) + self.assertEqual(42, getargs_H(42)) + self.assertEqual(42, getargs_H(42)) - 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.assertRaises(TypeError, getargs_I, 3.14) - self.failUnlessEqual(99, getargs_I(Long())) - self.failUnlessEqual(99, getargs_I(Int())) + 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(42)) + self.assertEqual(42, getargs_I(42)) + self.assertEqual(42, getargs_I(42)) - 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,47 +139,47 @@ 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(42)) + self.assertEqual(42, getargs_k(42)) + self.assertEqual(42, getargs_k(42)) - 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.assertRaises(TypeError, getargs_i, 3.14) - self.failUnlessEqual(99, getargs_i(Long())) - self.failUnlessEqual(99, getargs_i(Int())) + 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(42)) + self.assertEqual(42, getargs_i(42)) + self.assertEqual(42, getargs_i(42)) 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.assertRaises(TypeError, getargs_l, 3.14) - self.failUnlessEqual(99, getargs_l(Long())) - self.failUnlessEqual(99, getargs_l(Int())) + 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(42)) + self.assertEqual(42, getargs_l(42)) + self.assertEqual(42, getargs_l(42)) self.assertRaises(OverflowError, getargs_l, VERY_LARGE) def test_n(self): @@ -191,12 +191,12 @@ class Signed_TestCase(unittest.TestCase): self.assertRaises(TypeError, 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(42)) + self.assertEqual(42, getargs_n(42)) + self.assertEqual(42, getargs_n(42)) 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(42)) + self.assertEqual(42, getargs_L(42)) + self.assertEqual(42, getargs_L(42)) 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(42)) + self.assertEqual(42, getargs_K(42)) + self.assertEqual(42, getargs_K(42)) - 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 b7a6309..20b5690 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 0023941..d667819 100644 --- a/Lib/test/test_gettext.py +++ b/Lib/test/test_gettext.py @@ -306,7 +306,7 @@ class UnicodeTranslationsTest(GettextBaseTest): self._ = self.t.gettext def test_unicode_msgid(self): - unless = self.failUnless + unless = self.assertTrue unless(isinstance(self._(''), str)) unless(isinstance(self._(''), str)) diff --git a/Lib/test/test_grammar.py b/Lib/test/test_grammar.py index 977f0b8..b861207 100644 --- a/Lib/test/test_grammar.py +++ b/Lib/test/test_grammar.py @@ -38,9 +38,9 @@ class TokenTests(unittest.TestCase): if maxsize == 2147483647: self.assertEquals(-2147483647-1, -0o20000000000) # XXX -2147483648 - self.assert_(0o37777777777 > 0) - self.assert_(0xffffffff > 0) - self.assert_(0b1111111111111111111111111111111 > 0) + self.assertTrue(0o37777777777 > 0) + self.assertTrue(0xffffffff > 0) + self.assertTrue(0b1111111111111111111111111111111 > 0) for s in ('2147483648', '0o40000000000', '0x100000000', '0b10000000000000000000000000000000'): try: @@ -49,9 +49,9 @@ class TokenTests(unittest.TestCase): self.fail("OverflowError on huge integer literal %r" % s) elif maxsize == 9223372036854775807: self.assertEquals(-9223372036854775807-1, -0o1000000000000000000000) - self.assert_(0o1777777777777777777777 > 0) - self.assert_(0xffffffffffffffff > 0) - self.assert_(0b11111111111111111111111111111111111111111111111111111111111111 > 0) + self.assertTrue(0o1777777777777777777777 > 0) + self.assertTrue(0xffffffffffffffff > 0) + self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0) for s in '9223372036854775808', '0o2000000000000000000000', \ '0x10000000000000000', \ '0b100000000000000000000000000000000000000000000000000000000000000': @@ -87,15 +87,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 @@ -128,7 +128,7 @@ the \'lazy\' dog.\n\ def testEllipsis(self): x = ... - self.assert_(x is Ellipsis) + self.assertTrue(x is Ellipsis) self.assertRaises(SyntaxError, eval, ".. .") class GrammarTests(unittest.TestCase): @@ -494,7 +494,7 @@ class GrammarTests(unittest.TestCase): nonlocal x, y 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 1c1f75f..765b4b6 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, str)) + self.assertTrue(isinstance(value.gr_name, str)) self.assertEqual(value[1], value.gr_passwd) - self.assert_(isinstance(value.gr_passwd, str)) + self.assertTrue(isinstance(value.gr_passwd, str)) 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 baf3a21..d928635 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 not 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 5babc5a..569e5e0 100644 --- a/Lib/test/test_hash.py +++ b/Lib/test/test_hash.py @@ -91,7 +91,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 5bfea6b..d0ad07d 100644 --- a/Lib/test/test_hashlib.py +++ b/Lib/test/test_hashlib.py @@ -36,7 +36,7 @@ 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: diff --git a/Lib/test/test_heapq.py b/Lib/test/test_heapq.py index 94c3992..5e3b0ee 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 8dcbe7e..fb78eba 100644 --- a/Lib/test/test_hmac.py +++ b/Lib/test/test_hmac.py @@ -280,7 +280,7 @@ class CopyTestCase(unittest.TestCase): # Testing if attributes are of same type. h1 = hmac.HMAC(b"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.assertEqual(type(h1.inner), type(h2.inner), "Types of inner don't match.") @@ -292,10 +292,10 @@ class CopyTestCase(unittest.TestCase): h1 = hmac.HMAC(b"key") h2 = h1.copy() # Using id() in case somebody has overridden __eq__/__ne__. - 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): diff --git a/Lib/test/test_http_cookiejar.py b/Lib/test/test_http_cookiejar.py index 5ec0c25..e5f7143 100644 --- a/Lib/test/test_http_cookiejar.py +++ b/Lib/test/test_http_cookiejar.py @@ -25,7 +25,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): @@ -90,7 +90,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)) ) @@ -332,8 +332,8 @@ class CookieTests(TestCase): ]: request = urllib.request.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): # missing = sign in Cookie: header is regarded by Mozilla as a missing @@ -343,10 +343,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"; ' @@ -388,7 +388,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 @@ -410,28 +410,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 @@ -441,8 +441,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): # if expires is in future, keep cookie... @@ -457,7 +457,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 @@ -478,7 +478,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) @@ -488,39 +488,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): cases = [ @@ -589,14 +589,14 @@ class CookieTests(TestCase): self.assertEquals(request_host(req), "www.acme.com") def test_is_HDN(self): - 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): self.assertEquals(reach("www.acme.com"), ".acme.com") @@ -609,40 +609,40 @@ class CookieTests(TestCase): self.assertEquals(reach("192.168.0.1"), "192.168.0.1") def test_domain_match(self): - 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 @@ -789,7 +789,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): pol = DefaultCookiePolicy( @@ -813,7 +813,7 @@ class CookieTests(TestCase): self.assertEquals(len(c), 1) req = urllib.request.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() @@ -829,7 +829,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): for ns in True, False: @@ -847,10 +847,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") @@ -868,7 +868,7 @@ class CookieTests(TestCase): req = urllib.request.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): pol = DefaultCookiePolicy(rfc2965=True) @@ -877,21 +877,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): pol = DefaultCookiePolicy(rfc2965=True) @@ -900,14 +900,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): pol = DefaultCookiePolicy(rfc2965=True) @@ -916,28 +916,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") @@ -948,7 +948,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") @@ -977,7 +977,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]) @@ -1030,7 +1030,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): @@ -1104,7 +1104,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') @@ -1115,7 +1115,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) @@ -1123,7 +1123,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;"))) @@ -1174,7 +1174,7 @@ class LWPCookieTests(TestCase): req = urllib.request.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"))) @@ -1209,7 +1209,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 @@ -1231,7 +1231,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)) @@ -1256,10 +1256,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)) # @@ -1281,7 +1281,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) @@ -1330,7 +1330,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 @@ -1343,7 +1343,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): @@ -1357,7 +1357,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", @@ -1449,11 +1449,11 @@ class LWPCookieTests(TestCase): c, "http://www.acme.com/foo%2f%25/<<%0anew\345/\346\370\345", '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\345/\346\370\345") - self.assert_(not cookie) + self.assertTrue(not cookie) # unicode URL doesn't raise exception cookie = interact_2965(c, "http://www.acme.com/\xfc") @@ -1493,11 +1493,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. @@ -1519,7 +1519,7 @@ class LWPCookieTests(TestCase): req = urllib.request.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")) @@ -1530,11 +1530,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): c = CookieJar(DefaultCookiePolicy(rfc2965 = False)) @@ -1542,10 +1542,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): @@ -1614,7 +1614,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 accidently counter["perm_after"] != counter["perm_before"] or # a session cookie hasn't been cleared diff --git a/Lib/test/test_httplib.py b/Lib/test/test_httplib.py index d43c82d..2d76f7a 100644 --- a/Lib/test/test_httplib.py +++ b/Lib/test/test_httplib.py @@ -265,7 +265,7 @@ class TimeoutTest(TestCase): # 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 = client.HTTPConnection(HOST, TimeoutTest.PORT) @@ -276,7 +276,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 = client.HTTPConnection(HOST, TimeoutTest.PORT, diff --git a/Lib/test/test_httpservers.py b/Lib/test/test_httpservers.py index 837d4a6..13e4030 100644 --- a/Lib/test/test_httpservers.py +++ b/Lib/test/test_httpservers.py @@ -217,9 +217,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 cc6792a..70169e0 100644 --- a/Lib/test/test_imp.py +++ b/Lib/test/test_imp.py @@ -12,7 +12,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 dbfadfb7..7f1e37f 100644 --- a/Lib/test/test_import.py +++ b/Lib/test/test_import.py @@ -145,12 +145,12 @@ class ImportTest(unittest.TestCase): # import x.y.z binds x in the current namespace import test as x import test.support - self.assert_(x is test, x.__name__) - self.assert_(hasattr(test.support, "__file__")) + self.assertTrue(x is test, x.__name__) + self.assertTrue(hasattr(test.support, "__file__")) # import x.y.z as w binds z as w import test.support as y - self.assert_(y is test.support, y.__name__) + self.assertTrue(y is test.support, y.__name__) def test_import_initless_directory_warning(self): with warnings.catch_warnings(): @@ -168,7 +168,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") @@ -185,7 +185,7 @@ class ImportTest(unittest.TestCase): self.assertRaises(ZeroDivisionError, imp.reload, mod) # 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. @@ -207,12 +207,12 @@ class ImportTest(unittest.TestCase): sys.path.insert(0, os.curdir) try: mod = __import__(TESTFN) - self.failUnless(mod.__file__.endswith('.py')) + self.assertTrue(mod.__file__.endswith('.py')) os.remove(source) del sys.modules[TESTFN] mod = __import__(TESTFN) ext = mod.__file__[-4:] - self.failUnless(ext in ('.pyc', '.pyo'), ext) + self.assertTrue(ext in ('.pyc', '.pyo'), ext) finally: sys.path.pop(0) remove_files(TESTFN) diff --git a/Lib/test/test_importhooks.py b/Lib/test/test_importhooks.py index f267f79..bf2870d 100644 --- a/Lib/test/test_importhooks.py +++ b/Lib/test/test_importhooks.py @@ -177,7 +177,7 @@ class ImportHooksTestCase(ImportHooksBaseTestCase): TestImporter.modules['reloadmodule'] = (False, test_co) import reloadmodule - self.failIf(hasattr(reloadmodule,'reloaded')) + self.assertFalse(hasattr(reloadmodule,'reloaded')) import hooktestpackage.newrel self.assertEqual(hooktestpackage.newrel.get_name(), diff --git a/Lib/test/test_index.py b/Lib/test/test_index.py index 31609c3..ae905c2 100644 --- a/Lib/test/test_index.py +++ b/Lib/test/test_index.py @@ -59,10 +59,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): @@ -114,11 +114,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): @@ -151,7 +151,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) @@ -188,8 +188,8 @@ class OverflowTestCase(unittest.TestCase): (0, maxsize, 1)) 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 37be205..c1df23e 100644 --- a/Lib/test/test_inspect.py +++ b/Lib/test/test_inspect.py @@ -52,13 +52,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 range(2): @@ -91,15 +91,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') @@ -117,8 +117,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): @@ -132,7 +132,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(revise(*mod.st[0][1:]), (modfile, 16, 'eggs', [' st = inspect.stack()\n'], 0)) self.assertEqual(revise(*mod.st[1][1:]), @@ -449,25 +449,25 @@ 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, + 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: %r' % attrs) - self.assert_(('m1', 'method', A) in attrs, 'missing plain method') - self.assert_(('datablob', 'data', A) in attrs, 'missing data') + 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): @@ -476,24 +476,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 dd40ef6..d56e1f0 100644 --- a/Lib/test/test_int.py +++ b/Lib/test/test_int.py @@ -52,15 +52,15 @@ class IntTestCases(unittest.TestCase): s = repr(-1-sys.maxsize) x = int(s) self.assertEqual(x+1, -sys.maxsize) - self.assert_(isinstance(x, int)) + self.assertTrue(isinstance(x, int)) # should return long self.assertEqual(int(s[1:]), sys.maxsize+1) # should return long x = int(1e100) - self.assert_(isinstance(x, int)) + self.assertTrue(isinstance(x, int)) x = int(-1e100) - self.assert_(isinstance(x, int)) + self.assertTrue(isinstance(x, int)) # SF bug 434186: 0x80000000/2 != 0x80000000>>1. @@ -78,7 +78,7 @@ class IntTestCases(unittest.TestCase): self.assertRaises(ValueError, int, '123\x00 245', 20) x = int('1' * 600) - self.assert_(isinstance(x, int)) + self.assertTrue(isinstance(x, int)) self.assertRaises(TypeError, int, 1, 12) @@ -96,8 +96,8 @@ class IntTestCases(unittest.TestCase): self.assertRaises(ValueError, int, "0b", 0) # Bug #3236: Return small longs from PyLong_FromString - self.assert_(int("10") is 10) - self.assert_(int("-1") is -1) + self.assertTrue(int("10") is 10) + self.assertTrue(int("-1") is -1) # SF bug 1334662: int(string, base) wrong answers # Various representations of 2**32 evaluated to 0 diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py index 729c0ca..1f1cba2 100644 --- a/Lib/test/test_io.py +++ b/Lib/test/test_io.py @@ -391,7 +391,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 = [] @@ -509,7 +509,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") @@ -615,8 +615,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() @@ -713,7 +713,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): @@ -815,7 +815,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 @@ -864,7 +864,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. @@ -1075,7 +1075,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") @@ -1565,7 +1565,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): @@ -1735,8 +1735,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 @@ -2054,7 +2054,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") @@ -2278,7 +2278,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 dcb6695..50597ca 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 7788502..a826598 100644 --- a/Lib/test/test_iter.py +++ b/Lib/test/test_iter.py @@ -75,7 +75,7 @@ class TestCase(unittest.TestCase): seq = list(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): @@ -542,23 +542,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.values()) + self.assertTrue(k in d) + self.assertTrue(k not in d.values()) for v in d.values(): - self.assert_(v in d.values()) - self.assert_(v not in d) + self.assertTrue(v in d.values()) + self.assertTrue(v not in d) for k, v in d.items(): - self.assert_((k, v) in d.items()) - self.assert_((v, k) not in d.items()) + self.assertTrue((k, v) in d.items()) + self.assertTrue((v, k) not in d.items()) f = open(TESTFN, "w") try: @@ -569,9 +569,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 af2efa0..d917262 100644 --- a/Lib/test/test_itertools.py +++ b/Lib/test/test_itertools.py @@ -131,7 +131,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 @@ -195,14 +195,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 @@ -265,7 +265,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: @@ -836,7 +836,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') @@ -844,7 +844,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(range(10)) @@ -1356,7 +1356,7 @@ class SubclassWithKwargsTest(unittest.TestCase): Subclass(newarg=1) except TypeError as 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 42ef958..dd1ecc8 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.udata, 0) self.assertEqual(ev, ev) self.assertNotEqual(ev, other) - self.assert_(ev < other) - self.assert_(other >= ev) + self.assertTrue(ev < other) + self.assertTrue(other >= ev) for op in lt, le, gt, ge: self.assertRaises(TypeError, op, ev, None) self.assertRaises(TypeError, op, ev, 1) diff --git a/Lib/test/test_largefile.py b/Lib/test/test_largefile.py index 1e868e0..7fd3e0e 100644 --- a/Lib/test/test_largefile.py +++ b/Lib/test/test_largefile.py @@ -139,7 +139,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 279afec..3510bd5 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().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().test_len() diff --git a/Lib/test/test_logging.py b/Lib/test/test_logging.py index 69ec491..72b26bb 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, encoding="utf8") 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 53d3e6b..1b5e6d4 100644 --- a/Lib/test/test_long.py +++ b/Lib/test/test_long.py @@ -65,7 +65,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 = 0 @@ -74,13 +74,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 @@ -106,9 +106,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 = list(range(1, MAXDIGITS+1)) + list(range(KARATSUBA_CUTOFF, @@ -538,7 +538,7 @@ class LongTest(unittest.TestCase): y = int(x) except OverflowError: self.fail("int(long(sys.maxsize) + 1) mustn't overflow") - self.assert_(isinstance(y, int), + self.assertTrue(isinstance(y, int), "int(long(sys.maxsize) + 1) should have returned long") x = hugeneg_aslong - 1 @@ -546,14 +546,14 @@ class LongTest(unittest.TestCase): y = int(x) except OverflowError: self.fail("int(long(-sys.maxsize-1) - 1) mustn't overflow") - self.assert_(isinstance(y, int), + self.assertTrue(isinstance(y, int), "int(long(-sys.maxsize-1) - 1) should have returned long") class long2(int): pass x = long2(1<<100) y = int(x) - self.assert_(type(y) is int, + self.assertTrue(type(y) is int, "overflowing int conversion must return long not long subtype") # ----------------------------------- tests of auto int->long conversion @@ -958,7 +958,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)) @@ -995,7 +995,7 @@ class LongTest(unittest.TestCase): got = round(k+offset, -1) expected = v+offset self.assertEqual(got, expected) - self.assert_(type(got) is int) + self.assertTrue(type(got) is int) # larger second argument self.assertEqual(round(-150, -2), -200) @@ -1034,7 +1034,7 @@ class LongTest(unittest.TestCase): got = round(10**k + 324678, -3) expect = 10**k + 325000 self.assertEqual(got, expect) - self.assert_(type(got) is int) + self.assertTrue(type(got) is int) # nonnegative second argument: round(x, n) should just return x for n in range(5): @@ -1042,7 +1042,7 @@ class LongTest(unittest.TestCase): x = random.randrange(-10000, 10000) got = round(x, n) self.assertEqual(got, x) - self.assert_(type(got) is int) + self.assertTrue(type(got) is int) for huge_n in 2**31-1, 2**31, 2**63-1, 2**63, 2**100, 10**100: self.assertEqual(round(8979323, huge_n), 8979323) @@ -1051,7 +1051,7 @@ class LongTest(unittest.TestCase): x = random.randrange(-10000, 10000) got = round(x) self.assertEqual(got, x) - self.assert_(type(got) is int) + self.assertTrue(type(got) is int) # bad second argument bad_exponents = ('brian', 2.0, 0j, None) diff --git a/Lib/test/test_macpath.py b/Lib/test/test_macpath.py index 368d8f5..e13865d 100644 --- a/Lib/test/test_macpath.py +++ b/Lib/test/test_macpath.py @@ -10,37 +10,37 @@ class MacPathTestCase(unittest.TestCase): 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.assert_(isabs(b"xx:yy")) - self.assert_(isabs(b"xx:yy:")) - self.assert_(isabs(b"xx:")) - self.failIf(isabs(b"foo")) - self.failIf(isabs(b":foo")) - self.failIf(isabs(b":foo:bar")) - self.failIf(isabs(b":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:")) + + self.assertTrue(isabs(b"xx:yy")) + self.assertTrue(isabs(b"xx:yy:")) + self.assertTrue(isabs(b"xx:")) + self.assertFalse(isabs(b"foo")) + self.assertFalse(isabs(b":foo")) + self.assertFalse(isabs(b":foo:bar")) + self.assertFalse(isabs(b":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") - self.assert_(commonprefix([b"home:swenson:spam", b"home:swen:spam"]) + self.assertTrue(commonprefix([b"home:swenson:spam", b"home:swen:spam"]) == b"home:swen") - self.assert_(commonprefix([b":home:swen:spam", b":home:swen:eggs"]) + self.assertTrue(commonprefix([b":home:swen:spam", b":home:swen:eggs"]) == b":home:swen:") - self.assert_(commonprefix([b":home:swen:spam", b":home:swen:spam"]) + self.assertTrue(commonprefix([b":home:swen:spam", b":home:swen:spam"]) == b":home:swen:spam") def test_split(self): diff --git a/Lib/test/test_mailbox.py b/Lib/test/test_mailbox.py index 655b639..8994340 100644 --- a/Lib/test/test_mailbox.py +++ b/Lib/test/test_mailbox.py @@ -21,16 +21,16 @@ 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.items(): - self.assert_(value in msg.get_all(key)) - self.assert_(msg.is_multipart()) + self.assertTrue(value in msg.get_all(key)) + self.assertTrue(msg.is_multipart()) self.assertEqual(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.assertTrue(isinstance(part, email.message.Message)) + self.assertTrue(not isinstance(part, mailbox.Message)) self.assertEqual(part.get_payload(), payload) def _delete_recursively(self, target): @@ -92,7 +92,7 @@ class TestMailbox(TestBase): self.assertEqual(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.assertEqual(self._box.get_string(key1), self._template % 1) @@ -100,7 +100,7 @@ class TestMailbox(TestBase): self.assertEqual(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.assertEqual(self._box.get_string(key1), self._template % 1) @@ -127,8 +127,8 @@ class TestMailbox(TestBase): msg = self._box.get(key0) self.assertEqual(msg['from'], 'foo') self.assertEqual(msg.get_payload(), '0') - self.assert_(self._box.get('foo') is None) - self.assert_(self._box.get('foo', False) is False) + 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) key1 = self._box.add(self._template % 1) @@ -151,7 +151,7 @@ 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.assertTrue(isinstance(msg0, mailbox.Message)) self.assertEqual(msg0['from'], 'foo') self.assertEqual(msg0.get_payload(), '0') self._check_sample(self._box.get_message(key1)) @@ -228,29 +228,29 @@ class TestMailbox(TestBase): count = 0 for value in returned_values: self.assertEqual(value['from'], 'foo') - self.assert_(int(value.get_payload()) < repetitions) + self.assertTrue(int(value.get_payload()) < repetitions) count += 1 self.assertEqual(len(values), count) def test_contains(self): # Check existence of keys using __contains__() method = self._box.__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 @@ -297,7 +297,7 @@ class TestMailbox(TestBase): for i in range(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.assertEqual(len(self._box), 0) for i, key in enumerate(keys): @@ -306,19 +306,19 @@ class TestMailbox(TestBase): 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.assertTrue(key1 in self._box) self.assertEqual(self._box.pop(key0).get_payload(), '0') - self.assert_(key0 not in self._box) - self.assert_(key1 in self._box) + 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.assertTrue(key2 in self._box) self.assertEqual(self._box.pop(key2).get_payload(), '2') - self.assert_(key2 not in self._box) - self.assert_(key1 in self._box) + self.assertTrue(key2 not in self._box) + self.assertTrue(key1 in self._box) self.assertEqual(self._box.pop(key1).get_payload(), '1') - self.assert_(key1 not in self._box) + self.assertTrue(key1 not in self._box) self.assertEqual(len(self._box), 0) def test_popitem(self, iterations=10): @@ -329,8 +329,8 @@ class TestMailbox(TestBase): seen = [] for i in range(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.assertEqual(int(msg.get_payload()), keys.index(key)) self.assertEqual(len(self._box), 0) @@ -377,11 +377,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 @@ -400,7 +400,7 @@ class TestMailbox(TestBase): keys = self._box.keys() self.assertEqual(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) oldbox.close() def test_dump_message(self): @@ -469,7 +469,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): @@ -479,7 +479,7 @@ 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.assertTrue(isinstance(msg_returned, mailbox.MaildirMessage)) self.assertEqual(msg_returned.get_subdir(), 'cur') self.assertEqual(msg_returned.get_flags(), 'FR') @@ -519,7 +519,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 @@ -545,7 +545,7 @@ 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 @@ -561,7 +561,7 @@ 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.assertEqual(folder1.get_string(folder1.keys()[0]), self._template % 'bar') @@ -571,7 +571,7 @@ class TestMaildir(TestMailbox): self._box.add_folder('one') self._box.add_folder('two') self.assertEqual(len(self._box.list_folders()), 2) - self.assert_(set(self._box.list_folders()) == set(('one', 'two'))) + self.assertTrue(set(self._box.list_folders()) == set(('one', 'two'))) self._box.remove_folder('one') self.assertEqual(len(self._box.list_folders()), 1) self.assertEqual(set(self._box.list_folders()), set(('two',))) @@ -596,14 +596,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 @@ -623,13 +623,13 @@ 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])) @@ -691,10 +691,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 @@ -721,7 +721,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 & 0o111 == 0) + self.assertTrue(mode & 0o111 == 0) def test_folder_file_perms(self): # From bug #3228, we want to verify that the file created inside a Maildir @@ -802,7 +802,7 @@ class _TestMboxMMDF(TestMailbox): self._box = self._factory(self._path) self.assertEqual(len(self._box), 3) for key in self._box.keys(): - self.assert_(self._box.get_string(key) in values) + self.assertTrue(self._box.get_string(key) in values) self._box.close() self.assertEqual(mtime, os.path.getmtime(self._path)) @@ -859,7 +859,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() @@ -913,15 +913,15 @@ 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.assertEqual(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 @@ -990,7 +990,7 @@ class TestMH(TestMailbox): {'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 @@ -1082,11 +1082,11 @@ 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.assertTrue(isinstance(msg, email.message.Message)) + self.assertTrue(isinstance(msg, mailbox.Message)) + self.assertTrue(isinstance(msg, self._factory)) self.assertEqual(msg.keys(), []) - self.assert_(not msg.is_multipart()) + self.assertTrue(not msg.is_multipart()) self.assertEqual(msg.get_payload(), None) def test_initialize_incorrectly(self): @@ -1159,7 +1159,7 @@ class TestMaildirMessage(TestMessage): 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.assertEqual(msg.get_date(), 0.0) @@ -1234,7 +1234,7 @@ class _TestMboxMMDFMessage(TestMessage): # 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) @@ -1309,19 +1309,19 @@ class TestBabylMessage(TestMessage): msg = mailbox.BabylMessage(_sample_message) visible = msg.get_visible() self.assertEqual(visible.keys(), []) - self.assert_(visible.get_payload() is None) + self.assertTrue(visible.get_payload() is None) visible['User-Agent'] = 'FooBar 1.0' visible['X-Whatever'] = 'Blah' self.assertEqual(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.assertTrue(visible.keys() == ['User-Agent', 'X-Whatever']) + self.assertTrue(visible['User-Agent'] == 'FooBar 1.0') self.assertEqual(visible['X-Whatever'], 'Blah') - self.assert_(visible.get_payload() is None) + self.assertTrue(visible.get_payload() is None) msg.update_visible() self.assertEqual(visible.keys(), ['User-Agent', 'X-Whatever']) - self.assert_(visible.get_payload() is None) + self.assertTrue(visible.get_payload() is None) visible = msg.get_visible() self.assertEqual(visible.keys(), ['User-Agent', 'Date', 'From', 'To', 'Subject']) @@ -1423,7 +1423,7 @@ class TestMessageConversion(TestBase): msg_mboxMMDF.set_flags(setting) msg = mailbox.MaildirMessage(msg_mboxMMDF) self.assertEqual(msg.get_flags(), result) - self.assert_(msg.get_date() == 0.0, msg.get_date()) + self.assertTrue(msg.get_date() == 0.0, msg.get_date()) msg_mboxMMDF.set_flags('O') self.assertEqual(mailbox.MaildirMessage(msg_mboxMMDF).get_subdir(), 'cur') @@ -1655,7 +1655,7 @@ class TestProxyFileBase(TestBase): proxy.seek(2, 0) self.assertEqual(proxy.read(), b'o' + linesep + b'bar' + linesep) proxy.seek(100) - self.failIf(proxy.read()) + self.assertFalse(proxy.read()) def _test_close(self, proxy): # Close a file @@ -1820,36 +1820,36 @@ class MaildirTestCase(unittest.TestCase): # Test for regression on bug #117490: # Make sure the boxes attribute actually gets set. self.mbox = mailbox.Maildir(support.TESTFN) - #self.assert_(hasattr(self.mbox, "boxes")) + #self.assertTrue(hasattr(self.mbox, "boxes")) #self.assertEqual(len(self.mbox.boxes), 0) - self.assert_(self.mbox.next() is None) - self.assert_(self.mbox.next() is None) + 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(support.TESTFN) #self.assertEqual(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(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(support.TESTFN) #self.assertEqual(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(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(support.TESTFN) #self.assertEqual(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(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) ## End: tests from the original module (for backward compatibility). diff --git a/Lib/test/test_math.py b/Lib/test/test_math.py index d74f01f..2321a09 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) @@ -194,7 +194,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: def __ceil__(self): @@ -226,14 +226,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.) @@ -244,12 +244,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) @@ -257,7 +257,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) @@ -272,7 +272,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) @@ -309,7 +309,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: def __floor__(self): @@ -332,9 +332,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.) @@ -362,7 +362,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") @@ -464,8 +464,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) @@ -479,7 +479,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, 10**10, 10**20, 10**40]: @@ -489,7 +489,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) @@ -497,7 +497,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) @@ -509,7 +509,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) @@ -519,7 +519,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))) @@ -531,7 +531,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) @@ -549,8 +549,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) @@ -562,9 +562,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) @@ -578,7 +578,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) @@ -591,7 +591,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.) @@ -604,7 +604,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) @@ -617,7 +617,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.) @@ -630,7 +630,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.) @@ -713,12 +713,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) @@ -727,7 +727,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) @@ -736,7 +736,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) @@ -744,12 +744,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) @@ -757,7 +757,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.) @@ -804,20 +804,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 0d044e9..c98c307 100644 --- a/Lib/test/test_memoryio.py +++ b/Lib/test/test_memoryio.py @@ -222,8 +222,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 31bfa62..abda678 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(bytes([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: @@ -214,7 +214,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_mimetypes.py b/Lib/test/test_mimetypes.py index 9651a60..7918de6 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 76b7354..0a0a663 100644 --- a/Lib/test/test_minidom.py +++ b/Lib/test/test_minidom.py @@ -733,7 +733,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 dec0980..eae4157 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 = b"0123456789" diff --git a/Lib/test/test_module.py b/Lib/test/test_module.py index 45556e8..225e954 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 bddd6c5..b4fa06a 100644 --- a/Lib/test/test_modulefinder.py +++ b/Lib/test/test_modulefinder.py @@ -233,12 +233,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 1d9d9e35..b482b39 100644 --- a/Lib/test/test_multibytecodec.py +++ b/Lib/test/test_multibytecodec.py @@ -242,10 +242,10 @@ class Test_ISO2022(unittest.TestCase): self.assertEqual(iso2022jp2.decode('iso2022-jp-2'), uni) def test_iso2022_jp_g0(self): - self.failIf(b'\x0e' in '\N{SOFT HYPHEN}'.encode('iso-2022-jp-2')) + self.assertFalse(b'\x0e' in '\N{SOFT HYPHEN}'.encode('iso-2022-jp-2')) for encoding in ('iso-2022-jp-2004', 'iso-2022-jp-3'): e = '\u3406'.encode(encoding) - self.failIf(any(x > 0x80 for x in e)) + self.assertFalse(any(x > 0x80 for x in e)) def test_bug1572832(self): if sys.maxunicode >= 0x10000: diff --git a/Lib/test/test_multibytecodec_support.py b/Lib/test/test_multibytecodec_support.py index 3e0476e..5e68856 100644 --- a/Lib/test/test_multibytecodec_support.py +++ b/Lib/test/test_multibytecodec_support.py @@ -53,9 +53,9 @@ class TestBase: if expected: result = func(source, scheme)[0] if func is self.decode: - self.assert_(type(result) is str, type(result)) + self.assertTrue(type(result) is str, type(result)) else: - self.assert_(type(result) is bytes, type(result)) + self.assertTrue(type(result) is bytes, type(result)) self.assertEqual(result, expected) else: self.assertRaises(UnicodeError, func, source, scheme) diff --git a/Lib/test/test_netrc.py b/Lib/test/test_netrc.py index 938e255..21ff88c 100644 --- a/Lib/test/test_netrc.py +++ b/Lib/test/test_netrc.py @@ -34,11 +34,11 @@ class NetrcTestCase(unittest.TestCase): def test_case_1(self): nrc = netrc.netrc(temp_filename) - self.assert_(nrc.macros == {'macro1':['line1\n', 'line2\n'], + self.assertTrue(nrc.macros == {'macro1':['line1\n', 'line2\n'], 'macro2':['line3\n', 'line4\n']} ) - self.assert_(nrc.hosts['foo'] == ('log1', 'acct1', 'pass1')) - self.assert_(nrc.hosts['default'] == ('log2', None, 'pass2')) + self.assertTrue(nrc.hosts['foo'] == ('log1', 'acct1', 'pass1')) + self.assertTrue(nrc.hosts['default'] == ('log2', None, 'pass2')) def test_main(): support.run_unittest(NetrcTestCase) diff --git a/Lib/test/test_normalization.py b/Lib/test/test_normalization.py index 9e85e0a..f92a714 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 = chr(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_opcodes.py b/Lib/test/test_opcodes.py index 4403a11..8b7fd9e 100644 --- a/Lib/test/test_opcodes.py +++ b/Lib/test/test_opcodes.py @@ -60,7 +60,7 @@ class OpcodeTest(unittest.TestCase): try: raise DClass(a) except DClass as 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 bf38298..aa3219f 100644 --- a/Lib/test/test_operator.py +++ b/Lib/test/test_operator.py @@ -34,237 +34,237 @@ 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 - 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.assertRaises(TypeError, operator.abs) + self.assertRaises(TypeError, operator.abs, None) self.assertEqual(operator.abs(-1), 1) self.assertEqual(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_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_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.assertRaises(TypeError, operator.invert) + self.assertRaises(TypeError, operator.invert, None) self.assertEqual(operator.inv(4), -5) 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.assertRaises(TypeError, operator.neg) + self.assertRaises(TypeError, operator.neg, None) self.assertEqual(operator.neg(5), -5) self.assertEqual(operator.neg(-5), 5) self.assertEqual(operator.neg(0), 0) self.assertEqual(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.assertRaises(TypeError, operator.pos) + self.assertRaises(TypeError, operator.pos, None) self.assertEqual(operator.pos(5), 5) self.assertEqual(operator.pos(-5), -5) self.assertEqual(operator.pos(0), 0) self.assertEqual(operator.pos(-0), 0) def test_pow(self): - self.failUnlessRaises(TypeError, operator.pow) - self.failUnlessRaises(TypeError, operator.pow, None, None) + self.assertRaises(TypeError, operator.pow) + self.assertRaises(TypeError, operator.pow, None, None) self.assertEqual(operator.pow(3,5), 3**5) self.assertEqual(operator.__pow__(3,5), 3**5) self.assertRaises(TypeError, operator.pow, 1) self.assertRaises(TypeError, operator.pow, 1, 2, 3) 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.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)) def test_setitem(self): a = list(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_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 __bool__(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: @@ -290,7 +290,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() @@ -322,7 +322,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 9c52f86..cdbbc9d 100644 --- a/Lib/test/test_optparse.py +++ b/Lib/test/test_optparse.py @@ -109,7 +109,7 @@ Args were %(args)s.""" % locals ()) except expected_exception as 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/ @@ -165,7 +165,7 @@ and kwargs %(kwargs)r sys.stdout = save_stdout except InterceptedError as err: - self.assert_( + self.assertTrue( isinstance(output, str), "expected output to be an ordinary string, not %r" % type(output)) @@ -338,7 +338,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") @@ -349,33 +349,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, @@ -779,14 +779,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"], @@ -992,7 +992,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() ---------------------------- @@ -1088,15 +1088,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}) @@ -1134,7 +1134,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") @@ -1225,7 +1225,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 @@ -1281,7 +1281,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, @@ -1293,11 +1293,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( @@ -1317,8 +1317,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 0600cfc..63f409e 100644 --- a/Lib/test/test_os.py +++ b/Lib/test/test_os.py @@ -20,7 +20,7 @@ class FileTests(unittest.TestCase): def test_access(self): f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR) os.close(f) - self.assert_(os.access(support.TESTFN, os.W_OK)) + self.assertTrue(os.access(support.TESTFN, os.W_OK)) def test_closerange(self): first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR) @@ -85,7 +85,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") @@ -102,7 +102,7 @@ class TemporaryFileTests(unittest.TestCase): self.check_tempfile(name) name = os.tempnam(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): @@ -151,7 +151,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 @@ -176,7 +176,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) @@ -228,7 +228,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] @@ -520,7 +520,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 603aea3..dda6137 100644 --- a/Lib/test/test_ossaudiodev.py +++ b/Lib/test/test_ossaudiodev.py @@ -58,7 +58,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) @@ -84,7 +84,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 (%s) > 10%% off of expected time (%s)" % (elapsed_time, expected_time)) @@ -133,7 +133,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: @@ -157,7 +157,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_parser.py b/Lib/test/test_parser.py index 340ae2f..9e5d5c1 100644 --- a/Lib/test/test_parser.py +++ b/Lib/test/test_parser.py @@ -546,15 +546,15 @@ class STObjectTestCase(unittest.TestCase): bottom = min(st1, st2, st3) top = max(st1, st2, st3) mid = sorted([st1, st2, st3])[1] - self.assert_(bottom < mid) - self.assert_(bottom < top) - self.assert_(mid < top) - self.assert_(bottom <= mid) - self.assert_(bottom <= top) - self.assert_(mid <= top) - self.assert_(bottom <= bottom) - self.assert_(mid <= mid) - self.assert_(top <= top) + self.assertTrue(bottom < mid) + self.assertTrue(bottom < top) + self.assertTrue(mid < top) + self.assertTrue(bottom <= mid) + self.assertTrue(bottom <= top) + self.assertTrue(mid <= top) + self.assertTrue(bottom <= bottom) + self.assertTrue(mid <= mid) + self.assertTrue(top <= top) # interaction with other types self.assertEquals(st1 == 1588.602459, False) self.assertEquals('spanish armada' != st2, True) diff --git a/Lib/test/test_peepholer.py b/Lib/test/test_peepholer.py index 1543f3b..5696500 100644 --- a/Lib/test/test_peepholer.py +++ b/Lib/test/test_peepholer.py @@ -25,9 +25,9 @@ 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.assertTrue(elem not in asm) for elem in ('POP_JUMP_IF_TRUE',): - self.assert_(elem in asm) + self.assertTrue(elem in asm) def test_elim_inversion_of_is_or_in(self): for line, elem in ( @@ -37,7 +37,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_global_as_constant(self): # LOAD_GLOBAL None/True/False --> LOAD_CONST None/True/False @@ -54,14 +54,14 @@ class TestTranforms(unittest.TestCase): for func, name in ((f, 'None'), (g, 'True'), (h, 'False')): asm = disassemble(func) for elem in ('LOAD_GLOBAL',): - self.assert_(elem not in asm) + self.assertTrue(elem not in asm) for elem in ('LOAD_CONST', '('+name+')'): - 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 @@ -71,9 +71,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 ( @@ -82,9 +82,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 ( @@ -95,8 +95,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 . . . @@ -134,17 +134,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 ( @@ -152,8 +152,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 ( @@ -161,16 +161,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): @@ -178,8 +178,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): @@ -194,8 +194,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): @@ -204,7 +204,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) @@ -215,7 +215,7 @@ class TestTranforms(unittest.TestCase): pass return g asm = disassemble(f) - self.assert_('BINARY_ADD' not in asm) + self.assertTrue('BINARY_ADD' not in asm) def test_main(verbose=None): diff --git a/Lib/test/test_pep247.py b/Lib/test/test_pep247.py index 733109a..da8f816 100644 --- a/Lib/test/test_pep247.py +++ b/Lib/test/test_pep247.py @@ -11,8 +11,8 @@ from test import 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) self.check_object(module.new, module.digest_size, key) def check_object(self, cls, digest_size, key): @@ -31,7 +31,7 @@ class Pep247Test(unittest.TestCase): obj3.update(b'string') h2 = obj3.digest() self.assertEquals(h1, h2) - self.assert_(hasattr(obj1, 'digest_size')) + self.assertTrue(hasattr(obj1, 'digest_size')) if digest_size is not None: self.assertEquals(obj1.digest_size, digest_size) diff --git a/Lib/test/test_pep277.py b/Lib/test/test_pep277.py index e18f602..11039ac 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("\\".join((str(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_pep3120.py b/Lib/test/test_pep3120.py index 81d15bc..85da048 100644 --- a/Lib/test/test_pep3120.py +++ b/Lib/test/test_pep3120.py @@ -19,7 +19,7 @@ class PEP3120Test(unittest.TestCase): try: import test.badsyntax_pep3120 except SyntaxError as msg: - self.assert_(str(msg).find("Non-UTF-8 code starting with") >= 0) + self.assertTrue(str(msg).find("Non-UTF-8 code starting with") >= 0) else: self.fail("expected exception didn't occur") diff --git a/Lib/test/test_pep352.py b/Lib/test/test_pep352.py index 1481244..b9645d5 100644 --- a/Lib/test/test_pep352.py +++ b/Lib/test/test_pep352.py @@ -12,7 +12,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): for attr in ("args", "__str__", "__repr__"): @@ -38,7 +38,7 @@ class ExceptionClassTests(unittest.TestCase): last_exc = getattr(builtins, 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, '%s not found' % superclass_name) exc_set.discard(superclass_name) superclasses = [] # Loop will insert base exception @@ -66,20 +66,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", "str", "repr") diff --git a/Lib/test/test_pkg.py b/Lib/test/test_pkg.py index 1064617..0c568bb 100644 --- a/Lib/test/test_pkg.py +++ b/Lib/test/test_pkg.py @@ -130,7 +130,7 @@ class TestPkg(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 @@ -140,7 +140,7 @@ class TestPkg(unittest.TestCase): s = """ from t2 import * - self.failUnless(dir(), ['self', 'sub']) + self.assertTrue(dir(), ['self', 'sub']) """ self.run_code(s) @@ -258,25 +258,25 @@ class TestPkg(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 eff7b5a..60f5c32 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_(self.module_name not in sys.modules and + self.assertTrue(self.module_name not in sys.modules 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 9bb5bdd..8b1815e 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() @@ -148,7 +148,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 ad00802..7f36115 100644 --- a/Lib/test/test_poplib.py +++ b/Lib/test/test_poplib.py @@ -251,7 +251,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 8d1bb59..294b302 100644 --- a/Lib/test/test_posix.py +++ b/Lib/test/test_posix.py @@ -42,13 +42,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(support.TESTFN) try: - self.assert_(posix.fstatvfs(fp.fileno())) + self.assertTrue(posix.fstatvfs(fp.fileno())) finally: fp.close() @@ -68,7 +68,7 @@ class PosixTester(unittest.TestCase): fp = open(support.TESTFN) try: fd = posix.dup(fp.fileno()) - self.assert_(isinstance(fd, int)) + self.assertTrue(isinstance(fd, int)) os.close(fd) finally: fp.close() @@ -123,13 +123,13 @@ class PosixTester(unittest.TestCase): if hasattr(posix, 'fstat'): fp = open(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(support.TESTFN)) + self.assertTrue(posix.stat(support.TESTFN)) if hasattr(posix, 'chown'): def test_chown(self): @@ -165,21 +165,21 @@ class PosixTester(unittest.TestCase): def test_lsdir(self): if hasattr(posix, 'lsdir'): - self.assert_(support.TESTFN in posix.lsdir(os.curdir)) + self.assertTrue(support.TESTFN in posix.lsdir(os.curdir)) def test_access(self): if hasattr(posix, 'access'): - self.assert_(posix.access(support.TESTFN, os.R_OK)) + self.assertTrue(posix.access(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'): diff --git a/Lib/test/test_posixpath.py b/Lib/test/test_posixpath.py index eb918f4..0efe3ff 100644 --- a/Lib/test/test_posixpath.py +++ b/Lib/test/test_posixpath.py @@ -26,7 +26,7 @@ class PosixPathTest(unittest.TestCase): safe_rmdir(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 @@ -200,8 +200,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]) @@ -229,7 +229,7 @@ class PosixPathTest(unittest.TestCase): f.close() self.assertEqual(d, b"foobar") - self.assert_( + self.assertTrue( posixpath.getctime(support.TESTFN) <= posixpath.getmtime(support.TESTFN) ) @@ -402,8 +402,8 @@ class PosixPathTest(unittest.TestCase): except ImportError: pass else: - self.assert_(isinstance(posixpath.expanduser("~/"), str)) - self.assert_(isinstance(posixpath.expanduser(b"~/"), bytes)) + self.assertTrue(isinstance(posixpath.expanduser("~/"), str)) + self.assertTrue(isinstance(posixpath.expanduser(b"~/"), bytes)) # if home directory == root directory, this test makes no sense if posixpath.expanduser("~") != '/': self.assertEqual( @@ -414,10 +414,10 @@ class PosixPathTest(unittest.TestCase): posixpath.expanduser(b"~") + b"/", posixpath.expanduser(b"~/") ) - self.assert_(isinstance(posixpath.expanduser("~root/"), str)) - self.assert_(isinstance(posixpath.expanduser("~foo/"), str)) - self.assert_(isinstance(posixpath.expanduser(b"~root/"), bytes)) - self.assert_(isinstance(posixpath.expanduser(b"~foo/"), bytes)) + self.assertTrue(isinstance(posixpath.expanduser("~root/"), str)) + self.assertTrue(isinstance(posixpath.expanduser("~foo/"), str)) + self.assertTrue(isinstance(posixpath.expanduser(b"~root/"), bytes)) + self.assertTrue(isinstance(posixpath.expanduser(b"~foo/"), bytes)) with support.EnvironmentVarGuard() as env: env['HOME'] = '/' @@ -481,14 +481,14 @@ class PosixPathTest(unittest.TestCase): self.assertRaises(TypeError, posixpath.normpath) def test_abspath(self): - self.assert_("foo" in posixpath.abspath("foo")) - self.assert_(b"foo" in posixpath.abspath(b"foo")) + self.assertTrue("foo" in posixpath.abspath("foo")) + self.assertTrue(b"foo" in posixpath.abspath(b"foo")) self.assertRaises(TypeError, posixpath.abspath) def test_realpath(self): - self.assert_("foo" in realpath("foo")) - self.assert_(b"foo" in realpath(b"foo")) + self.assertTrue("foo" in realpath("foo")) + self.assertTrue(b"foo" in realpath(b"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 1469ff0..3d13b60 100644 --- a/Lib/test/test_pprint.py +++ b/Lib/test/test_pprint.py @@ -34,7 +34,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}, "yaddayadda", self.a, self.b): @@ -57,7 +57,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): @@ -85,7 +85,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 @@ -108,7 +108,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, 0, 0+0j, 0.0, "", b"", (), tuple2(), tuple3(), [], list2(), list3(), diff --git a/Lib/test/test_property.py b/Lib/test/test_property.py index 4ce1da2..d9469d9 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 450306c..406578a 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, str)) + self.assertTrue(isinstance(e.pw_name, str)) self.assertEqual(e[1], e.pw_passwd) - self.assert_(isinstance(e.pw_passwd, str)) + self.assertTrue(isinstance(e.pw_passwd, str)) 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, str)) + self.assertTrue(isinstance(e.pw_gecos, str)) self.assertEqual(e[5], e.pw_dir) - self.assert_(isinstance(e.pw_dir, str)) + self.assertTrue(isinstance(e.pw_dir, str)) self.assertEqual(e[6], e.pw_shell) - self.assert_(isinstance(e.pw_shell, str)) + self.assertTrue(isinstance(e.pw_shell, str)) # 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_pyclbr.py b/Lib/test/test_pyclbr.py index 9438c7b..30d8249 100644 --- a/Lib/test/test_pyclbr.py +++ b/Lib/test/test_pyclbr.py @@ -31,7 +31,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)) @@ -40,7 +40,7 @@ class PyclbrTest(TestCase): if key in ignore: return if key not in obj: print("***",key, file=sys.stderr) - self.failUnless(key in obj, "%r in %r" % (key, obj)) + self.assertTrue(key in obj, "%r in %r" % (key, obj)) def assertEqualsOrIgnored(self, a, b, ignore): ''' succeed iff a == b or a in ignore or b in ignore ''' @@ -84,12 +84,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, type)) + self.assertTrue(isinstance(py_item, 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 00a2ada..76822af 100644 --- a/Lib/test/test_pydoc.py +++ b/Lib/test/test_pydoc.py @@ -309,7 +309,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" @@ -317,7 +317,7 @@ class TestDescriptions(unittest.TestCase): self.assertEqual(pydoc.describe(C), 'class C') self.assertEqual(pydoc.describe(c), 'C') expected = '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" @@ -326,7 +326,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 22cdcad..95f80ac 100644 --- a/Lib/test/test_queue.py +++ b/Lib/test/test_queue.py @@ -103,12 +103,12 @@ 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_(q.qsize(), "Queue should not be empty") - self.assert_(not qfull(q), "Queue should not be full") + self.assertTrue(q.qsize(), "Queue should not be empty") + self.assertTrue(not qfull(q), "Queue should not be full") last = 2 * QUEUE_SIZE full = 3 * 2 * QUEUE_SIZE q.put(last) - self.assert_(qfull(q), "Queue should be full") + self.assertTrue(qfull(q), "Queue should be full") try: q.put(full, block=0) self.fail("Didn't appear to block with a full queue") @@ -125,7 +125,7 @@ class BaseQueueTest(unittest.TestCase, BlockingTestMixin): # Empty it for i in range(QUEUE_SIZE): q.get() - self.assert_(not q.qsize(), "Queue should be empty") + self.assertTrue(not q.qsize(), "Queue should be empty") try: q.get(block=0) self.fail("Didn't appear to block with an empty queue") @@ -247,7 +247,7 @@ class FailingQueueTest(unittest.TestCase, BlockingTestMixin): except FailingQueueException: pass q.put("last") - self.assert_(qfull(q), "Queue should be full") + self.assertTrue(qfull(q), "Queue should be full") # Test a failing blocking put q.fail_next_put = True try: @@ -269,17 +269,17 @@ class FailingQueueTest(unittest.TestCase, BlockingTestMixin): # Check the Queue isn't damaged. # put failed, but get succeeded - re-add q.put("last") - self.assert_(qfull(q), "Queue should be full") + self.assertTrue(qfull(q), "Queue should be full") q.get() - self.assert_(not qfull(q), "Queue should not be full") + self.assertTrue(not qfull(q), "Queue should not be full") q.put("last") - self.assert_(qfull(q), "Queue should be full") + self.assertTrue(qfull(q), "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_(not q.qsize(), "Queue should be empty") + self.assertTrue(not q.qsize(), "Queue should be empty") q.put("first") q.fail_next_get = True try: @@ -287,16 +287,16 @@ class FailingQueueTest(unittest.TestCase, BlockingTestMixin): self.fail("The queue didn't fail when it should have") except FailingQueueException: pass - self.assert_(q.qsize(), "Queue should not be empty") + self.assertTrue(q.qsize(), "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_(q.qsize(), "Queue should not be empty") + self.assertTrue(q.qsize(), "Queue should not be empty") q.get() - self.assert_(not q.qsize(), "Queue should be empty") + self.assertTrue(not q.qsize(), "Queue should be empty") q.fail_next_get = True try: self.do_exceptional_blocking_test(q.get, (), q.put, ('empty',), @@ -305,9 +305,9 @@ class FailingQueueTest(unittest.TestCase, BlockingTestMixin): except FailingQueueException: pass # put succeeded, but get failed. - self.assert_(q.qsize(), "Queue should not be empty") + self.assertTrue(q.qsize(), "Queue should not be empty") q.get() - self.assert_(not q.qsize(), "Queue should be empty") + self.assertTrue(not q.qsize(), "Queue should be empty") def test_failing_queue(self): # Test to make sure a queue is functioning correctly. diff --git a/Lib/test/test_raise.py b/Lib/test/test_raise.py index 5a63b86..ff4800b 100644 --- a/Lib/test/test_raise.py +++ b/Lib/test/test_raise.py @@ -28,7 +28,7 @@ class TestRaise(unittest.TestCase): try: raise except RuntimeError as e: - self.failUnless("No active exception" in str(e)) + self.assertTrue("No active exception" in str(e)) else: self.fail("No exception raised") @@ -40,7 +40,7 @@ class TestRaise(unittest.TestCase): exc1 = e raise except IndexError as exc2: - self.failUnless(exc1 is exc2) + self.assertTrue(exc1 is exc2) else: self.fail("No exception raised") @@ -127,7 +127,7 @@ class TestCause(unittest.TestCase): try: raise IndexError from 5 except TypeError as e: - self.failUnless("exception cause" in str(e)) + self.assertTrue("exception cause" in str(e)) else: self.fail("No exception raised") @@ -135,7 +135,7 @@ class TestCause(unittest.TestCase): try: raise IndexError from KeyError except IndexError as e: - self.failUnless(isinstance(e.__cause__, KeyError)) + self.assertTrue(isinstance(e.__cause__, KeyError)) else: self.fail("No exception raised") @@ -144,7 +144,7 @@ class TestCause(unittest.TestCase): try: raise IndexError from cause except IndexError as e: - self.failUnless(e.__cause__ is cause) + self.assertTrue(e.__cause__ is cause) else: self.fail("No exception raised") @@ -166,7 +166,7 @@ class TestTraceback(unittest.TestCase): try: raise IndexError() except IndexError as e: - self.failUnless(isinstance(e.__traceback__, types.TracebackType)) + self.assertTrue(isinstance(e.__traceback__, types.TracebackType)) else: self.fail("No exception raised") @@ -203,7 +203,7 @@ class TestContext(unittest.TestCase): raise OSError() except OSError as e: self.assertNotEqual(e.__context__, context) - self.failUnless(isinstance(e.__context__, context)) + self.assertTrue(isinstance(e.__context__, context)) else: self.fail("No exception raised") @@ -216,7 +216,7 @@ class TestContext(unittest.TestCase): raise OSError except OSError as e: self.assertNotEqual(e.__context__, context) - self.failUnless(isinstance(e.__context__, context)) + self.assertTrue(isinstance(e.__context__, context)) else: self.fail("No exception raised") @@ -227,7 +227,7 @@ class TestContext(unittest.TestCase): except: raise OSError except OSError as e: - self.failUnless(isinstance(e.__context__, ZeroDivisionError)) + self.assertTrue(isinstance(e.__context__, ZeroDivisionError)) else: self.fail("No exception raised") @@ -238,7 +238,7 @@ class TestContext(unittest.TestCase): except: xyzzy except NameError as e: - self.failUnless(isinstance(e.__context__, ZeroDivisionError)) + self.assertTrue(isinstance(e.__context__, ZeroDivisionError)) else: self.fail("No exception raised") @@ -249,7 +249,7 @@ class TestContext(unittest.TestCase): finally: raise OSError except OSError as e: - self.failUnless(e.__context__ is None) + self.assertTrue(e.__context__ is None) else: self.fail("No exception raised") @@ -260,7 +260,7 @@ class TestContext(unittest.TestCase): finally: raise OSError except OSError as e: - self.failUnless(isinstance(e.__context__, ZeroDivisionError)) + self.assertTrue(isinstance(e.__context__, ZeroDivisionError)) else: self.fail("No exception raised") @@ -274,7 +274,7 @@ class TestContext(unittest.TestCase): with ContextManager(): 1/0 except NameError as e: - self.failUnless(isinstance(e.__context__, ZeroDivisionError)) + self.assertTrue(isinstance(e.__context__, ZeroDivisionError)) else: self.fail("No exception raised") @@ -286,7 +286,7 @@ class TestContext(unittest.TestCase): except ZeroDivisionError as e: raise e except ZeroDivisionError as e: - self.failUnless(e.__context__ is None, e.__context__) + self.assertTrue(e.__context__ is None, e.__context__) def test_reraise_cycle_broken(self): # Non-trivial context cycles (through re-raising a previous exception) @@ -300,7 +300,7 @@ class TestContext(unittest.TestCase): except ZeroDivisionError: raise a except NameError as e: - self.failUnless(e.__context__.__context__ is None) + self.assertTrue(e.__context__.__context__ is None) def test_3118(self): # deleting the generator caused the __context__ to be cleared @@ -320,7 +320,7 @@ class TestContext(unittest.TestCase): del g raise KeyError except Exception as e: - self.assert_(isinstance(e.__context__, ValueError)) + self.assertTrue(isinstance(e.__context__, ValueError)) f() @@ -344,7 +344,7 @@ class TestContext(unittest.TestCase): raise TypeError except Exception as e: self.assertNotEqual(e.__context__, None) - self.assert_(isinstance(e.__context__, AttributeError)) + self.assertTrue(isinstance(e.__context__, AttributeError)) with support.captured_output("stderr"): f() diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py index f2af196..df07b76 100644 --- a/Lib/test/test_random.py +++ b/Lib/test/test_random.py @@ -52,7 +52,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): @@ -161,7 +161,7 @@ class SystemRandom_TestBasicOps(TestBasicOps): cum = 0 for i in range(100): r = self.gen.randrange(span) - self.assert_(0 <= r < span) + self.assertTrue(0 <= r < span) cum |= r self.assertEqual(cum, span-1) @@ -171,7 +171,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)]: @@ -181,7 +181,7 @@ class SystemRandom_TestBasicOps(TestBasicOps): def test_genrandbits(self): # Verify ranges for k in range(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 @@ -211,13 +211,13 @@ class SystemRandom_TestBasicOps(TestBasicOps): 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): @@ -313,7 +313,7 @@ class MersenneTwister_TestBasicOps(TestBasicOps): cum = 0 for i in range(100): r = self.gen.randrange(span) - self.assert_(0 <= r < span) + self.assertTrue(0 <= r < span) cum |= r self.assertEqual(cum, span-1) @@ -323,7 +323,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)]: @@ -337,7 +337,7 @@ class MersenneTwister_TestBasicOps(TestBasicOps): 97904845777343510404718956115) # Verify ranges for k in range(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 @@ -367,20 +367,20 @@ class MersenneTwister_TestBasicOps(TestBasicOps): 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): @@ -458,7 +458,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_range.py b/Lib/test/test_range.py index 7650103..24836d0 100644 --- a/Lib/test/test_range.py +++ b/Lib/test/test_range.py @@ -26,18 +26,18 @@ class RangeTest(unittest.TestCase): self.assertEqual(list(range(a+4, a, -2)), [a+4, a+2]) seq = list(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 = list(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 = list(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) diff --git a/Lib/test/test_re.py b/Lib/test/test_re.py index 11fff78..fa75fd0 100644 --- a/Lib/test/test_re.py +++ b/Lib/test/test_re.py @@ -585,7 +585,7 @@ class ReTests(unittest.TestCase): [":", "::", ":::"]) def test_bug_926075(self): - self.assert_(re.compile('bug_926075') is not + self.assertTrue(re.compile('bug_926075') is not re.compile(b'bug_926075')) def test_bug_931848(self): diff --git a/Lib/test/test_reprlib.py b/Lib/test/test_reprlib.py index 8bd0ccf..12e207b 100644 --- a/Lib/test/test_reprlib.py +++ b/Lib/test/test_reprlib.py @@ -123,12 +123,12 @@ 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("...") in [12, 13]) + self.assertTrue(s.startswith("<class ")) + self.assertTrue(s.endswith(">")) + self.assertTrue(s.find("...") in [12, 13]) 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 @@ -137,7 +137,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_range(self): @@ -178,9 +178,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 @@ -267,7 +267,7 @@ class baz: ''') from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz ibaz = baz.baz() - self.failUnless(repr(ibaz).startswith( + self.assertTrue(repr(ibaz).startswith( "<%s.baz object at 0x" % baz.__name__)) def test_method(self): @@ -278,11 +278,11 @@ class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ''') from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import qux # Unbound methods first - self.failUnless(repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod).startswith( + self.assertTrue(repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod).startswith( '<function 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 object at 0x' \ % (qux.__name__,) )) diff --git a/Lib/test/test_richcmp.py b/Lib/test/test_richcmp.py index 72e636d..a788c60 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 range(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 @@ -237,8 +237,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) @@ -248,9 +248,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): @@ -272,7 +272,7 @@ class DictTest(unittest.TestCase): self.assertEqual(imag1a, imag1a) self.assertEqual(imag1a, imag1b) self.assertEqual(imag2, imag2) - self.assert_(imag1a != imag2) + self.assertTrue(imag1a != imag2) for opname in ("lt", "le", "gt", "ge"): for op in opmap[opname]: self.assertRaises(TypeError, op, imag1a, imag2) @@ -280,7 +280,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 9c47e31..cc8b390 100644 --- a/Lib/test/test_robotparser.py +++ b/Lib/test/test_robotparser.py @@ -22,9 +22,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 43691cb..43141e5 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.assertTrue("result" not in d1) + self.assertTrue(d2["initial"] is initial) self.assertEqual(d2["result"], self.expected_result) self.assertEqual(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(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,14 +159,14 @@ 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.assertTrue("x" in d1) self.assertEqual(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.assertTrue("x" in d2) self.assertEqual(d2["x"], 1) del d2 # Ensure __loader__ entry doesn't keep file open finally: @@ -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 fb1e26f..84ceafa 100644 --- a/Lib/test/test_scope.py +++ b/Lib/test/test_scope.py @@ -443,7 +443,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): @@ -458,7 +458,7 @@ self.assert_(X.passed) return g d = f(2)(4) - self.assert_('h' in d) + self.assertTrue('h' in d) del d['h'] self.assertEqual(d, {'x': 2, 'y': 7, 'w': 6}) @@ -492,8 +492,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() @@ -671,7 +671,7 @@ result2 = h() c = f(0) self.assertEqual(c.get(), 1) - self.assert_("x" not in c.__class__.__dict__) + self.assertTrue("x" not in c.__class__.__dict__) def testNonLocalGenerator(self): diff --git a/Lib/test/test_set.py b/Lib/test/test_set.py index 15d3c6f..a13f886 100644 --- a/Lib/test/test_set.py +++ b/Lib/test/test_set.py @@ -65,7 +65,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) @@ -125,7 +125,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) @@ -205,19 +205,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): @@ -265,7 +265,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) @@ -334,7 +334,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 @@ -375,7 +375,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) @@ -383,13 +383,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): @@ -408,7 +408,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: @@ -416,26 +416,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 range(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')): @@ -453,16 +453,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', '')): @@ -480,18 +480,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, [[]]) @@ -517,18 +517,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')): @@ -541,9 +541,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() @@ -586,19 +586,19 @@ class TestSet(TestJointOps): myobj = TestRichSetCompare() myset < myobj - self.assert_(myobj.gt_called) + self.assertTrue(myobj.gt_called) myobj = TestRichSetCompare() myset > myobj - self.assert_(myobj.lt_called) + self.assertTrue(myobj.lt_called) myobj = TestRichSetCompare() myset <= myobj - self.assert_(myobj.ge_called) + self.assertTrue(myobj.ge_called) myobj = TestRichSetCompare() myset >= myobj - self.assert_(myobj.le_called) + self.assertTrue(myobj.le_called) # C API test only available in a debug build if hasattr(set, "test_c_api"): @@ -810,7 +810,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 @@ -845,10 +845,10 @@ class TestBasicOpsSingleton(TestBasicOps): self.repr = "{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) #------------------------------------------------------------------------------ @@ -862,10 +862,10 @@ class TestBasicOpsTuple(TestBasicOps): self.repr = "{(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) #------------------------------------------------------------------------------ @@ -1182,7 +1182,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(()) @@ -1451,7 +1451,7 @@ class TestCopying(unittest.TestCase): set_list = sorted(self.set, key=repr) 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) @@ -1501,13 +1501,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 @@ -1756,7 +1756,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_shutil.py b/Lib/test/test_shutil.py index 5a546ec..60352a2 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 ef19641..5fc4220 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 8d101b3..7ed0ee2 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]) @@ -196,7 +196,7 @@ class ImportSideEffectTests(unittest.TestCase): site.abs__file__() for module in (sys, os, builtins): try: - self.failUnless(os.path.isabs(module.__file__), repr(module)) + self.assertTrue(os.path.isabs(module.__file__), repr(module)) except AttributeError: continue # We could try everything in sys.modules; however, when regrtest.py @@ -209,7 +209,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): @@ -220,17 +220,17 @@ class ImportSideEffectTests(unittest.TestCase): def test_setting_quit(self): # 'quit' and 'exit' should be injected into builtins - self.failUnless(hasattr(builtins, "quit")) - self.failUnless(hasattr(builtins, "exit")) + self.assertTrue(hasattr(builtins, "quit")) + self.assertTrue(hasattr(builtins, "exit")) def test_setting_copyright(self): # 'copyright' and 'credits' should be in builtins - self.failUnless(hasattr(builtins, "copyright")) - self.failUnless(hasattr(builtins, "credits")) + self.assertTrue(hasattr(builtins, "copyright")) + self.assertTrue(hasattr(builtins, "credits")) def test_setting_help(self): # 'help' should be set in builtins - self.failUnless(hasattr(builtins, "help")) + self.assertTrue(hasattr(builtins, "help")) def test_aliasing_mbcs(self): if sys.platform == "win32": @@ -244,7 +244,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 640c8c0..2ecb59a 100644 --- a/Lib/test/test_slice.py +++ b/Lib/test/test_slice.py @@ -73,7 +73,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 e8a9fc4..8313006 100644 --- a/Lib/test/test_socket.py +++ b/Lib/test/test_socket.py @@ -224,7 +224,7 @@ class GeneralModuleTests(unittest.TestCase): def test_repr(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.assert_(repr(s).startswith("<socket.socket object")) + self.assertTrue(repr(s).startswith("<socket.socket object")) def test_weakref(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) @@ -247,11 +247,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): @@ -273,7 +273,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: @@ -501,7 +501,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): @@ -509,14 +509,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 @@ -549,10 +549,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): @@ -724,7 +724,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 @@ -801,7 +801,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) @@ -811,7 +811,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) @@ -879,10 +879,10 @@ class FileObjectClassTestCase(SocketConnectedTest): self.cli_file.flush() 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) def testAttributes(self): self.assertEqual(self.serv_file.mode, 'rb') @@ -977,7 +977,7 @@ class NetworkConnectionNoServer(unittest.TestCase): def testWithoutServer(self): port = support.find_unused_port() - self.failUnlessRaises( + self.assertRaises( socket.error, lambda: socket.create_connection((HOST, port)) ) @@ -1007,7 +1007,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)) @@ -1018,7 +1018,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) @@ -1063,7 +1063,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 TCPTimeoutTest(SocketTCPTest): @@ -1072,7 +1072,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): @@ -1129,7 +1129,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): @@ -1149,10 +1149,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_stringprep.py b/Lib/test/test_stringprep.py index f3d3327..aa71221 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("\u0221")) - self.failIf(in_table_a1("\u0222")) + self.assertTrue(in_table_a1("\u0221")) + self.assertFalse(in_table_a1("\u0222")) - self.failUnless(in_table_b1("\u00ad")) - self.failIf(in_table_b1("\u00ae")) + self.assertTrue(in_table_b1("\u00ad")) + self.assertFalse(in_table_b1("\u00ae")) - self.failUnless(map_table_b2("\u0041"), "\u0061") - self.failUnless(map_table_b2("\u0061"), "\u0061") + self.assertTrue(map_table_b2("\u0041"), "\u0061") + self.assertTrue(map_table_b2("\u0061"), "\u0061") - self.failUnless(map_table_b3("\u0041"), "\u0061") - self.failUnless(map_table_b3("\u0061"), "\u0061") + self.assertTrue(map_table_b3("\u0041"), "\u0061") + self.assertTrue(map_table_b3("\u0061"), "\u0061") - self.failUnless(in_table_c11("\u0020")) - self.failIf(in_table_c11("\u0021")) + self.assertTrue(in_table_c11("\u0020")) + self.assertFalse(in_table_c11("\u0021")) - self.failUnless(in_table_c12("\u00a0")) - self.failIf(in_table_c12("\u00a1")) + self.assertTrue(in_table_c12("\u00a0")) + self.assertFalse(in_table_c12("\u00a1")) - self.failUnless(in_table_c12("\u00a0")) - self.failIf(in_table_c12("\u00a1")) + self.assertTrue(in_table_c12("\u00a0")) + self.assertFalse(in_table_c12("\u00a1")) - self.failUnless(in_table_c11_c12("\u00a0")) - self.failIf(in_table_c11_c12("\u00a1")) + self.assertTrue(in_table_c11_c12("\u00a0")) + self.assertFalse(in_table_c11_c12("\u00a1")) - self.failUnless(in_table_c21("\u001f")) - self.failIf(in_table_c21("\u0020")) + self.assertTrue(in_table_c21("\u001f")) + self.assertFalse(in_table_c21("\u0020")) - self.failUnless(in_table_c22("\u009f")) - self.failIf(in_table_c22("\u00a0")) + self.assertTrue(in_table_c22("\u009f")) + self.assertFalse(in_table_c22("\u00a0")) - self.failUnless(in_table_c21_c22("\u009f")) - self.failIf(in_table_c21_c22("\u00a0")) + self.assertTrue(in_table_c21_c22("\u009f")) + self.assertFalse(in_table_c21_c22("\u00a0")) - self.failUnless(in_table_c3("\ue000")) - self.failIf(in_table_c3("\uf900")) + self.assertTrue(in_table_c3("\ue000")) + self.assertFalse(in_table_c3("\uf900")) - self.failUnless(in_table_c4("\uffff")) - self.failIf(in_table_c4("\u0000")) + self.assertTrue(in_table_c4("\uffff")) + self.assertFalse(in_table_c4("\u0000")) - self.failUnless(in_table_c5("\ud800")) - self.failIf(in_table_c5("\ud7ff")) + self.assertTrue(in_table_c5("\ud800")) + self.assertFalse(in_table_c5("\ud7ff")) - self.failUnless(in_table_c6("\ufff9")) - self.failIf(in_table_c6("\ufffe")) + self.assertTrue(in_table_c6("\ufff9")) + self.assertFalse(in_table_c6("\ufffe")) - self.failUnless(in_table_c7("\u2ff0")) - self.failIf(in_table_c7("\u2ffc")) + self.assertTrue(in_table_c7("\u2ff0")) + self.assertFalse(in_table_c7("\u2ffc")) - self.failUnless(in_table_c8("\u0340")) - self.failIf(in_table_c8("\u0342")) + self.assertTrue(in_table_c8("\u0340")) + self.assertFalse(in_table_c8("\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("\u05be")) - self.failIf(in_table_d1("\u05bf")) + self.assertTrue(in_table_d1("\u05be")) + self.assertFalse(in_table_d1("\u05bf")) - self.failUnless(in_table_d2("\u0041")) - self.failIf(in_table_d2("\u0040")) + self.assertTrue(in_table_d2("\u0041")) + self.assertFalse(in_table_d2("\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_strptime.py b/Lib/test/test_strptime.py index 436a487..fb60ee4 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 46e777b..39f6daf 100644 --- a/Lib/test/test_struct.py +++ b/Lib/test/test_struct.py @@ -126,7 +126,7 @@ class StructTest(unittest.TestCase): # encoding of the string when packed. arg = bytes(arg, 'latin1') if rev != arg: - self.assert_(asy) + self.assertTrue(asy) def test_native_qQ(self): # can't pack -1 as unsigned regardless @@ -192,7 +192,7 @@ class StructTest(unittest.TestCase): expected = x if x < 0: expected += 1 << self.bitsize - self.assert_(expected > 0) + self.assertTrue(expected > 0) expected = hex(expected)[2:] # chop "0x" if len(expected) & 1: expected = "0" + expected diff --git a/Lib/test/test_structseq.py b/Lib/test/test_structseq.py index 124acff..7adca53 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 66aebfc..326c996 100644 --- a/Lib/test/test_subprocess.py +++ b/Lib/test/test_subprocess.py @@ -491,7 +491,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) @@ -657,7 +657,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) @@ -665,7 +665,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) @@ -673,7 +673,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) @@ -751,7 +751,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) @@ -759,7 +759,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) @@ -767,7 +767,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_symtable.py b/Lib/test/test_symtable.py index f567c63..7fb368a 100644 --- a/Lib/test/test_symtable.py +++ b/Lib/test/test_symtable.py @@ -122,7 +122,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 8f68cf7..cac90f4 100644 --- a/Lib/test/test_sys.py +++ b/Lib/test/test_sys.py @@ -30,7 +30,7 @@ class SysModuleTest(unittest.TestCase): dh(None) self.assertEqual(out.getvalue(), "") - self.assert_(not hasattr(builtins, "_")) + self.assertTrue(not hasattr(builtins, "_")) dh(42) self.assertEqual(out.getvalue(), "42\n") self.assertEqual(builtins._, 42) @@ -62,12 +62,12 @@ class SysModuleTest(unittest.TestCase): except ValueError as exc: eh(*sys.exc_info()) - self.assert_(err.getvalue().endswith("ValueError: 42\n")) + self.assertTrue(err.getvalue().endswith("ValueError: 42\n")) def test_excepthook(self): with test.support.captured_output("stderr") as stderr: sys.excepthook(1, '1', 1) - self.assert_("TypeError: print_exception(): Exception expected for " \ + self.assertTrue("TypeError: print_exception(): Exception expected for " \ "value, str found" in stderr.getvalue()) # FIXME: testing the code for a lost or replaced excepthook in @@ -136,7 +136,7 @@ class SysModuleTest(unittest.TestCase): def test_getdefaultencoding(self): 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 @@ -203,20 +203,20 @@ 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_call_tracing(self): self.assertRaises(TypeError, sys.call_tracing, type, 2) 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) @@ -237,12 +237,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.__code__ \ is sys._getframe().f_code ) @@ -293,12 +293,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 @@ -316,7 +316,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() @@ -328,50 +328,50 @@ 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, str)) - self.assert_(isinstance(sys.exec_prefix, str)) - self.assert_(isinstance(sys.executable, str)) + 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, str)) + self.assertTrue(isinstance(sys.exec_prefix, str)) + self.assertTrue(isinstance(sys.executable, str)) self.assertEqual(len(sys.float_info), 11) self.assertEqual(sys.float_info.radix, 2) self.assertEqual(len(sys.int_info), 2) - self.assert_(sys.int_info.bits_per_digit % 5 == 0) - self.assert_(sys.int_info.sizeof_digit >= 1) + self.assertTrue(sys.int_info.bits_per_digit % 5 == 0) + self.assertTrue(sys.int_info.sizeof_digit >= 1) self.assertEqual(type(sys.int_info.bits_per_digit), int) self.assertEqual(type(sys.int_info.sizeof_digit), int) - self.assert_(isinstance(sys.hexversion, int)) - self.assert_(isinstance(sys.maxsize, int)) - self.assert_(isinstance(sys.maxunicode, int)) - self.assert_(isinstance(sys.platform, str)) - self.assert_(isinstance(sys.prefix, str)) - self.assert_(isinstance(sys.version, str)) + self.assertTrue(isinstance(sys.hexversion, int)) + self.assertTrue(isinstance(sys.maxsize, int)) + self.assertTrue(isinstance(sys.maxunicode, int)) + self.assertTrue(isinstance(sys.platform, str)) + self.assertTrue(isinstance(sys.prefix, str)) + self.assertTrue(isinstance(sys.version, str)) 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 StringIO object when @@ -381,9 +381,9 @@ class SysModuleTest(unittest.TestCase): def test_intern(self): self.assertRaises(TypeError, sys.intern) s = "never interned before" - self.assert_(sys.intern(s) is s) + self.assertTrue(sys.intern(s) is s) s2 = s.swapcase().swapcase() - self.assert_(sys.intern(s2) is s) + self.assertTrue(sys.intern(s2) is s) # Subclasses of string can't be interned, because they # provide too much opportunity for insane things to happen. @@ -398,15 +398,15 @@ class SysModuleTest(unittest.TestCase): def test_sys_flags(self): - self.failUnless(sys.flags) + self.assertTrue(sys.flags) attrs = ("debug", "division_warning", "inspect", "interactive", "optimize", "dont_write_bytecode", "no_user_site", "no_site", "ignore_environment", "verbose", "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)) self.assertEqual(len(sys.flags), len(attrs)) def test_clear_type_cache(self): diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py index f4c0035..76390c7 100644 --- a/Lib/test/test_tarfile.py +++ b/Lib/test/test_tarfile.py @@ -57,7 +57,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): @@ -68,11 +68,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") @@ -83,7 +83,7 @@ class UstarReadTest(ReadTest): fobj2 = self.tar.extractfile(tarinfo) lines1 = fobj1.readlines() lines2 = list(io.TextIOWrapper(fobj2)) - self.assert_(lines1 == lines2, + self.assertTrue(lines1 == lines2, "fileobj.__iter__() failed") def test_fileobj_seek(self): @@ -109,12 +109,12 @@ class UstarReadTest(ReadTest): self.assertEqual(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.assertEqual(tarinfo.size, fobj.tell(), "seek() to file's end failed") - self.assert_(fobj.read() == b"", + self.assertTrue(fobj.read() == b"", "read() at file's end did not return empty string") fobj.seek(-tarinfo.size, 2) self.assertEqual(0, fobj.tell(), @@ -123,13 +123,13 @@ class UstarReadTest(ReadTest): 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.assertEqual(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() @@ -204,7 +204,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): @@ -218,15 +218,15 @@ class MiscReadTest(ReadTest): def test_check_members(self): for tarinfo in self.tar: - self.assert_(int(tarinfo.mtime) == 0o7606136617, + self.assertTrue(int(tarinfo.mtime) == 0o7606136617, "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): @@ -275,7 +275,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): @@ -292,7 +292,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) @@ -302,7 +302,7 @@ class StreamReadTest(ReadTest): v2 = tar2.extractfile(t2) if v1 is None: continue - self.assert_(v2 is not None, "stream.extractfile() failed") + self.assertTrue(v2 is not None, "stream.extractfile() failed") self.assertEqual(v1.read(), v2.read(), "stream extraction failed") tar1.close() @@ -364,7 +364,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"] = 0o7606136617 @@ -375,7 +375,7 @@ class MemberReadTest(ReadTest): kwargs["uname"] = "tarfile" kwargs["gname"] = "tarfile" for k, v in kwargs.items(): - 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): @@ -424,7 +424,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") @@ -445,7 +445,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" @@ -454,7 +454,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" @@ -534,7 +534,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): @@ -553,7 +553,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() @@ -566,7 +566,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. @@ -627,16 +627,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") @@ -677,14 +677,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(b"\0") == tarfile.RECORDSIZE, + self.assertTrue(data.count(b"\0") == tarfile.RECORDSIZE, "incorrect zero padding") @@ -724,14 +724,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") @@ -791,18 +791,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") @@ -822,10 +822,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 = { @@ -847,8 +847,8 @@ class PaxWriteTest(GNUWriteTest): # Test if all the fields are strings. for key, val in tar.pax_headers.items(): - self.assert_(type(key) is not bytes) - self.assert_(type(val) is not bytes) + self.assertTrue(type(key) is not bytes) + self.assertTrue(type(val) is not bytes) if key in tarfile.PAX_NUMBER_FIELDS: try: tarfile.PAX_NUMBER_FIELDS[key](val) @@ -916,10 +916,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 69b2e6c..a1bafc2 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 range(TEST_FILES): s = next(r) self.nameCheck(s, '', '', '') - self.failIf(s in dict) + self.assertFalse(s in dict) dict[s] = 1 def 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, str), + self.assertTrue(isinstance(c, str), "%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, str)) - self.assert_(len(p) > 0) + self.assertTrue(isinstance(p, str)) + 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(b'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(b'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(b'blat ' * 5) - self.failUnless(f._rolled) + self.assertTrue(f._rolled) filename = f.name f.close() - self.failIf(isinstance(filename, str) and os.path.exists(filename), + self.assertFalse(isinstance(filename, str) and 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(b'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(b'x' * 20) - self.failIf(f._rolled) + self.assertFalse(f._rolled) f.write(b'x' * 10) - self.failIf(f._rolled) + self.assertFalse(f._rolled) f.write(b'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(b'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(b'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(b'abc\n') - self.failUnless(f._rolled) + self.assertTrue(f._rolled) f.close() try: f.close() @@ -768,51 +768,51 @@ class test_SpooledTemporaryFile(TC): f.write("\u039B\r\n") f.seek(0) self.assertEqual(f.read(), "\u039B\r\n") - self.failIf(f._rolled) + self.assertFalse(f._rolled) f.write("\u039B" * 20 + "\r\n") f.seek(0) self.assertEqual(f.read(), "\u039B\r\n" + ("\u039B" * 20) + "\r\n") - self.failUnless(f._rolled) + self.assertTrue(f._rolled) 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(b'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(b'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 eabd7f4..c7a2213 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())) @@ -74,18 +74,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) @@ -143,8 +143,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] @@ -204,7 +204,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) @@ -212,7 +212,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: @@ -283,8 +283,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): @@ -371,8 +371,8 @@ class ThreadJoinOnShutdown(unittest.TestCase): rc = p.wait() data = p.stdout.read().decode().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 977a38a..7f58e04 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 93d4d36..49a9d17 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_(int(time.mktime(time.localtime(self.t))) + self.assertTrue(int(time.mktime(time.localtime(self.t))) == int(self.t)) def test_sleep(self): @@ -153,36 +153,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 @@ -214,14 +214,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) class TestLocale(unittest.TestCase): def setUp(self): diff --git a/Lib/test/test_timeout.py b/Lib/test/test_timeout.py index 264704e..e8e2a6f 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_tokenize.py b/Lib/test/test_tokenize.py index 75a7a80..f395ed4 100644 --- a/Lib/test/test_tokenize.py +++ b/Lib/test/test_tokenize.py @@ -629,7 +629,7 @@ class TestTokenizerAdheresToPep0263(TestCase): behaviour of the interpreter when it encounters a similar condition. """ f = 'tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt' - self.failUnlessRaises(SyntaxError, self._testFile, f) + self.assertRaises(SyntaxError, self._testFile, f) def test_no_coding_cookie_and_utf8_bom(self): f = 'tokenize_tests-no-coding-cookie-and-utf8-bom-sig-only.txt' diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py index 9033238..2145710 100644 --- a/Lib/test/test_traceback.py +++ b/Lib/test/test_traceback.py @@ -40,15 +40,15 @@ class SyntaxTracebackCases(unittest.TestCase): err = self.get_exception_format(self.syntax_error_with_caret, SyntaxError) self.assertEqual(len(err), 4) - self.assert_(err[1].strip() == "return x!") - self.assert_("^" in err[2]) # third line has caret + self.assertTrue(err[1].strip() == "return x!") + self.assertTrue("^" in err[2]) # third line has caret self.assertEqual(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: @@ -57,14 +57,14 @@ class SyntaxTracebackCases(unittest.TestCase): err = self.get_exception_format(self.syntax_error_without_caret, SyntaxError) self.assertEqual(len(err), 3) - self.assert_(err[1].strip() == "[x for x in x] = x") + 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.assertEqual(len(err), 4) self.assertEqual(err[1].strip(), "print(2)") - self.assert_("^" in err[2]) + self.assertTrue("^" in err[2]) self.assertEqual(err[1].find(")"), err[2].find("^")) def test_base_exception(self): @@ -131,13 +131,13 @@ class SyntaxTracebackCases(unittest.TestCase): err_line = "raise RuntimeError('{0}')".format(message_ascii) err_msg = "RuntimeError: {0}".format(message_ascii) - self.assert_(("line %s" % lineno) in stdout[1], + self.assertTrue(("line %s" % lineno) in stdout[1], "Invalid line number: {0!r} instead of {1}".format( stdout[1], lineno)) - self.assert_(stdout[2].endswith(err_line), + self.assertTrue(stdout[2].endswith(err_line), "Invalid traceback line: {0!r} instead of {1!r}".format( stdout[2], err_line)) - self.assert_(stdout[3] == err_msg, + self.assertTrue(stdout[3] == err_msg, "Invalid error message: {0!r} instead of {1!r}".format( stdout[3], err_msg)) @@ -177,9 +177,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')) cause_message = ( @@ -209,9 +209,9 @@ class BaseExceptionReportingTests: def check_zero_div(self, msg): lines = msg.splitlines() - self.assert_(lines[-3].startswith(' File')) - self.assert_('1/0 # In zero_div' in lines[-2], lines[-2]) - self.assert_(lines[-1].startswith('ZeroDivisionError'), lines[-1]) + self.assertTrue(lines[-3].startswith(' File')) + self.assertTrue('1/0 # In zero_div' in lines[-2], lines[-2]) + self.assertTrue(lines[-1].startswith('ZeroDivisionError'), lines[-1]) def test_simple(self): try: @@ -220,10 +220,10 @@ class BaseExceptionReportingTests: e = _ lines = self.get_report(e).splitlines() self.assertEquals(len(lines), 4) - self.assert_(lines[0].startswith('Traceback')) - self.assert_(lines[1].startswith(' File')) - self.assert_('1/0 # Marker' in lines[2]) - self.assert_(lines[3].startswith('ZeroDivisionError')) + self.assertTrue(lines[0].startswith('Traceback')) + self.assertTrue(lines[1].startswith(' File')) + self.assertTrue('1/0 # Marker' in lines[2]) + self.assertTrue(lines[3].startswith('ZeroDivisionError')) def test_cause(self): def inner_raise(): @@ -237,7 +237,7 @@ class BaseExceptionReportingTests: self.assertEquals(len(blocks), 3) self.assertEquals(blocks[1], cause_message) self.check_zero_div(blocks[0]) - self.assert_('inner_raise() # Marker' in blocks[2]) + self.assertTrue('inner_raise() # Marker' in blocks[2]) def test_context(self): def inner_raise(): @@ -251,7 +251,7 @@ class BaseExceptionReportingTests: self.assertEquals(len(blocks), 3) self.assertEquals(blocks[1], context_message) self.check_zero_div(blocks[0]) - self.assert_('inner_raise() # Marker' in blocks[2]) + self.assertTrue('inner_raise() # Marker' in blocks[2]) def test_cause_recursive(self): def inner_raise(): @@ -269,11 +269,11 @@ class BaseExceptionReportingTests: self.assertEquals(len(blocks), 3) self.assertEquals(blocks[1], cause_message) # The first block is the KeyError raised from the ZeroDivisionError - self.assert_('raise KeyError from e' in blocks[0]) - self.assert_('1/0' not in blocks[0]) + self.assertTrue('raise KeyError from e' in blocks[0]) + self.assertTrue('1/0' not in blocks[0]) # The second block (apart from the boundary) is the ZeroDivisionError # re-raised from the KeyError - self.assert_('inner_raise() # Marker' in blocks[2]) + self.assertTrue('inner_raise() # Marker' in blocks[2]) self.check_zero_div(blocks[2]) diff --git a/Lib/test/test_tuple.py b/Lib/test/test_tuple.py index f82af31..c37adc2 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().test_truth() - self.assert_(not ()) - self.assert_((42, )) + self.assertTrue(not ()) + self.assertTrue((42, )) def test_len(self): super().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().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 + list(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_types.py b/Lib/test/test_types.py index b85d337..5f5a952 100644 --- a/Lib/test/test_types.py +++ b/Lib/test/test_types.py @@ -549,13 +549,13 @@ class TypesTests(unittest.TestCase): result = f.__format__(fmt) self.assertEqual(len(result), 98) self.assertEqual(result[-7], '.') - self.assert_(result[:12] in ('112340000000', '112339999999')) + self.assertTrue(result[:12] in ('112340000000', '112339999999')) f = 1.1234e200 for fmt in 'f', 'F': result = f.__format__(fmt) self.assertEqual(len(result), 208) self.assertEqual(result[-7], '.') - self.assert_(result[:12] in ('112340000000', '112339999999')) + self.assertTrue(result[:12] in ('112340000000', '112339999999')) test( 1.0, 'e', '1.000000e+00') diff --git a/Lib/test/test_unary.py b/Lib/test/test_unary.py index 7dd651e..b835564 100644 --- a/Lib/test/test_unary.py +++ b/Lib/test/test_unary.py @@ -6,12 +6,12 @@ from test.support import run_unittest class UnaryOpTestCase(unittest.TestCase): def test_negative(self): - self.assert_(-2 == 0 - 2) + self.assertTrue(-2 == 0 - 2) self.assertEqual(-0, 0) self.assertEqual(--2, 2) - self.assert_(-2 == 0 - 2) - self.assert_(-2.0 == 0 - 2.0) - self.assert_(-2j == 0 - 2j) + self.assertTrue(-2 == 0 - 2) + self.assertTrue(-2.0 == 0 - 2.0) + self.assertTrue(-2j == 0 - 2j) def test_positive(self): self.assertEqual(+2, 2) @@ -22,16 +22,16 @@ class UnaryOpTestCase(unittest.TestCase): self.assertEqual(+2j, 2j) def test_invert(self): - self.assert_(-2 == 0 - 2) + self.assertTrue(-2 == 0 - 2) self.assertEqual(-0, 0) self.assertEqual(--2, 2) - self.assert_(-2 == 0 - 2) + self.assertTrue(-2 == 0 - 2) def test_no_overflow(self): nines = "9" * 32 - self.assert_(eval("+" + nines) == 10**32-1) - self.assert_(eval("-" + nines) == -(10**32-1)) - self.assert_(eval("~" + nines) == ~(10**32-1)) + self.assertTrue(eval("+" + nines) == 10**32-1) + self.assertTrue(eval("-" + nines) == -(10**32-1)) + self.assertTrue(eval("~" + nines) == ~(10**32-1)) 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 1ff7ee3..7f87b43 100644 --- a/Lib/test/test_unicode.py +++ b/Lib/test/test_unicode.py @@ -48,7 +48,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 @@ -60,7 +60,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('\xff', '\u00ff') @@ -294,25 +294,25 @@ class UnicodeTest( self.assertEqual('abc', 'abc') self.assertEqual('abc', 'abc') self.assertEqual('abc', 'abc') - self.assert_('abcd' > 'abc') - self.assert_('abcd' > 'abc') - self.assert_('abcd' > 'abc') - self.assert_('abc' < 'abcd') - self.assert_('abc' < 'abcd') - self.assert_('abc' < 'abcd') + self.assertTrue('abcd' > 'abc') + self.assertTrue('abcd' > 'abc') + self.assertTrue('abcd' > 'abc') + self.assertTrue('abc' < 'abcd') + self.assertTrue('abc' < 'abcd') + self.assertTrue('abc' < '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_('\u0061' < '\u20ac') + self.assertTrue('\u0061' < '\u20ac') # Non surrogate below surrogate value, no fixup required - self.assert_('\u0061' < '\ud800\udc02') + self.assertTrue('\u0061' < '\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 = '\ud800\udc01' @@ -352,7 +352,7 @@ class UnicodeTest( test_fixup('\uff61') # Surrogates on both sides, no fixup required - self.assert_('\ud800\udc02' < '\ud84d\udc56') + self.assertTrue('\ud800\udc02' < '\ud84d\udc56') def test_islower(self): string_tests.MixinStrUnicodeUserStringTest.test_islower(self) @@ -436,32 +436,32 @@ class UnicodeTest( def test_contains(self): # Testing Unicode contains method - self.assert_('a' in 'abdb') - self.assert_('a' in 'bdab') - self.assert_('a' in 'bdaba') - self.assert_('a' in 'bdba') - self.assert_('a' not in 'bdb') - self.assert_('a' in 'bdba') - self.assert_('a' in ('a',1,None)) - self.assert_('a' in (1,None,'a')) - self.assert_('a' in ('a',1,None)) - self.assert_('a' in (1,None,'a')) - self.assert_('a' not in ('x',1,'y')) - self.assert_('a' not in ('x',1,None)) - self.assert_('abcd' not in 'abcxxxx') - self.assert_('ab' in 'abcd') - self.assert_('ab' in 'abc') - self.assert_('ab' in (1,None,'ab')) - self.assert_('' in 'abc') - self.assert_('' in '') - self.assert_('' in 'abc') - self.assert_('\0' not in 'abc') - self.assert_('\0' in '\0abc') - self.assert_('\0' in 'abc\0') - self.assert_('a' in '\0abc') - self.assert_('asdf' in 'asdf') - self.assert_('asdf' not in 'asd') - self.assert_('asdf' not in '') + self.assertTrue('a' in 'abdb') + self.assertTrue('a' in 'bdab') + self.assertTrue('a' in 'bdaba') + self.assertTrue('a' in 'bdba') + self.assertTrue('a' not in 'bdb') + self.assertTrue('a' in 'bdba') + self.assertTrue('a' in ('a',1,None)) + self.assertTrue('a' in (1,None,'a')) + self.assertTrue('a' in ('a',1,None)) + self.assertTrue('a' in (1,None,'a')) + self.assertTrue('a' not in ('x',1,'y')) + self.assertTrue('a' not in ('x',1,None)) + self.assertTrue('abcd' not in 'abcxxxx') + self.assertTrue('ab' in 'abcd') + self.assertTrue('ab' in 'abc') + self.assertTrue('ab' in (1,None,'ab')) + self.assertTrue('' in 'abc') + self.assertTrue('' in '') + self.assertTrue('' in 'abc') + self.assertTrue('\0' not in 'abc') + self.assertTrue('\0' in '\0abc') + self.assertTrue('\0' in 'abc\0') + self.assertTrue('a' in '\0abc') + self.assertTrue('asdf' in 'asdf') + self.assertTrue('asdf' not in 'asd') + self.assertTrue('asdf' not in '') self.assertRaises(TypeError, "abc".__contains__) diff --git a/Lib/test/test_unicode_file.py b/Lib/test/test_unicode_file.py index fd561f1..367715a 100644 --- a/Lib/test/test_unicode_file.py +++ b/Lib/test/test_unicode_file.py @@ -25,19 +25,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, 0o777) 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)) @@ -47,7 +47,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. @@ -55,12 +55,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) @@ -68,19 +68,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. @@ -107,7 +107,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: @@ -123,7 +123,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) @@ -134,7 +134,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 285a352..a658d7b 100644 --- a/Lib/test/test_unicodedata.py +++ b/Lib/test/test_unicodedata.py @@ -232,7 +232,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, @@ -245,7 +245,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"), '\U00010346') @@ -253,13 +253,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("\u0f3a")) - self.assert_(not unicodedata.ucd_3_2_0.mirrored("\u0f3a")) + self.assertTrue(unicodedata.mirrored("\u0f3a")) + self.assertTrue(not unicodedata.ucd_3_2_0.mirrored("\u0f3a")) # Also, we now have two ways of representing # the upper-case mapping: as delta, or as absolute value - self.assert_("a".upper()=='A') - self.assert_("\u1d79".upper()=='\ua77d') - self.assert_(".".upper()=='.') + self.assertTrue("a".upper()=='A') + self.assertTrue("\u1d79".upper()=='\ua77d') + self.assertTrue(".".upper()=='.') def test_bug_5828(self): self.assertEqual("\u1d79".lower(), "\u1d79") diff --git a/Lib/test/test_urllib.py b/Lib/test/test_urllib.py index ba742af..cae3619 100644 --- a/Lib/test/test_urllib.py +++ b/Lib/test/test_urllib.py @@ -63,7 +63,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) @@ -85,7 +85,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() " @@ -97,7 +97,7 @@ class urlopen_FileTests(unittest.TestCase): self.returned_obj.close() def test_info(self): - self.assert_(isinstance(self.returned_obj.info(), email.message.Message)) + self.assertTrue(isinstance(self.returned_obj.info(), email.message.Message)) def test_geturl(self): self.assertEqual(self.returned_obj.geturl(), self.pathname) @@ -246,7 +246,7 @@ class urlretrieve_FileTests(unittest.TestCase): # a headers value is returned. result = urllib.request.urlretrieve("file:%s" % support.TESTFN) self.assertEqual(result[0], support.TESTFN) - self.assert_(isinstance(result[1], email.message.Message), + self.assertTrue(isinstance(result[1], email.message.Message), "did not get a email.message.Message instance as second " "returned value") @@ -257,7 +257,7 @@ class urlretrieve_FileTests(unittest.TestCase): result = urllib.request.urlretrieve(self.constructLocalFileUrl( 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 = open(second_temp, 'rb') try: @@ -271,9 +271,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" % support.TESTFN @@ -727,7 +727,7 @@ class urlencode_Tests(unittest.TestCase): expect_somewhere = ["1st=1", "2nd=2", "3rd=3"] result = urllib.parse.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, @@ -736,7 +736,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 @@ -774,7 +774,7 @@ class urlencode_Tests(unittest.TestCase): result = urllib.parse.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('&')) @@ -915,7 +915,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, []) @@ -927,7 +927,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 39ec498..f996c71 100644 --- a/Lib/test/test_urllib2.py +++ b/Lib/test/test_urllib2.py @@ -519,15 +519,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)) @@ -577,7 +577,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) @@ -671,9 +671,9 @@ class HandlerTests(unittest.TestCase): h.file_open(req) # XXXX remove OSError when bug fixed except (urllib.error.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): @@ -754,8 +754,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"], @@ -812,19 +812,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", {})) @@ -836,12 +836,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" @@ -863,12 +863,12 @@ class HandlerTests(unittest.TestCase): MockHeaders({"location": to_url})) except urllib.error.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) @@ -878,8 +878,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) @@ -924,7 +924,7 @@ class HandlerTests(unittest.TestCase): cp = urllib.request.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() @@ -1107,7 +1107,7 @@ class MiscTests(unittest.TestCase): if h.__class__ == handler_class: break else: - self.assert_(False) + self.assertTrue(False) class RequestTests(unittest.TestCase): @@ -1122,10 +1122,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): @@ -1148,9 +1148,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 8641c4b..43485c2 100644 --- a/Lib/test/test_urllib2_localnet.py +++ b/Lib/test/test_urllib2_localnet.py @@ -438,10 +438,10 @@ class TestUrlopen(unittest.TestCase): handler = self.start_server() open_url = urllib.request.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() @@ -451,7 +451,7 @@ class TestUrlopen(unittest.TestCase): open_url = urllib.request.urlopen( "http://localhost:%s" % handler.port) info_obj = open_url.info() - self.assert_(isinstance(info_obj, email.message.Message), + self.assertTrue(isinstance(info_obj, email.message.Message), "object returned by 'info' is not an instance of " "email.message.Message") self.assertEqual(info_obj.get_content_subtype(), "plain") diff --git a/Lib/test/test_urllib2net.py b/Lib/test/test_urllib2net.py index dc2d99d..59a73c9 100644 --- a/Lib/test/test_urllib2net.py +++ b/Lib/test/test_urllib2net.py @@ -82,9 +82,9 @@ class CloseSocketTest(unittest.TestCase): response = _urlopen_with_retry("http://www.python.org/") sock = response.fp - self.assert_(not sock.closed) + self.assertTrue(not sock.closed) response.close() - self.assert_(sock.closed) + self.assertTrue(sock.closed) class OtherNetworkTests(unittest.TestCase): def setUp(self): @@ -172,7 +172,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 support.time_out, \ support.socket_peer_reset, \ diff --git a/Lib/test/test_urllibnet.py b/Lib/test/test_urllibnet.py index e2c8af3..63e061a 100644 --- a/Lib/test/test_urllibnet.py +++ b/Lib/test/test_urllibnet.py @@ -62,10 +62,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() @@ -73,9 +73,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(), bytes), + self.assertTrue(isinstance(open_url.readline(), bytes), "readline did not return bytes") - self.assert_(isinstance(open_url.readlines(), list), + self.assertTrue(isinstance(open_url.readlines(), list), "readlines did not return a list") finally: open_url.close() @@ -87,7 +87,7 @@ class urlopenNetworkTests(unittest.TestCase): info_obj = open_url.info() finally: open_url.close() - self.assert_(isinstance(info_obj, email.message.Message), + self.assertTrue(isinstance(info_obj, email.message.Message), "object returned by 'info' is not an instance of " "email.message.Message") self.assertEqual(info_obj.get_content_subtype(), "html") @@ -122,7 +122,7 @@ class urlopenNetworkTests(unittest.TestCase): fd = open_url.fileno() FILE = os.fdopen(fd, encoding='utf-8') 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() @@ -150,11 +150,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 = open(file_location, encoding='utf-8') 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() @@ -165,10 +165,10 @@ class urlretrieveNetworkTests(unittest.TestCase): file_location,info = self.urlretrieve("http://www.python.org/", support.TESTFN) self.assertEqual(file_location, support.TESTFN) - self.assert_(os.path.exists(file_location)) + self.assertTrue(os.path.exists(file_location)) FILE = open(file_location, encoding='utf-8') 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) @@ -177,7 +177,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, email.message.Message), + self.assertTrue(isinstance(header, email.message.Message), "header is not an instance of email.message.Message") diff --git a/Lib/test/test_userdict.py b/Lib/test/test_userdict.py index 5d4a0ff..9d0a8b1 100644 --- a/Lib/test/test_userdict.py +++ b/Lib/test/test_userdict.py @@ -38,9 +38,9 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol): self.assertEqual(collections.UserDict().fromkeys('one two'.split()), d4) self.assertEqual(collections.UserDict.fromkeys('one two'.split(), 1), d5) self.assertEqual(collections.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()), collections.UserDict)) - self.assert_(isinstance(u2.fromkeys('one two'.split()), collections.UserDict)) + self.assertTrue(u1.fromkeys('one two'.split()) is not u1) + self.assertTrue(isinstance(u1.fromkeys('one two'.split()), collections.UserDict)) + self.assertTrue(isinstance(u2.fromkeys('one two'.split()), collections.UserDict)) # Test __repr__ self.assertEqual(str(u0), str(d0)) @@ -95,7 +95,7 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol): # Test "in". for i in u2.keys(): - self.assert_(i in u2) + self.assertTrue(i in u2) self.assertEqual(i in u1, i in d1) self.assertEqual(i in u0, i in d0) @@ -122,7 +122,7 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol): # Test setdefault t = collections.UserDict() self.assertEqual(t.setdefault("x", 42), 42) - self.assert_("x" in t) + self.assertTrue("x" in t) self.assertEqual(t.setdefault("x", 23), 42) # Test pop @@ -152,8 +152,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(collections.UserDict): def __missing__(self, key): diff --git a/Lib/test/test_uuid.py b/Lib/test/test_uuid.py index cf9ea84..b749abc 100644 --- a/Lib/test/test_uuid.py +++ b/Lib/test/test_uuid.py @@ -293,8 +293,8 @@ class TestUUID(TestCase): self.assertEqual(universal_local_bit, 0, message) self.assertNotEqual(node, 0, message) self.assertNotEqual(node, 0xffffffffffff, message) - self.assert_(0 <= node, message) - self.assert_(node < (1 << 48), message) + self.assertTrue(0 <= node, message) + self.assertTrue(node < (1 << 48), message) TestUUID.source2node[source] = node if TestUUID.last_node: @@ -335,8 +335,8 @@ class TestUUID(TestCase): def test_random_getnode(self): node = uuid._random_getnode() - self.assert_(0 <= node) - self.assert_(node < (1 <<48)) + self.assertTrue(0 <= node) + self.assertTrue(node < (1 <<48)) def test_unixdll_getnode(self): import sys diff --git a/Lib/test/test_warnings.py b/Lib/test/test_warnings.py index 4bcc210..0910055 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) # Issue 3639 def test_warn_nonstandard_types(self): @@ -407,7 +407,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) @@ -415,7 +415,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 @@ -469,7 +469,7 @@ class _WarningsTests(BaseTest): with 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): @@ -490,19 +490,19 @@ class _WarningsTests(BaseTest): with 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): @@ -519,13 +519,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): @@ -539,7 +539,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, @@ -547,7 +547,7 @@ class WarningsDisplayTests(unittest.TestCase): file_object = 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 @@ -567,20 +567,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") @@ -593,8 +593,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 @@ -615,17 +615,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 049dba2..ffa28a6 100644 --- a/Lib/test/test_weakref.py +++ b/Lib/test/test_weakref.py @@ -65,11 +65,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,10 +108,10 @@ class ReferencesTestCase(TestBase): 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): @@ -119,9 +119,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): @@ -131,19 +131,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): @@ -151,7 +151,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): @@ -160,14 +160,14 @@ class ReferencesTestCase(TestBase): L = collections.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) @@ -221,19 +221,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() @@ -241,13 +241,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 @@ -258,24 +258,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): @@ -299,21 +299,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): @@ -321,22 +321,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): @@ -344,8 +344,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? @@ -598,7 +598,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 @@ -681,12 +681,12 @@ class SubclassableWeakrefTestCase(TestBase): return super().__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): @@ -694,16 +694,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): @@ -711,10 +711,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): @@ -731,7 +731,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 @@ -796,7 +796,7 @@ class MappingTestCase(TestBase): dict, objects = self.make_weak_valued_dict() for o in objects: self.assertEqual(weakref.getweakrefcount(o), 1) - self.assert_(o is dict[o.arg], + self.assertTrue(o is dict[o.arg], "wrong object returned by weak dict!") items1 = list(dict.items()) items2 = list(dict.copy().items()) @@ -825,9 +825,9 @@ 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() @@ -836,15 +836,15 @@ class MappingTestCase(TestBase): del items1, items2 self.assertEqual(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_(o in dict) - self.assert_(34 not in dict) + self.assertTrue(o in dict) + self.assertTrue(34 not in dict) 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_(ob in dict) - self.assert_(ob in dict) + self.assertTrue(ob in dict) + 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.keyrefs())), len(objects)) for wr in dict.keyrefs(): ob = wr() - self.assert_(ob in dict) - self.assert_(ob in dict) + self.assertTrue(ob in dict) + self.assertTrue(ob in dict) self.assertEqual(ob.arg, dict[ob]) objects2.remove(ob) self.assertEqual(len(objects2), 0) @@ -968,15 +968,15 @@ class MappingTestCase(TestBase): k, v = weakdict.popitem() self.assertEqual(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.assertEqual(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, @@ -987,21 +987,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_(key in weakdict) - self.assert_(weakdict.get(key) is value1) - self.assert_(weakdict[key] is value1) + self.assertTrue(o is value1) + self.assertTrue(key in weakdict) + 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_(key in weakdict) - self.assert_(weakdict.get(key) is value1) - self.assert_(weakdict[key] is value1) + self.assertTrue(o is value1) + self.assertTrue(key in weakdict) + 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, @@ -1020,17 +1020,17 @@ class MappingTestCase(TestBase): weakdict.update(dict) self.assertEqual(len(weakdict), len(dict)) for k in weakdict.keys(): - self.assert_(k in dict, + self.assertTrue(k in dict, "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_(k in weakdict, + self.assertTrue(k in weakdict, "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, @@ -1060,7 +1060,7 @@ class MappingTestCase(TestBase): self.assertEqual(len(d), 2) del d['something'] self.assertEqual(len(d), 1) - self.assert_(list(d.items()) == [('something else', o2)]) + self.assertTrue(list(d.items()) == [('something else', o2)]) def test_weak_keyed_bad_delitem(self): d = weakref.WeakKeyDictionary() diff --git a/Lib/test/test_weakset.py b/Lib/test/test_weakset.py index 4d54576..651efe2 100644 --- a/Lib/test/test_weakset.py +++ b/Lib/test/test_weakset.py @@ -33,7 +33,7 @@ class TestWeakSet(unittest.TestCase): for method in dir(set): if method == 'test_c_api' or method.startswith('_'): continue - self.assert_(method in weaksetmethods, + self.assertTrue(method in weaksetmethods, "WeakSet missing method " + method) def test_new_or_init(self): @@ -49,9 +49,9 @@ class TestWeakSet(unittest.TestCase): for c in self.letters: self.assertEqual(c in self.s, c in self.d) self.assertRaises(TypeError, self.s.__contains__, [[]]) - self.assert_(self.obj in self.fs) + self.assertTrue(self.obj in self.fs) del self.obj - self.assert_(ustr('F') not in self.fs) + self.assertTrue(ustr('F') not in self.fs) def test_union(self): u = self.s.union(self.items2) @@ -81,8 +81,8 @@ class TestWeakSet(unittest.TestCase): self.assertEqual(self.s.intersection(C(self.items2)), x) def test_isdisjoint(self): - self.assert_(self.s.isdisjoint(WeakSet(self.items2))) - self.assert_(not self.s.isdisjoint(WeakSet(self.letters))) + self.assertTrue(self.s.isdisjoint(WeakSet(self.items2))) + self.assertTrue(not self.s.isdisjoint(WeakSet(self.letters))) def test_and(self): i = self.s.intersection(self.items2) @@ -118,19 +118,19 @@ class TestWeakSet(unittest.TestCase): def test_sub_and_super(self): pl, ql, rl = map(lambda s: [ustr(c) for c in s], ['ab', 'abcde', 'def']) p, q, r = map(WeakSet, (pl, ql, rl)) - 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_gc(self): # Create a nest of cycles to exercise overall ref count check @@ -148,7 +148,7 @@ class TestWeakSet(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) @@ -183,79 +183,79 @@ class TestWeakSet(unittest.TestCase): def test_add(self): x = ustr('Q') self.s.add(x) - self.assert_(x in self.s) + self.assertTrue(x in self.s) dup = self.s.copy() self.s.add(x) self.assertEqual(self.s, dup) self.assertRaises(TypeError, self.s.add, []) self.fs.add(Foo()) - self.assert_(len(self.fs) == 1) + self.assertTrue(len(self.fs) == 1) self.fs.add(self.obj) - self.assert_(len(self.fs) == 1) + self.assertTrue(len(self.fs) == 1) def test_remove(self): x = ustr('a') self.s.remove(x) - self.assert_(x not in self.s) + self.assertTrue(x not in self.s) self.assertRaises(KeyError, self.s.remove, x) self.assertRaises(TypeError, self.s.remove, []) def test_discard(self): a, q = ustr('a'), ustr('Q') 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, []) def test_pop(self): for i in range(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.items2) self.assertEqual(retval, None) for c in (self.items + self.items2): - self.assert_(c in self.s) + self.assertTrue(c in self.s) self.assertRaises(TypeError, self.s.update, [[]]) def test_update_set(self): self.s.update(set(self.items2)) for c in (self.items + self.items2): - self.assert_(c in self.s) + self.assertTrue(c in self.s) def test_ior(self): self.s |= set(self.items2) for c in (self.items + self.items2): - self.assert_(c in self.s) + self.assertTrue(c in self.s) def test_intersection_update(self): retval = self.s.intersection_update(self.items2) self.assertEqual(retval, None) for c in (self.items + self.items2): if c in self.items2 and c in self.items: - 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(TypeError, self.s.intersection_update, [[]]) def test_iand(self): self.s &= set(self.items2) for c in (self.items + self.items2): if c in self.items2 and c in self.items: - 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.items2) self.assertEqual(retval, None) for c in (self.items + self.items2): if c in self.items and c not in self.items2: - 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(TypeError, self.s.difference_update, [[]]) self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]]) @@ -263,27 +263,27 @@ class TestWeakSet(unittest.TestCase): self.s -= set(self.items2) for c in (self.items + self.items2): if c in self.items and c not in self.items2: - 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.items2) self.assertEqual(retval, None) for c in (self.items + self.items2): if (c in self.items) ^ (c in self.items2): - 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(TypeError, self.s.symmetric_difference_update, [[]]) def test_ixor(self): self.s ^= set(self.items2) for c in (self.items + self.items2): if (c in self.items) ^ (c in self.items2): - 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() diff --git a/Lib/test/test_winreg.py b/Lib/test/test_winreg.py index 3b314dd..fd28852 100644 --- a/Lib/test/test_winreg.py +++ b/Lib/test/test_winreg.py @@ -53,7 +53,7 @@ class WinregTests(unittest.TestCase): # Set the default value for this key. SetValue(root_key, test_key_name, REG_SZ, "Default value") key = CreateKey(root_key, test_key_name) - self.assert_(key.handle != 0) + self.assertTrue(key.handle != 0) # Create a sub-key sub_key = CreateKey(key, subkeystr) # Give the sub-key some named values diff --git a/Lib/test/test_wsgiref.py b/Lib/test/test_wsgiref.py index cfadfbd..438d8ec 100755 --- a/Lib/test/test_wsgiref.py +++ b/Lib/test/test_wsgiref.py @@ -151,7 +151,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( b"A server error occurred. Please contact the administrator." )) self.assertEqual( @@ -166,7 +166,7 @@ class IntegrationTests(TestCase): s(b"200 OK", [(b"Content-Type", b"text/plain; charset=utf-8")]) return [b"data"] out, err = run_amock(validator(bad_app)) - self.failUnless(out.endswith( + self.assertTrue(out.endswith( b"A server error occurred. Please contact the administrator." )) self.assertEqual( @@ -181,7 +181,7 @@ class IntegrationTests(TestCase): ]) return [b"data"] out, err = run_amock(validator(app)) - self.failUnless(err.endswith('"GET / HTTP/1.0" 200 4\n')) + self.assertTrue(err.endswith('"GET / HTTP/1.0" 200 4\n')) ver = sys.version.split()[0].encode('ascii') self.assertEqual( b"HTTP/1.0 200 OK\r\n" @@ -210,16 +210,16 @@ 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)) elif isinstance(value,BytesIO): - self.failUnless(isinstance(env[key],BytesIO)) + self.assertTrue(isinstance(env[key],BytesIO)) 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) @@ -246,15 +246,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): @@ -354,14 +354,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): @@ -372,17 +372,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.__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' @@ -438,7 +438,7 @@ class HeaderTests(TestCase): h.get("content-disposition")) del h['content-disposition'] - self.assert_(b'content-disposition' not in h) + self.assertTrue(b'content-disposition' not in h) class ErrorHandler(BaseCGIHandler): @@ -486,7 +486,7 @@ class HandlerTests(TestCase): if k not in empty: self.assertEqual(env[k],v) for k,v in empty.items(): - self.failUnless(k in env) + self.assertTrue(k in env) def testEnviron(self): h = TestHandler(X="Y") @@ -499,7 +499,7 @@ class HandlerTests(TestCase): h = BaseCGIHandler(None,None,None,{}) h.setup_environ() for key in 'wsgi.url_scheme', 'wsgi.input', 'wsgi.errors': - self.assert_(key in h.environ) + self.assertTrue(key in h.environ) def testScheme(self): h=TestHandler(HTTPS="on"); h.setup_environ() @@ -586,7 +586,7 @@ class HandlerTests(TestCase): "\r\n%s" % (h.error_status,len(h.error_body),h.error_body) ).encode("iso-8859-1")) - self.failUnless("AssertionError" in h.stderr.getvalue()) + self.assertTrue("AssertionError" in h.stderr.getvalue()) def testErrorAfterOutput(self): MSG = "Some output has been sent" @@ -599,7 +599,7 @@ class HandlerTests(TestCase): self.assertEqual(h.stdout.getvalue(), ("Status: 200 OK\r\n" "\r\n"+MSG).encode("iso-8859-1")) - self.failUnless("AssertionError" in h.stderr.getvalue()) + self.assertTrue("AssertionError" in h.stderr.getvalue()) def testHeaderFormats(self): @@ -638,7 +638,7 @@ class HandlerTests(TestCase): if proto=="HTTP/0.9": self.assertEqual(h.stdout.getvalue(),b"") else: - self.failUnless( + self.assertTrue( re.match((stdpat%(version,sw)).encode("iso-8859-1"), h.stdout.getvalue()), ((stdpat%(version,sw)).encode("iso-8859-1"), diff --git a/Lib/test/test_xdrlib.py b/Lib/test/test_xdrlib.py index 11a44ff..073448c 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(), 45) self.assertAlmostEqual(up.unpack_float(), 1.9) diff --git a/Lib/test/test_xmlrpc.py b/Lib/test/test_xmlrpc.py index d4e8122..7bcb6ba 100644 --- a/Lib/test/test_xmlrpc.py +++ b/Lib/test/test_xmlrpc.py @@ -63,21 +63,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): @@ -171,7 +171,7 @@ class FaultTestCase(unittest.TestCase): # private methods self.assertRaises(AttributeError, xmlrpc.server.resolve_dotted_attribute, str, '__add') - self.assert_(xmlrpc.server.resolve_dotted_attribute(str, 'title')) + self.assertTrue(xmlrpc.server.resolve_dotted_attribute(str, 'title')) class DateTimeTestCase(unittest.TestCase): def test_default(self): @@ -473,7 +473,7 @@ class SimpleServerTestCase(unittest.TestCase): self.assertRaises(AttributeError, xmlrpc.server.resolve_dotted_attribute, str, '__add') - self.assert_(xmlrpc.server.resolve_dotted_attribute(str, 'title')) + self.assertTrue(xmlrpc.server.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() diff --git a/Lib/test/test_xmlrpc_net.py b/Lib/test/test_xmlrpc_net.py index f6ebbf0..56b74b2 100644 --- a/Lib/test/test_xmlrpc_net.py +++ b/Lib/test/test_xmlrpc_net.py @@ -33,7 +33,7 @@ class CurrentTimeTest(unittest.TestCase): delta = dt1 - dt0 # The difference between the system time here and the system # time on the server should not be too big. - self.assert_(delta.days <= 1) + self.assertTrue(delta.days <= 1) def test_main(): diff --git a/Lib/test/test_zipfile.py b/Lib/test/test_zipfile.py index 4b6d825..82602c1 100644 --- a/Lib/test/test_zipfile.py +++ b/Lib/test/test_zipfile.py @@ -57,9 +57,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') @@ -69,17 +69,17 @@ class TestsWithSourceFile(unittest.TestCase): # Check the namelist names = zipfp.namelist() self.assertEquals(len(names), 3) - self.assert_(TESTFN in names) - self.assert_("another.name" in names) - self.assert_("strfile" in names) + self.assertTrue(TESTFN in names) + self.assertTrue("another.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.name" in names) - self.assert_("strfile" in names) + self.assertTrue(TESTFN in names) + self.assertTrue("another.name" in names) + self.assertTrue("strfile" in names) for i in infos: self.assertEquals(i.file_size, len(self.data)) @@ -138,11 +138,11 @@ class TestsWithSourceFile(unittest.TestCase): data = b"" for info in infos: data += zipfp.open(info).read() - self.assert_(data == b"foobar" or data == b"barfoo") + self.assertTrue(data == b"foobar" or data == b"barfoo") data = b"" for info in infos: data += zipfp.read(info) - self.assert_(data == b"foobar" or data == b"barfoo") + self.assertTrue(data == b"foobar" or data == b"barfoo") zipfp.close() def zipRandomOpenTest(self, f, compression): @@ -439,9 +439,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') @@ -451,17 +451,17 @@ class TestZip64InSmallFiles(unittest.TestCase): # Check the namelist names = zipfp.namelist() self.assertEquals(len(names), 3) - self.assert_(TESTFN in names) - self.assert_("another.name" in names) - self.assert_("strfile" in names) + self.assertTrue(TESTFN in names) + self.assertTrue("another.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.name" in names) - self.assert_("strfile" in names) + self.assertTrue(TESTFN in names) + self.assertTrue("another.name" in names) + self.assertTrue("strfile" in names) for i in infos: self.assertEquals(i.file_size, len(self.data)) @@ -511,8 +511,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() @@ -524,8 +524,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): @@ -537,8 +537,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) @@ -559,9 +559,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) @@ -598,7 +598,7 @@ class OtherTests(unittest.TestCase): except IOError: 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) @@ -627,19 +627,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 = io.BytesIO() fp.write(b"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 @@ -650,21 +650,21 @@ class OtherTests(unittest.TestCase): zipf.writestr("foo.txt", b"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 = io.BytesIO() 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 f41deaf..5d163c7 100644 --- a/Lib/test/test_zipimport.py +++ b/Lib/test/test_zipimport.py @@ -287,7 +287,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) @@ -369,7 +369,7 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase): s = io.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 3f4cd3f..94a65fc 100644 --- a/Lib/test/test_zipimport_support.py +++ b/Lib/test/test_zipimport_support.py @@ -187,7 +187,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) @@ -196,7 +196,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("""\ @@ -211,13 +211,13 @@ class ZipSupportTests(ImportHooksBaseTestCase): p = _spawn_python(script_name) p.stdin.write(b'l\n') data = _kill_python(p).decode() - 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(b'l\n') data = _kill_python(p).decode() - 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 71f5ecf..3718ca7 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(b""), zlib.crc32(b"", 0)) - self.assert_(zlib.crc32(b"abc", 0xffffffff)) + self.assertTrue(zlib.crc32(b"abc", 0xffffffff)) def test_crc32empty(self): self.assertEqual(zlib.crc32(b"", 0), 0) @@ -19,7 +19,7 @@ class ChecksumTestCase(unittest.TestCase): def test_adler32start(self): self.assertEqual(zlib.adler32(b""), zlib.adler32(b"", 1)) - self.assert_(zlib.adler32(b"abc", 0xffffffff)) + self.assertTrue(zlib.adler32(b"abc", 0xffffffff)) def test_adler32empty(self): self.assertEqual(zlib.adler32(b"", 0), 0) @@ -111,8 +111,8 @@ class CompressObjectTestCase(unittest.TestCase): y1 = dco.decompress(x1 + x2) y2 = dco.flush() self.assertEqual(data, y1 + y2) - self.assert_(isinstance(dco.unconsumed_tail, bytes)) - self.assert_(isinstance(dco.unused_data, bytes)) + self.assertTrue(isinstance(dco.unconsumed_tail, bytes)) + self.assertTrue(isinstance(dco.unused_data, bytes)) def test_compressoptions(self): # specify lots of options to compressobj() @@ -157,7 +157,7 @@ class CompressObjectTestCase(unittest.TestCase): decombuf = zlib.decompress(combuf) # Test type of return value - self.assert_(isinstance(decombuf, bytes)) + self.assertTrue(isinstance(decombuf, bytes)) self.assertEqual(data, decombuf) @@ -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, b''.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(), b"") # Returns nothing @@ -356,7 +356,7 @@ class CompressObjectTestCase(unittest.TestCase): data = HAMLET_SCENE comp = zlib.compress(data) # Test type of return value - self.assert_(isinstance(comp, bytes)) + self.assertTrue(isinstance(comp, bytes)) d0 = zlib.decompressobj() bufs0 = [] diff --git a/Lib/tkinter/test/test_tkinter/test_text.py b/Lib/tkinter/test/test_tkinter/test_text.py index fffd455..a93c4ce 100644 --- a/Lib/tkinter/test/test_tkinter/test_text.py +++ b/Lib/tkinter/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/tkinter/test/test_ttk/test_extensions.py b/Lib/tkinter/test/test_ttk/test_extensions.py index 9e52fc6..5912af4 100644 --- a/Lib/tkinter/test/test_ttk/test_extensions.py +++ b/Lib/tkinter/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.maxsize + 1, sys.maxsize + 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/tkinter/test/test_ttk/test_functions.py b/Lib/tkinter/test/test_ttk/test_functions.py index c9f8d5d..f9b908e 100644 --- a/Lib/tkinter/test/test_ttk/test_functions.py +++ b/Lib/tkinter/test/test_ttk/test_functions.py @@ -27,12 +27,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( @@ -62,7 +62,7 @@ class InternalFunctionsTest(unittest.TestCase): # check if giving unicode keys is fine check_against(ttk._format_optdict(opts), {'-αβγ': True, '-á': 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( @@ -72,113 +72,113 @@ class InternalFunctionsTest(unittest.TestCase): # ignore an option amount_opts = len(ttk._format_optdict(opts, ignore=('á'))) / 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=('á', '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=list(opts.keys()))) + self.assertFalse(ttk._format_optdict(opts, ignore=list(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(list(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(list(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 = {'üñÃćódè': [('á', 'vãl')]} result = ttk._format_mapdict(opts) - self.failUnlessEqual(result, ('-üñÃćódè', 'á vãl')) + self.assertEqual(result, ('-üñÃćódè', 'á vãl')) # empty states valid = {'opt': [('', '', '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')) @@ -207,77 +207,77 @@ 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], '') # _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')]) 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 by internal functions # plain wrong format - self.failUnlessRaises(ValueError, ttk._format_layoutlist, + self.assertRaises(ValueError, ttk._format_layoutlist, ['bad', 'format']) # will try to use iteritems in the 'bad' string - self.failUnlessRaises(AttributeError, ttk._format_layoutlist, + self.assertRaises(AttributeError, ttk._format_layoutlist, [('name', 'bad')]) # 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 = {'αβγ': True, 'á': False} - self.failUnless( + self.assertTrue( ttk._script_from_settings({'name': {'configure': configdict}})) mapdict = {'üñÃćódè': [('á', '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}") @@ -285,28 +285,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)) @@ -323,19 +323,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': []})] ) @@ -348,7 +348,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', {})] @@ -357,13 +357,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 @@ -374,10 +374,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): @@ -386,34 +386,34 @@ 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) class TclObjsToPyTest(unittest.TestCase): def test_unicode(self): adict = {'opt': 'välúè'} - self.failUnlessEqual(ttk.tclobjs_to_py(adict), {'opt': 'välúè'}) + self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': 'välúè'}) adict['opt'] = MockTclObj(adict['opt']) - self.failUnlessEqual(ttk.tclobjs_to_py(adict), {'opt': 'välúè'}) + self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': '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'), 'válũè') - self.failUnlessEqual(ttk.tclobjs_to_py(adict), + self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [('a', 'b', '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/tkinter/test/test_ttk/test_style.py b/Lib/tkinter/test/test_ttk/test_style.py index 3eebb64..e9a1eb4 100644 --- a/Lib/tkinter/test/test_ttk/test_style.py +++ b/Lib/tkinter/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/tkinter/test/test_ttk/test_widgets.py b/Lib/tkinter/test/test_ttk/test_widgets.py index 29fdce0..48a5223 100644 --- a/Lib/tkinter/test/test_ttk/test_widgets.py +++ b/Lib/tkinter/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 = '\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 = ( |