Skip to content

Commit db98e0b

Browse files
[3.14] gh-71339: Use new assertion methods in tests (GH-129046) (GH-134498)
(cherry picked from commit 2602d8a) Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent d5f7e80 commit db98e0b

File tree

117 files changed

+407
-445
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

117 files changed

+407
-445
lines changed

Lib/test/_test_embed_structseq.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ def check_structseq(self, obj_type):
1111
# ob_refcnt
1212
self.assertGreaterEqual(sys.getrefcount(obj_type), 1)
1313
# tp_base
14-
self.assertTrue(issubclass(obj_type, tuple))
14+
self.assertIsSubclass(obj_type, tuple)
1515
# tp_bases
1616
self.assertEqual(obj_type.__bases__, (tuple,))
1717
# tp_dict

Lib/test/datetimetester.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ class NotEnough(tzinfo):
183183
def __init__(self, offset, name):
184184
self.__offset = offset
185185
self.__name = name
186-
self.assertTrue(issubclass(NotEnough, tzinfo))
186+
self.assertIsSubclass(NotEnough, tzinfo)
187187
ne = NotEnough(3, "NotByALongShot")
188188
self.assertIsInstance(ne, tzinfo)
189189

@@ -232,7 +232,7 @@ def test_pickling_subclass(self):
232232
self.assertIs(type(derived), otype)
233233
self.assertEqual(derived.utcoffset(None), offset)
234234
self.assertEqual(derived.tzname(None), oname)
235-
self.assertFalse(hasattr(derived, 'spam'))
235+
self.assertNotHasAttr(derived, 'spam')
236236

237237
def test_issue23600(self):
238238
DSTDIFF = DSTOFFSET = timedelta(hours=1)
@@ -813,7 +813,7 @@ def test_roundtrip(self):
813813

814814
# Verify td -> string -> td identity.
815815
s = repr(td)
816-
self.assertTrue(s.startswith('datetime.'))
816+
self.assertStartsWith(s, 'datetime.')
817817
s = s[9:]
818818
td2 = eval(s)
819819
self.assertEqual(td, td2)
@@ -1231,7 +1231,7 @@ def test_roundtrip(self):
12311231
self.theclass.today()):
12321232
# Verify dt -> string -> date identity.
12331233
s = repr(dt)
1234-
self.assertTrue(s.startswith('datetime.'))
1234+
self.assertStartsWith(s, 'datetime.')
12351235
s = s[9:]
12361236
dt2 = eval(s)
12371237
self.assertEqual(dt, dt2)
@@ -2218,7 +2218,7 @@ def test_roundtrip(self):
22182218
self.theclass.now()):
22192219
# Verify dt -> string -> datetime identity.
22202220
s = repr(dt)
2221-
self.assertTrue(s.startswith('datetime.'))
2221+
self.assertStartsWith(s, 'datetime.')
22222222
s = s[9:]
22232223
dt2 = eval(s)
22242224
self.assertEqual(dt, dt2)
@@ -3672,7 +3672,7 @@ def test_roundtrip(self):
36723672

36733673
# Verify t -> string -> time identity.
36743674
s = repr(t)
3675-
self.assertTrue(s.startswith('datetime.'))
3675+
self.assertStartsWith(s, 'datetime.')
36763676
s = s[9:]
36773677
t2 = eval(s)
36783678
self.assertEqual(t, t2)

Lib/test/mapping_tests.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,8 @@ def test_read(self):
7070
if not d: self.fail("Full mapping must compare to True")
7171
# keys(), items(), iterkeys() ...
7272
def check_iterandlist(iter, lst, ref):
73-
self.assertTrue(hasattr(iter, '__next__'))
74-
self.assertTrue(hasattr(iter, '__iter__'))
73+
self.assertHasAttr(iter, '__next__')
74+
self.assertHasAttr(iter, '__iter__')
7575
x = list(iter)
7676
self.assertTrue(set(x)==set(lst)==set(ref))
7777
check_iterandlist(iter(d.keys()), list(d.keys()),

Lib/test/pickletester.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3068,7 +3068,7 @@ def test_proto(self):
30683068
pickled = self.dumps(None, proto)
30693069
if proto >= 2:
30703070
proto_header = pickle.PROTO + bytes([proto])
3071-
self.assertTrue(pickled.startswith(proto_header))
3071+
self.assertStartsWith(pickled, proto_header)
30723072
else:
30733073
self.assertEqual(count_opcode(pickle.PROTO, pickled), 0)
30743074

@@ -5007,7 +5007,7 @@ def test_default_dispatch_table(self):
50075007
p = self.pickler_class(f, 0)
50085008
with self.assertRaises(AttributeError):
50095009
p.dispatch_table
5010-
self.assertFalse(hasattr(p, 'dispatch_table'))
5010+
self.assertNotHasAttr(p, 'dispatch_table')
50115011

50125012
def test_class_dispatch_table(self):
50135013
# A dispatch_table attribute can be specified class-wide

Lib/test/support/warnings_helper.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,7 @@ def check_syntax_warning(testcase, statement, errtext='',
2323
testcase.assertEqual(len(warns), 1, warns)
2424

2525
warn, = warns
26-
testcase.assertTrue(issubclass(warn.category, SyntaxWarning),
27-
warn.category)
26+
testcase.assertIsSubclass(warn.category, SyntaxWarning)
2827
if errtext:
2928
testcase.assertRegex(str(warn.message), errtext)
3029
testcase.assertEqual(warn.filename, '<testcase>')

Lib/test/test__osx_support.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,8 @@ def test__find_build_tool(self):
6666
'cc not found - check xcode-select')
6767

6868
def test__get_system_version(self):
69-
self.assertTrue(platform.mac_ver()[0].startswith(
70-
_osx_support._get_system_version()))
69+
self.assertStartsWith(platform.mac_ver()[0],
70+
_osx_support._get_system_version())
7171

7272
def test__remove_original_values(self):
7373
config_vars = {

Lib/test/test_abstract_numbers.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,11 @@ def not_implemented(*args, **kwargs):
2424

2525
class TestNumbers(unittest.TestCase):
2626
def test_int(self):
27-
self.assertTrue(issubclass(int, Integral))
28-
self.assertTrue(issubclass(int, Rational))
29-
self.assertTrue(issubclass(int, Real))
30-
self.assertTrue(issubclass(int, Complex))
31-
self.assertTrue(issubclass(int, Number))
27+
self.assertIsSubclass(int, Integral)
28+
self.assertIsSubclass(int, Rational)
29+
self.assertIsSubclass(int, Real)
30+
self.assertIsSubclass(int, Complex)
31+
self.assertIsSubclass(int, Number)
3232

3333
self.assertEqual(7, int(7).real)
3434
self.assertEqual(0, int(7).imag)
@@ -38,23 +38,23 @@ def test_int(self):
3838
self.assertEqual(1, int(7).denominator)
3939

4040
def test_float(self):
41-
self.assertFalse(issubclass(float, Integral))
42-
self.assertFalse(issubclass(float, Rational))
43-
self.assertTrue(issubclass(float, Real))
44-
self.assertTrue(issubclass(float, Complex))
45-
self.assertTrue(issubclass(float, Number))
41+
self.assertNotIsSubclass(float, Integral)
42+
self.assertNotIsSubclass(float, Rational)
43+
self.assertIsSubclass(float, Real)
44+
self.assertIsSubclass(float, Complex)
45+
self.assertIsSubclass(float, Number)
4646

4747
self.assertEqual(7.3, float(7.3).real)
4848
self.assertEqual(0, float(7.3).imag)
4949
self.assertEqual(7.3, float(7.3).conjugate())
5050
self.assertEqual(-7.3, float(-7.3).conjugate())
5151

5252
def test_complex(self):
53-
self.assertFalse(issubclass(complex, Integral))
54-
self.assertFalse(issubclass(complex, Rational))
55-
self.assertFalse(issubclass(complex, Real))
56-
self.assertTrue(issubclass(complex, Complex))
57-
self.assertTrue(issubclass(complex, Number))
53+
self.assertNotIsSubclass(complex, Integral)
54+
self.assertNotIsSubclass(complex, Rational)
55+
self.assertNotIsSubclass(complex, Real)
56+
self.assertIsSubclass(complex, Complex)
57+
self.assertIsSubclass(complex, Number)
5858

5959
c1, c2 = complex(3, 2), complex(4,1)
6060
# XXX: This is not ideal, but see the comment in math_trunc().

Lib/test/test_argparse.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6805,7 +6805,7 @@ class TestImportStar(TestCase):
68056805

68066806
def test(self):
68076807
for name in argparse.__all__:
6808-
self.assertTrue(hasattr(argparse, name))
6808+
self.assertHasAttr(argparse, name)
68096809

68106810
def test_all_exports_everything_but_modules(self):
68116811
items = [

Lib/test/test_ast/test_ast.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -275,12 +275,12 @@ def test_alias(self):
275275
self.assertEqual(alias.end_col_offset, 17)
276276

277277
def test_base_classes(self):
278-
self.assertTrue(issubclass(ast.For, ast.stmt))
279-
self.assertTrue(issubclass(ast.Name, ast.expr))
280-
self.assertTrue(issubclass(ast.stmt, ast.AST))
281-
self.assertTrue(issubclass(ast.expr, ast.AST))
282-
self.assertTrue(issubclass(ast.comprehension, ast.AST))
283-
self.assertTrue(issubclass(ast.Gt, ast.AST))
278+
self.assertIsSubclass(ast.For, ast.stmt)
279+
self.assertIsSubclass(ast.Name, ast.expr)
280+
self.assertIsSubclass(ast.stmt, ast.AST)
281+
self.assertIsSubclass(ast.expr, ast.AST)
282+
self.assertIsSubclass(ast.comprehension, ast.AST)
283+
self.assertIsSubclass(ast.Gt, ast.AST)
284284

285285
def test_field_attr_existence(self):
286286
for name, item in ast.__dict__.items():
@@ -1101,7 +1101,7 @@ def test_copy_with_parents(self):
11011101
def test_replace_interface(self):
11021102
for klass in self.iter_ast_classes():
11031103
with self.subTest(klass=klass):
1104-
self.assertTrue(hasattr(klass, '__replace__'))
1104+
self.assertHasAttr(klass, '__replace__')
11051105

11061106
fields = set(klass._fields)
11071107
with self.subTest(klass=klass, fields=fields):
@@ -1330,7 +1330,7 @@ def test_replace_reject_known_custom_instance_fields_commits(self):
13301330
context = node.ctx
13311331

13321332
# explicit rejection of known instance fields
1333-
self.assertTrue(hasattr(node, 'extra'))
1333+
self.assertHasAttr(node, 'extra')
13341334
msg = "Name.__replace__ got an unexpected keyword argument 'extra'."
13351335
with self.assertRaisesRegex(TypeError, re.escape(msg)):
13361336
copy.replace(node, extra=1)
@@ -3071,7 +3071,7 @@ def test_FunctionDef(self):
30713071
with self.assertWarnsRegex(DeprecationWarning,
30723072
r"FunctionDef\.__init__ missing 1 required positional argument: 'name'"):
30733073
node = ast.FunctionDef(args=args)
3074-
self.assertFalse(hasattr(node, "name"))
3074+
self.assertNotHasAttr(node, "name")
30753075
self.assertEqual(node.decorator_list, [])
30763076
node = ast.FunctionDef(name='foo', args=args)
30773077
self.assertEqual(node.name, 'foo')

Lib/test/test_audit.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def test_socket(self):
134134
self.assertEqual(events[0][0], "socket.gethostname")
135135
self.assertEqual(events[1][0], "socket.__new__")
136136
self.assertEqual(events[2][0], "socket.bind")
137-
self.assertTrue(events[2][2].endswith("('127.0.0.1', 8080)"))
137+
self.assertEndsWith(events[2][2], "('127.0.0.1', 8080)")
138138

139139
def test_gc(self):
140140
returncode, events, stderr = self.run_python("test_gc")

Lib/test/test_base64.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -812,7 +812,7 @@ def test_decode_nonascii_str(self):
812812
self.assertRaises(ValueError, f, 'with non-ascii \xcb')
813813

814814
def test_ErrorHeritage(self):
815-
self.assertTrue(issubclass(binascii.Error, ValueError))
815+
self.assertIsSubclass(binascii.Error, ValueError)
816816

817817
def test_RFC4648_test_cases(self):
818818
# test cases from RFC 4648 section 10

Lib/test/test_baseexception.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,11 @@ class ExceptionClassTests(unittest.TestCase):
1010
inheritance hierarchy)"""
1111

1212
def test_builtins_new_style(self):
13-
self.assertTrue(issubclass(Exception, object))
13+
self.assertIsSubclass(Exception, object)
1414

1515
def verify_instance_interface(self, ins):
1616
for attr in ("args", "__str__", "__repr__"):
17-
self.assertTrue(hasattr(ins, attr),
18-
"%s missing %s attribute" %
19-
(ins.__class__.__name__, attr))
17+
self.assertHasAttr(ins, attr)
2018

2119
def test_inheritance(self):
2220
# Make sure the inheritance hierarchy matches the documentation
@@ -65,7 +63,7 @@ def test_inheritance(self):
6563
elif last_depth > depth:
6664
while superclasses[-1][0] >= depth:
6765
superclasses.pop()
68-
self.assertTrue(issubclass(exc, superclasses[-1][1]),
66+
self.assertIsSubclass(exc, superclasses[-1][1],
6967
"%s is not a subclass of %s" % (exc.__name__,
7068
superclasses[-1][1].__name__))
7169
try: # Some exceptions require arguments; just skip them

Lib/test/test_binascii.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,13 @@ def assertConversion(self, original, converted, restored, **kwargs):
3838

3939
def test_exceptions(self):
4040
# Check module exceptions
41-
self.assertTrue(issubclass(binascii.Error, Exception))
42-
self.assertTrue(issubclass(binascii.Incomplete, Exception))
41+
self.assertIsSubclass(binascii.Error, Exception)
42+
self.assertIsSubclass(binascii.Incomplete, Exception)
4343

4444
def test_functions(self):
4545
# Check presence of all functions
4646
for name in all_functions:
47-
self.assertTrue(hasattr(getattr(binascii, name), '__call__'))
47+
self.assertHasAttr(getattr(binascii, name), '__call__')
4848
self.assertRaises(TypeError, getattr(binascii, name))
4949

5050
def test_returned_value(self):

Lib/test/test_binop.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -383,7 +383,7 @@ def test_comparison_orders(self):
383383
self.assertEqual(op_sequence(le, B, C), ['C.__ge__', 'B.__le__'])
384384
self.assertEqual(op_sequence(le, C, B), ['C.__le__', 'B.__ge__'])
385385

386-
self.assertTrue(issubclass(V, B))
386+
self.assertIsSubclass(V, B)
387387
self.assertEqual(op_sequence(eq, B, V), ['B.__eq__', 'V.__eq__'])
388388
self.assertEqual(op_sequence(le, B, V), ['B.__le__', 'V.__ge__'])
389389

Lib/test/test_buffer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2879,11 +2879,11 @@ def test_memoryview_tolist(self):
28792879
def test_memoryview_repr(self):
28802880
m = memoryview(bytearray(9))
28812881
r = m.__repr__()
2882-
self.assertTrue(r.startswith("<memory"))
2882+
self.assertStartsWith(r, "<memory")
28832883

28842884
m.release()
28852885
r = m.__repr__()
2886-
self.assertTrue(r.startswith("<released"))
2886+
self.assertStartsWith(r, "<released")
28872887

28882888
def test_memoryview_sequence(self):
28892889

Lib/test/test_builtin.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -393,7 +393,7 @@ def test_chr(self):
393393
self.assertRaises(ValueError, chr, -2**1000)
394394

395395
def test_cmp(self):
396-
self.assertTrue(not hasattr(builtins, "cmp"))
396+
self.assertNotHasAttr(builtins, "cmp")
397397

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

23092309
# first argument to object.__format__ must be string
23102310
self.assertRaises(TypeError, object().__format__, 3)

Lib/test/test_bytes.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1974,9 +1974,9 @@ def test_compare_bytes_to_bytearray(self):
19741974
@test.support.requires_docstrings
19751975
def test_doc(self):
19761976
self.assertIsNotNone(bytearray.__doc__)
1977-
self.assertTrue(bytearray.__doc__.startswith("bytearray("), bytearray.__doc__)
1977+
self.assertStartsWith(bytearray.__doc__, "bytearray(")
19781978
self.assertIsNotNone(bytes.__doc__)
1979-
self.assertTrue(bytes.__doc__.startswith("bytes("), bytes.__doc__)
1979+
self.assertStartsWith(bytes.__doc__, "bytes(")
19801980

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

21092109
def test_basic(self):
2110-
self.assertTrue(issubclass(self.type2test, self.basetype))
2110+
self.assertIsSubclass(self.type2test, self.basetype)
21112111
self.assertIsInstance(self.type2test(), self.basetype)
21122112

21132113
a, b = b"abcd", b"efgh"
@@ -2155,7 +2155,7 @@ def test_pickle(self):
21552155
self.assertEqual(a.z, b.z)
21562156
self.assertEqual(type(a), type(b))
21572157
self.assertEqual(type(a.z), type(b.z))
2158-
self.assertFalse(hasattr(b, 'y'))
2158+
self.assertNotHasAttr(b, 'y')
21592159

21602160
def test_copy(self):
21612161
a = self.type2test(b"abcd")
@@ -2169,7 +2169,7 @@ def test_copy(self):
21692169
self.assertEqual(a.z, b.z)
21702170
self.assertEqual(type(a), type(b))
21712171
self.assertEqual(type(a.z), type(b.z))
2172-
self.assertFalse(hasattr(b, 'y'))
2172+
self.assertNotHasAttr(b, 'y')
21732173

21742174
def test_fromhex(self):
21752175
b = self.type2test.fromhex('1a2B30')

Lib/test/test_bz2.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ def testPeek(self):
184184
with BZ2File(self.filename) as bz2f:
185185
pdata = bz2f.peek()
186186
self.assertNotEqual(len(pdata), 0)
187-
self.assertTrue(self.TEXT.startswith(pdata))
187+
self.assertStartsWith(self.TEXT, pdata)
188188
self.assertEqual(bz2f.read(), self.TEXT)
189189

190190
def testReadInto(self):
@@ -768,7 +768,7 @@ def testPeekBytesIO(self):
768768
with BZ2File(bio) as bz2f:
769769
pdata = bz2f.peek()
770770
self.assertNotEqual(len(pdata), 0)
771-
self.assertTrue(self.TEXT.startswith(pdata))
771+
self.assertStartsWith(self.TEXT, pdata)
772772
self.assertEqual(bz2f.read(), self.TEXT)
773773

774774
def testWriteBytesIO(self):

Lib/test/test_calendar.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1098,7 +1098,7 @@ def test_option_type(self):
10981098
output = run('--type', 'text', '2004')
10991099
self.assertEqual(output, conv(result_2004_text))
11001100
output = run('--type', 'html', '2004')
1101-
self.assertEqual(output[:6], b'<?xml ')
1101+
self.assertStartsWith(output, b'<?xml ')
11021102
self.assertIn(b'<title>Calendar for 2004</title>', output)
11031103

11041104
def test_html_output_current_year(self):

Lib/test/test_call.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -695,8 +695,8 @@ class DerivedType(SuperType):
695695
UnaffectedType2 = _testcapi.make_vectorcall_class(SuperType)
696696

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

701701
# Initial state: tp_call
702702
self.assertEqual(instance(), "tp_call")

0 commit comments

Comments
 (0)