Skip to content

Commit

Permalink
pythongh-71339: Use new assertion methods in tests
Browse files Browse the repository at this point in the history
Fix test_cmd_line.

Remove redundant msgs.

Move some changes out to other PRs.

Fix test_cmd_line again.
  • Loading branch information
serhiy-storchaka committed Jan 20, 2025
1 parent c463270 commit 576527b
Show file tree
Hide file tree
Showing 121 changed files with 431 additions and 472 deletions.
2 changes: 1 addition & 1 deletion Lib/idlelib/idle_test/test_grep.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ def test_found(self):
self.assertIn(pat, lines[0])
self.assertIn('py: 1:', lines[1]) # line number 1
self.assertIn('2', lines[3]) # hits found 2
self.assertTrue(lines[4].startswith('(Hint:'))
self.assertStartsWith(lines[4], '(Hint:')


class Default_commandTest(unittest.TestCase):
Expand Down
2 changes: 1 addition & 1 deletion Lib/idlelib/idle_test/test_redirector.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def test_close(self):
redir.register('insert', Func)
redir.close()
self.assertEqual(redir._operations, {})
self.assertFalse(hasattr(self.text, 'widget'))
self.assertNotHasAttr(self.text, 'widget')


class WidgetRedirectorTest(unittest.TestCase):
Expand Down
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 @@ -182,7 +182,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 @@ -231,7 +231,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 @@ -797,7 +797,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 @@ -1215,7 +1215,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 @@ -2172,7 +2172,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 @@ -3567,7 +3567,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 @@ -3059,7 +3059,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 @@ -4998,7 +4998,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 @@ -65,8 +65,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
4 changes: 2 additions & 2 deletions Lib/test/test_annotationlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,8 +301,8 @@ def test_special_attrs(self):
# __qualname__ make little sense for forward refs as they can store
# complex typing expressions.
fr = annotationlib.ForwardRef("set[Any]")
self.assertFalse(hasattr(fr, "__name__"))
self.assertFalse(hasattr(fr, "__qualname__"))
self.assertNotHasAttr(fr, "__name__")
self.assertNotHasAttr(fr, "__qualname__")
self.assertEqual(fr.__module__, "annotationlib")
# Forward refs are currently unpicklable once they contain a code object.
fr.__forward_code__ # fill the cache
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 @@ -6755,7 +6755,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 @@ -253,12 +253,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 @@ -909,7 +909,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 @@ -1129,7 +1129,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 @@ -2870,7 +2870,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 @@ -125,7 +125,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 @@ -804,7 +804,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 @@ -342,7 +342,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 @@ -2208,7 +2208,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 @@ -1880,9 +1880,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 @@ -2013,7 +2013,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 @@ -2061,7 +2061,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 @@ -2075,7 +2075,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
Loading

0 comments on commit 576527b

Please sign in to comment.