Skip to content

Commit a9bb009

Browse files
[3.13] gh-71339: Use new assertion methods in test_import and test_importlib (GH-129052) (#129123)
(cherry picked from commit f7cc7d2) Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
1 parent d2ec87f commit a9bb009

19 files changed

+68
-64
lines changed

Lib/test/test_import/__init__.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
TESTFN, rmtree, temp_umask, TESTFN_UNENCODABLE)
5151
from test.support import script_helper
5252
from test.support import threading_helper
53+
from test.support.testcase import ExtraAssertions
5354
from test.test_importlib.util import uncache
5455
from types import ModuleType
5556
try:
@@ -364,7 +365,7 @@ def _from_subinterp(cls, name, interpid, pipe, script_kwargs):
364365

365366

366367
@force_not_colorized_test_class
367-
class ImportTests(unittest.TestCase):
368+
class ImportTests(unittest.TestCase, ExtraAssertions):
368369

369370
def setUp(self):
370371
remove_files(TESTFN)
@@ -570,7 +571,7 @@ def test_import_name_binding(self):
570571
import test as x
571572
import test.support
572573
self.assertIs(x, test, x.__name__)
573-
self.assertTrue(hasattr(test.support, "__file__"))
574+
self.assertHasAttr(test.support, "__file__")
574575

575576
# import x.y.z as w binds z as w
576577
import test.support as y
@@ -641,7 +642,7 @@ def test_file_to_source(self):
641642
sys.path.insert(0, os.curdir)
642643
try:
643644
mod = __import__(TESTFN)
644-
self.assertTrue(mod.__file__.endswith('.py'))
645+
self.assertEndsWith(mod.__file__, '.py')
645646
os.remove(source)
646647
del sys.modules[TESTFN]
647648
make_legacy_pyc(source)
@@ -1447,7 +1448,7 @@ def test_foreign_code(self):
14471448
self.assertEqual(mod.constant.co_filename, foreign_code.co_filename)
14481449

14491450

1450-
class PathsTests(unittest.TestCase):
1451+
class PathsTests(unittest.TestCase, ExtraAssertions):
14511452
SAMPLES = ('test', 'test\u00e4\u00f6\u00fc\u00df', 'test\u00e9\u00e8',
14521453
'test\u00b0\u00b3\u00b2')
14531454
path = TESTFN
@@ -1497,11 +1498,11 @@ def test_UNC_path(self):
14971498
self.fail("could not import 'test_unc_path' from %r: %r"
14981499
% (unc, e))
14991500
self.assertEqual(mod.testdata, 'test_unc_path')
1500-
self.assertTrue(mod.__file__.startswith(unc), mod.__file__)
1501+
self.assertStartsWith(mod.__file__, unc)
15011502
unload("test_unc_path")
15021503

15031504

1504-
class RelativeImportTests(unittest.TestCase):
1505+
class RelativeImportTests(unittest.TestCase, ExtraAssertions):
15051506

15061507
def tearDown(self):
15071508
unload("test.relimport")
@@ -1510,7 +1511,7 @@ def tearDown(self):
15101511
def test_relimport_star(self):
15111512
# This will import * from .test_import.
15121513
from .. import relimport
1513-
self.assertTrue(hasattr(relimport, "RelativeImportTests"))
1514+
self.assertHasAttr(relimport, "RelativeImportTests")
15141515

15151516
def test_issue3221(self):
15161517
# Note for mergers: the 'absolute' tests from the 2.x branch
@@ -1827,7 +1828,7 @@ def test_symlinked_dir_importable(self):
18271828

18281829

18291830
@cpython_only
1830-
class ImportlibBootstrapTests(unittest.TestCase):
1831+
class ImportlibBootstrapTests(unittest.TestCase, ExtraAssertions):
18311832
# These tests check that importlib is bootstrapped.
18321833

18331834
def test_frozen_importlib(self):
@@ -1840,15 +1841,15 @@ def test_frozen_importlib_is_bootstrap(self):
18401841
self.assertIs(mod, _bootstrap)
18411842
self.assertEqual(mod.__name__, 'importlib._bootstrap')
18421843
self.assertEqual(mod.__package__, 'importlib')
1843-
self.assertTrue(mod.__file__.endswith('_bootstrap.py'), mod.__file__)
1844+
self.assertEndsWith(mod.__file__, '_bootstrap.py')
18441845

18451846
def test_frozen_importlib_external_is_bootstrap_external(self):
18461847
from importlib import _bootstrap_external
18471848
mod = sys.modules['_frozen_importlib_external']
18481849
self.assertIs(mod, _bootstrap_external)
18491850
self.assertEqual(mod.__name__, 'importlib._bootstrap_external')
18501851
self.assertEqual(mod.__package__, 'importlib')
1851-
self.assertTrue(mod.__file__.endswith('_bootstrap_external.py'), mod.__file__)
1852+
self.assertEndsWith(mod.__file__, '_bootstrap_external.py')
18521853

18531854
def test_there_can_be_only_one(self):
18541855
# Issue #15386 revealed a tricky loophole in the bootstrapping
@@ -2698,7 +2699,7 @@ def parse(cls, text):
26982699

26992700

27002701
@requires_singlephase_init
2701-
class SinglephaseInitTests(unittest.TestCase):
2702+
class SinglephaseInitTests(unittest.TestCase, ExtraAssertions):
27022703

27032704
NAME = '_testsinglephase'
27042705

@@ -2869,7 +2870,7 @@ def check_common(self, loaded):
28692870
self.assertEqual(mod.__file__, self.FILE)
28702871
self.assertEqual(mod.__spec__.origin, self.ORIGIN)
28712872
if not isolated:
2872-
self.assertTrue(issubclass(mod.error, Exception))
2873+
self.assertIsSubclass(mod.error, Exception)
28732874
self.assertEqual(mod.int_const, 1969)
28742875
self.assertEqual(mod.str_const, 'something different')
28752876
self.assertIsInstance(mod._module_initialized, float)

Lib/test/test_importlib/extension/test_path_hook.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def hook(self, entry):
2121
def test_success(self):
2222
# Path hook should handle a directory where a known extension module
2323
# exists.
24-
self.assertTrue(hasattr(self.hook(util.EXTENSIONS.path), 'find_spec'))
24+
self.assertHasAttr(self.hook(util.EXTENSIONS.path), 'find_spec')
2525

2626

2727
(Frozen_PathHooksTests,

Lib/test/test_importlib/frozen/test_loader.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ def exec_module(self, name, origname=None):
6161
module.main()
6262

6363
self.assertTrue(module.initialized)
64-
self.assertTrue(hasattr(module, '__spec__'))
64+
self.assertHasAttr(module, '__spec__')
6565
self.assertEqual(module.__spec__.origin, 'frozen')
6666
return module, stdout.getvalue()
6767

@@ -72,7 +72,7 @@ def test_module(self):
7272
for attr, value in check.items():
7373
self.assertEqual(getattr(module, attr), value)
7474
self.assertEqual(output, 'Hello world!\n')
75-
self.assertTrue(hasattr(module, '__spec__'))
75+
self.assertHasAttr(module, '__spec__')
7676
self.assertEqual(module.__spec__.loader_state.origname, name)
7777

7878
def test_package(self):
@@ -136,7 +136,7 @@ def test_get_code(self):
136136
exec(code, mod.__dict__)
137137
with captured_stdout() as stdout:
138138
mod.main()
139-
self.assertTrue(hasattr(mod, 'initialized'))
139+
self.assertHasAttr(mod, 'initialized')
140140
self.assertEqual(stdout.getvalue(), 'Hello world!\n')
141141

142142
def test_get_source(self):

Lib/test/test_importlib/import_/test_caching.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Test that sys.modules is used properly by import."""
22
from test.test_importlib import util
3+
from test.support.testcase import ExtraAssertions
34
import sys
45
from types import MethodType
56
import unittest
@@ -45,7 +46,7 @@ def test_None_in_cache(self):
4546
) = util.test_both(UseCache, __import__=util.__import__)
4647

4748

48-
class ImportlibUseCache(UseCache, unittest.TestCase):
49+
class ImportlibUseCache(UseCache, unittest.TestCase, ExtraAssertions):
4950

5051
# Pertinent only to PEP 302; exec_module() doesn't return a module.
5152

@@ -78,7 +79,7 @@ def test_using_cache_for_assigning_to_attribute(self):
7879
with self.create_mock('pkg.__init__', 'pkg.module') as importer:
7980
with util.import_state(meta_path=[importer]):
8081
module = self.__import__('pkg.module')
81-
self.assertTrue(hasattr(module, 'module'))
82+
self.assertHasAttr(module, 'module')
8283
self.assertEqual(id(module.module),
8384
id(sys.modules['pkg.module']))
8485

@@ -88,7 +89,7 @@ def test_using_cache_for_fromlist(self):
8889
with self.create_mock('pkg.__init__', 'pkg.module') as importer:
8990
with util.import_state(meta_path=[importer]):
9091
module = self.__import__('pkg', fromlist=['module'])
91-
self.assertTrue(hasattr(module, 'module'))
92+
self.assertHasAttr(module, 'module')
9293
self.assertEqual(id(module.module),
9394
id(sys.modules['pkg.module']))
9495

Lib/test/test_importlib/import_/test_fromlist.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -63,23 +63,23 @@ def test_nonexistent_object(self):
6363
with util.import_state(meta_path=[importer]):
6464
module = self.__import__('module', fromlist=['non_existent'])
6565
self.assertEqual(module.__name__, 'module')
66-
self.assertFalse(hasattr(module, 'non_existent'))
66+
self.assertNotHasAttr(module, 'non_existent')
6767

6868
def test_module_from_package(self):
6969
# [module]
7070
with util.mock_spec('pkg.__init__', 'pkg.module') as importer:
7171
with util.import_state(meta_path=[importer]):
7272
module = self.__import__('pkg', fromlist=['module'])
7373
self.assertEqual(module.__name__, 'pkg')
74-
self.assertTrue(hasattr(module, 'module'))
74+
self.assertHasAttr(module, 'module')
7575
self.assertEqual(module.module.__name__, 'pkg.module')
7676

7777
def test_nonexistent_from_package(self):
7878
with util.mock_spec('pkg.__init__') as importer:
7979
with util.import_state(meta_path=[importer]):
8080
module = self.__import__('pkg', fromlist=['non_existent'])
8181
self.assertEqual(module.__name__, 'pkg')
82-
self.assertFalse(hasattr(module, 'non_existent'))
82+
self.assertNotHasAttr(module, 'non_existent')
8383

8484
def test_module_from_package_triggers_ModuleNotFoundError(self):
8585
# If a submodule causes an ModuleNotFoundError because it tries
@@ -107,7 +107,7 @@ def basic_star_test(self, fromlist=['*']):
107107
mock['pkg'].__all__ = ['module']
108108
module = self.__import__('pkg', fromlist=fromlist)
109109
self.assertEqual(module.__name__, 'pkg')
110-
self.assertTrue(hasattr(module, 'module'))
110+
self.assertHasAttr(module, 'module')
111111
self.assertEqual(module.module.__name__, 'pkg.module')
112112

113113
def test_using_star(self):
@@ -125,8 +125,8 @@ def test_star_with_others(self):
125125
mock['pkg'].__all__ = ['module1']
126126
module = self.__import__('pkg', fromlist=['module2', '*'])
127127
self.assertEqual(module.__name__, 'pkg')
128-
self.assertTrue(hasattr(module, 'module1'))
129-
self.assertTrue(hasattr(module, 'module2'))
128+
self.assertHasAttr(module, 'module1')
129+
self.assertHasAttr(module, 'module2')
130130
self.assertEqual(module.module1.__name__, 'pkg.module1')
131131
self.assertEqual(module.module2.__name__, 'pkg.module2')
132132

@@ -136,15 +136,15 @@ def test_nonexistent_in_all(self):
136136
importer['pkg'].__all__ = ['non_existent']
137137
module = self.__import__('pkg', fromlist=['*'])
138138
self.assertEqual(module.__name__, 'pkg')
139-
self.assertFalse(hasattr(module, 'non_existent'))
139+
self.assertNotHasAttr(module, 'non_existent')
140140

141141
def test_star_in_all(self):
142142
with util.mock_spec('pkg.__init__') as importer:
143143
with util.import_state(meta_path=[importer]):
144144
importer['pkg'].__all__ = ['*']
145145
module = self.__import__('pkg', fromlist=['*'])
146146
self.assertEqual(module.__name__, 'pkg')
147-
self.assertFalse(hasattr(module, '*'))
147+
self.assertNotHasAttr(module, '*')
148148

149149
def test_invalid_type(self):
150150
with util.mock_spec('pkg.__init__') as importer:

Lib/test/test_importlib/import_/test_meta_path.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def test_empty(self):
4343
self.assertIsNone(importlib._bootstrap._find_spec('nothing',
4444
None))
4545
self.assertEqual(len(w), 1)
46-
self.assertTrue(issubclass(w[-1].category, ImportWarning))
46+
self.assertIsSubclass(w[-1].category, ImportWarning)
4747

4848

4949
(Frozen_CallingOrder,

Lib/test/test_importlib/import_/test_path.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def test_empty_path_hooks(self):
8080
self.assertIsNone(self.find('os'))
8181
self.assertIsNone(sys.path_importer_cache[path_entry])
8282
self.assertEqual(len(w), 1)
83-
self.assertTrue(issubclass(w[-1].category, ImportWarning))
83+
self.assertIsSubclass(w[-1].category, ImportWarning)
8484

8585
def test_path_importer_cache_empty_string(self):
8686
# The empty string should create a finder using the cwd.

Lib/test/test_importlib/import_/test_relative_imports.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def callback(global_):
8181
self.__import__('pkg') # For __import__().
8282
module = self.__import__('', global_, fromlist=['mod2'], level=1)
8383
self.assertEqual(module.__name__, 'pkg')
84-
self.assertTrue(hasattr(module, 'mod2'))
84+
self.assertHasAttr(module, 'mod2')
8585
self.assertEqual(module.mod2.attr, 'pkg.mod2')
8686
self.relative_import_test(create, globals_, callback)
8787

@@ -107,7 +107,7 @@ def callback(global_):
107107
module = self.__import__('', global_, fromlist=['module'],
108108
level=1)
109109
self.assertEqual(module.__name__, 'pkg')
110-
self.assertTrue(hasattr(module, 'module'))
110+
self.assertHasAttr(module, 'module')
111111
self.assertEqual(module.module.attr, 'pkg.module')
112112
self.relative_import_test(create, globals_, callback)
113113

@@ -131,7 +131,7 @@ def callback(global_):
131131
module = self.__import__('', global_, fromlist=['subpkg2'],
132132
level=2)
133133
self.assertEqual(module.__name__, 'pkg')
134-
self.assertTrue(hasattr(module, 'subpkg2'))
134+
self.assertHasAttr(module, 'subpkg2')
135135
self.assertEqual(module.subpkg2.attr, 'pkg.subpkg2.__init__')
136136
self.relative_import_test(create, globals_, callback)
137137

Lib/test/test_importlib/resources/test_path.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from importlib import resources
66
from . import util
7+
from test.support.testcase import ExtraAssertions
78

89

910
class CommonTests(util.CommonTests, unittest.TestCase):
@@ -12,15 +13,15 @@ def execute(self, package, path):
1213
pass
1314

1415

15-
class PathTests:
16+
class PathTests(ExtraAssertions):
1617
def test_reading(self):
1718
"""
1819
Path should be readable and a pathlib.Path instance.
1920
"""
2021
target = resources.files(self.data) / 'utf-8.file'
2122
with resources.as_file(target) as path:
2223
self.assertIsInstance(path, pathlib.Path)
23-
self.assertTrue(path.name.endswith("utf-8.file"), repr(path))
24+
self.assertEndsWith(path.name, "utf-8.file")
2425
self.assertEqual('Hello, UTF-8 world!\n', path.read_text(encoding='utf-8'))
2526

2627

Lib/test/test_importlib/source/test_finder.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def run_test(self, test, create=None, *, compile_=None, unlink=None):
7373
if error.errno != errno.ENOENT:
7474
raise
7575
loader = self.import_(mapping['.root'], test)
76-
self.assertTrue(hasattr(loader, 'load_module'))
76+
self.assertHasAttr(loader, 'load_module')
7777
return loader
7878

7979
def test_module(self):
@@ -100,15 +100,15 @@ def test_module_in_package(self):
100100
with util.create_modules('pkg.__init__', 'pkg.sub') as mapping:
101101
pkg_dir = os.path.dirname(mapping['pkg.__init__'])
102102
loader = self.import_(pkg_dir, 'pkg.sub')
103-
self.assertTrue(hasattr(loader, 'load_module'))
103+
self.assertHasAttr(loader, 'load_module')
104104

105105
# [sub package]
106106
def test_package_in_package(self):
107107
context = util.create_modules('pkg.__init__', 'pkg.sub.__init__')
108108
with context as mapping:
109109
pkg_dir = os.path.dirname(mapping['pkg.__init__'])
110110
loader = self.import_(pkg_dir, 'pkg.sub')
111-
self.assertTrue(hasattr(loader, 'load_module'))
111+
self.assertHasAttr(loader, 'load_module')
112112

113113
# [package over modules]
114114
def test_package_over_module(self):
@@ -129,7 +129,7 @@ def test_empty_string_for_dir(self):
129129
file.write("# test file for importlib")
130130
try:
131131
loader = self._find(finder, 'mod', loader_only=True)
132-
self.assertTrue(hasattr(loader, 'load_module'))
132+
self.assertHasAttr(loader, 'load_module')
133133
finally:
134134
os.unlink('mod.py')
135135

Lib/test/test_importlib/source/test_path_hook.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,12 @@ def path_hook(self):
1515

1616
def test_success(self):
1717
with util.create_modules('dummy') as mapping:
18-
self.assertTrue(hasattr(self.path_hook()(mapping['.root']),
19-
'find_spec'))
18+
self.assertHasAttr(self.path_hook()(mapping['.root']),
19+
'find_spec')
2020

2121
def test_empty_string(self):
2222
# The empty string represents the cwd.
23-
self.assertTrue(hasattr(self.path_hook()(''), 'find_spec'))
23+
self.assertHasAttr(self.path_hook()(''), 'find_spec')
2424

2525

2626
(Frozen_PathHookTest,

0 commit comments

Comments
 (0)