Skip to content

Commit

Permalink
[3.13] pythongh-71339: Use new assertion methods in test_import and t…
Browse files Browse the repository at this point in the history
…est_importlib (pythonGH-129052)

(cherry picked from commit f7cc7d2)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
  • Loading branch information
serhiy-storchaka committed Jan 21, 2025
1 parent f10f2a2 commit ceaf7f5
Show file tree
Hide file tree
Showing 19 changed files with 67 additions and 63 deletions.
23 changes: 12 additions & 11 deletions Lib/test/test_import/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
TESTFN, rmtree, temp_umask, TESTFN_UNENCODABLE)
from test.support import script_helper
from test.support import threading_helper
from test.support.testcase import ExtraAssertions
from test.test_importlib.util import uncache
from types import ModuleType
try:
Expand Down Expand Up @@ -352,7 +353,7 @@ def _from_subinterp(cls, name, interpid, pipe, script_kwargs):
return cls.parse(text.decode())


class ImportTests(unittest.TestCase):
class ImportTests(unittest.TestCase, ExtraAssertions):

def setUp(self):
remove_files(TESTFN)
Expand Down Expand Up @@ -558,7 +559,7 @@ def test_import_name_binding(self):
import test as x
import test.support
self.assertIs(x, test, x.__name__)
self.assertTrue(hasattr(test.support, "__file__"))
self.assertHasAttr(test.support, "__file__")

# import x.y.z as w binds z as w
import test.support as y
Expand Down Expand Up @@ -629,7 +630,7 @@ def test_file_to_source(self):
sys.path.insert(0, os.curdir)
try:
mod = __import__(TESTFN)
self.assertTrue(mod.__file__.endswith('.py'))
self.assertEndsWith(mod.__file__, '.py')
os.remove(source)
del sys.modules[TESTFN]
make_legacy_pyc(source)
Expand Down Expand Up @@ -1462,11 +1463,11 @@ def test_UNC_path(self):
self.fail("could not import 'test_unc_path' from %r: %r"
% (unc, e))
self.assertEqual(mod.testdata, 'test_unc_path')
self.assertTrue(mod.__file__.startswith(unc), mod.__file__)
self.assertStartsWith(mod.__file__, unc)
unload("test_unc_path")


class RelativeImportTests(unittest.TestCase):
class RelativeImportTests(unittest.TestCase, ExtraAssertions):

def tearDown(self):
unload("test.relimport")
Expand All @@ -1475,7 +1476,7 @@ def tearDown(self):
def test_relimport_star(self):
# This will import * from .test_import.
from .. import relimport
self.assertTrue(hasattr(relimport, "RelativeImportTests"))
self.assertHasAttr(relimport, "RelativeImportTests")

def test_issue3221(self):
# Note for mergers: the 'absolute' tests from the 2.x branch
Expand Down Expand Up @@ -1792,7 +1793,7 @@ def test_symlinked_dir_importable(self):


@cpython_only
class ImportlibBootstrapTests(unittest.TestCase):
class ImportlibBootstrapTests(unittest.TestCase, ExtraAssertions):
# These tests check that importlib is bootstrapped.

def test_frozen_importlib(self):
Expand All @@ -1805,15 +1806,15 @@ def test_frozen_importlib_is_bootstrap(self):
self.assertIs(mod, _bootstrap)
self.assertEqual(mod.__name__, 'importlib._bootstrap')
self.assertEqual(mod.__package__, 'importlib')
self.assertTrue(mod.__file__.endswith('_bootstrap.py'), mod.__file__)
self.assertEndsWith(mod.__file__, '_bootstrap.py')

def test_frozen_importlib_external_is_bootstrap_external(self):
from importlib import _bootstrap_external
mod = sys.modules['_frozen_importlib_external']
self.assertIs(mod, _bootstrap_external)
self.assertEqual(mod.__name__, 'importlib._bootstrap_external')
self.assertEqual(mod.__package__, 'importlib')
self.assertTrue(mod.__file__.endswith('_bootstrap_external.py'), mod.__file__)
self.assertEndsWith(mod.__file__, '_bootstrap_external.py')

def test_there_can_be_only_one(self):
# Issue #15386 revealed a tricky loophole in the bootstrapping
Expand Down Expand Up @@ -2648,7 +2649,7 @@ def parse(cls, text):


@requires_singlephase_init
class SinglephaseInitTests(unittest.TestCase):
class SinglephaseInitTests(unittest.TestCase, ExtraAssertions):

NAME = '_testsinglephase'

Expand Down Expand Up @@ -2819,7 +2820,7 @@ def check_common(self, loaded):
self.assertEqual(mod.__file__, self.FILE)
self.assertEqual(mod.__spec__.origin, self.ORIGIN)
if not isolated:
self.assertTrue(issubclass(mod.error, Exception))
self.assertIsSubclass(mod.error, Exception)
self.assertEqual(mod.int_const, 1969)
self.assertEqual(mod.str_const, 'something different')
self.assertIsInstance(mod._module_initialized, float)
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_importlib/extension/test_path_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def hook(self, entry):
def test_success(self):
# Path hook should handle a directory where a known extension module
# exists.
self.assertTrue(hasattr(self.hook(util.EXTENSIONS.path), 'find_spec'))
self.assertHasAttr(self.hook(util.EXTENSIONS.path), 'find_spec')


(Frozen_PathHooksTests,
Expand Down
6 changes: 3 additions & 3 deletions Lib/test/test_importlib/frozen/test_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def exec_module(self, name, origname=None):
module.main()

self.assertTrue(module.initialized)
self.assertTrue(hasattr(module, '__spec__'))
self.assertHasAttr(module, '__spec__')
self.assertEqual(module.__spec__.origin, 'frozen')
return module, stdout.getvalue()

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

def test_package(self):
Expand Down Expand Up @@ -136,7 +136,7 @@ def test_get_code(self):
exec(code, mod.__dict__)
with captured_stdout() as stdout:
mod.main()
self.assertTrue(hasattr(mod, 'initialized'))
self.assertHasAttr(mod, 'initialized')
self.assertEqual(stdout.getvalue(), 'Hello world!\n')

def test_get_source(self):
Expand Down
7 changes: 4 additions & 3 deletions Lib/test/test_importlib/import_/test_caching.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Test that sys.modules is used properly by import."""
from test.test_importlib import util
from test.support.testcase import ExtraAssertions
import sys
from types import MethodType
import unittest
Expand Down Expand Up @@ -45,7 +46,7 @@ def test_None_in_cache(self):
) = util.test_both(UseCache, __import__=util.__import__)


class ImportlibUseCache(UseCache, unittest.TestCase):
class ImportlibUseCache(UseCache, unittest.TestCase, ExtraAssertions):

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

Expand Down Expand Up @@ -78,7 +79,7 @@ def test_using_cache_for_assigning_to_attribute(self):
with self.create_mock('pkg.__init__', 'pkg.module') as importer:
with util.import_state(meta_path=[importer]):
module = self.__import__('pkg.module')
self.assertTrue(hasattr(module, 'module'))
self.assertHasAttr(module, 'module')
self.assertEqual(id(module.module),
id(sys.modules['pkg.module']))

Expand All @@ -88,7 +89,7 @@ def test_using_cache_for_fromlist(self):
with self.create_mock('pkg.__init__', 'pkg.module') as importer:
with util.import_state(meta_path=[importer]):
module = self.__import__('pkg', fromlist=['module'])
self.assertTrue(hasattr(module, 'module'))
self.assertHasAttr(module, 'module')
self.assertEqual(id(module.module),
id(sys.modules['pkg.module']))

Expand Down
16 changes: 8 additions & 8 deletions Lib/test/test_importlib/import_/test_fromlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,23 +63,23 @@ def test_nonexistent_object(self):
with util.import_state(meta_path=[importer]):
module = self.__import__('module', fromlist=['non_existent'])
self.assertEqual(module.__name__, 'module')
self.assertFalse(hasattr(module, 'non_existent'))
self.assertNotHasAttr(module, 'non_existent')

def test_module_from_package(self):
# [module]
with util.mock_spec('pkg.__init__', 'pkg.module') as importer:
with util.import_state(meta_path=[importer]):
module = self.__import__('pkg', fromlist=['module'])
self.assertEqual(module.__name__, 'pkg')
self.assertTrue(hasattr(module, 'module'))
self.assertHasAttr(module, 'module')
self.assertEqual(module.module.__name__, 'pkg.module')

def test_nonexistent_from_package(self):
with util.mock_spec('pkg.__init__') as importer:
with util.import_state(meta_path=[importer]):
module = self.__import__('pkg', fromlist=['non_existent'])
self.assertEqual(module.__name__, 'pkg')
self.assertFalse(hasattr(module, 'non_existent'))
self.assertNotHasAttr(module, 'non_existent')

def test_module_from_package_triggers_ModuleNotFoundError(self):
# If a submodule causes an ModuleNotFoundError because it tries
Expand Down Expand Up @@ -107,7 +107,7 @@ def basic_star_test(self, fromlist=['*']):
mock['pkg'].__all__ = ['module']
module = self.__import__('pkg', fromlist=fromlist)
self.assertEqual(module.__name__, 'pkg')
self.assertTrue(hasattr(module, 'module'))
self.assertHasAttr(module, 'module')
self.assertEqual(module.module.__name__, 'pkg.module')

def test_using_star(self):
Expand All @@ -125,8 +125,8 @@ def test_star_with_others(self):
mock['pkg'].__all__ = ['module1']
module = self.__import__('pkg', fromlist=['module2', '*'])
self.assertEqual(module.__name__, 'pkg')
self.assertTrue(hasattr(module, 'module1'))
self.assertTrue(hasattr(module, 'module2'))
self.assertHasAttr(module, 'module1')
self.assertHasAttr(module, 'module2')
self.assertEqual(module.module1.__name__, 'pkg.module1')
self.assertEqual(module.module2.__name__, 'pkg.module2')

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

def test_star_in_all(self):
with util.mock_spec('pkg.__init__') as importer:
with util.import_state(meta_path=[importer]):
importer['pkg'].__all__ = ['*']
module = self.__import__('pkg', fromlist=['*'])
self.assertEqual(module.__name__, 'pkg')
self.assertFalse(hasattr(module, '*'))
self.assertNotHasAttr(module, '*')

def test_invalid_type(self):
with util.mock_spec('pkg.__init__') as importer:
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_importlib/import_/test_meta_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def test_empty(self):
self.assertIsNone(importlib._bootstrap._find_spec('nothing',
None))
self.assertEqual(len(w), 1)
self.assertTrue(issubclass(w[-1].category, ImportWarning))
self.assertIsSubclass(w[-1].category, ImportWarning)


(Frozen_CallingOrder,
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_importlib/import_/test_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def test_empty_path_hooks(self):
self.assertIsNone(self.find('os'))
self.assertIsNone(sys.path_importer_cache[path_entry])
self.assertEqual(len(w), 1)
self.assertTrue(issubclass(w[-1].category, ImportWarning))
self.assertIsSubclass(w[-1].category, ImportWarning)

def test_path_importer_cache_empty_string(self):
# The empty string should create a finder using the cwd.
Expand Down
6 changes: 3 additions & 3 deletions Lib/test/test_importlib/import_/test_relative_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def callback(global_):
self.__import__('pkg') # For __import__().
module = self.__import__('', global_, fromlist=['mod2'], level=1)
self.assertEqual(module.__name__, 'pkg')
self.assertTrue(hasattr(module, 'mod2'))
self.assertHasAttr(module, 'mod2')
self.assertEqual(module.mod2.attr, 'pkg.mod2')
self.relative_import_test(create, globals_, callback)

Expand All @@ -107,7 +107,7 @@ def callback(global_):
module = self.__import__('', global_, fromlist=['module'],
level=1)
self.assertEqual(module.__name__, 'pkg')
self.assertTrue(hasattr(module, 'module'))
self.assertHasAttr(module, 'module')
self.assertEqual(module.module.attr, 'pkg.module')
self.relative_import_test(create, globals_, callback)

Expand All @@ -131,7 +131,7 @@ def callback(global_):
module = self.__import__('', global_, fromlist=['subpkg2'],
level=2)
self.assertEqual(module.__name__, 'pkg')
self.assertTrue(hasattr(module, 'subpkg2'))
self.assertHasAttr(module, 'subpkg2')
self.assertEqual(module.subpkg2.attr, 'pkg.subpkg2.__init__')
self.relative_import_test(create, globals_, callback)

Expand Down
5 changes: 3 additions & 2 deletions Lib/test/test_importlib/resources/test_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from importlib import resources
from . import util
from test.support.testcase import ExtraAssertions


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


class PathTests:
class PathTests(ExtraAssertions):
def test_reading(self):
"""
Path should be readable and a pathlib.Path instance.
"""
target = resources.files(self.data) / 'utf-8.file'
with resources.as_file(target) as path:
self.assertIsInstance(path, pathlib.Path)
self.assertTrue(path.name.endswith("utf-8.file"), repr(path))
self.assertEndsWith(path.name, "utf-8.file")
self.assertEqual('Hello, UTF-8 world!\n', path.read_text(encoding='utf-8'))


Expand Down
8 changes: 4 additions & 4 deletions Lib/test/test_importlib/source/test_finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def run_test(self, test, create=None, *, compile_=None, unlink=None):
if error.errno != errno.ENOENT:
raise
loader = self.import_(mapping['.root'], test)
self.assertTrue(hasattr(loader, 'load_module'))
self.assertHasAttr(loader, 'load_module')
return loader

def test_module(self):
Expand All @@ -100,15 +100,15 @@ def test_module_in_package(self):
with 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.assertTrue(hasattr(loader, 'load_module'))
self.assertHasAttr(loader, 'load_module')

# [sub package]
def test_package_in_package(self):
context = util.create_modules('pkg.__init__', 'pkg.sub.__init__')
with context as mapping:
pkg_dir = os.path.dirname(mapping['pkg.__init__'])
loader = self.import_(pkg_dir, 'pkg.sub')
self.assertTrue(hasattr(loader, 'load_module'))
self.assertHasAttr(loader, 'load_module')

# [package over modules]
def test_package_over_module(self):
Expand All @@ -129,7 +129,7 @@ def test_empty_string_for_dir(self):
file.write("# test file for importlib")
try:
loader = self._find(finder, 'mod', loader_only=True)
self.assertTrue(hasattr(loader, 'load_module'))
self.assertHasAttr(loader, 'load_module')
finally:
os.unlink('mod.py')

Expand Down
6 changes: 3 additions & 3 deletions Lib/test/test_importlib/source/test_path_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ def path_hook(self):

def test_success(self):
with util.create_modules('dummy') as mapping:
self.assertTrue(hasattr(self.path_hook()(mapping['.root']),
'find_spec'))
self.assertHasAttr(self.path_hook()(mapping['.root']),
'find_spec')

def test_empty_string(self):
# The empty string represents the cwd.
self.assertTrue(hasattr(self.path_hook()(''), 'find_spec'))
self.assertHasAttr(self.path_hook()(''), 'find_spec')


(Frozen_PathHookTest,
Expand Down
Loading

0 comments on commit ceaf7f5

Please sign in to comment.