Skip to content

gh-71339: Use new assertion methods in tests #129046

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
May 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Lib/test/_test_embed_structseq.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def check_structseq(self, obj_type):
# ob_refcnt
self.assertGreaterEqual(sys.getrefcount(obj_type), 1)
# tp_base
self.assertTrue(issubclass(obj_type, tuple))
self.assertIsSubclass(obj_type, tuple)
# tp_bases
self.assertEqual(obj_type.__bases__, (tuple,))
# tp_dict
Expand Down
12 changes: 6 additions & 6 deletions Lib/test/datetimetester.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ class NotEnough(tzinfo):
def __init__(self, offset, name):
self.__offset = offset
self.__name = name
self.assertTrue(issubclass(NotEnough, tzinfo))
self.assertIsSubclass(NotEnough, tzinfo)
ne = NotEnough(3, "NotByALongShot")
self.assertIsInstance(ne, tzinfo)

Expand Down Expand Up @@ -232,7 +232,7 @@ def test_pickling_subclass(self):
self.assertIs(type(derived), otype)
self.assertEqual(derived.utcoffset(None), offset)
self.assertEqual(derived.tzname(None), oname)
self.assertFalse(hasattr(derived, 'spam'))
self.assertNotHasAttr(derived, 'spam')

def test_issue23600(self):
DSTDIFF = DSTOFFSET = timedelta(hours=1)
Expand Down Expand Up @@ -813,7 +813,7 @@ def test_roundtrip(self):

# Verify td -> string -> td identity.
s = repr(td)
self.assertTrue(s.startswith('datetime.'))
self.assertStartsWith(s, 'datetime.')
s = s[9:]
td2 = eval(s)
self.assertEqual(td, td2)
Expand Down Expand Up @@ -1231,7 +1231,7 @@ def test_roundtrip(self):
self.theclass.today()):
# Verify dt -> string -> date identity.
s = repr(dt)
self.assertTrue(s.startswith('datetime.'))
self.assertStartsWith(s, 'datetime.')
s = s[9:]
dt2 = eval(s)
self.assertEqual(dt, dt2)
Expand Down Expand Up @@ -2218,7 +2218,7 @@ def test_roundtrip(self):
self.theclass.now()):
# Verify dt -> string -> datetime identity.
s = repr(dt)
self.assertTrue(s.startswith('datetime.'))
self.assertStartsWith(s, 'datetime.')
s = s[9:]
dt2 = eval(s)
self.assertEqual(dt, dt2)
Expand Down Expand Up @@ -3687,7 +3687,7 @@ def test_roundtrip(self):

# Verify t -> string -> time identity.
s = repr(t)
self.assertTrue(s.startswith('datetime.'))
self.assertStartsWith(s, 'datetime.')
s = s[9:]
t2 = eval(s)
self.assertEqual(t, t2)
Expand Down
4 changes: 2 additions & 2 deletions Lib/test/mapping_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ def test_read(self):
if not d: self.fail("Full mapping must compare to True")
# keys(), items(), iterkeys() ...
def check_iterandlist(iter, lst, ref):
self.assertTrue(hasattr(iter, '__next__'))
self.assertTrue(hasattr(iter, '__iter__'))
self.assertHasAttr(iter, '__next__')
self.assertHasAttr(iter, '__iter__')
x = list(iter)
self.assertTrue(set(x)==set(lst)==set(ref))
check_iterandlist(iter(d.keys()), list(d.keys()),
Expand Down
4 changes: 2 additions & 2 deletions Lib/test/pickletester.py
Original file line number Diff line number Diff line change
Expand Up @@ -3068,7 +3068,7 @@ def test_proto(self):
pickled = self.dumps(None, proto)
if proto >= 2:
proto_header = pickle.PROTO + bytes([proto])
self.assertTrue(pickled.startswith(proto_header))
self.assertStartsWith(pickled, proto_header)
else:
self.assertEqual(count_opcode(pickle.PROTO, pickled), 0)

Expand Down Expand Up @@ -5007,7 +5007,7 @@ def test_default_dispatch_table(self):
p = self.pickler_class(f, 0)
with self.assertRaises(AttributeError):
p.dispatch_table
self.assertFalse(hasattr(p, 'dispatch_table'))
self.assertNotHasAttr(p, 'dispatch_table')

def test_class_dispatch_table(self):
# A dispatch_table attribute can be specified class-wide
Expand Down
3 changes: 1 addition & 2 deletions Lib/test/support/warnings_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ def check_syntax_warning(testcase, statement, errtext='',
testcase.assertEqual(len(warns), 1, warns)

warn, = warns
testcase.assertTrue(issubclass(warn.category, SyntaxWarning),
warn.category)
testcase.assertIsSubclass(warn.category, SyntaxWarning)
if errtext:
testcase.assertRegex(str(warn.message), errtext)
testcase.assertEqual(warn.filename, '<testcase>')
Expand Down
4 changes: 2 additions & 2 deletions Lib/test/test__osx_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ def test__find_build_tool(self):
'cc not found - check xcode-select')

def test__get_system_version(self):
self.assertTrue(platform.mac_ver()[0].startswith(
_osx_support._get_system_version()))
self.assertStartsWith(platform.mac_ver()[0],
_osx_support._get_system_version())

def test__remove_original_values(self):
config_vars = {
Expand Down
30 changes: 15 additions & 15 deletions Lib/test/test_abstract_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ def not_implemented(*args, **kwargs):

class TestNumbers(unittest.TestCase):
def test_int(self):
self.assertTrue(issubclass(int, Integral))
self.assertTrue(issubclass(int, Rational))
self.assertTrue(issubclass(int, Real))
self.assertTrue(issubclass(int, Complex))
self.assertTrue(issubclass(int, Number))
self.assertIsSubclass(int, Integral)
self.assertIsSubclass(int, Rational)
self.assertIsSubclass(int, Real)
self.assertIsSubclass(int, Complex)
self.assertIsSubclass(int, Number)

self.assertEqual(7, int(7).real)
self.assertEqual(0, int(7).imag)
Expand All @@ -38,23 +38,23 @@ def test_int(self):
self.assertEqual(1, int(7).denominator)

def test_float(self):
self.assertFalse(issubclass(float, Integral))
self.assertFalse(issubclass(float, Rational))
self.assertTrue(issubclass(float, Real))
self.assertTrue(issubclass(float, Complex))
self.assertTrue(issubclass(float, Number))
self.assertNotIsSubclass(float, Integral)
self.assertNotIsSubclass(float, Rational)
self.assertIsSubclass(float, Real)
self.assertIsSubclass(float, Complex)
self.assertIsSubclass(float, Number)

self.assertEqual(7.3, float(7.3).real)
self.assertEqual(0, float(7.3).imag)
self.assertEqual(7.3, float(7.3).conjugate())
self.assertEqual(-7.3, float(-7.3).conjugate())

def test_complex(self):
self.assertFalse(issubclass(complex, Integral))
self.assertFalse(issubclass(complex, Rational))
self.assertFalse(issubclass(complex, Real))
self.assertTrue(issubclass(complex, Complex))
self.assertTrue(issubclass(complex, Number))
self.assertNotIsSubclass(complex, Integral)
self.assertNotIsSubclass(complex, Rational)
self.assertNotIsSubclass(complex, Real)
self.assertIsSubclass(complex, Complex)
self.assertIsSubclass(complex, Number)

c1, c2 = complex(3, 2), complex(4,1)
# XXX: This is not ideal, but see the comment in math_trunc().
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -6805,7 +6805,7 @@ class TestImportStar(TestCase):

def test(self):
for name in argparse.__all__:
self.assertTrue(hasattr(argparse, name))
self.assertHasAttr(argparse, name)

def test_all_exports_everything_but_modules(self):
items = [
Expand Down
18 changes: 9 additions & 9 deletions Lib/test/test_ast/test_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,12 +275,12 @@ def test_alias(self):
self.assertEqual(alias.end_col_offset, 17)

def test_base_classes(self):
self.assertTrue(issubclass(ast.For, ast.stmt))
self.assertTrue(issubclass(ast.Name, ast.expr))
self.assertTrue(issubclass(ast.stmt, ast.AST))
self.assertTrue(issubclass(ast.expr, ast.AST))
self.assertTrue(issubclass(ast.comprehension, ast.AST))
self.assertTrue(issubclass(ast.Gt, ast.AST))
self.assertIsSubclass(ast.For, ast.stmt)
self.assertIsSubclass(ast.Name, ast.expr)
self.assertIsSubclass(ast.stmt, ast.AST)
self.assertIsSubclass(ast.expr, ast.AST)
self.assertIsSubclass(ast.comprehension, ast.AST)
self.assertIsSubclass(ast.Gt, ast.AST)

def test_field_attr_existence(self):
for name, item in ast.__dict__.items():
Expand Down Expand Up @@ -1101,7 +1101,7 @@ def test_copy_with_parents(self):
def test_replace_interface(self):
for klass in self.iter_ast_classes():
with self.subTest(klass=klass):
self.assertTrue(hasattr(klass, '__replace__'))
self.assertHasAttr(klass, '__replace__')

fields = set(klass._fields)
with self.subTest(klass=klass, fields=fields):
Expand Down Expand Up @@ -1330,7 +1330,7 @@ def test_replace_reject_known_custom_instance_fields_commits(self):
context = node.ctx

# explicit rejection of known instance fields
self.assertTrue(hasattr(node, 'extra'))
self.assertHasAttr(node, 'extra')
msg = "Name.__replace__ got an unexpected keyword argument 'extra'."
with self.assertRaisesRegex(TypeError, re.escape(msg)):
copy.replace(node, extra=1)
Expand Down Expand Up @@ -3071,7 +3071,7 @@ def test_FunctionDef(self):
with self.assertWarnsRegex(DeprecationWarning,
r"FunctionDef\.__init__ missing 1 required positional argument: 'name'"):
node = ast.FunctionDef(args=args)
self.assertFalse(hasattr(node, "name"))
self.assertNotHasAttr(node, "name")
self.assertEqual(node.decorator_list, [])
node = ast.FunctionDef(name='foo', args=args)
self.assertEqual(node.name, 'foo')
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ def test_socket(self):
self.assertEqual(events[0][0], "socket.gethostname")
self.assertEqual(events[1][0], "socket.__new__")
self.assertEqual(events[2][0], "socket.bind")
self.assertTrue(events[2][2].endswith("('127.0.0.1', 8080)"))
self.assertEndsWith(events[2][2], "('127.0.0.1', 8080)")

def test_gc(self):
returncode, events, stderr = self.run_python("test_gc")
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_base64.py
Original file line number Diff line number Diff line change
Expand Up @@ -812,7 +812,7 @@ def test_decode_nonascii_str(self):
self.assertRaises(ValueError, f, 'with non-ascii \xcb')

def test_ErrorHeritage(self):
self.assertTrue(issubclass(binascii.Error, ValueError))
self.assertIsSubclass(binascii.Error, ValueError)

def test_RFC4648_test_cases(self):
# test cases from RFC 4648 section 10
Expand Down
8 changes: 3 additions & 5 deletions Lib/test/test_baseexception.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,11 @@ class ExceptionClassTests(unittest.TestCase):
inheritance hierarchy)"""

def test_builtins_new_style(self):
self.assertTrue(issubclass(Exception, object))
self.assertIsSubclass(Exception, object)

def verify_instance_interface(self, ins):
for attr in ("args", "__str__", "__repr__"):
self.assertTrue(hasattr(ins, attr),
"%s missing %s attribute" %
(ins.__class__.__name__, attr))
self.assertHasAttr(ins, attr)

def test_inheritance(self):
# Make sure the inheritance hierarchy matches the documentation
Expand Down Expand Up @@ -65,7 +63,7 @@ def test_inheritance(self):
elif last_depth > depth:
while superclasses[-1][0] >= depth:
superclasses.pop()
self.assertTrue(issubclass(exc, superclasses[-1][1]),
self.assertIsSubclass(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
Expand Down
6 changes: 3 additions & 3 deletions Lib/test/test_binascii.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ def assertConversion(self, original, converted, restored, **kwargs):

def test_exceptions(self):
# Check module exceptions
self.assertTrue(issubclass(binascii.Error, Exception))
self.assertTrue(issubclass(binascii.Incomplete, Exception))
self.assertIsSubclass(binascii.Error, Exception)
self.assertIsSubclass(binascii.Incomplete, Exception)

def test_functions(self):
# Check presence of all functions
for name in all_functions:
self.assertTrue(hasattr(getattr(binascii, name), '__call__'))
self.assertHasAttr(getattr(binascii, name), '__call__')
self.assertRaises(TypeError, getattr(binascii, name))

def test_returned_value(self):
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_binop.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ def test_comparison_orders(self):
self.assertEqual(op_sequence(le, B, C), ['C.__ge__', 'B.__le__'])
self.assertEqual(op_sequence(le, C, B), ['C.__le__', 'B.__ge__'])

self.assertTrue(issubclass(V, B))
self.assertIsSubclass(V, B)
self.assertEqual(op_sequence(eq, B, V), ['B.__eq__', 'V.__eq__'])
self.assertEqual(op_sequence(le, B, V), ['B.__le__', 'V.__ge__'])

Expand Down
4 changes: 2 additions & 2 deletions Lib/test/test_buffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2879,11 +2879,11 @@ def test_memoryview_tolist(self):
def test_memoryview_repr(self):
m = memoryview(bytearray(9))
r = m.__repr__()
self.assertTrue(r.startswith("<memory"))
self.assertStartsWith(r, "<memory")

m.release()
r = m.__repr__()
self.assertTrue(r.startswith("<released"))
self.assertStartsWith(r, "<released")

def test_memoryview_sequence(self):

Expand Down
4 changes: 2 additions & 2 deletions Lib/test/test_builtin.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ def test_chr(self):
self.assertRaises(ValueError, chr, -2**1000)

def test_cmp(self):
self.assertTrue(not hasattr(builtins, "cmp"))
self.assertNotHasAttr(builtins, "cmp")

def test_compile(self):
compile('print(1)\n', '', 'exec')
Expand Down Expand Up @@ -2304,7 +2304,7 @@ def __format__(self, format_spec):
# tests for object.__format__ really belong elsewhere, but
# there's no good place to put them
x = object().__format__('')
self.assertTrue(x.startswith('<object object at'))
self.assertStartsWith(x, '<object object at')

# first argument to object.__format__ must be string
self.assertRaises(TypeError, object().__format__, 3)
Expand Down
10 changes: 5 additions & 5 deletions Lib/test/test_bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1974,9 +1974,9 @@ def test_compare_bytes_to_bytearray(self):
@test.support.requires_docstrings
def test_doc(self):
self.assertIsNotNone(bytearray.__doc__)
self.assertTrue(bytearray.__doc__.startswith("bytearray("), bytearray.__doc__)
self.assertStartsWith(bytearray.__doc__, "bytearray(")
self.assertIsNotNone(bytes.__doc__)
self.assertTrue(bytes.__doc__.startswith("bytes("), bytes.__doc__)
self.assertStartsWith(bytes.__doc__, "bytes(")

def test_from_bytearray(self):
sample = bytes(b"Hello world\n\x80\x81\xfe\xff")
Expand Down Expand Up @@ -2107,7 +2107,7 @@ class BytesAsStringTest(FixedStringTest, unittest.TestCase):
class SubclassTest:

def test_basic(self):
self.assertTrue(issubclass(self.type2test, self.basetype))
self.assertIsSubclass(self.type2test, self.basetype)
self.assertIsInstance(self.type2test(), self.basetype)

a, b = b"abcd", b"efgh"
Expand Down Expand Up @@ -2155,7 +2155,7 @@ def test_pickle(self):
self.assertEqual(a.z, b.z)
self.assertEqual(type(a), type(b))
self.assertEqual(type(a.z), type(b.z))
self.assertFalse(hasattr(b, 'y'))
self.assertNotHasAttr(b, 'y')

def test_copy(self):
a = self.type2test(b"abcd")
Expand All @@ -2169,7 +2169,7 @@ def test_copy(self):
self.assertEqual(a.z, b.z)
self.assertEqual(type(a), type(b))
self.assertEqual(type(a.z), type(b.z))
self.assertFalse(hasattr(b, 'y'))
self.assertNotHasAttr(b, 'y')

def test_fromhex(self):
b = self.type2test.fromhex('1a2B30')
Expand Down
4 changes: 2 additions & 2 deletions Lib/test/test_bz2.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ def testPeek(self):
with BZ2File(self.filename) as bz2f:
pdata = bz2f.peek()
self.assertNotEqual(len(pdata), 0)
self.assertTrue(self.TEXT.startswith(pdata))
self.assertStartsWith(self.TEXT, pdata)
self.assertEqual(bz2f.read(), self.TEXT)

def testReadInto(self):
Expand Down Expand Up @@ -768,7 +768,7 @@ def testPeekBytesIO(self):
with BZ2File(bio) as bz2f:
pdata = bz2f.peek()
self.assertNotEqual(len(pdata), 0)
self.assertTrue(self.TEXT.startswith(pdata))
self.assertStartsWith(self.TEXT, pdata)
self.assertEqual(bz2f.read(), self.TEXT)

def testWriteBytesIO(self):
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -1098,7 +1098,7 @@ def test_option_type(self):
output = run('--type', 'text', '2004')
self.assertEqual(output, conv(result_2004_text))
output = run('--type', 'html', '2004')
self.assertEqual(output[:6], b'<?xml ')
self.assertStartsWith(output, b'<?xml ')
self.assertIn(b'<title>Calendar for 2004</title>', output)

def test_html_output_current_year(self):
Expand Down
4 changes: 2 additions & 2 deletions Lib/test/test_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -695,8 +695,8 @@ class DerivedType(SuperType):
UnaffectedType2 = _testcapi.make_vectorcall_class(SuperType)

# Aside: Quickly check that the C helper actually made derived types
self.assertTrue(issubclass(UnaffectedType1, DerivedType))
self.assertTrue(issubclass(UnaffectedType2, SuperType))
self.assertIsSubclass(UnaffectedType1, DerivedType)
self.assertIsSubclass(UnaffectedType2, SuperType)

# Initial state: tp_call
self.assertEqual(instance(), "tp_call")
Expand Down
Loading
Loading