From 3c50821d74f4ced3f5331d16eba7d570a8dd2360 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Sun, 31 Jul 2022 19:39:29 -0400 Subject: [PATCH 01/16] Run pyupgrade --py37-plus --- distutils/_msvccompiler.py | 10 +++++----- distutils/bcppcompiler.py | 4 ++-- distutils/ccompiler.py | 2 +- distutils/cmd.py | 8 ++++---- distutils/command/bdist_dumb.py | 2 +- distutils/command/bdist_msi.py | 10 +++++----- distutils/command/bdist_rpm.py | 8 ++++---- distutils/command/bdist_wininst.py | 16 ++++++++-------- distutils/command/build.py | 2 +- distutils/command/build_ext.py | 2 +- distutils/command/check.py | 2 +- distutils/command/register.py | 6 +++--- distutils/command/sdist.py | 2 +- distutils/command/upload.py | 6 +++--- distutils/core.py | 8 ++++---- distutils/cygwinccompiler.py | 10 +++++----- distutils/dir_util.py | 6 +++--- distutils/dist.py | 10 +++++----- distutils/extension.py | 2 +- distutils/fancy_getopt.py | 6 +++--- distutils/file_util.py | 16 ++++++++-------- distutils/filelist.py | 8 ++++---- distutils/msvc9compiler.py | 10 +++++----- distutils/msvccompiler.py | 6 +++--- distutils/py38compat.py | 2 +- distutils/spawn.py | 4 ++-- distutils/tests/support.py | 4 ++-- distutils/tests/test_archive_util.py | 1 - distutils/tests/test_bdist_dumb.py | 6 +++--- distutils/tests/test_bdist_rpm.py | 4 ++-- distutils/tests/test_build.py | 2 +- distutils/tests/test_build_ext.py | 12 +++++------- distutils/tests/test_build_py.py | 2 +- distutils/tests/test_config.py | 4 ++-- distutils/tests/test_config_cmd.py | 4 ++-- distutils/tests/test_core.py | 4 ++-- distutils/tests/test_cygwinccompiler.py | 6 +++--- distutils/tests/test_dir_util.py | 6 +++--- distutils/tests/test_dist.py | 10 +++++----- distutils/tests/test_file_util.py | 12 ++++++------ distutils/tests/test_register.py | 8 ++++---- distutils/tests/test_sdist.py | 4 ++-- distutils/tests/test_sysconfig.py | 4 ++-- distutils/tests/test_unixccompiler.py | 2 +- distutils/tests/test_upload.py | 6 +++--- distutils/tests/test_util.py | 4 ++-- distutils/tests/test_version.py | 12 ++++++------ distutils/text_file.py | 2 +- distutils/util.py | 4 ++-- distutils/version.py | 2 +- 50 files changed, 145 insertions(+), 148 deletions(-) diff --git a/distutils/_msvccompiler.py b/distutils/_msvccompiler.py index aa0ceccbc6..c2af5f2b3c 100644 --- a/distutils/_msvccompiler.py +++ b/distutils/_msvccompiler.py @@ -144,12 +144,12 @@ def _get_vc_env(plat_spec): try: out = subprocess.check_output( - 'cmd /u /c "{}" {} && set'.format(vcvarsall, plat_spec), + f'cmd /u /c "{vcvarsall}" {plat_spec} && set', stderr=subprocess.STDOUT, ).decode('utf-16le', errors='replace') except subprocess.CalledProcessError as exc: log.error(exc.output) - raise DistutilsPlatformError("Error executing {}".format(exc.cmd)) + raise DistutilsPlatformError(f"Error executing {exc.cmd}") env = { key.lower(): value @@ -232,7 +232,7 @@ def initialize(self, plat_name=None): # sanity check for platforms to prevent obscure errors later. if plat_name not in PLAT_TO_VCVARS: raise DistutilsPlatformError( - "--plat-name must be one of {}".format(tuple(PLAT_TO_VCVARS)) + f"--plat-name must be one of {tuple(PLAT_TO_VCVARS)}" ) # Get the vcvarsall.bat spec for the requested platform. @@ -341,7 +341,7 @@ def make_out_path(p): # Better to raise an exception instead of silently continuing # and later complain about sources and targets having # different lengths - raise CompileError("Don't know how to compile {}".format(p)) + raise CompileError(f"Don't know how to compile {p}") return list(map(make_out_path, source_filenames)) @@ -426,7 +426,7 @@ def compile( # noqa: C901 else: # how to handle this file? raise CompileError( - "Don't know how to compile {} to {}".format(src, obj) + f"Don't know how to compile {src} to {obj}" ) args = [self.cc] + compile_opts + pp_opts diff --git a/distutils/bcppcompiler.py b/distutils/bcppcompiler.py index 7a6f951fa8..ee033ed94a 100644 --- a/distutils/bcppcompiler.py +++ b/distutils/bcppcompiler.py @@ -234,7 +234,7 @@ def link( # noqa: C901 def_file = os.path.join(temp_dir, '%s.def' % modname) contents = ['EXPORTS'] for sym in export_symbols or []: - contents.append(' %s=_%s' % (sym, sym)) + contents.append(' {}=_{}'.format(sym, sym)) self.execute(write_file, (def_file, contents), "writing %s" % def_file) # Borland C++ has problems with '/' in paths @@ -346,7 +346,7 @@ def object_filenames(self, source_filenames, strip_dir=0, output_dir=''): (base, ext) = os.path.splitext(os.path.normcase(src_name)) if ext not in (self.src_extensions + ['.rc', '.res']): raise UnknownFileError( - "unknown file type '%s' (from '%s')" % (ext, src_name) + "unknown file type '{}' (from '{}')".format(ext, src_name) ) if strip_dir: base = os.path.basename(base) diff --git a/distutils/ccompiler.py b/distutils/ccompiler.py index c1761d0214..b4d3d0fbe0 100644 --- a/distutils/ccompiler.py +++ b/distutils/ccompiler.py @@ -930,7 +930,7 @@ def object_filenames(self, source_filenames, strip_dir=0, output_dir=''): base = base[os.path.isabs(base) :] # If abs, chop off leading / if ext not in self.src_extensions: raise UnknownFileError( - "unknown file type '%s' (from '%s')" % (ext, src_name) + "unknown file type '{}' (from '{}')".format(ext, src_name) ) if strip_dir: base = os.path.basename(base) diff --git a/distutils/cmd.py b/distutils/cmd.py index 6f68801db8..68a9267c65 100644 --- a/distutils/cmd.py +++ b/distutils/cmd.py @@ -163,7 +163,7 @@ def dump_options(self, header=None, indent=""): if option[-1] == "=": option = option[:-1] value = getattr(self, option) - self.announce(indent + "%s = %s" % (option, value), level=log.INFO) + self.announce(indent + "{} = {}".format(option, value), level=log.INFO) def run(self): """A command's raison d'etre: carry out the action it exists to @@ -215,7 +215,7 @@ def _ensure_stringlike(self, option, what, default=None): return default elif not isinstance(val, str): raise DistutilsOptionError( - "'%s' must be a %s (got `%s`)" % (option, what, val) + "'{}' must be a {} (got `{}`)".format(option, what, val) ) return val @@ -243,7 +243,7 @@ def ensure_string_list(self, option): ok = False if not ok: raise DistutilsOptionError( - "'%s' must be a list of strings (got %r)" % (option, val) + "'{}' must be a list of strings (got {!r})".format(option, val) ) def _ensure_tested_string(self, option, tester, what, error_fmt, default=None): @@ -424,7 +424,7 @@ def make_file( raise TypeError("'infiles' must be a string, or a list or tuple of strings") if exec_msg is None: - exec_msg = "generating %s from %s" % (outfile, ', '.join(infiles)) + exec_msg = "generating {} from {}".format(outfile, ', '.join(infiles)) # If 'outfile' must be regenerated (either because it doesn't # exist, is out-of-date, or the 'force' flag is true) then diff --git a/distutils/command/bdist_dumb.py b/distutils/command/bdist_dumb.py index d3f519e078..9e1434deae 100644 --- a/distutils/command/bdist_dumb.py +++ b/distutils/command/bdist_dumb.py @@ -105,7 +105,7 @@ def run(self): # And make an archive relative to the root of the # pseudo-installation tree. - archive_basename = "%s.%s" % (self.distribution.get_fullname(), self.plat_name) + archive_basename = "{}.{}".format(self.distribution.get_fullname(), self.plat_name) pseudoinstall_root = os.path.join(self.dist_dir, archive_basename) if not self.relative: diff --git a/distutils/command/bdist_msi.py b/distutils/command/bdist_msi.py index 6e1e1abd86..57931c733d 100644 --- a/distutils/command/bdist_msi.py +++ b/distutils/command/bdist_msi.py @@ -253,7 +253,7 @@ def run(self): # noqa: C901 if not target_version: assert self.skip_build, "Should have already checked this" target_version = '%d.%d' % sys.version_info[:2] - plat_specifier = ".%s-%s" % (self.plat_name, target_version) + plat_specifier = ".{}-{}".format(self.plat_name, target_version) build = self.get_finalized_command('build') build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier) @@ -286,7 +286,7 @@ def run(self): # noqa: C901 # in Add-Remove-Programs (APR) fullname = self.distribution.get_fullname() if self.target_version: - product_name = "Python %s %s" % (self.target_version, fullname) + product_name = "Python {} {}".format(self.target_version, fullname) else: product_name = "Python %s" % (fullname) self.db = msilib.init_database( @@ -347,7 +347,7 @@ def add_files(self): # noqa: C901 for file in os.listdir(dir.absolute): afile = os.path.join(dir.absolute, file) if os.path.isdir(afile): - short = "%s|%s" % (dir.make_short(file), file) + short = "{}|{}".format(dir.make_short(file), file) default = file + version newdir = Directory(db, cab, dir, file, default, short) todo.append(newdir) @@ -1103,12 +1103,12 @@ def add_ui(self): def get_installer_filename(self, fullname): # Factored out to allow overriding in subclasses if self.target_version: - base_name = "%s.%s-py%s.msi" % ( + base_name = "{}.{}-py{}.msi".format( fullname, self.plat_name, self.target_version, ) else: - base_name = "%s.%s.msi" % (fullname, self.plat_name) + base_name = "{}.{}.msi".format(fullname, self.plat_name) installer_name = os.path.join(self.dist_dir, base_name) return installer_name diff --git a/distutils/command/bdist_rpm.py b/distutils/command/bdist_rpm.py index fcfd7cd8fe..6a50ef34ea 100644 --- a/distutils/command/bdist_rpm.py +++ b/distutils/command/bdist_rpm.py @@ -353,7 +353,7 @@ def run(self): # noqa: C901 nvr_string = "%{name}-%{version}-%{release}" src_rpm = nvr_string + ".src.rpm" non_src_rpm = "%{arch}/" + nvr_string + ".%{arch}.rpm" - q_cmd = r"rpm -q --qf '%s %s\n' --specfile '%s'" % ( + q_cmd = r"rpm -q --qf '{} {}\n' --specfile '{}'".format( src_rpm, non_src_rpm, spec_path, @@ -488,9 +488,9 @@ def _make_spec_file(self): # noqa: C901 ): val = getattr(self, field.lower()) if isinstance(val, list): - spec_file.append('%s: %s' % (field, ' '.join(val))) + spec_file.append('{}: {}'.format(field, ' '.join(val))) elif val is not None: - spec_file.append('%s: %s' % (field, val)) + spec_file.append('{}: {}'.format(field, val)) if self.distribution.get_url(): spec_file.append('Url: ' + self.distribution.get_url()) @@ -527,7 +527,7 @@ def _make_spec_file(self): # noqa: C901 # rpm scripts # figure out default build script - def_setup_call = "%s %s" % (self.python, os.path.basename(sys.argv[0])) + def_setup_call = "{} {}".format(self.python, os.path.basename(sys.argv[0])) def_build = "%s build" % def_setup_call if self.use_rpm_opt_flags: def_build = 'env CFLAGS="$RPM_OPT_FLAGS" ' + def_build diff --git a/distutils/command/bdist_wininst.py b/distutils/command/bdist_wininst.py index 7e9a64a5bc..02bd7200c5 100644 --- a/distutils/command/bdist_wininst.py +++ b/distutils/command/bdist_wininst.py @@ -185,7 +185,7 @@ def run(self): if not target_version: assert self.skip_build, "Should have already checked this" target_version = '%d.%d' % sys.version_info[:2] - plat_specifier = ".%s-%s" % (self.plat_name, target_version) + plat_specifier = ".{}-{}".format(self.plat_name, target_version) build = self.get_finalized_command('build') build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier) @@ -259,8 +259,8 @@ def escape(s): ]: data = getattr(metadata, name, "") if data: - info = info + ("\n %s: %s" % (name.capitalize(), escape(data))) - lines.append("%s=%s" % (name, escape(data))) + info = info + ("\n {}: {}".format(name.capitalize(), escape(data))) + lines.append("{}={}".format(name, escape(data))) # The [setup] section contains entries controlling # the installer runtime. @@ -280,7 +280,7 @@ def escape(s): import time import distutils - build_info = "Built %s with distutils-%s" % ( + build_info = "Built {} with distutils-{}".format( time.ctime(time.time()), distutils.__version__, ) @@ -319,7 +319,7 @@ def create_exe(self, arcname, fullname, bitmap=None): # We need to normalize newlines, so we open in text mode and # convert back to bytes. "latin-1" simply avoids any possible # failures. - with open(self.pre_install_script, "r", encoding="latin-1") as script: + with open(self.pre_install_script, encoding="latin-1") as script: script_data = script.read().encode("latin-1") cfgdata = cfgdata + script_data + b"\n\0" else: @@ -349,11 +349,11 @@ def get_installer_filename(self, fullname): # it's better to include this in the name installer_name = os.path.join( self.dist_dir, - "%s.%s-py%s.exe" % (fullname, self.plat_name, self.target_version), + "{}.{}-py{}.exe".format(fullname, self.plat_name, self.target_version), ) else: installer_name = os.path.join( - self.dist_dir, "%s.%s.exe" % (fullname, self.plat_name) + self.dist_dir, "{}.{}.exe".format(fullname, self.plat_name) ) return installer_name @@ -410,7 +410,7 @@ def get_exe_bytes(self): # noqa: C901 else: sfix = '' - filename = os.path.join(directory, "wininst-%s%s.exe" % (bv, sfix)) + filename = os.path.join(directory, "wininst-{}{}.exe".format(bv, sfix)) f = open(filename, "rb") try: return f.read() diff --git a/distutils/command/build.py b/distutils/command/build.py index e4b064250c..6d453419d0 100644 --- a/distutils/command/build.py +++ b/distutils/command/build.py @@ -79,7 +79,7 @@ def finalize_options(self): # noqa: C901 "using './configure --help' on your platform)" ) - plat_specifier = ".%s-%s" % (self.plat_name, sys.implementation.cache_tag) + plat_specifier = ".{}-{}".format(self.plat_name, sys.implementation.cache_tag) # Make it so Python 2.x and Python 2.x with --with-pydebug don't # share the same build directories. Doing so confuses the build diff --git a/distutils/command/build_ext.py b/distutils/command/build_ext.py index 153a0b6dc1..3c6cee7e36 100644 --- a/distutils/command/build_ext.py +++ b/distutils/command/build_ext.py @@ -498,7 +498,7 @@ def _filter_build_errors(self, ext): except (CCompilerError, DistutilsError, CompileError) as e: if not ext.optional: raise - self.warn('building extension "%s" failed: %s' % (ext.name, e)) + self.warn('building extension "{}" failed: {}'.format(ext.name, e)) def build_extension(self, ext): sources = ext.sources diff --git a/distutils/command/check.py b/distutils/command/check.py index 9c3523a858..aaf30713fe 100644 --- a/distutils/command/check.py +++ b/distutils/command/check.py @@ -117,7 +117,7 @@ def check_restructuredtext(self): if line is None: warning = warning[1] else: - warning = '%s (line %s)' % (warning[1], line) + warning = '{} (line {})'.format(warning[1], line) self.warn(warning) def _check_rst_data(self, data): diff --git a/distutils/command/register.py b/distutils/command/register.py index d2351ab8bf..2c6424725d 100644 --- a/distutils/command/register.py +++ b/distutils/command/register.py @@ -174,7 +174,7 @@ def send_metadata(self): # noqa: C901 auth.add_password(self.realm, host, username, password) # send the info to the server and report the result code, result = self.post_to_server(self.build_post_data('submit'), auth) - self.announce('Server response (%s): %s' % (code, result), log.INFO) + self.announce('Server response ({}): {}'.format(code, result), log.INFO) # possibly save the login if code == 200: @@ -224,7 +224,7 @@ def send_metadata(self): # noqa: C901 log.info('Server response (%s): %s', code, result) else: log.info('You will receive an email shortly.') - log.info(('Follow the instructions in it to ' 'complete registration.')) + log.info('Follow the instructions in it to ' 'complete registration.') elif choice == '3': data = {':action': 'password_reset'} data['email'] = '' @@ -265,7 +265,7 @@ def post_to_server(self, data, auth=None): # noqa: C901 '''Post a query to the server, and return a string response.''' if 'name' in data: self.announce( - 'Registering %s to %s' % (data['name'], self.repository), log.INFO + 'Registering {} to {}'.format(data['name'], self.repository), log.INFO ) # Build up the MIME payload for the urllib2 POST data boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254' diff --git a/distutils/command/sdist.py b/distutils/command/sdist.py index ec3c97ac72..d6e9489d1b 100644 --- a/distutils/command/sdist.py +++ b/distutils/command/sdist.py @@ -402,7 +402,7 @@ def prune_file_list(self): seps = '/' vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr', '_darcs'] - vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps) + vcs_ptrn = r'(^|{})({})({}).*'.format(seps, '|'.join(vcs_dirs), seps) self.filelist.exclude_pattern(vcs_ptrn, is_regex=1) def write_manifest(self): diff --git a/distutils/command/upload.py b/distutils/command/upload.py index f2a8118e32..6af5394339 100644 --- a/distutils/command/upload.py +++ b/distutils/command/upload.py @@ -170,7 +170,7 @@ def upload_file(self, command, pyversion, filename): # noqa: C901 body.write(end_boundary) body = body.getvalue() - msg = "Submitting %s to %s" % (filename, self.repository) + msg = "Submitting {} to {}".format(filename, self.repository) self.announce(msg, log.INFO) # build the Request @@ -194,12 +194,12 @@ def upload_file(self, command, pyversion, filename): # noqa: C901 raise if status == 200: - self.announce('Server response (%s): %s' % (status, reason), log.INFO) + self.announce('Server response ({}): {}'.format(status, reason), log.INFO) if self.show_response: text = self._read_pypi_response(result) msg = '\n'.join(('-' * 75, text, '-' * 75)) self.announce(msg, log.INFO) else: - msg = 'Upload failed (%s): %s' % (status, reason) + msg = 'Upload failed ({}): {}'.format(status, reason) self.announce(msg, log.ERROR) raise DistutilsError(msg) diff --git a/distutils/core.py b/distutils/core.py index 333596acc7..de13978f02 100644 --- a/distutils/core.py +++ b/distutils/core.py @@ -149,7 +149,7 @@ class found in 'cmdclass' is used in place of the default, which is if 'name' not in attrs: raise SystemExit("error in setup command: %s" % msg) else: - raise SystemExit("error in %s setup command: %s" % (attrs['name'], msg)) + raise SystemExit("error in {} setup command: {}".format(attrs['name'], msg)) if _setup_stop_after == "init": return dist @@ -203,10 +203,10 @@ def run_commands(dist): raise SystemExit("interrupted") except OSError as exc: if DEBUG: - sys.stderr.write("error: %s\n" % (exc,)) + sys.stderr.write("error: {}\n".format(exc)) raise else: - raise SystemExit("error: %s" % (exc,)) + raise SystemExit("error: {}".format(exc)) except (DistutilsError, CCompilerError) as msg: if DEBUG: @@ -249,7 +249,7 @@ def run_setup(script_name, script_args=None, stop_after="run"): used to drive the Distutils. """ if stop_after not in ('init', 'config', 'commandline', 'run'): - raise ValueError("invalid value for 'stop_after': %r" % (stop_after,)) + raise ValueError("invalid value for 'stop_after': {!r}".format(stop_after)) global _setup_stop_after, _setup_distribution _setup_stop_after = stop_after diff --git a/distutils/cygwinccompiler.py b/distutils/cygwinccompiler.py index e376446f1b..28c60089cb 100644 --- a/distutils/cygwinccompiler.py +++ b/distutils/cygwinccompiler.py @@ -125,7 +125,7 @@ def __init__(self, verbose=0, dry_run=0, force=0): super().__init__(verbose, dry_run, force) status, details = check_config_h() - self.debug_print("Python's GCC status: %s (details: %s)" % (status, details)) + self.debug_print("Python's GCC status: {} (details: {})".format(status, details)) if status is not CONFIG_H_OK: self.warn( "Python's pyconfig.h doesn't seem to support your compiler. " @@ -144,7 +144,7 @@ def __init__(self, verbose=0, dry_run=0, force=0): compiler_so='%s -mcygwin -mdll -O -Wall' % self.cc, compiler_cxx='%s -mcygwin -O -Wall' % self.cxx, linker_exe='%s -mcygwin' % self.cc, - linker_so=('%s -mcygwin %s' % (self.linker_dll, shared_option)), + linker_so=('{} -mcygwin {}'.format(self.linker_dll, shared_option)), ) # Include the appropriate MSVC runtime library if Python was built @@ -291,7 +291,7 @@ def object_filenames(self, source_filenames, strip_dir=0, output_dir=''): base, ext = os.path.splitext(os.path.normcase(src_name)) if ext not in (self.src_extensions + ['.rc', '.res']): raise UnknownFileError( - "unknown file type '%s' (from '%s')" % (ext, src_name) + "unknown file type '{}' (from '{}')".format(ext, src_name) ) if strip_dir: base = os.path.basename(base) @@ -325,7 +325,7 @@ def __init__(self, verbose=0, dry_run=0, force=0): compiler_so='%s -mdll -O -Wall' % self.cc, compiler_cxx='%s -O -Wall' % self.cxx, linker_exe='%s' % self.cc, - linker_so='%s %s' % (self.linker_dll, shared_option), + linker_so='{} {}'.format(self.linker_dll, shared_option), ) # Maybe we should also append -mthreads, but then the finished @@ -396,7 +396,7 @@ def check_config_h(): finally: config_h.close() except OSError as exc: - return (CONFIG_H_UNCERTAIN, "couldn't read '%s': %s" % (fn, exc.strerror)) + return (CONFIG_H_UNCERTAIN, "couldn't read '{}': {}".format(fn, exc.strerror)) def is_cygwincc(cc): diff --git a/distutils/dir_util.py b/distutils/dir_util.py index 7a132e3144..6f0bb8ad76 100644 --- a/distutils/dir_util.py +++ b/distutils/dir_util.py @@ -34,7 +34,7 @@ def mkpath(name, mode=0o777, verbose=1, dry_run=0): # noqa: C901 # Detect a common bug -- name is None if not isinstance(name, str): raise DistutilsInternalError( - "mkpath: 'name' must be a string (got %r)" % (name,) + "mkpath: 'name' must be a string (got {!r})".format(name) ) # XXX what's the better way to handle verbosity? print as we create @@ -76,7 +76,7 @@ def mkpath(name, mode=0o777, verbose=1, dry_run=0): # noqa: C901 except OSError as exc: if not (exc.errno == errno.EEXIST and os.path.isdir(head)): raise DistutilsFileError( - "could not create '%s': %s" % (head, exc.args[-1]) + "could not create '{}': {}".format(head, exc.args[-1]) ) created_dirs.append(head) @@ -144,7 +144,7 @@ def copy_tree( # noqa: C901 names = [] else: raise DistutilsFileError( - "error listing files in '%s': %s" % (src, e.strerror) + "error listing files in '{}': {}".format(src, e.strerror) ) if not dry_run: diff --git a/distutils/dist.py b/distutils/dist.py index b4535eb75e..0406ab19cb 100644 --- a/distutils/dist.py +++ b/distutils/dist.py @@ -825,7 +825,7 @@ def get_command_class(self, command): return klass for pkgname in self.get_command_packages(): - module_name = "%s.%s" % (pkgname, command) + module_name = "{}.{}".format(pkgname, command) klass_name = command try: @@ -893,7 +893,7 @@ def _set_command_options(self, command_obj, option_dict=None): # noqa: C901 self.announce(" setting options for '%s' command:" % command_name) for (option, (source, value)) in option_dict.items(): if DEBUG: - self.announce(" %s = %s (from %s)" % (option, value, source)) + self.announce(" {} = {} (from {})".format(option, value, source)) try: bool_opts = [translate_longopt(o) for o in command_obj.boolean_options] except AttributeError: @@ -1159,7 +1159,7 @@ def write_pkg_file(self, file): def maybe_write(header, val): if val: - file.write("{}: {}\n".format(header, val)) + file.write(f"{header}: {val}\n") # optional fields maybe_write("Summary", self.get_description()) @@ -1182,7 +1182,7 @@ def maybe_write(header, val): def _write_list(self, file, name, values): values = values or [] for value in values: - file.write('%s: %s\n' % (name, value)) + file.write('{}: {}\n'.format(name, value)) # -- Metadata query methods ---------------------------------------- @@ -1193,7 +1193,7 @@ def get_version(self): return self.version or "0.0.0" def get_fullname(self): - return "%s-%s" % (self.get_name(), self.get_version()) + return "{}-{}".format(self.get_name(), self.get_version()) def get_author(self): return self.author diff --git a/distutils/extension.py b/distutils/extension.py index dff2be9edf..6b8575de29 100644 --- a/distutils/extension.py +++ b/distutils/extension.py @@ -134,7 +134,7 @@ def __init__( warnings.warn(msg) def __repr__(self): - return '<%s.%s(%r) at %#x>' % ( + return '<{}.{}({!r}) at {:#x}>'.format( self.__class__.__module__, self.__class__.__qualname__, self.name, diff --git a/distutils/fancy_getopt.py b/distutils/fancy_getopt.py index 9ee06420de..830f047e28 100644 --- a/distutils/fancy_getopt.py +++ b/distutils/fancy_getopt.py @@ -22,7 +22,7 @@ longopt_re = re.compile(r'^%s$' % longopt_pat) # For recognizing "negative alias" options, eg. "quiet=!verbose" -neg_alias_re = re.compile("^(%s)=!(%s)$" % (longopt_pat, longopt_pat)) +neg_alias_re = re.compile("^({})=!({})$".format(longopt_pat, longopt_pat)) # This is used to translate long options to legitimate Python identifiers # (for use as attributes of some object). @@ -157,7 +157,7 @@ def _grok_option_table(self): # noqa: C901 else: # the option table is part of the code, so simply # assert that it is correct - raise ValueError("invalid option tuple: %r" % (option,)) + raise ValueError("invalid option tuple: {!r}".format(option)) # Type- and value-check the option names if not isinstance(long, str) or len(long) < 2: @@ -359,7 +359,7 @@ def generate_help(self, header=None): # noqa: C901 # Case 2: we have a short option, so we have to include it # just after the long option else: - opt_names = "%s (-%s)" % (long, short) + opt_names = "{} (-{})".format(long, short) if text: lines.append(" --%-*s %s" % (max_opt, opt_names, text[0])) else: diff --git a/distutils/file_util.py b/distutils/file_util.py index 0662fe40f3..1ffe52dac2 100644 --- a/distutils/file_util.py +++ b/distutils/file_util.py @@ -26,27 +26,27 @@ def _copy_file_contents(src, dst, buffer_size=16 * 1024): # noqa: C901 try: fsrc = open(src, 'rb') except OSError as e: - raise DistutilsFileError("could not open '%s': %s" % (src, e.strerror)) + raise DistutilsFileError("could not open '{}': {}".format(src, e.strerror)) if os.path.exists(dst): try: os.unlink(dst) except OSError as e: raise DistutilsFileError( - "could not delete '%s': %s" % (dst, e.strerror) + "could not delete '{}': {}".format(dst, e.strerror) ) try: fdst = open(dst, 'wb') except OSError as e: - raise DistutilsFileError("could not create '%s': %s" % (dst, e.strerror)) + raise DistutilsFileError("could not create '{}': {}".format(dst, e.strerror)) while True: try: buf = fsrc.read(buffer_size) except OSError as e: raise DistutilsFileError( - "could not read from '%s': %s" % (src, e.strerror) + "could not read from '{}': {}".format(src, e.strerror) ) if not buf: @@ -56,7 +56,7 @@ def _copy_file_contents(src, dst, buffer_size=16 * 1024): # noqa: C901 fdst.write(buf) except OSError as e: raise DistutilsFileError( - "could not write to '%s': %s" % (dst, e.strerror) + "could not write to '{}': {}".format(dst, e.strerror) ) finally: if fdst: @@ -198,12 +198,12 @@ def move_file(src, dst, verbose=1, dry_run=0): # noqa: C901 dst = os.path.join(dst, basename(src)) elif exists(dst): raise DistutilsFileError( - "can't move '%s': destination '%s' already exists" % (src, dst) + "can't move '{}': destination '{}' already exists".format(src, dst) ) if not isdir(dirname(dst)): raise DistutilsFileError( - "can't move '%s': destination '%s' not a valid path" % (src, dst) + "can't move '{}': destination '{}' not a valid path".format(src, dst) ) copy_it = False @@ -214,7 +214,7 @@ def move_file(src, dst, verbose=1, dry_run=0): # noqa: C901 if num == errno.EXDEV: copy_it = True else: - raise DistutilsFileError("couldn't move '%s' to '%s': %s" % (src, dst, msg)) + raise DistutilsFileError("couldn't move '{}' to '{}': {}".format(src, dst, msg)) if copy_it: copy_file(src, dst, verbose=verbose) diff --git a/distutils/filelist.py b/distutils/filelist.py index 4396d9dee5..987931a988 100644 --- a/distutils/filelist.py +++ b/distutils/filelist.py @@ -159,7 +159,7 @@ def process_template_line(self, line): # noqa: C901 ) elif action == 'recursive-include': - self.debug_print("recursive-include %s %s" % (dir, ' '.join(patterns))) + self.debug_print("recursive-include {} {}".format(dir, ' '.join(patterns))) for pattern in patterns: if not self.include_pattern(pattern, prefix=dir): msg = ( @@ -168,7 +168,7 @@ def process_template_line(self, line): # noqa: C901 log.warn(msg, pattern, dir) elif action == 'recursive-exclude': - self.debug_print("recursive-exclude %s %s" % (dir, ' '.join(patterns))) + self.debug_print("recursive-exclude {} {}".format(dir, ' '.join(patterns))) for pattern in patterns: if not self.exclude_pattern(pattern, prefix=dir): log.warn( @@ -363,9 +363,9 @@ def translate_pattern(pattern, anchor=1, prefix=None, is_regex=0): if os.sep == '\\': sep = r'\\' pattern_re = pattern_re[len(start) : len(pattern_re) - len(end)] - pattern_re = r'%s\A%s%s.*%s%s' % (start, prefix_re, sep, pattern_re, end) + pattern_re = r'{}\A{}{}.*{}{}'.format(start, prefix_re, sep, pattern_re, end) else: # no prefix -- respect anchor flag if anchor: - pattern_re = r'%s\A%s' % (start, pattern_re[len(start) :]) + pattern_re = r'{}\A{}'.format(start, pattern_re[len(start) :]) return re.compile(pattern_re) diff --git a/distutils/msvc9compiler.py b/distutils/msvc9compiler.py index 276e137916..160b6f2a3e 100644 --- a/distutils/msvc9compiler.py +++ b/distutils/msvc9compiler.py @@ -167,7 +167,7 @@ def load_macros(self, version): except RegError: continue key = RegEnumKey(h, 0) - d = Reg.get_value(base, r"%s\%s" % (p, key)) + d = Reg.get_value(base, r"{}\{}".format(p, key)) self.macros["$(FrameworkVersion)"] = d["version"] def sub(self, s): @@ -273,7 +273,7 @@ def query_vcvarsall(version, arch="x86"): raise DistutilsPlatformError("Unable to find vcvarsall.bat") log.debug("Calling 'vcvarsall.bat %s' (version=%s)", arch, version) popen = subprocess.Popen( - '"%s" %s & set' % (vcvarsall, arch), + '"{}" {} & set'.format(vcvarsall, arch), stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) @@ -362,7 +362,7 @@ def initialize(self, plat_name=None): # noqa: C901 # sanity check for platforms to prevent obscure errors later. ok_plats = 'win32', 'win-amd64' if plat_name not in ok_plats: - raise DistutilsPlatformError("--plat-name must be one of %s" % (ok_plats,)) + raise DistutilsPlatformError("--plat-name must be one of {}".format(ok_plats)) if ( "DISTUTILS_USE_SDK" in os.environ @@ -555,7 +555,7 @@ def compile( # noqa: C901 continue else: # how to handle this file? - raise CompileError("Don't know how to compile %s to %s" % (src, obj)) + raise CompileError("Don't know how to compile {} to {}".format(src, obj)) output_opt = "/Fo" + obj try: @@ -678,7 +678,7 @@ def link( # noqa: C901 mfinfo = self.manifest_get_embed_info(target_desc, ld_args) if mfinfo is not None: mffilename, mfid = mfinfo - out_arg = '-outputresource:%s;%s' % (output_filename, mfid) + out_arg = '-outputresource:{};{}'.format(output_filename, mfid) try: self.spawn(['mt.exe', '-nologo', '-manifest', mffilename, out_arg]) except DistutilsExecError as msg: diff --git a/distutils/msvccompiler.py b/distutils/msvccompiler.py index 8e509ac50c..f45b93ea43 100644 --- a/distutils/msvccompiler.py +++ b/distutils/msvccompiler.py @@ -150,7 +150,7 @@ def load_macros(self, version): except RegError: continue key = RegEnumKey(h, 0) - d = read_values(base, r"%s\%s" % (p, key)) + d = read_values(base, r"{}\{}".format(p, key)) self.macros["$(FrameworkVersion)"] = d["version"] def sub(self, s): @@ -446,7 +446,7 @@ def compile( # noqa: C901 continue else: # how to handle this file? - raise CompileError("Don't know how to compile %s to %s" % (src, obj)) + raise CompileError("Don't know how to compile {} to {}".format(src, obj)) output_opt = "/Fo" + obj try: @@ -629,7 +629,7 @@ def get_msvc_paths(self, path, platform='x86'): path = path + " dirs" if self.__version >= 7: - key = r"%s\%0.1f\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories" % ( + key = r"{}\{:0.1f}\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories".format( self.__root, self.__version, ) diff --git a/distutils/py38compat.py b/distutils/py38compat.py index e556b69ee9..59224e71e5 100644 --- a/distutils/py38compat.py +++ b/distutils/py38compat.py @@ -5,4 +5,4 @@ def aix_platform(osname, version, release): return _aix_support.aix_platform() except ImportError: pass - return "%s-%s.%s" % (osname, version, release) + return "{}-{}.{}".format(osname, version, release) diff --git a/distutils/spawn.py b/distutils/spawn.py index db9f08ee6b..02d5c879dc 100644 --- a/distutils/spawn.py +++ b/distutils/spawn.py @@ -60,13 +60,13 @@ def spawn(cmd, search_path=1, verbose=0, dry_run=0, env=None): # noqa: C901 except OSError as exc: if not DEBUG: cmd = cmd[0] - raise DistutilsExecError("command %r failed: %s" % (cmd, exc.args[-1])) from exc + raise DistutilsExecError("command {!r} failed: {}".format(cmd, exc.args[-1])) from exc if exitcode: if not DEBUG: cmd = cmd[0] raise DistutilsExecError( - "command %r failed with exit code %s" % (cmd, exitcode) + "command {!r} failed with exit code {}".format(cmd, exitcode) ) diff --git a/distutils/tests/support.py b/distutils/tests/support.py index 2e9d66b7cf..d81da1b492 100644 --- a/distutils/tests/support.py +++ b/distutils/tests/support.py @@ -13,7 +13,7 @@ from distutils.core import Distribution -class LoggingSilencer(object): +class LoggingSilencer: def setUp(self): super().setUp() self.threshold = log.set_threshold(log.FATAL) @@ -43,7 +43,7 @@ def clear_logs(self): self.logs = [] -class TempdirManager(object): +class TempdirManager: """Mix-in class that handles temporary directories for test cases. This is intended to be used with unittest.TestCase. diff --git a/distutils/tests/test_archive_util.py b/distutils/tests/test_archive_util.py index 7a324c4588..b653cf2155 100644 --- a/distutils/tests/test_archive_util.py +++ b/distutils/tests/test_archive_util.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """Tests for distutils.archive_util.""" import unittest import os diff --git a/distutils/tests/test_bdist_dumb.py b/distutils/tests/test_bdist_dumb.py index 7c4d5964ca..5fe7d1392a 100644 --- a/distutils/tests/test_bdist_dumb.py +++ b/distutils/tests/test_bdist_dumb.py @@ -28,7 +28,7 @@ class BuildDumbTestCase( unittest.TestCase, ): def setUp(self): - super(BuildDumbTestCase, self).setUp() + super().setUp() self.old_location = os.getcwd() self.old_sys_argv = sys.argv, sys.argv[:] @@ -36,7 +36,7 @@ def tearDown(self): os.chdir(self.old_location) sys.argv = self.old_sys_argv[0] sys.argv[:] = self.old_sys_argv[1] - super(BuildDumbTestCase, self).tearDown() + super().tearDown() @pytest.mark.usefixtures('needs_zlib') def test_simple_built(self): @@ -75,7 +75,7 @@ def test_simple_built(self): # see what we have dist_created = os.listdir(os.path.join(pkg_dir, 'dist')) - base = "%s.%s.zip" % (dist.get_fullname(), cmd.plat_name) + base = "{}.{}.zip".format(dist.get_fullname(), cmd.plat_name) self.assertEqual(dist_created, [base]) diff --git a/distutils/tests/test_bdist_rpm.py b/distutils/tests/test_bdist_rpm.py index ba809392b0..893ac7677f 100644 --- a/distutils/tests/test_bdist_rpm.py +++ b/distutils/tests/test_bdist_rpm.py @@ -36,7 +36,7 @@ def setUp(self): except UnicodeEncodeError: raise unittest.SkipTest("sys.executable is not encodable to UTF-8") - super(BuildRpmTestCase, self).setUp() + super().setUp() self.old_location = os.getcwd() self.old_sys_argv = sys.argv, sys.argv[:] @@ -44,7 +44,7 @@ def tearDown(self): os.chdir(self.old_location) sys.argv = self.old_sys_argv[0] sys.argv[:] = self.old_sys_argv[1] - super(BuildRpmTestCase, self).tearDown() + super().tearDown() # XXX I am unable yet to make this test work without # spurious sdtout/stderr output under Mac OS X diff --git a/distutils/tests/test_build.py b/distutils/tests/test_build.py index 712b0d5329..9233a3e0a5 100644 --- a/distutils/tests/test_build.py +++ b/distutils/tests/test_build.py @@ -24,7 +24,7 @@ def test_finalize_options(self): # build_platlib is 'build/lib.platform-cache_tag[-pydebug]' # examples: # build/lib.macosx-10.3-i386-cpython39 - plat_spec = '.%s-%s' % (cmd.plat_name, sys.implementation.cache_tag) + plat_spec = '.{}-{}'.format(cmd.plat_name, sys.implementation.cache_tag) if hasattr(sys, 'gettotalrefcount'): self.assertTrue(cmd.build_platlib.endswith('-pydebug')) plat_spec += '-pydebug' diff --git a/distutils/tests/test_build_ext.py b/distutils/tests/test_build_ext.py index 39d7920a5d..d1865b7187 100644 --- a/distutils/tests/test_build_ext.py +++ b/distutils/tests/test_build_ext.py @@ -33,7 +33,7 @@ class BuildExtTestCase(TempdirManager, LoggingSilencer, unittest.TestCase): def setUp(self): # Create a simple test environment - super(BuildExtTestCase, self).setUp() + super().setUp() self.tmp_dir = self.mkdtemp() import site @@ -57,7 +57,7 @@ def tearDown(self): from distutils.command import build_ext build_ext.USER_BASE = self.old_user_base - super(BuildExtTestCase, self).tearDown() + super().tearDown() def build_ext(self, *args, **kwargs): return build_ext(*args, **kwargs) @@ -93,7 +93,7 @@ def test_build_ext(self): ALREADY_TESTED = type(self).__name__ code = textwrap.dedent( - """ + f""" tmp_dir = {self.tmp_dir!r} import sys @@ -119,9 +119,7 @@ def test_xx(self): unittest.main() - """.format( - **locals() - ) + """ ) assert_python_ok('-c', code) @@ -531,7 +529,7 @@ def _try_compile_deployment_target(self, operator, target): deptarget_ext = Extension( 'deptarget', [deptarget_c], - extra_compile_args=['-DTARGET=%s' % (target,)], + extra_compile_args=['-DTARGET={}'.format(target)], ) dist = Distribution({'name': 'deptarget', 'ext_modules': [deptarget_ext]}) dist.package_dir = self.tmp_dir diff --git a/distutils/tests/test_build_py.py b/distutils/tests/test_build_py.py index 4a8582e4b7..4e833b1604 100644 --- a/distutils/tests/test_build_py.py +++ b/distutils/tests/test_build_py.py @@ -118,7 +118,7 @@ def test_byte_compile_optimized(self): found = os.listdir(cmd.build_lib) self.assertEqual(sorted(found), ['__pycache__', 'boiledeggs.py']) found = os.listdir(os.path.join(cmd.build_lib, '__pycache__')) - expect = 'boiledeggs.{}.opt-1.pyc'.format(sys.implementation.cache_tag) + expect = f'boiledeggs.{sys.implementation.cache_tag}.opt-1.pyc' self.assertEqual(sorted(found), [expect]) def test_dir_in_package_data(self): diff --git a/distutils/tests/test_config.py b/distutils/tests/test_config.py index 5bca4da83a..c841db163f 100644 --- a/distutils/tests/test_config.py +++ b/distutils/tests/test_config.py @@ -59,7 +59,7 @@ class BasePyPIRCCommandTestCase( ): def setUp(self): """Patches the environment.""" - super(BasePyPIRCCommandTestCase, self).setUp() + super().setUp() self.tmp_dir = self.mkdtemp() os.environ['HOME'] = self.tmp_dir os.environ['USERPROFILE'] = self.tmp_dir @@ -81,7 +81,7 @@ def initialize_options(self): def tearDown(self): """Removes the patch.""" set_threshold(self.old_threshold) - super(BasePyPIRCCommandTestCase, self).tearDown() + super().tearDown() class PyPIRCCommandTestCase(BasePyPIRCCommandTestCase): diff --git a/distutils/tests/test_config_cmd.py b/distutils/tests/test_config_cmd.py index 3c0879b59f..90b168d83b 100644 --- a/distutils/tests/test_config_cmd.py +++ b/distutils/tests/test_config_cmd.py @@ -17,14 +17,14 @@ def _info(self, msg, *args): self._logs.append(line) def setUp(self): - super(ConfigTestCase, self).setUp() + super().setUp() self._logs = [] self.old_log = log.info log.info = self._info def tearDown(self): log.info = self.old_log - super(ConfigTestCase, self).tearDown() + super().tearDown() def test_dump_file(self): this_file = os.path.splitext(__file__)[0] + '.py' diff --git a/distutils/tests/test_core.py b/distutils/tests/test_core.py index c3943866b9..b4cbdc9717 100644 --- a/distutils/tests/test_core.py +++ b/distutils/tests/test_core.py @@ -62,7 +62,7 @@ def main(): @pytest.mark.usefixtures('save_env') class CoreTestCase(unittest.TestCase): def setUp(self): - super(CoreTestCase, self).setUp() + super().setUp() self.old_stdout = sys.stdout self.cleanup_testfn() self.old_argv = sys.argv, sys.argv[:] @@ -73,7 +73,7 @@ def tearDown(self): self.cleanup_testfn() sys.argv = self.old_argv[0] sys.argv[:] = self.old_argv[1] - super(CoreTestCase, self).tearDown() + super().tearDown() def cleanup_testfn(self): path = os_helper.TESTFN diff --git a/distutils/tests/test_cygwinccompiler.py b/distutils/tests/test_cygwinccompiler.py index da73adc65a..8a55825235 100644 --- a/distutils/tests/test_cygwinccompiler.py +++ b/distutils/tests/test_cygwinccompiler.py @@ -15,7 +15,7 @@ class CygwinCCompilerTestCase(support.TempdirManager, unittest.TestCase): def setUp(self): - super(CygwinCCompilerTestCase, self).setUp() + super().setUp() self.version = sys.version self.python_h = os.path.join(self.mkdtemp(), 'python.h') from distutils import sysconfig @@ -28,7 +28,7 @@ def tearDown(self): from distutils import sysconfig sysconfig.get_config_h_filename = self.old_get_config_h_filename - super(CygwinCCompilerTestCase, self).tearDown() + super().tearDown() def _get_config_h_filename(self): return self.python_h @@ -45,7 +45,7 @@ def test_find_library_file(self): linkable_file = compiler.find_library_file(["/usr/lib"], link_name) self.assertIsNotNone(linkable_file) self.assertTrue(os.path.exists(linkable_file)) - self.assertEquals(linkable_file, "/usr/lib/lib{:s}.dll.a".format(link_name)) + self.assertEqual(linkable_file, f"/usr/lib/lib{link_name:s}.dll.a") @unittest.skipIf(sys.platform != "cygwin", "Not running on Cygwin") def test_runtime_library_dir_option(self): diff --git a/distutils/tests/test_dir_util.py b/distutils/tests/test_dir_util.py index 8231df695c..a9ebaeea29 100644 --- a/distutils/tests/test_dir_util.py +++ b/distutils/tests/test_dir_util.py @@ -26,7 +26,7 @@ def _log(self, msg, *args): self._logs.append(msg) def setUp(self): - super(DirUtilTestCase, self).setUp() + super().setUp() self._logs = [] tmp_dir = self.mkdtemp() self.root_target = os.path.join(tmp_dir, 'deep') @@ -37,7 +37,7 @@ def setUp(self): def tearDown(self): log.info = self.old_log - super(DirUtilTestCase, self).tearDown() + super().tearDown() def test_mkpath_remove_tree_verbosity(self): @@ -94,7 +94,7 @@ def test_copy_tree_verbosity(self): with open(a_file, 'w') as f: f.write('some content') - wanted = ['copying %s -> %s' % (a_file, self.target2)] + wanted = ['copying {} -> {}'.format(a_file, self.target2)] copy_tree(self.target, self.target2, verbose=1) self.assertEqual(self._logs, wanted) diff --git a/distutils/tests/test_dist.py b/distutils/tests/test_dist.py index 59d165a44e..92a42fb2d3 100644 --- a/distutils/tests/test_dist.py +++ b/distutils/tests/test_dist.py @@ -49,14 +49,14 @@ class DistributionTestCase( unittest.TestCase, ): def setUp(self): - super(DistributionTestCase, self).setUp() + super().setUp() self.argv = sys.argv, sys.argv[:] del sys.argv[1:] def tearDown(self): sys.argv = self.argv[0] sys.argv[:] = self.argv[1] - super(DistributionTestCase, self).tearDown() + super().tearDown() def create_distribution(self, configfiles=()): d = TestDistribution() @@ -275,13 +275,13 @@ def _expander(path): @pytest.mark.usefixtures('save_env') class MetadataTestCase(support.TempdirManager, unittest.TestCase): def setUp(self): - super(MetadataTestCase, self).setUp() + super().setUp() self.argv = sys.argv, sys.argv[:] def tearDown(self): sys.argv = self.argv[0] sys.argv[:] = self.argv[1] - super(MetadataTestCase, self).tearDown() + super().tearDown() def format_metadata(self, dist): sio = io.StringIO() @@ -503,7 +503,7 @@ def test_custom_pydistutils(self): os.environ['USERPROFILE'] = temp_dir files = dist.find_config_files() self.assertIn( - user_filename, files, '%r not found in %r' % (user_filename, files) + user_filename, files, '{!r} not found in {!r}'.format(user_filename, files) ) finally: os.remove(user_filename) diff --git a/distutils/tests/test_file_util.py b/distutils/tests/test_file_util.py index 6b333d5ea9..8bd573056d 100644 --- a/distutils/tests/test_file_util.py +++ b/distutils/tests/test_file_util.py @@ -19,7 +19,7 @@ def _log(self, msg, *args): self._logs.append(msg) def setUp(self): - super(FileUtilTestCase, self).setUp() + super().setUp() self._logs = [] self.old_log = log.info log.info = self._log @@ -30,7 +30,7 @@ def setUp(self): def tearDown(self): log.info = self.old_log - super(FileUtilTestCase, self).tearDown() + super().tearDown() def test_move_file_verbosity(self): f = open(self.source, 'w') @@ -47,7 +47,7 @@ def test_move_file_verbosity(self): move_file(self.target, self.source, verbose=0) move_file(self.source, self.target, verbose=1) - wanted = ['moving %s -> %s' % (self.source, self.target)] + wanted = ['moving {} -> {}'.format(self.source, self.target)] self.assertEqual(self._logs, wanted) # back to original state @@ -57,7 +57,7 @@ def test_move_file_verbosity(self): # now the target is a dir os.mkdir(self.target_dir) move_file(self.source, self.target_dir, verbose=1) - wanted = ['moving %s -> %s' % (self.source, self.target_dir)] + wanted = ['moving {} -> {}'.format(self.source, self.target_dir)] self.assertEqual(self._logs, wanted) def test_move_file_exception_unpacking_rename(self): @@ -95,7 +95,7 @@ def test_copy_file_hard_link(self): st3 = os.stat(self.target) self.assertTrue(os.path.samestat(st, st2), (st, st2)) self.assertTrue(os.path.samestat(st2, st3), (st2, st3)) - with open(self.source, 'r') as f: + with open(self.source) as f: self.assertEqual(f.read(), 'some content') def test_copy_file_hard_link_failure(self): @@ -112,5 +112,5 @@ def test_copy_file_hard_link_failure(self): self.assertTrue(os.path.samestat(st, st2), (st, st2)) self.assertFalse(os.path.samestat(st2, st3), (st2, st3)) for fn in (self.source, self.target): - with open(fn, 'r') as f: + with open(fn) as f: self.assertEqual(f.read(), 'some content') diff --git a/distutils/tests/test_register.py b/distutils/tests/test_register.py index 76fec68521..2b142ad590 100644 --- a/distutils/tests/test_register.py +++ b/distutils/tests/test_register.py @@ -41,7 +41,7 @@ """ -class Inputs(object): +class Inputs: """Fakes user inputs.""" def __init__(self, *answers): @@ -55,7 +55,7 @@ def __call__(self, prompt=''): self.index += 1 -class FakeOpener(object): +class FakeOpener: """Fakes a PyPI server""" def __init__(self): @@ -79,7 +79,7 @@ def getheader(self, name, default=None): class RegisterTestCase(BasePyPIRCCommandTestCase): def setUp(self): - super(RegisterTestCase, self).setUp() + super().setUp() # patching the password prompt self._old_getpass = getpass.getpass @@ -95,7 +95,7 @@ def tearDown(self): getpass.getpass = self._old_getpass urllib.request._opener = None urllib.request.build_opener = self.old_opener - super(RegisterTestCase, self).tearDown() + super().tearDown() def _get_cmd(self, metadata=None): if metadata is None: diff --git a/distutils/tests/test_sdist.py b/distutils/tests/test_sdist.py index f0ca829549..97d57dd042 100644 --- a/distutils/tests/test_sdist.py +++ b/distutils/tests/test_sdist.py @@ -49,7 +49,7 @@ class SDistTestCase(BasePyPIRCCommandTestCase): def setUp(self): # PyPIRCCommandTestCase creates a temp dir already # and put it in self.tmp_dir - super(SDistTestCase, self).setUp() + super().setUp() # setting up an environment self.old_path = os.getcwd() os.mkdir(join(self.tmp_dir, 'somecode')) @@ -63,7 +63,7 @@ def setUp(self): def tearDown(self): # back to normal os.chdir(self.old_path) - super(SDistTestCase, self).tearDown() + super().tearDown() def get_cmd(self, metadata=None): """Returns a cmd""" diff --git a/distutils/tests/test_sysconfig.py b/distutils/tests/test_sysconfig.py index 2d68b5a3de..b3ef26e467 100644 --- a/distutils/tests/test_sysconfig.py +++ b/distutils/tests/test_sysconfig.py @@ -22,14 +22,14 @@ @pytest.mark.usefixtures('save_env') class SysconfigTestCase(unittest.TestCase): def setUp(self): - super(SysconfigTestCase, self).setUp() + super().setUp() self.makefile = None def tearDown(self): if self.makefile is not None: os.unlink(self.makefile) self.cleanup_testfn() - super(SysconfigTestCase, self).tearDown() + super().tearDown() def cleanup_testfn(self): if os.path.isfile(TESTFN): diff --git a/distutils/tests/test_unixccompiler.py b/distutils/tests/test_unixccompiler.py index 3cd7c6caa7..204bb76dc0 100644 --- a/distutils/tests/test_unixccompiler.py +++ b/distutils/tests/test_unixccompiler.py @@ -74,7 +74,7 @@ def gcv(var): def do_darwin_test(syscfg_macosx_ver, env_macosx_ver, expected_flag): env = os.environ - msg = "macOS version = (sysconfig=%r, env=%r)" % ( + msg = "macOS version = (sysconfig={!r}, env={!r})".format( syscfg_macosx_ver, env_macosx_ver, ) diff --git a/distutils/tests/test_upload.py b/distutils/tests/test_upload.py index a1d373064c..4435eb1fda 100644 --- a/distutils/tests/test_upload.py +++ b/distutils/tests/test_upload.py @@ -42,7 +42,7 @@ """ -class FakeOpen(object): +class FakeOpen: def __init__(self, url, msg=None, code=None): self.url = url if not isinstance(url, str): @@ -66,7 +66,7 @@ def getcode(self): class uploadTestCase(BasePyPIRCCommandTestCase): def setUp(self): - super(uploadTestCase, self).setUp() + super().setUp() self.old_open = upload_mod.urlopen upload_mod.urlopen = self._urlopen self.last_open = None @@ -75,7 +75,7 @@ def setUp(self): def tearDown(self): upload_mod.urlopen = self.old_open - super(uploadTestCase, self).tearDown() + super().tearDown() def _urlopen(self, url): self.last_open = FakeOpen(url, msg=self.next_msg, code=self.next_code) diff --git a/distutils/tests/test_util.py b/distutils/tests/test_util.py index 5a44f10a96..3c90b87f61 100644 --- a/distutils/tests/test_util.py +++ b/distutils/tests/test_util.py @@ -28,7 +28,7 @@ @pytest.mark.usefixtures('save_env') class UtilTestCase(unittest.TestCase): def setUp(self): - super(UtilTestCase, self).setUp() + super().setUp() # saving the environment self.name = os.name self.platform = sys.platform @@ -63,7 +63,7 @@ def tearDown(self): else: del os.uname sysconfig._config_vars = copy(self._config_vars) - super(UtilTestCase, self).tearDown() + super().tearDown() def _set_uname(self, uname): self._uname = uname diff --git a/distutils/tests/test_version.py b/distutils/tests/test_version.py index 3727bac87d..c3dfb598fc 100644 --- a/distutils/tests/test_version.py +++ b/distutils/tests/test_version.py @@ -52,17 +52,17 @@ def test_cmp_strict(self): ("cmp(%s, %s) " "shouldn't raise ValueError") % (v1, v2) ) self.assertEqual( - res, wanted, 'cmp(%s, %s) should be %s, got %s' % (v1, v2, wanted, res) + res, wanted, 'cmp({}, {}) should be {}, got {}'.format(v1, v2, wanted, res) ) res = StrictVersion(v1)._cmp(v2) self.assertEqual( - res, wanted, 'cmp(%s, %s) should be %s, got %s' % (v1, v2, wanted, res) + res, wanted, 'cmp({}, {}) should be {}, got {}'.format(v1, v2, wanted, res) ) res = StrictVersion(v1)._cmp(object()) self.assertIs( res, NotImplemented, - 'cmp(%s, %s) should be NotImplemented, got %s' % (v1, v2, res), + 'cmp({}, {}) should be NotImplemented, got {}'.format(v1, v2, res), ) def test_cmp(self): @@ -80,15 +80,15 @@ def test_cmp(self): for v1, v2, wanted in versions: res = LooseVersion(v1)._cmp(LooseVersion(v2)) self.assertEqual( - res, wanted, 'cmp(%s, %s) should be %s, got %s' % (v1, v2, wanted, res) + res, wanted, 'cmp({}, {}) should be {}, got {}'.format(v1, v2, wanted, res) ) res = LooseVersion(v1)._cmp(v2) self.assertEqual( - res, wanted, 'cmp(%s, %s) should be %s, got %s' % (v1, v2, wanted, res) + res, wanted, 'cmp({}, {}) should be {}, got {}'.format(v1, v2, wanted, res) ) res = LooseVersion(v1)._cmp(object()) self.assertIs( res, NotImplemented, - 'cmp(%s, %s) should be NotImplemented, got %s' % (v1, v2, res), + 'cmp({}, {}) should be NotImplemented, got {}'.format(v1, v2, res), ) diff --git a/distutils/text_file.py b/distutils/text_file.py index cffcd0994c..44c0f27f8b 100644 --- a/distutils/text_file.py +++ b/distutils/text_file.py @@ -116,7 +116,7 @@ def open(self, filename): """Open a new file named 'filename'. This overrides both the 'filename' and 'file' arguments to the constructor.""" self.filename = filename - self.file = io.open(self.filename, 'r', errors=self.errors) + self.file = open(self.filename, errors=self.errors) self.current_line = 0 def close(self): diff --git a/distutils/util.py b/distutils/util.py index b22cf98486..d95992ec99 100644 --- a/distutils/util.py +++ b/distutils/util.py @@ -334,7 +334,7 @@ def execute(func, args, msg=None, verbose=0, dry_run=0): print. """ if msg is None: - msg = "%s%r" % (func.__name__, args) + msg = "{}{!r}".format(func.__name__, args) if msg[-2:] == ',)': # correct for singleton tuple msg = msg[0:-2] + ')' @@ -356,7 +356,7 @@ def strtobool(val): elif val in ('n', 'no', 'f', 'false', 'off', '0'): return 0 else: - raise ValueError("invalid truth value %r" % (val,)) + raise ValueError("invalid truth value {!r}".format(val)) def byte_compile( # noqa: C901 diff --git a/distutils/version.py b/distutils/version.py index 7e33fb7c94..e29e265750 100644 --- a/distutils/version.py +++ b/distutils/version.py @@ -60,7 +60,7 @@ def __init__(self, vstring=None): ) def __repr__(self): - return "%s ('%s')" % (self.__class__.__name__, str(self)) + return "{} ('{}')".format(self.__class__.__name__, str(self)) def __eq__(self, other): c = self._cmp(other) From 26a7b62348b183acd00ad4594f645bea9812a303 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Sun, 31 Jul 2022 19:42:10 -0400 Subject: [PATCH 02/16] In DummyCommand, simplify setting of kwargs. --- distutils/tests/support.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/distutils/tests/support.py b/distutils/tests/support.py index d81da1b492..099e4d2dcb 100644 --- a/distutils/tests/support.py +++ b/distutils/tests/support.py @@ -108,8 +108,7 @@ class DummyCommand: """Class to store options for retrieval via set_undefined_options().""" def __init__(self, **kwargs): - for kw, val in kwargs.items(): - setattr(self, kw, val) + vars(self).update(kwargs) def ensure_finalized(self): pass From 4cc6842cf51a3ecb40ff66baa7ea847a8c25ab49 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Sun, 31 Jul 2022 20:22:28 -0400 Subject: [PATCH 03/16] Implement TempdirManager setup and teardown as a pytest fixture. --- conftest.py | 17 +++++++++++++++++ distutils/tests/support.py | 17 ++--------------- 2 files changed, 19 insertions(+), 15 deletions(-) diff --git a/conftest.py b/conftest.py index 57d8f5f86a..0f80f46c79 100644 --- a/conftest.py +++ b/conftest.py @@ -32,3 +32,20 @@ def save_env(): @pytest.fixture def needs_zlib(): pytest.importorskip('zlib') + + +@pytest.fixture +def distutils_managed_tempdir(request): + from distutils.tests import py38compat as os_helper + self = request.instance + self.old_cwd = os.getcwd() + self.tempdirs = [] + try: + yield + finally: + # Restore working dir, for Solaris and derivatives, where rmdir() + # on the current directory fails. + os.chdir(self.old_cwd) + while self.tempdirs: + tmpdir = self.tempdirs.pop() + os_helper.rmtree(tmpdir) diff --git a/distutils/tests/support.py b/distutils/tests/support.py index 099e4d2dcb..359e54fecf 100644 --- a/distutils/tests/support.py +++ b/distutils/tests/support.py @@ -6,7 +6,7 @@ import unittest import sysconfig -from . import py38compat as os_helper +import pytest from distutils import log from distutils.log import DEBUG, INFO, WARN, ERROR, FATAL @@ -43,26 +43,13 @@ def clear_logs(self): self.logs = [] +@pytest.mark.usefixtures('distutils_managed_tempdir') class TempdirManager: """Mix-in class that handles temporary directories for test cases. This is intended to be used with unittest.TestCase. """ - def setUp(self): - super().setUp() - self.old_cwd = os.getcwd() - self.tempdirs = [] - - def tearDown(self): - # Restore working dir, for Solaris and derivatives, where rmdir() - # on the current directory fails. - os.chdir(self.old_cwd) - super().tearDown() - while self.tempdirs: - tmpdir = self.tempdirs.pop() - os_helper.rmtree(tmpdir) - def mkdtemp(self): """Create a temporary directory that will be cleaned up. From 518d91454c3fdc69d09909ba65fdaee3f343814b Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Sun, 31 Jul 2022 21:02:53 -0400 Subject: [PATCH 04/16] Implement LoggingSilencer setup and teardown as a pytest fixture. Required building a fixture combiner. --- conftest.py | 19 ++++++++++++++++++ distutils/tests/support.py | 31 +++++++++++++++-------------- distutils/tests/test_build_py.py | 1 + distutils/tests/test_check.py | 1 + distutils/tests/test_config.py | 1 + distutils/tests/test_config_cmd.py | 1 + distutils/tests/test_dist.py | 1 + distutils/tests/test_install.py | 1 + distutils/tests/test_install_lib.py | 1 + 9 files changed, 42 insertions(+), 15 deletions(-) diff --git a/conftest.py b/conftest.py index 0f80f46c79..94d1c27f65 100644 --- a/conftest.py +++ b/conftest.py @@ -34,6 +34,25 @@ def needs_zlib(): pytest.importorskip('zlib') +@pytest.fixture +def distutils_logging_silencer(request): + from distutils import log + self = request.instance + self.threshold = log.set_threshold(log.FATAL) + # catching warnings + # when log will be replaced by logging + # we won't need such monkey-patch anymore + self._old_log = log.Log._log + log.Log._log = self._log + self.logs = [] + + try: + yield + finally: + log.set_threshold(self.threshold) + log.Log._log = self._old_log + + @pytest.fixture def distutils_managed_tempdir(request): from distutils.tests import py38compat as os_helper diff --git a/distutils/tests/support.py b/distutils/tests/support.py index 359e54fecf..e922faf257 100644 --- a/distutils/tests/support.py +++ b/distutils/tests/support.py @@ -5,29 +5,16 @@ import tempfile import unittest import sysconfig +import itertools import pytest -from distutils import log from distutils.log import DEBUG, INFO, WARN, ERROR, FATAL from distutils.core import Distribution +@pytest.mark.usefixtures('distutils_logging_silencer') class LoggingSilencer: - def setUp(self): - super().setUp() - self.threshold = log.set_threshold(log.FATAL) - # catching warnings - # when log will be replaced by logging - # we won't need such monkey-patch anymore - self._old_log = log.Log._log - log.Log._log = self._log - self.logs = [] - - def tearDown(self): - log.set_threshold(self.threshold) - log.Log._log = self._old_log - super().tearDown() def _log(self, level, msg, args): if level not in (DEBUG, INFO, WARN, ERROR, FATAL): @@ -173,3 +160,17 @@ def fixup_build_ext(cmd): else: name, equals, value = runshared.partition('=') cmd.library_dirs = [d for d in value.split(os.pathsep) if d] + + +def combine_markers(cls): + """ + pytest will honor markers as found on the class, but when + markers are on multiple subclasses, only one appears. Use + this decorator to combine those markers. + """ + cls.pytestmark = [ + mark + for base in itertools.chain([cls], cls.__bases__) + for mark in getattr(base, 'pytestmark', []) + ] + return cls diff --git a/distutils/tests/test_build_py.py b/distutils/tests/test_build_py.py index 4e833b1604..188f69f57c 100644 --- a/distutils/tests/test_build_py.py +++ b/distutils/tests/test_build_py.py @@ -12,6 +12,7 @@ from distutils.tests import support +@support.combine_markers class BuildPyTestCase( support.TempdirManager, support.LoggingSilencer, unittest.TestCase ): diff --git a/distutils/tests/test_check.py b/distutils/tests/test_check.py index 21035f5d4e..17becdcdce 100644 --- a/distutils/tests/test_check.py +++ b/distutils/tests/test_check.py @@ -16,6 +16,7 @@ HERE = os.path.dirname(__file__) +@support.combine_markers class CheckTestCase(support.LoggingSilencer, support.TempdirManager, unittest.TestCase): def _run(self, metadata=None, cwd=None, **options): if metadata is None: diff --git a/distutils/tests/test_config.py b/distutils/tests/test_config.py index c841db163f..bc54a756fe 100644 --- a/distutils/tests/test_config.py +++ b/distutils/tests/test_config.py @@ -51,6 +51,7 @@ """ +@support.combine_markers @pytest.mark.usefixtures('save_env') class BasePyPIRCCommandTestCase( support.TempdirManager, diff --git a/distutils/tests/test_config_cmd.py b/distutils/tests/test_config_cmd.py index 90b168d83b..47e652ac42 100644 --- a/distutils/tests/test_config_cmd.py +++ b/distutils/tests/test_config_cmd.py @@ -9,6 +9,7 @@ from distutils import log +@support.combine_markers class ConfigTestCase( support.LoggingSilencer, support.TempdirManager, unittest.TestCase ): diff --git a/distutils/tests/test_dist.py b/distutils/tests/test_dist.py index 92a42fb2d3..42348fca6f 100644 --- a/distutils/tests/test_dist.py +++ b/distutils/tests/test_dist.py @@ -42,6 +42,7 @@ def find_config_files(self): return self._config_files +@support.combine_markers @pytest.mark.usefixtures('save_env') class DistributionTestCase( support.LoggingSilencer, diff --git a/distutils/tests/test_install.py b/distutils/tests/test_install.py index 32ee02c74d..ea68ab7400 100644 --- a/distutils/tests/test_install.py +++ b/distutils/tests/test_install.py @@ -26,6 +26,7 @@ def _make_ext_name(modname): return modname + sysconfig.get_config_var('EXT_SUFFIX') +@support.combine_markers @pytest.mark.usefixtures('save_env') class InstallTestCase( support.TempdirManager, diff --git a/distutils/tests/test_install_lib.py b/distutils/tests/test_install_lib.py index cebc88e745..8c5709c262 100644 --- a/distutils/tests/test_install_lib.py +++ b/distutils/tests/test_install_lib.py @@ -12,6 +12,7 @@ from distutils.errors import DistutilsOptionError +@support.combine_markers @pytest.mark.usefixtures('save_env') class InstallLibTestCase( support.TempdirManager, From a4e0f2ba72716f631ad0828dec6116465c16a909 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Sun, 31 Jul 2022 21:12:41 -0400 Subject: [PATCH 05/16] Ran unittest2pytest --- distutils/tests/test_archive_util.py | 85 ++++++----- distutils/tests/test_bdist.py | 8 +- distutils/tests/test_bdist_dumb.py | 4 +- distutils/tests/test_bdist_rpm.py | 16 +-- distutils/tests/test_bdist_wininst.py | 2 +- distutils/tests/test_build.py | 16 +-- distutils/tests/test_build_clib.py | 50 +++---- distutils/tests/test_build_ext.py | 107 +++++++------- distutils/tests/test_build_py.py | 22 +-- distutils/tests/test_build_scripts.py | 12 +- distutils/tests/test_check.py | 50 +++---- distutils/tests/test_clean.py | 2 +- distutils/tests/test_cmd.py | 40 +++--- distutils/tests/test_config.py | 12 +- distutils/tests/test_config_cmd.py | 16 +-- distutils/tests/test_core.py | 18 +-- distutils/tests/test_cygwinccompiler.py | 32 +++-- distutils/tests/test_dep_util.py | 23 +-- distutils/tests/test_dir_util.py | 33 +++-- distutils/tests/test_dist.py | 184 +++++++++++------------- distutils/tests/test_extension.py | 28 ++-- distutils/tests/test_file_util.py | 25 ++-- distutils/tests/test_filelist.py | 88 ++++++------ distutils/tests/test_install.py | 62 ++++---- distutils/tests/test_install_data.py | 20 +-- distutils/tests/test_install_headers.py | 4 +- distutils/tests/test_install_lib.py | 22 +-- distutils/tests/test_install_scripts.py | 18 +-- distutils/tests/test_log.py | 16 +-- distutils/tests/test_msvc9compiler.py | 19 +-- distutils/tests/test_msvccompiler.py | 19 ++- distutils/tests/test_register.py | 44 +++--- distutils/tests/test_sdist.py | 62 ++++---- distutils/tests/test_spawn.py | 28 ++-- distutils/tests/test_sysconfig.py | 115 +++++++-------- distutils/tests/test_text_file.py | 2 +- distutils/tests/test_unixccompiler.py | 31 ++-- distutils/tests/test_upload.py | 52 ++++--- distutils/tests/test_util.py | 64 ++++----- distutils/tests/test_version.py | 40 ++---- 40 files changed, 718 insertions(+), 773 deletions(-) diff --git a/distutils/tests/test_archive_util.py b/distutils/tests/test_archive_util.py index b653cf2155..1cffe9d8b5 100644 --- a/distutils/tests/test_archive_util.py +++ b/distutils/tests/test_archive_util.py @@ -116,8 +116,8 @@ def _make_tarball(self, tmpdir, target_name, suffix, **kwargs): # check if the compressed tarball was created tarball = base_name + suffix - self.assertTrue(os.path.exists(tarball)) - self.assertEqual(self._tarinfo(tarball), self._created_files) + assert os.path.exists(tarball) + assert self._tarinfo(tarball) == self._created_files def _tarinfo(self, path): tar = tarfile.open(path) @@ -168,7 +168,7 @@ def test_tarfile_vs_tar(self): # check if the compressed tarball was created tarball = base_name + '.tar.gz' - self.assertTrue(os.path.exists(tarball)) + assert os.path.exists(tarball) # now create another tarball using `tar` tarball2 = os.path.join(tmpdir, 'archive2.tar.gz') @@ -182,10 +182,10 @@ def test_tarfile_vs_tar(self): finally: os.chdir(old_dir) - self.assertTrue(os.path.exists(tarball2)) + assert os.path.exists(tarball2) # let's compare both tarballs - self.assertEqual(self._tarinfo(tarball), self._created_files) - self.assertEqual(self._tarinfo(tarball2), self._created_files) + assert self._tarinfo(tarball) == self._created_files + assert self._tarinfo(tarball2) == self._created_files # trying an uncompressed one base_name = os.path.join(tmpdir2, 'archive') @@ -196,7 +196,7 @@ def test_tarfile_vs_tar(self): finally: os.chdir(old_dir) tarball = base_name + '.tar' - self.assertTrue(os.path.exists(tarball)) + assert os.path.exists(tarball) # now for a dry_run base_name = os.path.join(tmpdir2, 'archive') @@ -207,7 +207,7 @@ def test_tarfile_vs_tar(self): finally: os.chdir(old_dir) tarball = base_name + '.tar' - self.assertTrue(os.path.exists(tarball)) + assert os.path.exists(tarball) @unittest.skipUnless( find_executable('compress'), 'The compress program is required' @@ -226,8 +226,8 @@ def test_compress_deprecated(self): finally: os.chdir(old_dir) tarball = base_name + '.tar.Z' - self.assertTrue(os.path.exists(tarball)) - self.assertEqual(len(w.warnings), 1) + assert os.path.exists(tarball) + assert len(w.warnings) == 1 # same test with dry_run os.remove(tarball) @@ -239,8 +239,8 @@ def test_compress_deprecated(self): make_tarball(base_name, 'dist', compress='compress', dry_run=True) finally: os.chdir(old_dir) - self.assertFalse(os.path.exists(tarball)) - self.assertEqual(len(w.warnings), 1) + assert not os.path.exists(tarball) + assert len(w.warnings) == 1 @pytest.mark.usefixtures('needs_zlib') @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run') @@ -253,9 +253,9 @@ def test_make_zipfile(self): # check if the compressed tarball was created tarball = base_name + '.zip' - self.assertTrue(os.path.exists(tarball)) + assert os.path.exists(tarball) with zipfile.ZipFile(tarball) as zf: - self.assertEqual(sorted(zf.namelist()), self._zip_created_files) + assert sorted(zf.namelist()) == self._zip_created_files @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run') def test_make_zipfile_no_zlib(self): @@ -278,23 +278,20 @@ def fake_zipfile(*a, **kw): make_zipfile(base_name, 'dist') tarball = base_name + '.zip' - self.assertEqual( - called, [((tarball, "w"), {'compression': zipfile.ZIP_STORED})] - ) - self.assertTrue(os.path.exists(tarball)) + assert called == [((tarball, "w"), {'compression': zipfile.ZIP_STORED})] + assert os.path.exists(tarball) with zipfile.ZipFile(tarball) as zf: - self.assertEqual(sorted(zf.namelist()), self._zip_created_files) + assert sorted(zf.namelist()) == self._zip_created_files def test_check_archive_formats(self): - self.assertEqual(check_archive_formats(['gztar', 'xxx', 'zip']), 'xxx') - self.assertIsNone( - check_archive_formats(['gztar', 'bztar', 'xztar', 'ztar', 'tar', 'zip']) - ) + assert check_archive_formats(['gztar', 'xxx', 'zip']) == 'xxx' + assert check_archive_formats(['gztar', 'bztar', 'xztar', 'ztar', 'tar', 'zip']) is None def test_make_archive(self): tmpdir = self.mkdtemp() base_name = os.path.join(tmpdir, 'archive') - self.assertRaises(ValueError, make_archive, base_name, 'xxx') + with pytest.raises(ValueError): + make_archive(base_name, 'xxx') def test_make_archive_cwd(self): current_dir = os.getcwd() @@ -308,7 +305,7 @@ def _breaks(*args, **kw): make_archive('xxx', 'xxx', root_dir=self.mkdtemp()) except Exception: pass - self.assertEqual(os.getcwd(), current_dir) + assert os.getcwd() == current_dir finally: del ARCHIVE_FORMATS['xxx'] @@ -316,36 +313,36 @@ def test_make_archive_tar(self): base_dir = self._create_files() base_name = os.path.join(self.mkdtemp(), 'archive') res = make_archive(base_name, 'tar', base_dir, 'dist') - self.assertTrue(os.path.exists(res)) - self.assertEqual(os.path.basename(res), 'archive.tar') - self.assertEqual(self._tarinfo(res), self._created_files) + assert os.path.exists(res) + assert os.path.basename(res) == 'archive.tar' + assert self._tarinfo(res) == self._created_files @pytest.mark.usefixtures('needs_zlib') def test_make_archive_gztar(self): base_dir = self._create_files() base_name = os.path.join(self.mkdtemp(), 'archive') res = make_archive(base_name, 'gztar', base_dir, 'dist') - self.assertTrue(os.path.exists(res)) - self.assertEqual(os.path.basename(res), 'archive.tar.gz') - self.assertEqual(self._tarinfo(res), self._created_files) + assert os.path.exists(res) + assert os.path.basename(res) == 'archive.tar.gz' + assert self._tarinfo(res) == self._created_files @unittest.skipUnless(bz2, 'Need bz2 support to run') def test_make_archive_bztar(self): base_dir = self._create_files() base_name = os.path.join(self.mkdtemp(), 'archive') res = make_archive(base_name, 'bztar', base_dir, 'dist') - self.assertTrue(os.path.exists(res)) - self.assertEqual(os.path.basename(res), 'archive.tar.bz2') - self.assertEqual(self._tarinfo(res), self._created_files) + assert os.path.exists(res) + assert os.path.basename(res) == 'archive.tar.bz2' + assert self._tarinfo(res) == self._created_files @unittest.skipUnless(lzma, 'Need xz support to run') def test_make_archive_xztar(self): base_dir = self._create_files() base_name = os.path.join(self.mkdtemp(), 'archive') res = make_archive(base_name, 'xztar', base_dir, 'dist') - self.assertTrue(os.path.exists(res)) - self.assertEqual(os.path.basename(res), 'archive.tar.xz') - self.assertEqual(self._tarinfo(res), self._created_files) + assert os.path.exists(res) + assert os.path.basename(res) == 'archive.tar.xz' + assert self._tarinfo(res) == self._created_files def test_make_archive_owner_group(self): # testing make_archive with owner and group, with various combinations @@ -362,20 +359,20 @@ def test_make_archive_owner_group(self): res = make_archive( base_name, 'zip', root_dir, base_dir, owner=owner, group=group ) - self.assertTrue(os.path.exists(res)) + assert os.path.exists(res) res = make_archive(base_name, 'zip', root_dir, base_dir) - self.assertTrue(os.path.exists(res)) + assert os.path.exists(res) res = make_archive( base_name, 'tar', root_dir, base_dir, owner=owner, group=group ) - self.assertTrue(os.path.exists(res)) + assert os.path.exists(res) res = make_archive( base_name, 'tar', root_dir, base_dir, owner='kjhkjhkjg', group='oihohoh' ) - self.assertTrue(os.path.exists(res)) + assert os.path.exists(res) @pytest.mark.usefixtures('needs_zlib') @require_unix_id @@ -395,13 +392,13 @@ def test_tarfile_root_owner(self): os.chdir(old_dir) # check if the compressed tarball was created - self.assertTrue(os.path.exists(archive_name)) + assert os.path.exists(archive_name) # now checks the rights archive = tarfile.open(archive_name) try: for member in archive.getmembers(): - self.assertEqual(member.uid, 0) - self.assertEqual(member.gid, 0) + assert member.uid == 0 + assert member.gid == 0 finally: archive.close() diff --git a/distutils/tests/test_bdist.py b/distutils/tests/test_bdist.py index 8dbb829b6d..d7a7da250c 100644 --- a/distutils/tests/test_bdist.py +++ b/distutils/tests/test_bdist.py @@ -15,7 +15,7 @@ def test_formats(self): cmd = bdist(dist) cmd.formats = ['msi'] cmd.ensure_finalized() - self.assertEqual(cmd.formats, ['msi']) + assert cmd.formats == ['msi'] # what formats does bdist offer? formats = [ @@ -30,7 +30,7 @@ def test_formats(self): 'ztar', ] found = sorted(cmd.format_commands) - self.assertEqual(found, formats) + assert found == formats def test_skip_build(self): # bug #10946: bdist --skip-build should trickle down to subcommands @@ -56,6 +56,4 @@ def test_skip_build(self): if getattr(subcmd, '_unsupported', False): # command is not supported on this build continue - self.assertTrue( - subcmd.skip_build, '%s should take --skip-build from bdist' % name - ) + assert subcmd.skip_build, '%s should take --skip-build from bdist' % name diff --git a/distutils/tests/test_bdist_dumb.py b/distutils/tests/test_bdist_dumb.py index 5fe7d1392a..aa4c8db174 100644 --- a/distutils/tests/test_bdist_dumb.py +++ b/distutils/tests/test_bdist_dumb.py @@ -77,7 +77,7 @@ def test_simple_built(self): dist_created = os.listdir(os.path.join(pkg_dir, 'dist')) base = "{}.{}.zip".format(dist.get_fullname(), cmd.plat_name) - self.assertEqual(dist_created, [base]) + assert dist_created == [base] # now let's check what we have in the zip file fp = zipfile.ZipFile(os.path.join('dist', base)) @@ -90,4 +90,4 @@ def test_simple_built(self): wanted = ['foo-0.1-py%s.%s.egg-info' % sys.version_info[:2], 'foo.py'] if not sys.dont_write_bytecode: wanted.append('foo.%s.pyc' % sys.implementation.cache_tag) - self.assertEqual(contents, sorted(wanted)) + assert contents == sorted(wanted) diff --git a/distutils/tests/test_bdist_rpm.py b/distutils/tests/test_bdist_rpm.py index 893ac7677f..d1de5ffe51 100644 --- a/distutils/tests/test_bdist_rpm.py +++ b/distutils/tests/test_bdist_rpm.py @@ -90,13 +90,11 @@ def test_quiet(self): cmd.run() dist_created = os.listdir(os.path.join(pkg_dir, 'dist')) - self.assertIn('foo-0.1-1.noarch.rpm', dist_created) + assert 'foo-0.1-1.noarch.rpm' in dist_created # bug #2945: upload ignores bdist_rpm files - self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm'), dist.dist_files) - self.assertIn( - ('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm'), dist.dist_files - ) + assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm') in dist.dist_files + assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm') in dist.dist_files # XXX I am unable yet to make this test work without # spurious sdtout/stderr output under Mac OS X @@ -142,12 +140,10 @@ def test_no_optimize_flag(self): cmd.run() dist_created = os.listdir(os.path.join(pkg_dir, 'dist')) - self.assertIn('foo-0.1-1.noarch.rpm', dist_created) + assert 'foo-0.1-1.noarch.rpm' in dist_created # bug #2945: upload ignores bdist_rpm files - self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm'), dist.dist_files) - self.assertIn( - ('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm'), dist.dist_files - ) + assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm') in dist.dist_files + assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm') in dist.dist_files os.remove(os.path.join(pkg_dir, 'dist', 'foo-0.1-1.noarch.rpm')) diff --git a/distutils/tests/test_bdist_wininst.py b/distutils/tests/test_bdist_wininst.py index 4e4fcc5b76..4c76b613b5 100644 --- a/distutils/tests/test_bdist_wininst.py +++ b/distutils/tests/test_bdist_wininst.py @@ -34,4 +34,4 @@ def test_get_exe_bytes(self): # and make sure it finds it and returns its content # no matter what platform we have exe_file = cmd.get_exe_bytes() - self.assertGreater(len(exe_file), 10) + assert len(exe_file) > 10 diff --git a/distutils/tests/test_build.py b/distutils/tests/test_build.py index 9233a3e0a5..45bc22f822 100644 --- a/distutils/tests/test_build.py +++ b/distutils/tests/test_build.py @@ -15,32 +15,32 @@ def test_finalize_options(self): cmd.finalize_options() # if not specified, plat_name gets the current platform - self.assertEqual(cmd.plat_name, get_platform()) + assert cmd.plat_name == get_platform() # build_purelib is build + lib wanted = os.path.join(cmd.build_base, 'lib') - self.assertEqual(cmd.build_purelib, wanted) + assert cmd.build_purelib == wanted # build_platlib is 'build/lib.platform-cache_tag[-pydebug]' # examples: # build/lib.macosx-10.3-i386-cpython39 plat_spec = '.{}-{}'.format(cmd.plat_name, sys.implementation.cache_tag) if hasattr(sys, 'gettotalrefcount'): - self.assertTrue(cmd.build_platlib.endswith('-pydebug')) + assert cmd.build_platlib.endswith('-pydebug') plat_spec += '-pydebug' wanted = os.path.join(cmd.build_base, 'lib' + plat_spec) - self.assertEqual(cmd.build_platlib, wanted) + assert cmd.build_platlib == wanted # by default, build_lib = build_purelib - self.assertEqual(cmd.build_lib, cmd.build_purelib) + assert cmd.build_lib == cmd.build_purelib # build_temp is build/temp. wanted = os.path.join(cmd.build_base, 'temp' + plat_spec) - self.assertEqual(cmd.build_temp, wanted) + assert cmd.build_temp == wanted # build_scripts is build/scripts-x.x wanted = os.path.join(cmd.build_base, 'scripts-%d.%d' % sys.version_info[:2]) - self.assertEqual(cmd.build_scripts, wanted) + assert cmd.build_scripts == wanted # executable is os.path.normpath(sys.executable) - self.assertEqual(cmd.executable, os.path.normpath(sys.executable)) + assert cmd.executable == os.path.normpath(sys.executable) diff --git a/distutils/tests/test_build_clib.py b/distutils/tests/test_build_clib.py index c8fbb5c263..84335741a7 100644 --- a/distutils/tests/test_build_clib.py +++ b/distutils/tests/test_build_clib.py @@ -8,6 +8,7 @@ from distutils.command.build_clib import build_clib from distutils.errors import DistutilsSetupError from distutils.tests import support +import pytest class BuildCLibTestCase( @@ -18,30 +19,25 @@ def test_check_library_dist(self): cmd = build_clib(dist) # 'libraries' option must be a list - self.assertRaises(DistutilsSetupError, cmd.check_library_list, 'foo') + with pytest.raises(DistutilsSetupError): + cmd.check_library_list('foo') # each element of 'libraries' must a 2-tuple - self.assertRaises(DistutilsSetupError, cmd.check_library_list, ['foo1', 'foo2']) + with pytest.raises(DistutilsSetupError): + cmd.check_library_list(['foo1', 'foo2']) # first element of each tuple in 'libraries' # must be a string (the library name) - self.assertRaises( - DistutilsSetupError, cmd.check_library_list, [(1, 'foo1'), ('name', 'foo2')] - ) + with pytest.raises(DistutilsSetupError): + cmd.check_library_list([(1, 'foo1'), ('name', 'foo2')]) # library name may not contain directory separators - self.assertRaises( - DistutilsSetupError, - cmd.check_library_list, - [('name', 'foo1'), ('another/name', 'foo2')], - ) + with pytest.raises(DistutilsSetupError): + cmd.check_library_list([('name', 'foo1'), ('another/name', 'foo2')],) # second element of each tuple must be a dictionary (build info) - self.assertRaises( - DistutilsSetupError, - cmd.check_library_list, - [('name', {}), ('another', 'foo2')], - ) + with pytest.raises(DistutilsSetupError): + cmd.check_library_list([('name', {}), ('another', 'foo2')],) # those work libs = [('name', {}), ('name', {'ok': 'good'})] @@ -54,22 +50,24 @@ def test_get_source_files(self): # "in 'libraries' option 'sources' must be present and must be # a list of source filenames cmd.libraries = [('name', {})] - self.assertRaises(DistutilsSetupError, cmd.get_source_files) + with pytest.raises(DistutilsSetupError): + cmd.get_source_files() cmd.libraries = [('name', {'sources': 1})] - self.assertRaises(DistutilsSetupError, cmd.get_source_files) + with pytest.raises(DistutilsSetupError): + cmd.get_source_files() cmd.libraries = [('name', {'sources': ['a', 'b']})] - self.assertEqual(cmd.get_source_files(), ['a', 'b']) + assert cmd.get_source_files() == ['a', 'b'] cmd.libraries = [('name', {'sources': ('a', 'b')})] - self.assertEqual(cmd.get_source_files(), ['a', 'b']) + assert cmd.get_source_files() == ['a', 'b'] cmd.libraries = [ ('name', {'sources': ('a', 'b')}), ('name2', {'sources': ['c', 'd']}), ] - self.assertEqual(cmd.get_source_files(), ['a', 'b', 'c', 'd']) + assert cmd.get_source_files() == ['a', 'b', 'c', 'd'] def test_build_libraries(self): @@ -86,7 +84,8 @@ def compile(*args, **kw): # build_libraries is also doing a bit of typo checking lib = [('name', {'sources': 'notvalid'})] - self.assertRaises(DistutilsSetupError, cmd.build_libraries, lib) + with pytest.raises(DistutilsSetupError): + cmd.build_libraries(lib) lib = [('name', {'sources': list()})] cmd.build_libraries(lib) @@ -100,14 +99,15 @@ def test_finalize_options(self): cmd.include_dirs = 'one-dir' cmd.finalize_options() - self.assertEqual(cmd.include_dirs, ['one-dir']) + assert cmd.include_dirs == ['one-dir'] cmd.include_dirs = None cmd.finalize_options() - self.assertEqual(cmd.include_dirs, []) + assert cmd.include_dirs == [] cmd.distribution.libraries = 'WONTWORK' - self.assertRaises(DistutilsSetupError, cmd.finalize_options) + with pytest.raises(DistutilsSetupError): + cmd.finalize_options() @unittest.skipIf(sys.platform == 'win32', "can't test on Windows") def test_run(self): @@ -133,4 +133,4 @@ def test_run(self): cmd.run() # let's check the result - self.assertIn('libfoo.a', os.listdir(build_temp)) + assert 'libfoo.a' in os.listdir(build_temp) diff --git a/distutils/tests/test_build_ext.py b/distutils/tests/test_build_ext.py index d1865b7187..3e97907f9a 100644 --- a/distutils/tests/test_build_ext.py +++ b/distutils/tests/test_build_ext.py @@ -24,6 +24,8 @@ from test import support from . import py38compat as os_helper from test.support.script_helper import assert_python_ok +import pytest +import re # http://bugs.python.org/issue4373 # Don't load the xx module more than once. @@ -143,7 +145,7 @@ def test_solaris_enable_shared(self): _config_vars['Py_ENABLE_SHARED'] = old_var # make sure we get some library dirs under solaris - self.assertGreater(len(cmd.library_dirs), 0) + assert len(cmd.library_dirs) > 0 def test_user_site(self): import site @@ -153,7 +155,7 @@ def test_user_site(self): # making sure the user option is there options = [name for name, short, lable in cmd.user_options] - self.assertIn('user', options) + assert 'user' in options # setting a value cmd.user = 1 @@ -169,9 +171,9 @@ def test_user_site(self): # see if include_dirs and library_dirs # were set - self.assertIn(lib, cmd.library_dirs) - self.assertIn(lib, cmd.rpath) - self.assertIn(incl, cmd.include_dirs) + assert lib in cmd.library_dirs + assert lib in cmd.rpath + assert incl in cmd.include_dirs def test_optional_extension(self): @@ -181,9 +183,8 @@ def test_optional_extension(self): dist = Distribution({'name': 'xx', 'ext_modules': modules}) cmd = self.build_ext(dist) cmd.ensure_finalized() - self.assertRaises( - (UnknownFileError, CompileError), cmd.run - ) # should raise an error + with pytest.raises((UnknownFileError, CompileError)): + cmd.run() # should raise an error modules = [Extension('foo', ['xxx'], optional=True)] dist = Distribution({'name': 'xx', 'ext_modules': modules}) @@ -201,40 +202,40 @@ def test_finalize_options(self): py_include = sysconfig.get_python_inc() for p in py_include.split(os.path.pathsep): - self.assertIn(p, cmd.include_dirs) + assert p in cmd.include_dirs plat_py_include = sysconfig.get_python_inc(plat_specific=1) for p in plat_py_include.split(os.path.pathsep): - self.assertIn(p, cmd.include_dirs) + assert p in cmd.include_dirs # make sure cmd.libraries is turned into a list # if it's a string cmd = self.build_ext(dist) cmd.libraries = 'my_lib, other_lib lastlib' cmd.finalize_options() - self.assertEqual(cmd.libraries, ['my_lib', 'other_lib', 'lastlib']) + assert cmd.libraries == ['my_lib', 'other_lib', 'lastlib'] # make sure cmd.library_dirs is turned into a list # if it's a string cmd = self.build_ext(dist) cmd.library_dirs = 'my_lib_dir%sother_lib_dir' % os.pathsep cmd.finalize_options() - self.assertIn('my_lib_dir', cmd.library_dirs) - self.assertIn('other_lib_dir', cmd.library_dirs) + assert 'my_lib_dir' in cmd.library_dirs + assert 'other_lib_dir' in cmd.library_dirs # make sure rpath is turned into a list # if it's a string cmd = self.build_ext(dist) cmd.rpath = 'one%stwo' % os.pathsep cmd.finalize_options() - self.assertEqual(cmd.rpath, ['one', 'two']) + assert cmd.rpath == ['one', 'two'] # make sure cmd.link_objects is turned into a list # if it's a string cmd = build_ext(dist) cmd.link_objects = 'one two,three' cmd.finalize_options() - self.assertEqual(cmd.link_objects, ['one', 'two', 'three']) + assert cmd.link_objects == ['one', 'two', 'three'] # XXX more tests to perform for win32 @@ -243,25 +244,25 @@ def test_finalize_options(self): cmd = self.build_ext(dist) cmd.define = 'one,two' cmd.finalize_options() - self.assertEqual(cmd.define, [('one', '1'), ('two', '1')]) + assert cmd.define == [('one', '1'), ('two', '1')] # make sure undef is turned into a list of # strings if they are ','-separated strings cmd = self.build_ext(dist) cmd.undef = 'one,two' cmd.finalize_options() - self.assertEqual(cmd.undef, ['one', 'two']) + assert cmd.undef == ['one', 'two'] # make sure swig_opts is turned into a list cmd = self.build_ext(dist) cmd.swig_opts = None cmd.finalize_options() - self.assertEqual(cmd.swig_opts, []) + assert cmd.swig_opts == [] cmd = self.build_ext(dist) cmd.swig_opts = '1 2' cmd.finalize_options() - self.assertEqual(cmd.swig_opts, ['1', '2']) + assert cmd.swig_opts == ['1', '2'] def test_check_extensions_list(self): dist = Distribution() @@ -269,35 +270,39 @@ def test_check_extensions_list(self): cmd.finalize_options() # 'extensions' option must be a list of Extension instances - self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, 'foo') + with pytest.raises(DistutilsSetupError): + cmd.check_extensions_list('foo') # each element of 'ext_modules' option must be an # Extension instance or 2-tuple exts = [('bar', 'foo', 'bar'), 'foo'] - self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, exts) + with pytest.raises(DistutilsSetupError): + cmd.check_extensions_list(exts) # first element of each tuple in 'ext_modules' # must be the extension name (a string) and match # a python dotted-separated name exts = [('foo-bar', '')] - self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, exts) + with pytest.raises(DistutilsSetupError): + cmd.check_extensions_list(exts) # second element of each tuple in 'ext_modules' # must be a dictionary (build info) exts = [('foo.bar', '')] - self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, exts) + with pytest.raises(DistutilsSetupError): + cmd.check_extensions_list(exts) # ok this one should pass exts = [('foo.bar', {'sources': [''], 'libraries': 'foo', 'some': 'bar'})] cmd.check_extensions_list(exts) ext = exts[0] - self.assertIsInstance(ext, Extension) + assert isinstance(ext, Extension) # check_extensions_list adds in ext the values passed # when they are in ('include_dirs', 'library_dirs', 'libraries' # 'extra_objects', 'extra_compile_args', 'extra_link_args') - self.assertEqual(ext.libraries, 'foo') - self.assertFalse(hasattr(ext, 'some')) + assert ext.libraries == 'foo' + assert not hasattr(ext, 'some') # 'macros' element of build info dict must be 1- or 2-tuple exts = [ @@ -311,19 +316,20 @@ def test_check_extensions_list(self): }, ) ] - self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, exts) + with pytest.raises(DistutilsSetupError): + cmd.check_extensions_list(exts) exts[0][1]['macros'] = [('1', '2'), ('3',)] cmd.check_extensions_list(exts) - self.assertEqual(exts[0].undef_macros, ['3']) - self.assertEqual(exts[0].define_macros, [('1', '2')]) + assert exts[0].undef_macros == ['3'] + assert exts[0].define_macros == [('1', '2')] def test_get_source_files(self): modules = [Extension('foo', ['xxx'], optional=False)] dist = Distribution({'name': 'xx', 'ext_modules': modules}) cmd = self.build_ext(dist) cmd.ensure_finalized() - self.assertEqual(cmd.get_source_files(), ['xxx']) + assert cmd.get_source_files() == ['xxx'] def test_unicode_module_names(self): modules = [ @@ -333,10 +339,10 @@ def test_unicode_module_names(self): dist = Distribution({'name': 'xx', 'ext_modules': modules}) cmd = self.build_ext(dist) cmd.ensure_finalized() - self.assertRegex(cmd.get_ext_filename(modules[0].name), r'foo(_d)?\..*') - self.assertRegex(cmd.get_ext_filename(modules[1].name), r'föö(_d)?\..*') - self.assertEqual(cmd.get_export_symbols(modules[0]), ['PyInit_foo']) - self.assertEqual(cmd.get_export_symbols(modules[1]), ['PyInitU_f_1gaa']) + assert re.search(r'foo(_d)?\..*', cmd.get_ext_filename(modules[0].name)) + assert re.search(r'föö(_d)?\..*', cmd.get_ext_filename(modules[1].name)) + assert cmd.get_export_symbols(modules[0]) == ['PyInit_foo'] + assert cmd.get_export_symbols(modules[1]) == ['PyInitU_f_1gaa'] def test_compiler_option(self): # cmd.compiler is an option and @@ -347,7 +353,7 @@ def test_compiler_option(self): cmd.compiler = 'unix' cmd.ensure_finalized() cmd.run() - self.assertEqual(cmd.compiler, 'unix') + assert cmd.compiler == 'unix' def test_get_outputs(self): cmd = support.missing_compiler_executable() @@ -361,7 +367,7 @@ def test_get_outputs(self): cmd = self.build_ext(dist) fixup_build_ext(cmd) cmd.ensure_finalized() - self.assertEqual(len(cmd.get_outputs()), 1) + assert len(cmd.get_outputs()) == 1 cmd.build_lib = os.path.join(self.tmp_dir, 'build') cmd.build_temp = os.path.join(self.tmp_dir, 'tempt') @@ -377,20 +383,20 @@ def test_get_outputs(self): so_file = cmd.get_outputs()[0] finally: os.chdir(old_wd) - self.assertTrue(os.path.exists(so_file)) + assert os.path.exists(so_file) ext_suffix = sysconfig.get_config_var('EXT_SUFFIX') - self.assertTrue(so_file.endswith(ext_suffix)) + assert so_file.endswith(ext_suffix) so_dir = os.path.dirname(so_file) - self.assertEqual(so_dir, other_tmp_dir) + assert so_dir == other_tmp_dir cmd.inplace = 0 cmd.compiler = None cmd.run() so_file = cmd.get_outputs()[0] - self.assertTrue(os.path.exists(so_file)) - self.assertTrue(so_file.endswith(ext_suffix)) + assert os.path.exists(so_file) + assert so_file.endswith(ext_suffix) so_dir = os.path.dirname(so_file) - self.assertEqual(so_dir, cmd.build_lib) + assert so_dir == cmd.build_lib # inplace = 0, cmd.package = 'bar' build_py = cmd.get_finalized_command('build_py') @@ -398,7 +404,7 @@ def test_get_outputs(self): path = cmd.get_ext_fullpath('foo') # checking that the last directory is the build_dir path = os.path.split(path)[0] - self.assertEqual(path, cmd.build_lib) + assert path == cmd.build_lib # inplace = 1, cmd.package = 'bar' cmd.inplace = 1 @@ -412,7 +418,7 @@ def test_get_outputs(self): # checking that the last directory is bar path = os.path.split(path)[0] lastdir = os.path.split(path)[-1] - self.assertEqual(lastdir, 'bar') + assert lastdir == 'bar' def test_ext_fullpath(self): ext = sysconfig.get_config_var('EXT_SUFFIX') @@ -428,14 +434,14 @@ def test_ext_fullpath(self): curdir = os.getcwd() wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext) path = cmd.get_ext_fullpath('lxml.etree') - self.assertEqual(wanted, path) + assert wanted == path # building lxml.etree not inplace cmd.inplace = 0 cmd.build_lib = os.path.join(curdir, 'tmpdir') wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree' + ext) path = cmd.get_ext_fullpath('lxml.etree') - self.assertEqual(wanted, path) + assert wanted == path # building twisted.runner.portmap not inplace build_py = cmd.get_finalized_command('build_py') @@ -443,13 +449,13 @@ def test_ext_fullpath(self): cmd.distribution.packages = ['twisted', 'twisted.runner.portmap'] path = cmd.get_ext_fullpath('twisted.runner.portmap') wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner', 'portmap' + ext) - self.assertEqual(wanted, path) + assert wanted == path # building twisted.runner.portmap inplace cmd.inplace = 1 path = cmd.get_ext_fullpath('twisted.runner.portmap') wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext) - self.assertEqual(wanted, path) + assert wanted == path @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX') def test_deployment_target_default(self): @@ -462,9 +468,8 @@ def test_deployment_target_default(self): def test_deployment_target_too_low(self): # Issue 9516: Test that an extension module is not allowed to be # compiled with a deployment target less than that of the interpreter. - self.assertRaises( - DistutilsPlatformError, self._try_compile_deployment_target, '>', '10.1' - ) + with pytest.raises(DistutilsPlatformError): + self._try_compile_deployment_target('>', '10.1') @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX') def test_deployment_target_higher_ok(self): diff --git a/distutils/tests/test_build_py.py b/distutils/tests/test_build_py.py index 188f69f57c..a60b3c2acc 100644 --- a/distutils/tests/test_build_py.py +++ b/distutils/tests/test_build_py.py @@ -42,24 +42,24 @@ def test_package_data(self): cmd = build_py(dist) cmd.compile = 1 cmd.ensure_finalized() - self.assertEqual(cmd.package_data, dist.package_data) + assert cmd.package_data == dist.package_data cmd.run() # This makes sure the list of outputs includes byte-compiled # files for Python modules but not for package data files # (there shouldn't *be* byte-code files for those!). - self.assertEqual(len(cmd.get_outputs()), 3) + assert len(cmd.get_outputs()) == 3 pkgdest = os.path.join(destination, "pkg") files = os.listdir(pkgdest) pycache_dir = os.path.join(pkgdest, "__pycache__") - self.assertIn("__init__.py", files) - self.assertIn("README.txt", files) + assert "__init__.py" in files + assert "README.txt" in files if sys.dont_write_bytecode: - self.assertFalse(os.path.exists(pycache_dir)) + assert not os.path.exists(pycache_dir) else: pyc_files = os.listdir(pycache_dir) - self.assertIn("__init__.%s.pyc" % sys.implementation.cache_tag, pyc_files) + assert "__init__.%s.pyc" % sys.implementation.cache_tag in pyc_files def test_empty_package_dir(self): # See bugs #1668596/#1720897 @@ -100,9 +100,9 @@ def test_byte_compile(self): cmd.run() found = os.listdir(cmd.build_lib) - self.assertEqual(sorted(found), ['__pycache__', 'boiledeggs.py']) + assert sorted(found) == ['__pycache__', 'boiledeggs.py'] found = os.listdir(os.path.join(cmd.build_lib, '__pycache__')) - self.assertEqual(found, ['boiledeggs.%s.pyc' % sys.implementation.cache_tag]) + assert found == ['boiledeggs.%s.pyc' % sys.implementation.cache_tag] @unittest.skipIf(sys.dont_write_bytecode, 'byte-compile disabled') def test_byte_compile_optimized(self): @@ -117,10 +117,10 @@ def test_byte_compile_optimized(self): cmd.run() found = os.listdir(cmd.build_lib) - self.assertEqual(sorted(found), ['__pycache__', 'boiledeggs.py']) + assert sorted(found) == ['__pycache__', 'boiledeggs.py'] found = os.listdir(os.path.join(cmd.build_lib, '__pycache__')) expect = f'boiledeggs.{sys.implementation.cache_tag}.opt-1.pyc' - self.assertEqual(sorted(found), [expect]) + assert sorted(found) == [expect] def test_dir_in_package_data(self): """ @@ -166,7 +166,7 @@ def test_dont_write_bytecode(self): finally: sys.dont_write_bytecode = old_dont_write_bytecode - self.assertIn('byte-compiling is disabled', self.logs[0][1] % self.logs[0][2]) + assert 'byte-compiling is disabled' in self.logs[0][1] % self.logs[0][2] @patch("distutils.command.build_py.log.warn") def test_namespace_package_does_not_warn(self, log_warn): diff --git a/distutils/tests/test_build_scripts.py b/distutils/tests/test_build_scripts.py index 6ef9dd6188..fbcb4372cb 100644 --- a/distutils/tests/test_build_scripts.py +++ b/distutils/tests/test_build_scripts.py @@ -15,13 +15,13 @@ class BuildScriptsTestCase( ): def test_default_settings(self): cmd = self.get_build_scripts_cmd("/foo/bar", []) - self.assertFalse(cmd.force) - self.assertIsNone(cmd.build_dir) + assert not cmd.force + assert cmd.build_dir is None cmd.finalize_options() - self.assertTrue(cmd.force) - self.assertEqual(cmd.build_dir, "/foo/bar") + assert cmd.force + assert cmd.build_dir == "/foo/bar" def test_build(self): source = self.mkdtemp() @@ -36,7 +36,7 @@ def test_build(self): built = os.listdir(target) for name in expected: - self.assertIn(name, built) + assert name in built def get_build_scripts_cmd(self, target, scripts): import sys @@ -106,4 +106,4 @@ def test_version_int(self): built = os.listdir(target) for name in expected: - self.assertIn(name, built) + assert name in built diff --git a/distutils/tests/test_check.py b/distutils/tests/test_check.py index 17becdcdce..c6a0cf32f4 100644 --- a/distutils/tests/test_check.py +++ b/distutils/tests/test_check.py @@ -6,6 +6,7 @@ from distutils.command.check import check, HAS_DOCUTILS from distutils.tests import support from distutils.errors import DistutilsSetupError +import pytest try: import pygments @@ -40,7 +41,7 @@ def test_check_metadata(self): # by default, check is checking the metadata # should have some warnings cmd = self._run() - self.assertEqual(cmd._warnings, 1) + assert cmd._warnings == 1 # now let's add the required fields # and run it again, to make sure we don't get @@ -53,15 +54,16 @@ def test_check_metadata(self): 'version': 'xxx', } cmd = self._run(metadata) - self.assertEqual(cmd._warnings, 0) + assert cmd._warnings == 0 # now with the strict mode, we should # get an error if there are missing metadata - self.assertRaises(DistutilsSetupError, self._run, {}, **{'strict': 1}) + with pytest.raises(DistutilsSetupError): + self._run({}, **{'strict': 1}) # and of course, no error when all metadata are present cmd = self._run(metadata, strict=1) - self.assertEqual(cmd._warnings, 0) + assert cmd._warnings == 0 # now a test with non-ASCII characters metadata = { @@ -74,7 +76,7 @@ def test_check_metadata(self): 'long_description': 'More things about esszet \u00df', } cmd = self._run(metadata) - self.assertEqual(cmd._warnings, 0) + assert cmd._warnings == 0 def test_check_author_maintainer(self): for kind in ("author", "maintainer"): @@ -87,18 +89,18 @@ def test_check_author_maintainer(self): 'version': 'xxx', } cmd = self._run(metadata) - self.assertEqual(cmd._warnings, 0) + assert cmd._warnings == 0 # the check should not warn if only email is given metadata[kind + '_email'] = 'name@email.com' cmd = self._run(metadata) - self.assertEqual(cmd._warnings, 0) + assert cmd._warnings == 0 # the check should not warn if only the name is given metadata[kind] = "Name" del metadata[kind + '_email'] cmd = self._run(metadata) - self.assertEqual(cmd._warnings, 0) + assert cmd._warnings == 0 @unittest.skipUnless(HAS_DOCUTILS, "won't test without docutils") def test_check_document(self): @@ -108,12 +110,12 @@ def test_check_document(self): # let's see if it detects broken rest broken_rest = 'title\n===\n\ntest' msgs = cmd._check_rst_data(broken_rest) - self.assertEqual(len(msgs), 1) + assert len(msgs) == 1 # and non-broken rest rest = 'title\n=====\n\ntest' msgs = cmd._check_rst_data(rest) - self.assertEqual(len(msgs), 0) + assert len(msgs) == 0 @unittest.skipUnless(HAS_DOCUTILS, "won't test without docutils") def test_check_restructuredtext(self): @@ -122,7 +124,7 @@ def test_check_restructuredtext(self): pkg_info, dist = self.create_dist(long_description=broken_rest) cmd = check(dist) cmd.check_restructuredtext() - self.assertEqual(cmd._warnings, 1) + assert cmd._warnings == 1 # let's see if we have an error with strict=1 metadata = { @@ -133,22 +135,19 @@ def test_check_restructuredtext(self): 'version': 'xxx', 'long_description': broken_rest, } - self.assertRaises( - DistutilsSetupError, - self._run, - metadata, - **{'strict': 1, 'restructuredtext': 1} - ) + with pytest.raises(DistutilsSetupError): + self._run(metadata, + **{'strict': 1, 'restructuredtext': 1}) # and non-broken rest, including a non-ASCII character to test #12114 metadata['long_description'] = 'title\n=====\n\ntest \u00df' cmd = self._run(metadata, strict=1, restructuredtext=1) - self.assertEqual(cmd._warnings, 0) + assert cmd._warnings == 0 # check that includes work to test #31292 metadata['long_description'] = 'title\n=====\n\n.. include:: includetest.rst' cmd = self._run(metadata, cwd=HERE, strict=1, restructuredtext=1) - self.assertEqual(cmd._warnings, 0) + assert cmd._warnings == 0 @unittest.skipUnless(HAS_DOCUTILS, "won't test without docutils") def test_check_restructuredtext_with_syntax_highlight(self): @@ -186,14 +185,11 @@ def foo(): cmd.check_restructuredtext() msgs = cmd._check_rst_data(rest_with_code) if pygments is not None: - self.assertEqual(len(msgs), 0) + assert len(msgs) == 0 else: - self.assertEqual(len(msgs), 1) - self.assertEqual( - str(msgs[0][1]), 'Cannot analyze code. Pygments package not found.' - ) + assert len(msgs) == 1 + assert str(msgs[0][1]) == 'Cannot analyze code. Pygments package not found.' def test_check_all(self): - self.assertRaises( - DistutilsSetupError, self._run, {}, **{'strict': 1, 'restructuredtext': 1} - ) + with pytest.raises(DistutilsSetupError): + self._run({}, **{'strict': 1, 'restructuredtext': 1}) diff --git a/distutils/tests/test_clean.py b/distutils/tests/test_clean.py index 796ca0fca6..6193a1d9c2 100644 --- a/distutils/tests/test_clean.py +++ b/distutils/tests/test_clean.py @@ -38,7 +38,7 @@ def test_simple_run(self): # make sure the files where removed for name, path in dirs: - self.assertFalse(os.path.exists(path), '%s was not removed' % path) + assert not os.path.exists(path), '%s was not removed' % path # let's run the command again (should spit warnings but succeed) cmd.all = 1 diff --git a/distutils/tests/test_cmd.py b/distutils/tests/test_cmd.py index 6a771a1106..ecaee7e709 100644 --- a/distutils/tests/test_cmd.py +++ b/distutils/tests/test_cmd.py @@ -7,6 +7,7 @@ from distutils.dist import Distribution from distutils.errors import DistutilsOptionError from distutils import debug +import pytest class MyCmd(Command): @@ -29,36 +30,34 @@ def test_ensure_string_list(self): cmd.ensure_string_list('yes_string_list') cmd.ensure_string_list('yes_string_list2') - self.assertRaises( - DistutilsOptionError, cmd.ensure_string_list, 'not_string_list' - ) + with pytest.raises(DistutilsOptionError): + cmd.ensure_string_list('not_string_list') - self.assertRaises( - DistutilsOptionError, cmd.ensure_string_list, 'not_string_list2' - ) + with pytest.raises(DistutilsOptionError): + cmd.ensure_string_list('not_string_list2') cmd.option1 = 'ok,dok' cmd.ensure_string_list('option1') - self.assertEqual(cmd.option1, ['ok', 'dok']) + assert cmd.option1 == ['ok', 'dok'] cmd.option2 = ['xxx', 'www'] cmd.ensure_string_list('option2') cmd.option3 = ['ok', 2] - self.assertRaises(DistutilsOptionError, cmd.ensure_string_list, 'option3') + with pytest.raises(DistutilsOptionError): + cmd.ensure_string_list('option3') def test_make_file(self): cmd = self.cmd # making sure it raises when infiles is not a string or a list/tuple - self.assertRaises( - TypeError, cmd.make_file, infiles=1, outfile='', func='func', args=() - ) + with pytest.raises(TypeError): + cmd.make_file(infiles=1, outfile='', func='func', args=()) # making sure execute gets called properly def _execute(func, args, exec_msg, level): - self.assertEqual(exec_msg, 'generating out from in') + assert exec_msg == 'generating out from in' cmd.force = True cmd.execute = _execute @@ -79,7 +78,7 @@ def _announce(msg, level): cmd.dump_options() wanted = ["command options for 'MyCmd':", ' option1 = 1', ' option2 = 1'] - self.assertEqual(msgs, wanted) + assert msgs == wanted def test_ensure_string(self): cmd = self.cmd @@ -88,37 +87,40 @@ def test_ensure_string(self): cmd.option2 = None cmd.ensure_string('option2', 'xxx') - self.assertTrue(hasattr(cmd, 'option2')) + assert hasattr(cmd, 'option2') cmd.option3 = 1 - self.assertRaises(DistutilsOptionError, cmd.ensure_string, 'option3') + with pytest.raises(DistutilsOptionError): + cmd.ensure_string('option3') def test_ensure_filename(self): cmd = self.cmd cmd.option1 = __file__ cmd.ensure_filename('option1') cmd.option2 = 'xxx' - self.assertRaises(DistutilsOptionError, cmd.ensure_filename, 'option2') + with pytest.raises(DistutilsOptionError): + cmd.ensure_filename('option2') def test_ensure_dirname(self): cmd = self.cmd cmd.option1 = os.path.dirname(__file__) or os.curdir cmd.ensure_dirname('option1') cmd.option2 = 'xxx' - self.assertRaises(DistutilsOptionError, cmd.ensure_dirname, 'option2') + with pytest.raises(DistutilsOptionError): + cmd.ensure_dirname('option2') def test_debug_print(self): cmd = self.cmd with captured_stdout() as stdout: cmd.debug_print('xxx') stdout.seek(0) - self.assertEqual(stdout.read(), '') + assert stdout.read() == '' debug.DEBUG = True try: with captured_stdout() as stdout: cmd.debug_print('xxx') stdout.seek(0) - self.assertEqual(stdout.read(), 'xxx\n') + assert stdout.read() == 'xxx\n' finally: debug.DEBUG = False diff --git a/distutils/tests/test_config.py b/distutils/tests/test_config.py index bc54a756fe..b088d6007f 100644 --- a/distutils/tests/test_config.py +++ b/distutils/tests/test_config.py @@ -104,7 +104,7 @@ def test_server_registration(self): ('server', 'server1'), ('username', 'me'), ] - self.assertEqual(config, waited) + assert config == waited # old format self.write_file(self.rc, PYPIRC_OLD) @@ -117,18 +117,18 @@ def test_server_registration(self): ('server', 'server-login'), ('username', 'tarek'), ] - self.assertEqual(config, waited) + assert config == waited def test_server_empty_registration(self): cmd = self._cmd(self.dist) rc = cmd._get_rc_file() - self.assertFalse(os.path.exists(rc)) + assert not os.path.exists(rc) cmd._store_pypirc('tarek', 'xxx') - self.assertTrue(os.path.exists(rc)) + assert os.path.exists(rc) f = open(rc) try: content = f.read() - self.assertEqual(content, WANTED) + assert content == WANTED finally: f.close() @@ -147,4 +147,4 @@ def test_config_interpolation(self): ('server', 'server3'), ('username', 'cbiggles'), ] - self.assertEqual(config, waited) + assert config == waited diff --git a/distutils/tests/test_config_cmd.py b/distutils/tests/test_config_cmd.py index 47e652ac42..425cc1ba48 100644 --- a/distutils/tests/test_config_cmd.py +++ b/distutils/tests/test_config_cmd.py @@ -36,7 +36,7 @@ def test_dump_file(self): f.close() dump_file(this_file, 'I am the header') - self.assertEqual(len(self._logs), numlines + 1) + assert len(self._logs) == numlines + 1 @unittest.skipIf(sys.platform == 'win32', "can't test on Windows") def test_search_cpp(self): @@ -54,10 +54,10 @@ def test_search_cpp(self): # simple pattern searches match = cmd.search_cpp(pattern='xxx', body='/* xxx */') - self.assertEqual(match, 0) + assert match == 0 match = cmd.search_cpp(pattern='_configtest', body='/* xxx */') - self.assertEqual(match, 1) + assert match == 1 def test_finalize_options(self): # finalize_options does a bit of transformation @@ -69,9 +69,9 @@ def test_finalize_options(self): cmd.library_dirs = 'three%sfour' % os.pathsep cmd.ensure_finalized() - self.assertEqual(cmd.include_dirs, ['one', 'two']) - self.assertEqual(cmd.libraries, ['one']) - self.assertEqual(cmd.library_dirs, ['three', 'four']) + assert cmd.include_dirs == ['one', 'two'] + assert cmd.libraries == ['one'] + assert cmd.library_dirs == ['three', 'four'] def test_clean(self): # _clean removes files @@ -83,11 +83,11 @@ def test_clean(self): self.write_file(f2, 'xxx') for f in (f1, f2): - self.assertTrue(os.path.exists(f)) + assert os.path.exists(f) pkg_dir, dist = self.create_dist() cmd = config(dist) cmd._clean(f1, f2) for f in (f1, f2): - self.assertFalse(os.path.exists(f)) + assert not os.path.exists(f) diff --git a/distutils/tests/test_core.py b/distutils/tests/test_core.py index b4cbdc9717..08eccdb1a2 100644 --- a/distutils/tests/test_core.py +++ b/distutils/tests/test_core.py @@ -99,14 +99,14 @@ def test_run_setup_preserves_sys_argv(self): # Make sure run_setup does not clobber sys.argv argv_copy = sys.argv.copy() distutils.core.run_setup(self.write_setup(setup_does_nothing)) - self.assertEqual(sys.argv, argv_copy) + assert sys.argv == argv_copy def test_run_setup_defines_subclass(self): # Make sure the script can use __file__; if that's missing, the test # setup.py script will raise NameError. dist = distutils.core.run_setup(self.write_setup(setup_defines_subclass)) install = dist.get_command_obj('install') - self.assertIn('cmd', install.sub_commands) + assert 'cmd' in install.sub_commands def test_run_setup_uses_current_dir(self): # This tests that the setup script is run with the current directory @@ -123,23 +123,23 @@ def test_run_setup_uses_current_dir(self): output = sys.stdout.getvalue() if output.endswith("\n"): output = output[:-1] - self.assertEqual(cwd, output) + assert cwd == output def test_run_setup_within_if_main(self): dist = distutils.core.run_setup( self.write_setup(setup_within_if_main), stop_after="config" ) - self.assertIsInstance(dist, Distribution) - self.assertEqual(dist.get_name(), "setup_within_if_main") + assert isinstance(dist, Distribution) + assert dist.get_name() == "setup_within_if_main" def test_run_commands(self): sys.argv = ['setup.py', 'build'] dist = distutils.core.run_setup( self.write_setup(setup_within_if_main), stop_after="commandline" ) - self.assertNotIn('build', dist.have_run) + assert 'build' not in dist.have_run distutils.core.run_commands(dist) - self.assertIn('build', dist.have_run) + assert 'build' in dist.have_run def test_debug_mode(self): # this covers the code called when DEBUG is set @@ -147,7 +147,7 @@ def test_debug_mode(self): with captured_stdout() as stdout: distutils.core.setup(name='bar') stdout.seek(0) - self.assertEqual(stdout.read(), 'bar\n') + assert stdout.read() == 'bar\n' distutils.core.DEBUG = True try: @@ -157,4 +157,4 @@ def test_debug_mode(self): distutils.core.DEBUG = False stdout.seek(0) wanted = "options (after parsing config files):\n" - self.assertEqual(stdout.readlines()[0], wanted) + assert stdout.readlines()[0] == wanted diff --git a/distutils/tests/test_cygwinccompiler.py b/distutils/tests/test_cygwinccompiler.py index 8a55825235..7eebd9ba86 100644 --- a/distutils/tests/test_cygwinccompiler.py +++ b/distutils/tests/test_cygwinccompiler.py @@ -11,6 +11,7 @@ get_msvcr, ) from distutils.tests import support +import pytest class CygwinCCompilerTestCase(support.TempdirManager, unittest.TestCase): @@ -43,16 +44,16 @@ def test_find_library_file(self): compiler = CygwinCCompiler() link_name = "bash" linkable_file = compiler.find_library_file(["/usr/lib"], link_name) - self.assertIsNotNone(linkable_file) - self.assertTrue(os.path.exists(linkable_file)) - self.assertEqual(linkable_file, f"/usr/lib/lib{link_name:s}.dll.a") + assert linkable_file is not None + assert os.path.exists(linkable_file) + assert linkable_file == f"/usr/lib/lib{link_name:s}.dll.a" @unittest.skipIf(sys.platform != "cygwin", "Not running on Cygwin") def test_runtime_library_dir_option(self): from distutils.cygwinccompiler import CygwinCCompiler compiler = CygwinCCompiler() - self.assertEqual(compiler.runtime_library_dir_option('/foo'), []) + assert compiler.runtime_library_dir_option('/foo') == [] def test_check_config_h(self): @@ -63,21 +64,21 @@ def test_check_config_h(self): '4.0.1 (Apple Computer, Inc. build 5370)]' ) - self.assertEqual(check_config_h()[0], CONFIG_H_OK) + assert check_config_h()[0] == CONFIG_H_OK # then it tries to see if it can find "__GNUC__" in pyconfig.h sys.version = 'something without the *CC word' # if the file doesn't exist it returns CONFIG_H_UNCERTAIN - self.assertEqual(check_config_h()[0], CONFIG_H_UNCERTAIN) + assert check_config_h()[0] == CONFIG_H_UNCERTAIN # if it exists but does not contain __GNUC__, it returns CONFIG_H_NOTOK self.write_file(self.python_h, 'xxx') - self.assertEqual(check_config_h()[0], CONFIG_H_NOTOK) + assert check_config_h()[0] == CONFIG_H_NOTOK # and CONFIG_H_OK if __GNUC__ is found self.write_file(self.python_h, 'xxx __GNUC__ xxx') - self.assertEqual(check_config_h()[0], CONFIG_H_OK) + assert check_config_h()[0] == CONFIG_H_OK def test_get_msvcr(self): @@ -86,40 +87,41 @@ def test_get_msvcr(self): '2.6.1 (r261:67515, Dec 6 2008, 16:42:21) ' '\n[GCC 4.0.1 (Apple Computer, Inc. build 5370)]' ) - self.assertEqual(get_msvcr(), None) + assert get_msvcr() == None # MSVC 7.0 sys.version = ( '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.1300 32 bits (Intel)]' ) - self.assertEqual(get_msvcr(), ['msvcr70']) + assert get_msvcr() == ['msvcr70'] # MSVC 7.1 sys.version = ( '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.1310 32 bits (Intel)]' ) - self.assertEqual(get_msvcr(), ['msvcr71']) + assert get_msvcr() == ['msvcr71'] # VS2005 / MSVC 8.0 sys.version = ( '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.1400 32 bits (Intel)]' ) - self.assertEqual(get_msvcr(), ['msvcr80']) + assert get_msvcr() == ['msvcr80'] # VS2008 / MSVC 9.0 sys.version = ( '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.1500 32 bits (Intel)]' ) - self.assertEqual(get_msvcr(), ['msvcr90']) + assert get_msvcr() == ['msvcr90'] sys.version = ( '3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 18:46:30) ' '[MSC v.1929 32 bit (Intel)]' ) - self.assertEqual(get_msvcr(), ['ucrt', 'vcruntime140']) + assert get_msvcr() == ['ucrt', 'vcruntime140'] # unknown sys.version = ( '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.2000 32 bits (Intel)]' ) - self.assertRaises(ValueError, get_msvcr) + with pytest.raises(ValueError): + get_msvcr() diff --git a/distutils/tests/test_dep_util.py b/distutils/tests/test_dep_util.py index fb170c6f45..e5d78c58ae 100644 --- a/distutils/tests/test_dep_util.py +++ b/distutils/tests/test_dep_util.py @@ -5,6 +5,7 @@ from distutils.dep_util import newer, newer_pairwise, newer_group from distutils.errors import DistutilsFileError from distutils.tests import support +import pytest class DepUtilTestCase(support.TempdirManager, unittest.TestCase): @@ -15,17 +16,18 @@ def test_newer(self): old_file = os.path.abspath(__file__) # Raise DistutilsFileError if 'new_file' does not exist. - self.assertRaises(DistutilsFileError, newer, new_file, old_file) + with pytest.raises(DistutilsFileError): + newer(new_file, old_file) # Return true if 'new_file' exists and is more recently modified than # 'old_file', or if 'new_file' exists and 'old_file' doesn't. self.write_file(new_file) - self.assertTrue(newer(new_file, 'I_dont_exist')) - self.assertTrue(newer(new_file, old_file)) + assert newer(new_file, 'I_dont_exist') + assert newer(new_file, old_file) # Return false if both exist and 'old_file' is the same age or younger # than 'new_file'. - self.assertFalse(newer(old_file, new_file)) + assert not newer(old_file, new_file) def test_newer_pairwise(self): tmpdir = self.mkdtemp() @@ -41,7 +43,7 @@ def test_newer_pairwise(self): self.write_file(two) self.write_file(four) - self.assertEqual(newer_pairwise([one, two], [three, four]), ([one], [three])) + assert newer_pairwise([one, two], [three, four]) == ([one], [three]) def test_newer_group(self): tmpdir = self.mkdtemp() @@ -57,13 +59,14 @@ def test_newer_group(self): self.write_file(one) self.write_file(two) self.write_file(three) - self.assertTrue(newer_group([one, two, three], old_file)) - self.assertFalse(newer_group([one, two, old_file], three)) + assert newer_group([one, two, three], old_file) + assert not newer_group([one, two, old_file], three) # missing handling os.remove(one) - self.assertRaises(OSError, newer_group, [one, two, old_file], three) + with pytest.raises(OSError): + newer_group([one, two, old_file], three) - self.assertFalse(newer_group([one, two, old_file], three, missing='ignore')) + assert not newer_group([one, two, old_file], three, missing='ignore') - self.assertTrue(newer_group([one, two, old_file], three, missing='newer')) + assert newer_group([one, two, old_file], three, missing='newer') diff --git a/distutils/tests/test_dir_util.py b/distutils/tests/test_dir_util.py index a9ebaeea29..18a18c090a 100644 --- a/distutils/tests/test_dir_util.py +++ b/distutils/tests/test_dir_util.py @@ -16,6 +16,7 @@ from distutils import log from distutils.tests import support +import pytest class DirUtilTestCase(support.TempdirManager, unittest.TestCase): @@ -43,17 +44,17 @@ def test_mkpath_remove_tree_verbosity(self): mkpath(self.target, verbose=0) wanted = [] - self.assertEqual(self._logs, wanted) + assert self._logs == wanted remove_tree(self.root_target, verbose=0) mkpath(self.target, verbose=1) wanted = ['creating %s' % self.root_target, 'creating %s' % self.target] - self.assertEqual(self._logs, wanted) + assert self._logs == wanted self._logs = [] remove_tree(self.root_target, verbose=1) wanted = ["removing '%s' (and everything under it)" % self.root_target] - self.assertEqual(self._logs, wanted) + assert self._logs == wanted @unittest.skipIf( sys.platform.startswith('win'), @@ -64,19 +65,19 @@ def test_mkpath_with_custom_mode(self): umask = os.umask(0o002) os.umask(umask) mkpath(self.target, 0o700) - self.assertEqual(stat.S_IMODE(os.stat(self.target).st_mode), 0o700 & ~umask) + assert stat.S_IMODE(os.stat(self.target).st_mode) == 0o700 & ~umask mkpath(self.target2, 0o555) - self.assertEqual(stat.S_IMODE(os.stat(self.target2).st_mode), 0o555 & ~umask) + assert stat.S_IMODE(os.stat(self.target2).st_mode) == 0o555 & ~umask def test_create_tree_verbosity(self): create_tree(self.root_target, ['one', 'two', 'three'], verbose=0) - self.assertEqual(self._logs, []) + assert self._logs == [] remove_tree(self.root_target, verbose=0) wanted = ['creating %s' % self.root_target] create_tree(self.root_target, ['one', 'two', 'three'], verbose=1) - self.assertEqual(self._logs, wanted) + assert self._logs == wanted remove_tree(self.root_target, verbose=0) @@ -85,7 +86,7 @@ def test_copy_tree_verbosity(self): mkpath(self.target, verbose=0) copy_tree(self.target, self.target2, verbose=0) - self.assertEqual(self._logs, []) + assert self._logs == [] remove_tree(self.root_target, verbose=0) @@ -96,7 +97,7 @@ def test_copy_tree_verbosity(self): wanted = ['copying {} -> {}'.format(a_file, self.target2)] copy_tree(self.target, self.target2, verbose=1) - self.assertEqual(self._logs, wanted) + assert self._logs == wanted remove_tree(self.root_target, verbose=0) remove_tree(self.target2, verbose=0) @@ -111,25 +112,23 @@ def test_copy_tree_skips_nfs_temp_files(self): fh.write('some content') copy_tree(self.target, self.target2) - self.assertEqual(os.listdir(self.target2), ['ok.txt']) + assert os.listdir(self.target2) == ['ok.txt'] remove_tree(self.root_target, verbose=0) remove_tree(self.target2, verbose=0) def test_ensure_relative(self): if os.sep == '/': - self.assertEqual(ensure_relative('/home/foo'), 'home/foo') - self.assertEqual(ensure_relative('some/path'), 'some/path') + assert ensure_relative('/home/foo') == 'home/foo' + assert ensure_relative('some/path') == 'some/path' else: # \\ - self.assertEqual(ensure_relative('c:\\home\\foo'), 'c:home\\foo') - self.assertEqual(ensure_relative('home\\foo'), 'home\\foo') + assert ensure_relative('c:\\home\\foo') == 'c:home\\foo' + assert ensure_relative('home\\foo') == 'home\\foo' def test_copy_tree_exception_in_listdir(self): """ An exception in listdir should raise a DistutilsFileError """ - with patch("os.listdir", side_effect=OSError()), self.assertRaises( - errors.DistutilsFileError - ): + with patch("os.listdir", side_effect=OSError()), pytest.raises(errors.DistutilsFileError): src = self.tempdirs[-1] dir_util.copy_tree(src, None) diff --git a/distutils/tests/test_dist.py b/distutils/tests/test_dist.py index 42348fca6f..ed0bee9e9b 100644 --- a/distutils/tests/test_dist.py +++ b/distutils/tests/test_dist.py @@ -69,7 +69,7 @@ def create_distribution(self, configfiles=()): def test_command_packages_unspecified(self): sys.argv.append("build") d = self.create_distribution() - self.assertEqual(d.get_command_packages(), ["distutils.command"]) + assert d.get_command_packages() == ["distutils.command"] def test_command_packages_cmdline(self): from distutils.tests.test_dist import test_dist @@ -84,13 +84,11 @@ def test_command_packages_cmdline(self): ) d = self.create_distribution() # let's actually try to load our test command: - self.assertEqual( - d.get_command_packages(), - ["distutils.command", "foo.bar", "distutils.tests"], - ) + assert d.get_command_packages() == \ + ["distutils.command", "foo.bar", "distutils.tests"] cmd = d.get_command_obj("test_dist") - self.assertIsInstance(cmd, test_dist) - self.assertEqual(cmd.sample_option, "sometext") + assert isinstance(cmd, test_dist) + assert cmd.sample_option == "sometext" @unittest.skipIf( 'distutils' not in Distribution.parse_config_files.__module__, @@ -145,19 +143,17 @@ def test_venv_install_options(self): 'root': option_tuple, } - self.assertEqual( - sorted(d.command_options.get('install').keys()), sorted(result_dict.keys()) - ) + assert sorted(d.command_options.get('install').keys()) == sorted(result_dict.keys()) for (key, value) in d.command_options.get('install').items(): - self.assertEqual(value, result_dict[key]) + assert value == result_dict[key] # Test case: In a Virtual Environment with mock.patch.multiple(sys, prefix='/a', base_prefix='/b'): d = self.create_distribution([TESTFN]) for key in result_dict.keys(): - self.assertNotIn(key, d.command_options.get('install', {})) + assert key not in d.command_options.get('install', {}) def test_command_packages_configfile(self): sys.argv.append("build") @@ -170,20 +166,18 @@ def test_command_packages_configfile(self): f.close() d = self.create_distribution([TESTFN]) - self.assertEqual( - d.get_command_packages(), ["distutils.command", "foo.bar", "splat"] - ) + assert d.get_command_packages() == ["distutils.command", "foo.bar", "splat"] # ensure command line overrides config: sys.argv[1:] = ["--command-packages", "spork", "build"] d = self.create_distribution([TESTFN]) - self.assertEqual(d.get_command_packages(), ["distutils.command", "spork"]) + assert d.get_command_packages() == ["distutils.command", "spork"] # Setting --command-packages to '' should cause the default to # be used even if a config file specified something else: sys.argv[1:] = ["--command-packages", "", "build"] d = self.create_distribution([TESTFN]) - self.assertEqual(d.get_command_packages(), ["distutils.command"]) + assert d.get_command_packages() == ["distutils.command"] def test_empty_options(self): # an empty options dictionary should not stay in the @@ -207,8 +201,8 @@ def _warn(msg): } ) - self.assertEqual(len(warns), 0) - self.assertNotIn('options', dir(dist)) + assert len(warns) == 0 + assert 'options' not in dir(dist) def test_finalize_options(self): attrs = {'keywords': 'one,two', 'platforms': 'one,two'} @@ -217,32 +211,33 @@ def test_finalize_options(self): dist.finalize_options() # finalize_option splits platforms and keywords - self.assertEqual(dist.metadata.platforms, ['one', 'two']) - self.assertEqual(dist.metadata.keywords, ['one', 'two']) + assert dist.metadata.platforms == ['one', 'two'] + assert dist.metadata.keywords == ['one', 'two'] attrs = {'keywords': 'foo bar', 'platforms': 'foo bar'} dist = Distribution(attrs=attrs) dist.finalize_options() - self.assertEqual(dist.metadata.platforms, ['foo bar']) - self.assertEqual(dist.metadata.keywords, ['foo bar']) + assert dist.metadata.platforms == ['foo bar'] + assert dist.metadata.keywords == ['foo bar'] def test_get_command_packages(self): dist = Distribution() - self.assertEqual(dist.command_packages, None) + assert dist.command_packages == None cmds = dist.get_command_packages() - self.assertEqual(cmds, ['distutils.command']) - self.assertEqual(dist.command_packages, ['distutils.command']) + assert cmds == ['distutils.command'] + assert dist.command_packages == ['distutils.command'] dist.command_packages = 'one,two' cmds = dist.get_command_packages() - self.assertEqual(cmds, ['distutils.command', 'one', 'two']) + assert cmds == ['distutils.command', 'one', 'two'] def test_announce(self): # make sure the level is known dist = Distribution() args = ('ok',) kwargs = {'level': 'ok2'} - self.assertRaises(ValueError, dist.announce, args, kwargs) + with pytest.raises(ValueError): + dist.announce(args, kwargs) def test_find_config_files_disable(self): # Ticket #1180: Allow user to disable their home config file. @@ -270,7 +265,7 @@ def _expander(path): os.path.expanduser = old_expander # make sure --no-user-cfg disables the user cfg file - self.assertEqual(len(all_files) - 1, len(files)) + assert len(all_files) - 1 == len(files) @pytest.mark.usefixtures('save_env') @@ -293,10 +288,10 @@ def test_simple_metadata(self): attrs = {"name": "package", "version": "1.0"} dist = Distribution(attrs) meta = self.format_metadata(dist) - self.assertIn("Metadata-Version: 1.0", meta) - self.assertNotIn("provides:", meta.lower()) - self.assertNotIn("requires:", meta.lower()) - self.assertNotIn("obsoletes:", meta.lower()) + assert "Metadata-Version: 1.0" in meta + assert "provides:" not in meta.lower() + assert "requires:" not in meta.lower() + assert "obsoletes:" not in meta.lower() def test_provides(self): attrs = { @@ -305,19 +300,16 @@ def test_provides(self): "provides": ["package", "package.sub"], } dist = Distribution(attrs) - self.assertEqual(dist.metadata.get_provides(), ["package", "package.sub"]) - self.assertEqual(dist.get_provides(), ["package", "package.sub"]) + assert dist.metadata.get_provides() == ["package", "package.sub"] + assert dist.get_provides() == ["package", "package.sub"] meta = self.format_metadata(dist) - self.assertIn("Metadata-Version: 1.1", meta) - self.assertNotIn("requires:", meta.lower()) - self.assertNotIn("obsoletes:", meta.lower()) + assert "Metadata-Version: 1.1" in meta + assert "requires:" not in meta.lower() + assert "obsoletes:" not in meta.lower() def test_provides_illegal(self): - self.assertRaises( - ValueError, - Distribution, - {"name": "package", "version": "1.0", "provides": ["my.pkg (splat)"]}, - ) + with pytest.raises(ValueError): + Distribution({"name": "package", "version": "1.0", "provides": ["my.pkg (splat)"]},) def test_requires(self): attrs = { @@ -326,26 +318,23 @@ def test_requires(self): "requires": ["other", "another (==1.0)"], } dist = Distribution(attrs) - self.assertEqual(dist.metadata.get_requires(), ["other", "another (==1.0)"]) - self.assertEqual(dist.get_requires(), ["other", "another (==1.0)"]) + assert dist.metadata.get_requires() == ["other", "another (==1.0)"] + assert dist.get_requires() == ["other", "another (==1.0)"] meta = self.format_metadata(dist) - self.assertIn("Metadata-Version: 1.1", meta) - self.assertNotIn("provides:", meta.lower()) - self.assertIn("Requires: other", meta) - self.assertIn("Requires: another (==1.0)", meta) - self.assertNotIn("obsoletes:", meta.lower()) + assert "Metadata-Version: 1.1" in meta + assert "provides:" not in meta.lower() + assert "Requires: other" in meta + assert "Requires: another (==1.0)" in meta + assert "obsoletes:" not in meta.lower() def test_requires_illegal(self): - self.assertRaises( - ValueError, - Distribution, - {"name": "package", "version": "1.0", "requires": ["my.pkg (splat)"]}, - ) + with pytest.raises(ValueError): + Distribution({"name": "package", "version": "1.0", "requires": ["my.pkg (splat)"]},) def test_requires_to_list(self): attrs = {"name": "package", "requires": iter(["other"])} dist = Distribution(attrs) - self.assertIsInstance(dist.metadata.requires, list) + assert isinstance(dist.metadata.requires, list) def test_obsoletes(self): attrs = { @@ -354,26 +343,23 @@ def test_obsoletes(self): "obsoletes": ["other", "another (<1.0)"], } dist = Distribution(attrs) - self.assertEqual(dist.metadata.get_obsoletes(), ["other", "another (<1.0)"]) - self.assertEqual(dist.get_obsoletes(), ["other", "another (<1.0)"]) + assert dist.metadata.get_obsoletes() == ["other", "another (<1.0)"] + assert dist.get_obsoletes() == ["other", "another (<1.0)"] meta = self.format_metadata(dist) - self.assertIn("Metadata-Version: 1.1", meta) - self.assertNotIn("provides:", meta.lower()) - self.assertNotIn("requires:", meta.lower()) - self.assertIn("Obsoletes: other", meta) - self.assertIn("Obsoletes: another (<1.0)", meta) + assert "Metadata-Version: 1.1" in meta + assert "provides:" not in meta.lower() + assert "requires:" not in meta.lower() + assert "Obsoletes: other" in meta + assert "Obsoletes: another (<1.0)" in meta def test_obsoletes_illegal(self): - self.assertRaises( - ValueError, - Distribution, - {"name": "package", "version": "1.0", "obsoletes": ["my.pkg (splat)"]}, - ) + with pytest.raises(ValueError): + Distribution({"name": "package", "version": "1.0", "obsoletes": ["my.pkg (splat)"]},) def test_obsoletes_to_list(self): attrs = {"name": "package", "obsoletes": iter(["other"])} dist = Distribution(attrs) - self.assertIsInstance(dist.metadata.obsoletes, list) + assert isinstance(dist.metadata.obsoletes, list) def test_classifier(self): attrs = { @@ -382,11 +368,9 @@ def test_classifier(self): 'classifiers': ['Programming Language :: Python :: 3'], } dist = Distribution(attrs) - self.assertEqual( - dist.get_classifiers(), ['Programming Language :: Python :: 3'] - ) + assert dist.get_classifiers() == ['Programming Language :: Python :: 3'] meta = self.format_metadata(dist) - self.assertIn('Metadata-Version: 1.1', meta) + assert 'Metadata-Version: 1.1' in meta def test_classifier_invalid_type(self): attrs = { @@ -397,10 +381,10 @@ def test_classifier_invalid_type(self): with captured_stderr() as error: d = Distribution(attrs) # should have warning about passing a non-list - self.assertIn('should be a list', error.getvalue()) + assert 'should be a list' in error.getvalue() # should be converted to a list - self.assertIsInstance(d.metadata.classifiers, list) - self.assertEqual(d.metadata.classifiers, list(attrs['classifiers'])) + assert isinstance(d.metadata.classifiers, list) + assert d.metadata.classifiers == list(attrs['classifiers']) def test_keywords(self): attrs = { @@ -409,7 +393,7 @@ def test_keywords(self): 'keywords': ['spam', 'eggs', 'life of brian'], } dist = Distribution(attrs) - self.assertEqual(dist.get_keywords(), ['spam', 'eggs', 'life of brian']) + assert dist.get_keywords() == ['spam', 'eggs', 'life of brian'] def test_keywords_invalid_type(self): attrs = { @@ -420,10 +404,10 @@ def test_keywords_invalid_type(self): with captured_stderr() as error: d = Distribution(attrs) # should have warning about passing a non-list - self.assertIn('should be a list', error.getvalue()) + assert 'should be a list' in error.getvalue() # should be converted to a list - self.assertIsInstance(d.metadata.keywords, list) - self.assertEqual(d.metadata.keywords, list(attrs['keywords'])) + assert isinstance(d.metadata.keywords, list) + assert d.metadata.keywords == list(attrs['keywords']) def test_platforms(self): attrs = { @@ -432,7 +416,7 @@ def test_platforms(self): 'platforms': ['GNU/Linux', 'Some Evil Platform'], } dist = Distribution(attrs) - self.assertEqual(dist.get_platforms(), ['GNU/Linux', 'Some Evil Platform']) + assert dist.get_platforms() == ['GNU/Linux', 'Some Evil Platform'] def test_platforms_invalid_types(self): attrs = { @@ -443,10 +427,10 @@ def test_platforms_invalid_types(self): with captured_stderr() as error: d = Distribution(attrs) # should have warning about passing a non-list - self.assertIn('should be a list', error.getvalue()) + assert 'should be a list' in error.getvalue() # should be converted to a list - self.assertIsInstance(d.metadata.platforms, list) - self.assertEqual(d.metadata.platforms, list(attrs['platforms'])) + assert isinstance(d.metadata.platforms, list) + assert d.metadata.platforms == list(attrs['platforms']) def test_download_url(self): attrs = { @@ -456,7 +440,7 @@ def test_download_url(self): } dist = Distribution(attrs) meta = self.format_metadata(dist) - self.assertIn('Metadata-Version: 1.1', meta) + assert 'Metadata-Version: 1.1' in meta def test_long_description(self): long_desc = textwrap.dedent( @@ -471,7 +455,7 @@ def test_long_description(self): dist = Distribution(attrs) meta = self.format_metadata(dist) meta = meta.replace('\n' + 8 * ' ', '\n') - self.assertIn(long_desc, meta) + assert long_desc in meta def test_custom_pydistutils(self): # fixes #2166 @@ -496,24 +480,22 @@ def test_custom_pydistutils(self): if sys.platform in ('linux', 'darwin'): os.environ['HOME'] = temp_dir files = dist.find_config_files() - self.assertIn(user_filename, files) + assert user_filename in files # win32-style if sys.platform == 'win32': # home drive should be found os.environ['USERPROFILE'] = temp_dir files = dist.find_config_files() - self.assertIn( - user_filename, files, '{!r} not found in {!r}'.format(user_filename, files) - ) + assert user_filename in files, '{!r} not found in {!r}'.format(user_filename, files) finally: os.remove(user_filename) def test_fix_help_options(self): help_tuples = [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] fancy_options = fix_help_options(help_tuples) - self.assertEqual(fancy_options[0], ('a', 'b', 'c')) - self.assertEqual(fancy_options[1], (1, 2, 3)) + assert fancy_options[0] == ('a', 'b', 'c') + assert fancy_options[1] == (1, 2, 3) def test_show_help(self): # smoke test, just makes sure some help is displayed @@ -526,7 +508,7 @@ def test_show_help(self): dist.parse_command_line() output = [line for line in s.getvalue().split('\n') if line.strip() != ''] - self.assertTrue(output) + assert output def test_read_metadata(self): attrs = { @@ -548,11 +530,11 @@ def test_read_metadata(self): PKG_INFO.seek(0) metadata.read_pkg_file(PKG_INFO) - self.assertEqual(metadata.name, "package") - self.assertEqual(metadata.version, "1.0") - self.assertEqual(metadata.description, "xxx") - self.assertEqual(metadata.download_url, 'http://example.com') - self.assertEqual(metadata.keywords, ['one', 'two']) - self.assertEqual(metadata.platforms, None) - self.assertEqual(metadata.obsoletes, None) - self.assertEqual(metadata.requires, ['foo']) + assert metadata.name == "package" + assert metadata.version == "1.0" + assert metadata.description == "xxx" + assert metadata.download_url == 'http://example.com' + assert metadata.keywords == ['one', 'two'] + assert metadata.platforms == None + assert metadata.obsoletes == None + assert metadata.requires == ['foo'] diff --git a/distutils/tests/test_extension.py b/distutils/tests/test_extension.py index bf5739304c..67de503f7c 100644 --- a/distutils/tests/test_extension.py +++ b/distutils/tests/test_extension.py @@ -6,6 +6,7 @@ from distutils.extension import read_setup_file, Extension from .py38compat import check_warnings +import pytest class ExtensionTestCase(unittest.TestCase): @@ -57,20 +58,23 @@ def test_read_setup_file(self): 'transform', ] - self.assertEqual(names, wanted) + assert names == wanted def test_extension_init(self): # the first argument, which is the name, must be a string - self.assertRaises(AssertionError, Extension, 1, []) + with pytest.raises(AssertionError): + Extension(1, []) ext = Extension('name', []) - self.assertEqual(ext.name, 'name') + assert ext.name == 'name' # the second argument, which is the list of files, must # be a list of strings - self.assertRaises(AssertionError, Extension, 'name', 'file') - self.assertRaises(AssertionError, Extension, 'name', ['file', 1]) + with pytest.raises(AssertionError): + Extension('name', 'file') + with pytest.raises(AssertionError): + Extension('name', ['file', 1]) ext = Extension('name', ['file1', 'file2']) - self.assertEqual(ext.sources, ['file1', 'file2']) + assert ext.sources == ['file1', 'file2'] # others arguments have defaults for attr in ( @@ -87,17 +91,15 @@ def test_extension_init(self): 'swig_opts', 'depends', ): - self.assertEqual(getattr(ext, attr), []) + assert getattr(ext, attr) == [] - self.assertEqual(ext.language, None) - self.assertEqual(ext.optional, None) + assert ext.language == None + assert ext.optional == None # if there are unknown keyword options, warn about them with check_warnings() as w: warnings.simplefilter('always') ext = Extension('name', ['file1', 'file2'], chic=True) - self.assertEqual(len(w.warnings), 1) - self.assertEqual( - str(w.warnings[0].message), "Unknown Extension options: 'chic'" - ) + assert len(w.warnings) == 1 + assert str(w.warnings[0].message) == "Unknown Extension options: 'chic'" diff --git a/distutils/tests/test_file_util.py b/distutils/tests/test_file_util.py index 8bd573056d..88fb5b8ce8 100644 --- a/distutils/tests/test_file_util.py +++ b/distutils/tests/test_file_util.py @@ -9,6 +9,7 @@ from distutils.tests import support from distutils.errors import DistutilsFileError from .py38compat import unlink +import pytest class FileUtilTestCase(support.TempdirManager, unittest.TestCase): @@ -41,14 +42,14 @@ def test_move_file_verbosity(self): move_file(self.source, self.target, verbose=0) wanted = [] - self.assertEqual(self._logs, wanted) + assert self._logs == wanted # back to original state move_file(self.target, self.source, verbose=0) move_file(self.source, self.target, verbose=1) wanted = ['moving {} -> {}'.format(self.source, self.target)] - self.assertEqual(self._logs, wanted) + assert self._logs == wanted # back to original state move_file(self.target, self.source, verbose=0) @@ -58,13 +59,11 @@ def test_move_file_verbosity(self): os.mkdir(self.target_dir) move_file(self.source, self.target_dir, verbose=1) wanted = ['moving {} -> {}'.format(self.source, self.target_dir)] - self.assertEqual(self._logs, wanted) + assert self._logs == wanted def test_move_file_exception_unpacking_rename(self): # see issue 22182 - with patch("os.rename", side_effect=OSError("wrong", 1)), self.assertRaises( - DistutilsFileError - ): + with patch("os.rename", side_effect=OSError("wrong", 1)), pytest.raises(DistutilsFileError): with open(self.source, 'w') as fobj: fobj.write('spam eggs') move_file(self.source, self.target, verbose=0) @@ -73,7 +72,7 @@ def test_move_file_exception_unpacking_unlink(self): # see issue 22182 with patch("os.rename", side_effect=OSError(errno.EXDEV, "wrong")), patch( "os.unlink", side_effect=OSError("wrong", 1) - ), self.assertRaises(DistutilsFileError): + ), pytest.raises(DistutilsFileError): with open(self.source, 'w') as fobj: fobj.write('spam eggs') move_file(self.source, self.target, verbose=0) @@ -93,10 +92,10 @@ def test_copy_file_hard_link(self): copy_file(self.source, self.target, link='hard') st2 = os.stat(self.source) st3 = os.stat(self.target) - self.assertTrue(os.path.samestat(st, st2), (st, st2)) - self.assertTrue(os.path.samestat(st2, st3), (st2, st3)) + assert os.path.samestat(st, st2), (st, st2) + assert os.path.samestat(st2, st3), (st2, st3) with open(self.source) as f: - self.assertEqual(f.read(), 'some content') + assert f.read() == 'some content' def test_copy_file_hard_link_failure(self): # If hard linking fails, copy_file() falls back on copying file @@ -109,8 +108,8 @@ def test_copy_file_hard_link_failure(self): copy_file(self.source, self.target, link='hard') st2 = os.stat(self.source) st3 = os.stat(self.target) - self.assertTrue(os.path.samestat(st, st2), (st, st2)) - self.assertFalse(os.path.samestat(st2, st3), (st2, st3)) + assert os.path.samestat(st, st2), (st, st2) + assert not os.path.samestat(st2, st3), (st2, st3) for fn in (self.source, self.target): with open(fn) as f: - self.assertEqual(f.read(), 'some content') + assert f.read() == 'some content' diff --git a/distutils/tests/test_filelist.py b/distutils/tests/test_filelist.py index 0673139e6d..a01a59351d 100644 --- a/distutils/tests/test_filelist.py +++ b/distutils/tests/test_filelist.py @@ -12,6 +12,7 @@ from distutils.tests import support from . import py38compat as os_helper +import pytest MANIFEST_IN = """\ @@ -37,11 +38,11 @@ def make_local_path(s): class FileListTestCase(support.LoggingSilencer, unittest.TestCase): def assertNoWarnings(self): - self.assertEqual(self.get_logs(WARN), []) + assert self.get_logs(WARN) == [] self.clear_logs() def assertWarnings(self): - self.assertGreater(len(self.get_logs(WARN)), 0) + assert len(self.get_logs(WARN)) > 0 self.clear_logs() def test_glob_to_re(self): @@ -61,7 +62,7 @@ def test_glob_to_re(self): (r'foo\\??', r'(?s:foo\\\\[^%(sep)s][^%(sep)s])\Z'), ): regex = regex % {'sep': sep} - self.assertEqual(glob_to_re(glob), regex) + assert glob_to_re(glob) == regex def test_process_template_line(self): # testing all MANIFEST.in template patterns @@ -106,19 +107,19 @@ def test_process_template_line(self): mlp('dir/dir2/graft2'), ] - self.assertEqual(file_list.files, wanted) + assert file_list.files == wanted def test_debug_print(self): file_list = FileList() with captured_stdout() as stdout: file_list.debug_print('xxx') - self.assertEqual(stdout.getvalue(), '') + assert stdout.getvalue() == '' debug.DEBUG = True try: with captured_stdout() as stdout: file_list.debug_print('xxx') - self.assertEqual(stdout.getvalue(), 'xxx\n') + assert stdout.getvalue() == 'xxx\n' finally: debug.DEBUG = False @@ -126,7 +127,7 @@ def test_set_allfiles(self): file_list = FileList() files = ['a', 'b', 'c'] file_list.set_allfiles(files) - self.assertEqual(file_list.allfiles, files) + assert file_list.allfiles == files def test_remove_duplicates(self): file_list = FileList() @@ -134,61 +135,55 @@ def test_remove_duplicates(self): # files must be sorted beforehand (sdist does it) file_list.sort() file_list.remove_duplicates() - self.assertEqual(file_list.files, ['a', 'b', 'c', 'g']) + assert file_list.files == ['a', 'b', 'c', 'g'] def test_translate_pattern(self): # not regex - self.assertTrue( - hasattr(translate_pattern('a', anchor=True, is_regex=False), 'search') - ) + assert hasattr(translate_pattern('a', anchor=True, is_regex=False), 'search') # is a regex regex = re.compile('a') - self.assertEqual(translate_pattern(regex, anchor=True, is_regex=True), regex) + assert translate_pattern(regex, anchor=True, is_regex=True) == regex # plain string flagged as regex - self.assertTrue( - hasattr(translate_pattern('a', anchor=True, is_regex=True), 'search') - ) + assert hasattr(translate_pattern('a', anchor=True, is_regex=True), 'search') # glob support - self.assertTrue( - translate_pattern('*.py', anchor=True, is_regex=False).search('filelist.py') - ) + assert translate_pattern('*.py', anchor=True, is_regex=False).search('filelist.py') def test_exclude_pattern(self): # return False if no match file_list = FileList() - self.assertFalse(file_list.exclude_pattern('*.py')) + assert not file_list.exclude_pattern('*.py') # return True if files match file_list = FileList() file_list.files = ['a.py', 'b.py'] - self.assertTrue(file_list.exclude_pattern('*.py')) + assert file_list.exclude_pattern('*.py') # test excludes file_list = FileList() file_list.files = ['a.py', 'a.txt'] file_list.exclude_pattern('*.py') - self.assertEqual(file_list.files, ['a.txt']) + assert file_list.files == ['a.txt'] def test_include_pattern(self): # return False if no match file_list = FileList() file_list.set_allfiles([]) - self.assertFalse(file_list.include_pattern('*.py')) + assert not file_list.include_pattern('*.py') # return True if files match file_list = FileList() file_list.set_allfiles(['a.py', 'b.txt']) - self.assertTrue(file_list.include_pattern('*.py')) + assert file_list.include_pattern('*.py') # test * matches all files file_list = FileList() - self.assertIsNone(file_list.allfiles) + assert file_list.allfiles is None file_list.set_allfiles(['a.py', 'b.txt']) file_list.include_pattern('*') - self.assertEqual(file_list.allfiles, ['a.py', 'b.txt']) + assert file_list.allfiles == ['a.py', 'b.txt'] def test_process_template(self): mlp = make_local_path @@ -205,20 +200,19 @@ def test_process_template(self): 'prune', 'blarg', ): - self.assertRaises( - DistutilsTemplateError, file_list.process_template_line, action - ) + with pytest.raises(DistutilsTemplateError): + file_list.process_template_line(action) # include file_list = FileList() file_list.set_allfiles(['a.py', 'b.txt', mlp('d/c.py')]) file_list.process_template_line('include *.py') - self.assertEqual(file_list.files, ['a.py']) + assert file_list.files == ['a.py'] self.assertNoWarnings() file_list.process_template_line('include *.rb') - self.assertEqual(file_list.files, ['a.py']) + assert file_list.files == ['a.py'] self.assertWarnings() # exclude @@ -226,11 +220,11 @@ def test_process_template(self): file_list.files = ['a.py', 'b.txt', mlp('d/c.py')] file_list.process_template_line('exclude *.py') - self.assertEqual(file_list.files, ['b.txt', mlp('d/c.py')]) + assert file_list.files == ['b.txt', mlp('d/c.py')] self.assertNoWarnings() file_list.process_template_line('exclude *.rb') - self.assertEqual(file_list.files, ['b.txt', mlp('d/c.py')]) + assert file_list.files == ['b.txt', mlp('d/c.py')] self.assertWarnings() # global-include @@ -238,11 +232,11 @@ def test_process_template(self): file_list.set_allfiles(['a.py', 'b.txt', mlp('d/c.py')]) file_list.process_template_line('global-include *.py') - self.assertEqual(file_list.files, ['a.py', mlp('d/c.py')]) + assert file_list.files == ['a.py', mlp('d/c.py')] self.assertNoWarnings() file_list.process_template_line('global-include *.rb') - self.assertEqual(file_list.files, ['a.py', mlp('d/c.py')]) + assert file_list.files == ['a.py', mlp('d/c.py')] self.assertWarnings() # global-exclude @@ -250,11 +244,11 @@ def test_process_template(self): file_list.files = ['a.py', 'b.txt', mlp('d/c.py')] file_list.process_template_line('global-exclude *.py') - self.assertEqual(file_list.files, ['b.txt']) + assert file_list.files == ['b.txt'] self.assertNoWarnings() file_list.process_template_line('global-exclude *.rb') - self.assertEqual(file_list.files, ['b.txt']) + assert file_list.files == ['b.txt'] self.assertWarnings() # recursive-include @@ -262,11 +256,11 @@ def test_process_template(self): file_list.set_allfiles(['a.py', mlp('d/b.py'), mlp('d/c.txt'), mlp('d/d/e.py')]) file_list.process_template_line('recursive-include d *.py') - self.assertEqual(file_list.files, [mlp('d/b.py'), mlp('d/d/e.py')]) + assert file_list.files == [mlp('d/b.py'), mlp('d/d/e.py')] self.assertNoWarnings() file_list.process_template_line('recursive-include e *.py') - self.assertEqual(file_list.files, [mlp('d/b.py'), mlp('d/d/e.py')]) + assert file_list.files == [mlp('d/b.py'), mlp('d/d/e.py')] self.assertWarnings() # recursive-exclude @@ -274,11 +268,11 @@ def test_process_template(self): file_list.files = ['a.py', mlp('d/b.py'), mlp('d/c.txt'), mlp('d/d/e.py')] file_list.process_template_line('recursive-exclude d *.py') - self.assertEqual(file_list.files, ['a.py', mlp('d/c.txt')]) + assert file_list.files == ['a.py', mlp('d/c.txt')] self.assertNoWarnings() file_list.process_template_line('recursive-exclude e *.py') - self.assertEqual(file_list.files, ['a.py', mlp('d/c.txt')]) + assert file_list.files == ['a.py', mlp('d/c.txt')] self.assertWarnings() # graft @@ -286,11 +280,11 @@ def test_process_template(self): file_list.set_allfiles(['a.py', mlp('d/b.py'), mlp('d/d/e.py'), mlp('f/f.py')]) file_list.process_template_line('graft d') - self.assertEqual(file_list.files, [mlp('d/b.py'), mlp('d/d/e.py')]) + assert file_list.files == [mlp('d/b.py'), mlp('d/d/e.py')] self.assertNoWarnings() file_list.process_template_line('graft e') - self.assertEqual(file_list.files, [mlp('d/b.py'), mlp('d/d/e.py')]) + assert file_list.files == [mlp('d/b.py'), mlp('d/d/e.py')] self.assertWarnings() # prune @@ -298,11 +292,11 @@ def test_process_template(self): file_list.files = ['a.py', mlp('d/b.py'), mlp('d/d/e.py'), mlp('f/f.py')] file_list.process_template_line('prune d') - self.assertEqual(file_list.files, ['a.py', mlp('f/f.py')]) + assert file_list.files == ['a.py', mlp('f/f.py')] self.assertNoWarnings() file_list.process_template_line('prune e') - self.assertEqual(file_list.files, ['a.py', mlp('f/f.py')]) + assert file_list.files == ['a.py', mlp('f/f.py')] self.assertWarnings() @@ -311,7 +305,7 @@ class FindAllTestCase(unittest.TestCase): def test_missing_symlink(self): with os_helper.temp_cwd(): os.symlink('foo', 'bar') - self.assertEqual(filelist.findall(), []) + assert filelist.findall() == [] def test_basic_discovery(self): """ @@ -327,7 +321,7 @@ def test_basic_discovery(self): file2 = os.path.join('bar', 'file2.txt') os_helper.create_empty_file(file2) expected = [file2, file1] - self.assertEqual(sorted(filelist.findall()), expected) + assert sorted(filelist.findall()) == expected def test_non_local_discovery(self): """ @@ -338,7 +332,7 @@ def test_non_local_discovery(self): file1 = os.path.join(temp_dir, 'file1.txt') os_helper.create_empty_file(file1) expected = [file1] - self.assertEqual(filelist.findall(temp_dir), expected) + assert filelist.findall(temp_dir) == expected @os_helper.skip_unless_symlink def test_symlink_loop(self): diff --git a/distutils/tests/test_install.py b/distutils/tests/test_install.py index ea68ab7400..e4a38ea45f 100644 --- a/distutils/tests/test_install.py +++ b/distutils/tests/test_install.py @@ -56,13 +56,13 @@ def test_home_installation_scheme(self): cmd.home = destination cmd.ensure_finalized() - self.assertEqual(cmd.install_base, destination) - self.assertEqual(cmd.install_platbase, destination) + assert cmd.install_base == destination + assert cmd.install_platbase == destination def check_path(got, expected): got = os.path.normpath(got) expected = os.path.normpath(expected) - self.assertEqual(got, expected) + assert got == expected impl_name = sys.implementation.name.replace("cpython", "python") libdir = os.path.join(destination, "lib", impl_name) @@ -109,31 +109,31 @@ def cleanup(): self.addCleanup(cleanup) for key in ('nt_user', 'posix_user'): - self.assertIn(key, INSTALL_SCHEMES) + assert key in INSTALL_SCHEMES dist = Distribution({'name': 'xx'}) cmd = install(dist) # making sure the user option is there options = [name for name, short, lable in cmd.user_options] - self.assertIn('user', options) + assert 'user' in options # setting a value cmd.user = 1 # user base and site shouldn't be created yet - self.assertFalse(os.path.exists(self.user_base)) - self.assertFalse(os.path.exists(self.user_site)) + assert not os.path.exists(self.user_base) + assert not os.path.exists(self.user_site) # let's run finalize cmd.ensure_finalized() # now they should - self.assertTrue(os.path.exists(self.user_base)) - self.assertTrue(os.path.exists(self.user_site)) + assert os.path.exists(self.user_base) + assert os.path.exists(self.user_site) - self.assertIn('userbase', cmd.config_vars) - self.assertIn('usersite', cmd.config_vars) + assert 'userbase' in cmd.config_vars + assert 'usersite' in cmd.config_vars actual_headers = os.path.relpath(cmd.install_headers, self.user_base) if os.name == 'nt': @@ -145,9 +145,7 @@ def cleanup(): include = sysconfig.get_python_inc(0, '') expect_headers = os.path.join(include, 'xx') - self.assertEqual( - os.path.normcase(actual_headers), os.path.normcase(expect_headers) - ) + assert os.path.normcase(actual_headers) == os.path.normcase(expect_headers) def test_handle_extra_path(self): dist = Distribution({'name': 'xx', 'extra_path': 'path,dirs'}) @@ -155,27 +153,28 @@ def test_handle_extra_path(self): # two elements cmd.handle_extra_path() - self.assertEqual(cmd.extra_path, ['path', 'dirs']) - self.assertEqual(cmd.extra_dirs, 'dirs') - self.assertEqual(cmd.path_file, 'path') + assert cmd.extra_path == ['path', 'dirs'] + assert cmd.extra_dirs == 'dirs' + assert cmd.path_file == 'path' # one element cmd.extra_path = ['path'] cmd.handle_extra_path() - self.assertEqual(cmd.extra_path, ['path']) - self.assertEqual(cmd.extra_dirs, 'path') - self.assertEqual(cmd.path_file, 'path') + assert cmd.extra_path == ['path'] + assert cmd.extra_dirs == 'path' + assert cmd.path_file == 'path' # none dist.extra_path = cmd.extra_path = None cmd.handle_extra_path() - self.assertEqual(cmd.extra_path, None) - self.assertEqual(cmd.extra_dirs, '') - self.assertEqual(cmd.path_file, None) + assert cmd.extra_path == None + assert cmd.extra_dirs == '' + assert cmd.path_file == None # three elements (no way !) cmd.extra_path = 'path,dirs,again' - self.assertRaises(DistutilsOptionError, cmd.handle_extra_path) + with pytest.raises(DistutilsOptionError): + cmd.handle_extra_path() def test_finalize_options(self): dist = Distribution({'name': 'xx'}) @@ -185,18 +184,21 @@ def test_finalize_options(self): # install-base/install-platbase -- not both cmd.prefix = 'prefix' cmd.install_base = 'base' - self.assertRaises(DistutilsOptionError, cmd.finalize_options) + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() # must supply either home or prefix/exec-prefix -- not both cmd.install_base = None cmd.home = 'home' - self.assertRaises(DistutilsOptionError, cmd.finalize_options) + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() # can't combine user with prefix/exec_prefix/home or # install_(plat)base cmd.prefix = None cmd.user = 'user' - self.assertRaises(DistutilsOptionError, cmd.finalize_options) + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() def test_record(self): install_dir = self.mkdtemp() @@ -225,7 +227,7 @@ def test_record(self): 'sayhi', 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2], ] - self.assertEqual(found, expected) + assert found == expected def test_record_extensions(self): cmd = test_support.missing_compiler_executable() @@ -261,7 +263,7 @@ def test_record_extensions(self): _make_ext_name('xx'), 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2], ] - self.assertEqual(found, expected) + assert found == expected def test_debug_mode(self): # this covers the code called when DEBUG is set @@ -272,4 +274,4 @@ def test_debug_mode(self): self.test_record() finally: install_module.DEBUG = False - self.assertGreater(len(self.logs), old_logs_len) + assert len(self.logs) > old_logs_len diff --git a/distutils/tests/test_install_data.py b/distutils/tests/test_install_data.py index a66e5d406f..33e0de64b2 100644 --- a/distutils/tests/test_install_data.py +++ b/distutils/tests/test_install_data.py @@ -29,18 +29,18 @@ def test_simple_run(self): self.write_file(two, 'xxx') cmd.data_files = [one, (inst2, [two])] - self.assertEqual(cmd.get_inputs(), [one, (inst2, [two])]) + assert cmd.get_inputs() == [one, (inst2, [two])] # let's run the command cmd.ensure_finalized() cmd.run() # let's check the result - self.assertEqual(len(cmd.get_outputs()), 2) + assert len(cmd.get_outputs()) == 2 rtwo = os.path.split(two)[-1] - self.assertTrue(os.path.exists(os.path.join(inst2, rtwo))) + assert os.path.exists(os.path.join(inst2, rtwo)) rone = os.path.split(one)[-1] - self.assertTrue(os.path.exists(os.path.join(inst, rone))) + assert os.path.exists(os.path.join(inst, rone)) cmd.outfiles = [] # let's try with warn_dir one @@ -49,9 +49,9 @@ def test_simple_run(self): cmd.run() # let's check the result - self.assertEqual(len(cmd.get_outputs()), 2) - self.assertTrue(os.path.exists(os.path.join(inst2, rtwo))) - self.assertTrue(os.path.exists(os.path.join(inst, rone))) + assert len(cmd.get_outputs()) == 2 + assert os.path.exists(os.path.join(inst2, rtwo)) + assert os.path.exists(os.path.join(inst, rone)) cmd.outfiles = [] # now using root and empty dir @@ -64,6 +64,6 @@ def test_simple_run(self): cmd.run() # let's check the result - self.assertEqual(len(cmd.get_outputs()), 4) - self.assertTrue(os.path.exists(os.path.join(inst2, rtwo))) - self.assertTrue(os.path.exists(os.path.join(inst, rone))) + assert len(cmd.get_outputs()) == 4 + assert os.path.exists(os.path.join(inst2, rtwo)) + assert os.path.exists(os.path.join(inst, rone)) diff --git a/distutils/tests/test_install_headers.py b/distutils/tests/test_install_headers.py index 9029f7e45a..e91fe14ca0 100644 --- a/distutils/tests/test_install_headers.py +++ b/distutils/tests/test_install_headers.py @@ -25,7 +25,7 @@ def test_simple_run(self): pkg_dir, dist = self.create_dist(headers=headers) cmd = install_headers(dist) - self.assertEqual(cmd.get_inputs(), headers) + assert cmd.get_inputs() == headers # let's run the command cmd.install_dir = os.path.join(pkg_dir, 'inst') @@ -33,4 +33,4 @@ def test_simple_run(self): cmd.run() # let's check the results - self.assertEqual(len(cmd.get_outputs()), 2) + assert len(cmd.get_outputs()) == 2 diff --git a/distutils/tests/test_install_lib.py b/distutils/tests/test_install_lib.py index 8c5709c262..601a81ff98 100644 --- a/distutils/tests/test_install_lib.py +++ b/distutils/tests/test_install_lib.py @@ -24,18 +24,20 @@ def test_finalize_options(self): cmd = install_lib(dist) cmd.finalize_options() - self.assertEqual(cmd.compile, 1) - self.assertEqual(cmd.optimize, 0) + assert cmd.compile == 1 + assert cmd.optimize == 0 # optimize must be 0, 1, or 2 cmd.optimize = 'foo' - self.assertRaises(DistutilsOptionError, cmd.finalize_options) + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() cmd.optimize = '4' - self.assertRaises(DistutilsOptionError, cmd.finalize_options) + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() cmd.optimize = '2' cmd.finalize_options() - self.assertEqual(cmd.optimize, 2) + assert cmd.optimize == 2 @unittest.skipIf(sys.dont_write_bytecode, 'byte-compile disabled') def test_byte_compile(self): @@ -51,8 +53,8 @@ def test_byte_compile(self): pyc_opt_file = importlib.util.cache_from_source( 'foo.py', optimization=cmd.optimize ) - self.assertTrue(os.path.exists(pyc_file)) - self.assertTrue(os.path.exists(pyc_opt_file)) + assert os.path.exists(pyc_file) + assert os.path.exists(pyc_opt_file) def test_get_outputs(self): project_dir, dist = self.create_dist() @@ -72,7 +74,7 @@ def test_get_outputs(self): # get_outputs should return 4 elements: spam/__init__.py and .pyc, # foo.import-tag-abiflags.so / foo.pyd outputs = cmd.get_outputs() - self.assertEqual(len(outputs), 4, outputs) + assert len(outputs) == 4, outputs def test_get_inputs(self): project_dir, dist = self.create_dist() @@ -92,7 +94,7 @@ def test_get_inputs(self): # get_inputs should return 2 elements: spam/__init__.py and # foo.import-tag-abiflags.so / foo.pyd inputs = cmd.get_inputs() - self.assertEqual(len(inputs), 2, inputs) + assert len(inputs) == 2, inputs def test_dont_write_bytecode(self): # makes sure byte_compile is not used @@ -108,4 +110,4 @@ def test_dont_write_bytecode(self): finally: sys.dont_write_bytecode = old_dont_write_bytecode - self.assertIn('byte-compiling is disabled', self.logs[0][1] % self.logs[0][2]) + assert 'byte-compiling is disabled' in self.logs[0][1] % self.logs[0][2] diff --git a/distutils/tests/test_install_scripts.py b/distutils/tests/test_install_scripts.py index 2b19d73630..8c69c646d0 100644 --- a/distutils/tests/test_install_scripts.py +++ b/distutils/tests/test_install_scripts.py @@ -21,17 +21,17 @@ def test_default_settings(self): skip_build=1, ) cmd = install_scripts(dist) - self.assertFalse(cmd.force) - self.assertFalse(cmd.skip_build) - self.assertIsNone(cmd.build_dir) - self.assertIsNone(cmd.install_dir) + assert not cmd.force + assert not cmd.skip_build + assert cmd.build_dir is None + assert cmd.install_dir is None cmd.finalize_options() - self.assertTrue(cmd.force) - self.assertTrue(cmd.skip_build) - self.assertEqual(cmd.build_dir, "/foo/bar") - self.assertEqual(cmd.install_dir, "/splat/funk") + assert cmd.force + assert cmd.skip_build + assert cmd.build_dir == "/foo/bar" + assert cmd.install_dir == "/splat/funk" def test_installation(self): source = self.mkdtemp() @@ -75,4 +75,4 @@ def write_script(name, text): installed = os.listdir(target) for name in expected: - self.assertIn(name, installed) + assert name in installed diff --git a/distutils/tests/test_log.py b/distutils/tests/test_log.py index 4a5c5a05c0..61e4e9bf96 100644 --- a/distutils/tests/test_log.py +++ b/distutils/tests/test_log.py @@ -34,20 +34,16 @@ def test_non_ascii(self): log.set_threshold(old_threshold) stdout.seek(0) - self.assertEqual( - stdout.read().rstrip(), - 'Dεbug\tM?ss?ge' + assert stdout.read().rstrip() == \ + ('Dεbug\tM?ss?ge' if errors == 'replace' else 'Dεbug\tMssge' if errors == 'ignore' - else 'Dεbug\tM\\u0117ss\\xe3ge', - ) + else 'Dεbug\tM\\u0117ss\\xe3ge') stderr.seek(0) - self.assertEqual( - stderr.read().rstrip(), - 'Fαtal\t?rr?r' + assert stderr.read().rstrip() == \ + ('Fαtal\t?rr?r' if errors == 'replace' else 'Fαtal\trrr' if errors == 'ignore' - else 'Fαtal\t\\xc8rr\\u014dr', - ) + else 'Fαtal\t\\xc8rr\\u014dr') diff --git a/distutils/tests/test_msvc9compiler.py b/distutils/tests/test_msvc9compiler.py index 11a45557ac..3cfd3ac98e 100644 --- a/distutils/tests/test_msvc9compiler.py +++ b/distutils/tests/test_msvc9compiler.py @@ -5,6 +5,7 @@ from distutils.errors import DistutilsPlatformError from distutils.tests import support +import pytest # A manifest with the only assembly reference being the msvcrt assembly, so # should have the assembly completely stripped. Note that although the @@ -116,31 +117,31 @@ def _find_vcvarsall(version): old_find_vcvarsall = msvc9compiler.find_vcvarsall msvc9compiler.find_vcvarsall = _find_vcvarsall try: - self.assertRaises( - DistutilsPlatformError, query_vcvarsall, 'wont find this version' - ) + with pytest.raises(DistutilsPlatformError): + query_vcvarsall('wont find this version') finally: msvc9compiler.find_vcvarsall = old_find_vcvarsall def test_reg_class(self): from distutils.msvc9compiler import Reg - self.assertRaises(KeyError, Reg.get_value, 'xxx', 'xxx') + with pytest.raises(KeyError): + Reg.get_value('xxx', 'xxx') # looking for values that should exist on all # windows registry versions. path = r'Control Panel\Desktop' v = Reg.get_value(path, 'dragfullwindows') - self.assertIn(v, ('0', '1', '2')) + assert v in ('0', '1', '2') import winreg HKCU = winreg.HKEY_CURRENT_USER keys = Reg.read_keys(HKCU, 'xxxx') - self.assertEqual(keys, None) + assert keys == None keys = Reg.read_keys(HKCU, r'Control Panel') - self.assertIn('Desktop', keys) + assert 'Desktop' in keys def test_remove_visual_c_ref(self): from distutils.msvc9compiler import MSVCCompiler @@ -165,7 +166,7 @@ def test_remove_visual_c_ref(self): f.close() # makes sure the manifest was properly cleaned - self.assertEqual(content, _CLEANED_MANIFEST) + assert content == _CLEANED_MANIFEST def test_remove_entire_manifest(self): from distutils.msvc9compiler import MSVCCompiler @@ -180,4 +181,4 @@ def test_remove_entire_manifest(self): compiler = MSVCCompiler() got = compiler._remove_visual_c_ref(manifest) - self.assertIsNone(got) + assert got is None diff --git a/distutils/tests/test_msvccompiler.py b/distutils/tests/test_msvccompiler.py index 9357a22310..22a36d0af8 100644 --- a/distutils/tests/test_msvccompiler.py +++ b/distutils/tests/test_msvccompiler.py @@ -25,11 +25,8 @@ def _find_vcvarsall(plat_spec): old_find_vcvarsall = _msvccompiler._find_vcvarsall _msvccompiler._find_vcvarsall = _find_vcvarsall try: - self.assertRaises( - DistutilsPlatformError, - _msvccompiler._get_vc_env, - 'wont find this version', - ) + with pytest.raises(DistutilsPlatformError): + _msvccompiler._get_vc_env('wont find this version',) finally: _msvccompiler._find_vcvarsall = old_find_vcvarsall @@ -43,8 +40,8 @@ def test_get_vc_env_unicode(self): os.environ[test_var] = test_value try: env = _msvccompiler._get_vc_env('x86') - self.assertIn(test_var.lower(), env) - self.assertEqual(test_value, env[test_var.lower()]) + assert test_var.lower() in env + assert test_value == env[test_var.lower()] finally: os.environ.pop(test_var) if old_distutils_use_sdk: @@ -56,8 +53,8 @@ def test_get_vc2017(self): # and mark it skipped if we do not. version, path = _msvccompiler._find_vc2017() if version: - self.assertGreaterEqual(version, 15) - self.assertTrue(os.path.isdir(path)) + assert version >= 15 + assert os.path.isdir(path) else: raise unittest.SkipTest("VS 2017 is not installed") @@ -67,8 +64,8 @@ def test_get_vc2015(self): # and mark it skipped if we do not. version, path = _msvccompiler._find_vc2015() if version: - self.assertGreaterEqual(version, 14) - self.assertTrue(os.path.isdir(path)) + assert version >= 14 + assert os.path.isdir(path) else: raise unittest.SkipTest("VS 2015 is not installed") diff --git a/distutils/tests/test_register.py b/distutils/tests/test_register.py index 2b142ad590..7657f3914f 100644 --- a/distutils/tests/test_register.py +++ b/distutils/tests/test_register.py @@ -14,6 +14,7 @@ from distutils.log import INFO from distutils.tests.test_config import BasePyPIRCCommandTestCase +import pytest try: import docutils @@ -117,7 +118,7 @@ def test_create_pypirc(self): cmd = self._get_cmd() # we shouldn't have a .pypirc file yet - self.assertFalse(os.path.exists(self.rc)) + assert not os.path.exists(self.rc) # patching input and getpass.getpass # so register gets happy @@ -136,13 +137,13 @@ def test_create_pypirc(self): del register_module.input # we should have a brand new .pypirc file - self.assertTrue(os.path.exists(self.rc)) + assert os.path.exists(self.rc) # with the content similar to WANTED_PYPIRC f = open(self.rc) try: content = f.read() - self.assertEqual(content, WANTED_PYPIRC) + assert content == WANTED_PYPIRC finally: f.close() @@ -159,13 +160,13 @@ def _no_way(prompt=''): # let's see what the server received : we should # have 2 similar requests - self.assertEqual(len(self.conn.reqs), 2) + assert len(self.conn.reqs) == 2 req1 = dict(self.conn.reqs[0].headers) req2 = dict(self.conn.reqs[1].headers) - self.assertEqual(req1['Content-length'], '1359') - self.assertEqual(req2['Content-length'], '1359') - self.assertIn(b'xxx', self.conn.reqs[1].data) + assert req1['Content-length'] == '1359' + assert req2['Content-length'] == '1359' + assert b'xxx' in self.conn.reqs[1].data def test_password_not_in_file(self): @@ -177,7 +178,7 @@ def test_password_not_in_file(self): # dist.password should be set # therefore used afterwards by other commands - self.assertEqual(cmd.distribution.password, 'password') + assert cmd.distribution.password == 'password' def test_registering(self): # this test runs choice 2 @@ -191,11 +192,11 @@ def test_registering(self): del register_module.input # we should have send a request - self.assertEqual(len(self.conn.reqs), 1) + assert len(self.conn.reqs) == 1 req = self.conn.reqs[0] headers = dict(req.headers) - self.assertEqual(headers['Content-length'], '608') - self.assertIn(b'tarek', req.data) + assert headers['Content-length'] == '608' + assert b'tarek' in req.data def test_password_reset(self): # this test runs choice 3 @@ -209,11 +210,11 @@ def test_password_reset(self): del register_module.input # we should have send a request - self.assertEqual(len(self.conn.reqs), 1) + assert len(self.conn.reqs) == 1 req = self.conn.reqs[0] headers = dict(req.headers) - self.assertEqual(headers['Content-length'], '290') - self.assertIn(b'tarek', req.data) + assert headers['Content-length'] == '290' + assert b'tarek' in req.data @unittest.skipUnless(docutils is not None, 'needs docutils') def test_strict(self): @@ -226,7 +227,8 @@ def test_strict(self): cmd = self._get_cmd({}) cmd.ensure_finalized() cmd.strict = 1 - self.assertRaises(DistutilsSetupError, cmd.run) + with pytest.raises(DistutilsSetupError): + cmd.run() # metadata are OK but long_description is broken metadata = { @@ -241,7 +243,8 @@ def test_strict(self): cmd = self._get_cmd(metadata) cmd.ensure_finalized() cmd.strict = 1 - self.assertRaises(DistutilsSetupError, cmd.run) + with pytest.raises(DistutilsSetupError): + cmd.run() # now something that works metadata['long_description'] = 'title\n=====\n\ntext' @@ -307,7 +310,8 @@ def test_register_invalid_long_description(self): register_module.input = inputs self.addCleanup(delattr, register_module, 'input') - self.assertRaises(DistutilsSetupError, cmd.run) + with pytest.raises(DistutilsSetupError): + cmd.run() def test_check_metadata_deprecated(self): # makes sure make_metadata is deprecated @@ -315,14 +319,14 @@ def test_check_metadata_deprecated(self): with check_warnings() as w: warnings.simplefilter("always") cmd.check_metadata() - self.assertEqual(len(w.warnings), 1) + assert len(w.warnings) == 1 def test_list_classifiers(self): cmd = self._get_cmd() cmd.list_classifiers = 1 cmd.run() results = self.get_logs(INFO) - self.assertEqual(results, ['running check', 'xxx']) + assert results == ['running check', 'xxx'] def test_show_response(self): # test that the --show-response option return a well formatted response @@ -336,4 +340,4 @@ def test_show_response(self): del register_module.input results = self.get_logs(INFO) - self.assertEqual(results[3], 75 * '-' + '\nxxx\n' + 75 * '-') + assert results[3] == 75 * '-' + '\nxxx\n' + 75 * '-' diff --git a/distutils/tests/test_sdist.py b/distutils/tests/test_sdist.py index 97d57dd042..a6f1b86df4 100644 --- a/distutils/tests/test_sdist.py +++ b/distutils/tests/test_sdist.py @@ -113,7 +113,7 @@ def test_prune_file_list(self): # now let's check what we have dist_folder = join(self.tmp_dir, 'dist') files = os.listdir(dist_folder) - self.assertEqual(files, ['fake-1.0.zip']) + assert files == ['fake-1.0.zip'] zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip')) try: @@ -130,7 +130,7 @@ def test_prune_file_list(self): 'somecode/', 'somecode/__init__.py', ] - self.assertEqual(sorted(content), ['fake-1.0/' + x for x in expected]) + assert sorted(content) == ['fake-1.0/' + x for x in expected] @pytest.mark.usefixtures('needs_zlib') @unittest.skipIf(find_executable('tar') is None, "The tar command is not found") @@ -148,7 +148,7 @@ def test_make_distribution(self): dist_folder = join(self.tmp_dir, 'dist') result = os.listdir(dist_folder) result.sort() - self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz']) + assert result == ['fake-1.0.tar', 'fake-1.0.tar.gz'] os.remove(join(dist_folder, 'fake-1.0.tar')) os.remove(join(dist_folder, 'fake-1.0.tar.gz')) @@ -161,7 +161,7 @@ def test_make_distribution(self): result = os.listdir(dist_folder) result.sort() - self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz']) + assert result == ['fake-1.0.tar', 'fake-1.0.tar.gz'] @pytest.mark.usefixtures('needs_zlib') def test_add_defaults(self): @@ -215,7 +215,7 @@ def test_add_defaults(self): # now let's check what we have dist_folder = join(self.tmp_dir, 'dist') files = os.listdir(dist_folder) - self.assertEqual(files, ['fake-1.0.zip']) + assert files == ['fake-1.0.zip'] zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip')) try: @@ -243,7 +243,7 @@ def test_add_defaults(self): 'somecode/doc.dat', 'somecode/doc.txt', ] - self.assertEqual(sorted(content), ['fake-1.0/' + x for x in expected]) + assert sorted(content) == ['fake-1.0/' + x for x in expected] # checking the MANIFEST f = open(join(self.tmp_dir, 'MANIFEST')) @@ -251,7 +251,7 @@ def test_add_defaults(self): manifest = f.read() finally: f.close() - self.assertEqual(manifest, MANIFEST % {'sep': os.sep}) + assert manifest == MANIFEST % {'sep': os.sep} @pytest.mark.usefixtures('needs_zlib') def test_metadata_check_option(self): @@ -265,7 +265,7 @@ def test_metadata_check_option(self): warnings = [ msg for msg in self.get_logs(WARN) if msg.startswith('warning: check:') ] - self.assertEqual(len(warnings), 1) + assert len(warnings) == 1 # trying with a complete set of metadata self.clear_logs() @@ -276,7 +276,7 @@ def test_metadata_check_option(self): warnings = [ msg for msg in self.get_logs(WARN) if msg.startswith('warning: check:') ] - self.assertEqual(len(warnings), 0) + assert len(warnings) == 0 def test_check_metadata_deprecated(self): # makes sure make_metadata is deprecated @@ -284,7 +284,7 @@ def test_check_metadata_deprecated(self): with check_warnings() as w: warnings.simplefilter("always") cmd.check_metadata() - self.assertEqual(len(w.warnings), 1) + assert len(w.warnings) == 1 def test_show_formats(self): with captured_stdout() as stdout: @@ -297,27 +297,29 @@ def test_show_formats(self): for line in stdout.getvalue().split('\n') if line.strip().startswith('--formats=') ] - self.assertEqual(len(output), num_formats) + assert len(output) == num_formats def test_finalize_options(self): dist, cmd = self.get_cmd() cmd.finalize_options() # default options set by finalize - self.assertEqual(cmd.manifest, 'MANIFEST') - self.assertEqual(cmd.template, 'MANIFEST.in') - self.assertEqual(cmd.dist_dir, 'dist') + assert cmd.manifest == 'MANIFEST' + assert cmd.template == 'MANIFEST.in' + assert cmd.dist_dir == 'dist' # formats has to be a string splitable on (' ', ',') or # a stringlist cmd.formats = 1 - self.assertRaises(DistutilsOptionError, cmd.finalize_options) + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() cmd.formats = ['zip'] cmd.finalize_options() # formats has to be known cmd.formats = 'supazipa' - self.assertRaises(DistutilsOptionError, cmd.finalize_options) + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() # the following tests make sure there is a nice error message instead # of a traceback when parsing an invalid manifest template @@ -330,7 +332,7 @@ def _check_template(self, content): cmd.filelist = FileList() cmd.read_template() warnings = self.get_logs(WARN) - self.assertEqual(len(warnings), 1) + assert len(warnings) == 1 def test_invalid_template_unknown_command(self): self._check_template('taunt knights *') @@ -365,7 +367,7 @@ def test_get_file_list(self): finally: f.close() - self.assertEqual(len(manifest), 5) + assert len(manifest) == 5 # adding a file self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#') @@ -386,8 +388,8 @@ def test_get_file_list(self): f.close() # do we have the new file in MANIFEST ? - self.assertEqual(len(manifest2), 6) - self.assertIn('doc2.txt', manifest2[-1]) + assert len(manifest2) == 6 + assert 'doc2.txt' in manifest2[-1] @pytest.mark.usefixtures('needs_zlib') def test_manifest_marker(self): @@ -404,7 +406,7 @@ def test_manifest_marker(self): finally: f.close() - self.assertEqual(manifest[0], '# file GENERATED by distutils, do NOT edit') + assert manifest[0] == '# file GENERATED by distutils, do NOT edit' @pytest.mark.usefixtures('needs_zlib') def test_manifest_comments(self): @@ -423,7 +425,7 @@ def test_manifest_comments(self): self.write_file((self.tmp_dir, 'bad.py'), "# don't pick me!") self.write_file((self.tmp_dir, '#bad.py'), "# don't pick me!") cmd.run() - self.assertEqual(cmd.filelist.files, ['good.py']) + assert cmd.filelist.files == ['good.py'] @pytest.mark.usefixtures('needs_zlib') def test_manual_manifest(self): @@ -437,7 +439,7 @@ def test_manual_manifest(self): 'This project maintains its MANIFEST file itself.', ) cmd.run() - self.assertEqual(cmd.filelist.files, ['README.manual']) + assert cmd.filelist.files == ['README.manual'] f = open(cmd.manifest) try: @@ -447,7 +449,7 @@ def test_manual_manifest(self): finally: f.close() - self.assertEqual(manifest, ['README.manual']) + assert manifest == ['README.manual'] archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz') archive = tarfile.open(archive_name) @@ -455,10 +457,8 @@ def test_manual_manifest(self): filenames = [tarinfo.name for tarinfo in archive] finally: archive.close() - self.assertEqual( - sorted(filenames), - ['fake-1.0', 'fake-1.0/PKG-INFO', 'fake-1.0/README.manual'], - ) + assert sorted(filenames) == \ + ['fake-1.0', 'fake-1.0/PKG-INFO', 'fake-1.0/README.manual'] @pytest.mark.usefixtures('needs_zlib') @require_unix_id @@ -481,8 +481,8 @@ def test_make_distribution_owner_group(self): archive = tarfile.open(archive_name) try: for member in archive.getmembers(): - self.assertEqual(member.uid, 0) - self.assertEqual(member.gid, 0) + assert member.uid == 0 + assert member.gid == 0 finally: archive.close() @@ -503,6 +503,6 @@ def test_make_distribution_owner_group(self): # rights (see #7408) try: for member in archive.getmembers(): - self.assertEqual(member.uid, os.getuid()) + assert member.uid == os.getuid() finally: archive.close() diff --git a/distutils/tests/test_spawn.py b/distutils/tests/test_spawn.py index b86c157f8e..91fb4c580b 100644 --- a/distutils/tests/test_spawn.py +++ b/distutils/tests/test_spawn.py @@ -11,6 +11,7 @@ from distutils.spawn import spawn from distutils.errors import DistutilsExecError from distutils.tests import support +import pytest class SpawnTestCase(support.TempdirManager, support.LoggingSilencer, unittest.TestCase): @@ -28,7 +29,8 @@ def test_spawn(self): self.write_file(exe, 'exit 1') os.chmod(exe, 0o777) - self.assertRaises(DistutilsExecError, spawn, [exe]) + with pytest.raises(DistutilsExecError): + spawn([exe]) # now something that works if sys.platform != 'win32': @@ -56,22 +58,22 @@ def test_find_executable(self): # test path parameter rv = find_executable(program, path=tmp_dir) - self.assertEqual(rv, filename) + assert rv == filename if sys.platform == 'win32': # test without ".exe" extension rv = find_executable(program_noeext, path=tmp_dir) - self.assertEqual(rv, filename) + assert rv == filename # test find in the current directory with os_helper.change_cwd(tmp_dir): rv = find_executable(program) - self.assertEqual(rv, program) + assert rv == program # test non-existent program dont_exist_program = "dontexist_" + program rv = find_executable(dont_exist_program, path=tmp_dir) - self.assertIsNone(rv) + assert rv is None # PATH='': no match, except in the current directory with os_helper.EnvironmentVarGuard() as env: @@ -80,12 +82,12 @@ def test_find_executable(self): 'distutils.spawn.os.confstr', return_value=tmp_dir, create=True ), unittest.mock.patch('distutils.spawn.os.defpath', tmp_dir): rv = find_executable(program) - self.assertIsNone(rv) + assert rv is None # look in current directory with os_helper.change_cwd(tmp_dir): rv = find_executable(program) - self.assertEqual(rv, program) + assert rv == program # PATH=':': explicitly looks in the current directory with os_helper.EnvironmentVarGuard() as env: @@ -94,12 +96,12 @@ def test_find_executable(self): 'distutils.spawn.os.confstr', return_value='', create=True ), unittest.mock.patch('distutils.spawn.os.defpath', ''): rv = find_executable(program) - self.assertIsNone(rv) + assert rv is None # look in current directory with os_helper.change_cwd(tmp_dir): rv = find_executable(program) - self.assertEqual(rv, program) + assert rv == program # missing PATH: test os.confstr("CS_PATH") and os.defpath with os_helper.EnvironmentVarGuard() as env: @@ -110,16 +112,16 @@ def test_find_executable(self): 'distutils.spawn.os.confstr', side_effect=ValueError, create=True ), unittest.mock.patch('distutils.spawn.os.defpath', tmp_dir): rv = find_executable(program) - self.assertEqual(rv, filename) + assert rv == filename # with confstr with unittest.mock.patch( 'distutils.spawn.os.confstr', return_value=tmp_dir, create=True ), unittest.mock.patch('distutils.spawn.os.defpath', ''): rv = find_executable(program) - self.assertEqual(rv, filename) + assert rv == filename def test_spawn_missing_exe(self): - with self.assertRaises(DistutilsExecError) as ctx: + with pytest.raises(DistutilsExecError) as ctx: spawn(['does-not-exist']) - self.assertIn("command 'does-not-exist' failed", str(ctx.exception)) + assert "command 'does-not-exist' failed" in str(ctx.value) diff --git a/distutils/tests/test_sysconfig.py b/distutils/tests/test_sysconfig.py index b3ef26e467..cc403242bc 100644 --- a/distutils/tests/test_sysconfig.py +++ b/distutils/tests/test_sysconfig.py @@ -39,7 +39,7 @@ def cleanup_testfn(self): def test_get_config_h_filename(self): config_h = sysconfig.get_config_h_filename() - self.assertTrue(os.path.isfile(config_h), config_h) + assert os.path.isfile(config_h), config_h @unittest.skipIf( sys.platform == 'win32', 'Makefile only exists on Unix like systems' @@ -49,37 +49,35 @@ def test_get_config_h_filename(self): ) def test_get_makefile_filename(self): makefile = sysconfig.get_makefile_filename() - self.assertTrue(os.path.isfile(makefile), makefile) + assert os.path.isfile(makefile), makefile def test_get_python_lib(self): # XXX doesn't work on Linux when Python was never installed before # self.assertTrue(os.path.isdir(lib_dir), lib_dir) # test for pythonxx.lib? - self.assertNotEqual( - sysconfig.get_python_lib(), sysconfig.get_python_lib(prefix=TESTFN) - ) + assert sysconfig.get_python_lib() != sysconfig.get_python_lib(prefix=TESTFN) def test_get_config_vars(self): cvars = sysconfig.get_config_vars() - self.assertIsInstance(cvars, dict) - self.assertTrue(cvars) + assert isinstance(cvars, dict) + assert cvars @unittest.skip('sysconfig.IS_PYPY') def test_srcdir(self): # See Issues #15322, #15364. srcdir = sysconfig.get_config_var('srcdir') - self.assertTrue(os.path.isabs(srcdir), srcdir) - self.assertTrue(os.path.isdir(srcdir), srcdir) + assert os.path.isabs(srcdir), srcdir + assert os.path.isdir(srcdir), srcdir if sysconfig.python_build: # The python executable has not been installed so srcdir # should be a full source checkout. Python_h = os.path.join(srcdir, 'Include', 'Python.h') - self.assertTrue(os.path.exists(Python_h), Python_h) - self.assertTrue(sysconfig._is_python_source_dir(srcdir)) + assert os.path.exists(Python_h), Python_h + assert sysconfig._is_python_source_dir(srcdir) elif os.name == 'posix': - self.assertEqual(os.path.dirname(sysconfig.get_makefile_filename()), srcdir) + assert os.path.dirname(sysconfig.get_makefile_filename()) == srcdir def test_srcdir_independent_of_cwd(self): # srcdir should be independent of the current working directory @@ -91,7 +89,7 @@ def test_srcdir_independent_of_cwd(self): srcdir2 = sysconfig.get_config_var('srcdir') finally: os.chdir(cwd) - self.assertEqual(srcdir, srcdir2) + assert srcdir == srcdir2 def customize_compiler(self): # make sure AR gets caught @@ -146,27 +144,21 @@ def test_customize_compiler(self): os.environ['RANLIB'] = 'env_ranlib' comp = self.customize_compiler() - self.assertEqual(comp.exes['archiver'], 'env_ar --env-arflags') - self.assertEqual(comp.exes['preprocessor'], 'env_cpp --env-cppflags') - self.assertEqual( - comp.exes['compiler'], 'env_cc --sc-cflags --env-cflags --env-cppflags' - ) - self.assertEqual( - comp.exes['compiler_so'], - ('env_cc --sc-cflags ' '--env-cflags ' '--env-cppflags --sc-ccshared'), - ) - self.assertEqual(comp.exes['compiler_cxx'], 'env_cxx --env-cxx-flags') - self.assertEqual(comp.exes['linker_exe'], 'env_cc') - self.assertEqual( - comp.exes['linker_so'], - ('env_ldshared --env-ldflags --env-cflags' ' --env-cppflags'), - ) - self.assertEqual(comp.shared_lib_extension, 'sc_shutil_suffix') + assert comp.exes['archiver'] == 'env_ar --env-arflags' + assert comp.exes['preprocessor'] == 'env_cpp --env-cppflags' + assert comp.exes['compiler'] == 'env_cc --sc-cflags --env-cflags --env-cppflags' + assert comp.exes['compiler_so'] == \ + ('env_cc --sc-cflags ' '--env-cflags ' '--env-cppflags --sc-ccshared') + assert comp.exes['compiler_cxx'] == 'env_cxx --env-cxx-flags' + assert comp.exes['linker_exe'] == 'env_cc' + assert comp.exes['linker_so'] == \ + ('env_ldshared --env-ldflags --env-cflags' ' --env-cppflags') + assert comp.shared_lib_extension == 'sc_shutil_suffix' if sys.platform == "darwin": - self.assertEqual(comp.exes['ranlib'], 'env_ranlib') + assert comp.exes['ranlib'] == 'env_ranlib' else: - self.assertTrue('ranlib' not in comp.exes) + assert 'ranlib' not in comp.exes del os.environ['AR'] del os.environ['CC'] @@ -180,15 +172,15 @@ def test_customize_compiler(self): del os.environ['RANLIB'] comp = self.customize_compiler() - self.assertEqual(comp.exes['archiver'], 'sc_ar --sc-arflags') - self.assertEqual(comp.exes['preprocessor'], 'sc_cc -E') - self.assertEqual(comp.exes['compiler'], 'sc_cc --sc-cflags') - self.assertEqual(comp.exes['compiler_so'], 'sc_cc --sc-cflags --sc-ccshared') - self.assertEqual(comp.exes['compiler_cxx'], 'sc_cxx') - self.assertEqual(comp.exes['linker_exe'], 'sc_cc') - self.assertEqual(comp.exes['linker_so'], 'sc_ldshared') - self.assertEqual(comp.shared_lib_extension, 'sc_shutil_suffix') - self.assertTrue('ranlib' not in comp.exes) + assert comp.exes['archiver'] == 'sc_ar --sc-arflags' + assert comp.exes['preprocessor'] == 'sc_cc -E' + assert comp.exes['compiler'] == 'sc_cc --sc-cflags' + assert comp.exes['compiler_so'] == 'sc_cc --sc-cflags --sc-ccshared' + assert comp.exes['compiler_cxx'] == 'sc_cxx' + assert comp.exes['linker_exe'] == 'sc_cc' + assert comp.exes['linker_so'] == 'sc_ldshared' + assert comp.shared_lib_extension == 'sc_shutil_suffix' + assert 'ranlib' not in comp.exes def test_parse_makefile_base(self): self.makefile = TESTFN @@ -199,9 +191,7 @@ def test_parse_makefile_base(self): finally: fd.close() d = sysconfig.parse_makefile(self.makefile) - self.assertEqual( - d, {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'", 'OTHER': 'foo'} - ) + assert d == {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'", 'OTHER': 'foo'} def test_parse_makefile_literal_dollar(self): self.makefile = TESTFN @@ -212,21 +202,15 @@ def test_parse_makefile_literal_dollar(self): finally: fd.close() d = sysconfig.parse_makefile(self.makefile) - self.assertEqual( - d, {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'", 'OTHER': 'foo'} - ) + assert d == {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'", 'OTHER': 'foo'} def test_sysconfig_module(self): import sysconfig as global_sysconfig - self.assertEqual( - global_sysconfig.get_config_var('CFLAGS'), - sysconfig.get_config_var('CFLAGS'), - ) - self.assertEqual( - global_sysconfig.get_config_var('LDFLAGS'), - sysconfig.get_config_var('LDFLAGS'), - ) + assert global_sysconfig.get_config_var('CFLAGS') == \ + sysconfig.get_config_var('CFLAGS') + assert global_sysconfig.get_config_var('LDFLAGS') == \ + sysconfig.get_config_var('LDFLAGS') @unittest.skipIf( sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'), 'compiler flags customized' @@ -250,20 +234,17 @@ def test_sysconfig_compiler_vars(self): if sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'): self.skipTest('compiler flags customized') - self.assertEqual( - global_sysconfig.get_config_var('LDSHARED'), - sysconfig.get_config_var('LDSHARED'), - ) - self.assertEqual( - global_sysconfig.get_config_var('CC'), sysconfig.get_config_var('CC') - ) + assert global_sysconfig.get_config_var('LDSHARED') == \ + sysconfig.get_config_var('LDSHARED') + assert global_sysconfig.get_config_var('CC') == sysconfig.get_config_var('CC') @unittest.skipIf( sysconfig.get_config_var('EXT_SUFFIX') is None, 'EXT_SUFFIX required for this test', ) def test_SO_deprecation(self): - self.assertWarns(DeprecationWarning, sysconfig.get_config_var, 'SO') + with pytest.warns(DeprecationWarning): + sysconfig.get_config_var('SO') def test_customize_compiler_before_get_config_vars(self): # Issue #21923: test that a Distribution compiler @@ -288,25 +269,25 @@ def test_customize_compiler_before_get_config_vars(self): universal_newlines=True, ) outs, errs = p.communicate() - self.assertEqual(0, p.returncode, "Subprocess failed: " + outs) + assert 0 == p.returncode, "Subprocess failed: " + outs def test_parse_config_h(self): config_h = sysconfig.get_config_h_filename() input = {} with open(config_h, encoding="utf-8") as f: result = sysconfig.parse_config_h(f, g=input) - self.assertTrue(input is result) + assert input is result with open(config_h, encoding="utf-8") as f: result = sysconfig.parse_config_h(f) - self.assertTrue(isinstance(result, dict)) + assert isinstance(result, dict) @unittest.skipUnless(sys.platform == 'win32', 'Testing windows pyd suffix') @unittest.skipUnless( sys.implementation.name == 'cpython', 'Need cpython for this test' ) def test_win_ext_suffix(self): - self.assertTrue(sysconfig.get_config_var("EXT_SUFFIX").endswith(".pyd")) - self.assertNotEqual(sysconfig.get_config_var("EXT_SUFFIX"), ".pyd") + assert sysconfig.get_config_var("EXT_SUFFIX").endswith(".pyd") + assert sysconfig.get_config_var("EXT_SUFFIX") != ".pyd" @unittest.skipUnless(sys.platform == 'win32', 'Testing Windows build layout') @unittest.skipUnless( diff --git a/distutils/tests/test_text_file.py b/distutils/tests/test_text_file.py index ad10b6d505..e53bbcbc91 100644 --- a/distutils/tests/test_text_file.py +++ b/distutils/tests/test_text_file.py @@ -51,7 +51,7 @@ def test_class(self): def test_input(count, description, file, expected_result): result = file.readlines() - self.assertEqual(result, expected_result) + assert result == expected_result tmpdir = self.mkdtemp() filename = os.path.join(tmpdir, "test.txt") diff --git a/distutils/tests/test_unixccompiler.py b/distutils/tests/test_unixccompiler.py index 204bb76dc0..f5147aa735 100644 --- a/distutils/tests/test_unixccompiler.py +++ b/distutils/tests/test_unixccompiler.py @@ -12,6 +12,7 @@ from distutils.util import _clear_cached_macosx_ver from . import support +import pytest class UnixCCompilerTestCase(support.TempdirManager, unittest.TestCase): @@ -93,11 +94,9 @@ def do_darwin_test(syscfg_macosx_ver, env_macosx_ver, expected_flag): # Run the test if expected_flag is not None: - self.assertEqual(self.cc.rpath_foo(), expected_flag, msg=msg) + assert self.cc.rpath_foo() == expected_flag, msg else: - with self.assertRaisesRegex( - DistutilsPlatformError, darwin_ver_var + r' mismatch', msg=msg - ): + with pytest.raises(DistutilsPlatformError, match=darwin_ver_var + r' mismatch'): self.cc.rpath_foo() # Restore @@ -128,19 +127,19 @@ def gcv(v): return 'xxx' sysconfig.get_config_var = gcv - self.assertEqual(self.cc.rpath_foo(), ['+s', '-L/foo']) + assert self.cc.rpath_foo() == ['+s', '-L/foo'] def gcv(v): return 'gcc' sysconfig.get_config_var = gcv - self.assertEqual(self.cc.rpath_foo(), ['-Wl,+s', '-L/foo']) + assert self.cc.rpath_foo() == ['-Wl,+s', '-L/foo'] def gcv(v): return 'g++' sysconfig.get_config_var = gcv - self.assertEqual(self.cc.rpath_foo(), ['-Wl,+s', '-L/foo']) + assert self.cc.rpath_foo() == ['-Wl,+s', '-L/foo'] sysconfig.get_config_var = old_gcv @@ -154,7 +153,7 @@ def gcv(v): return 'yes' sysconfig.get_config_var = gcv - self.assertEqual(self.cc.rpath_foo(), '-Wl,--enable-new-dtags,-R/foo') + assert self.cc.rpath_foo() == '-Wl,--enable-new-dtags,-R/foo' def gcv(v): if v == 'CC': @@ -163,7 +162,7 @@ def gcv(v): return 'yes' sysconfig.get_config_var = gcv - self.assertEqual(self.cc.rpath_foo(), '-Wl,--enable-new-dtags,-R/foo') + assert self.cc.rpath_foo() == '-Wl,--enable-new-dtags,-R/foo' # GCC non-GNULD sys.platform = 'bar' @@ -175,7 +174,7 @@ def gcv(v): return 'no' sysconfig.get_config_var = gcv - self.assertEqual(self.cc.rpath_foo(), '-Wl,-R/foo') + assert self.cc.rpath_foo() == '-Wl,-R/foo' # GCC GNULD with fully qualified configuration prefix # see #7617 @@ -188,7 +187,7 @@ def gcv(v): return 'yes' sysconfig.get_config_var = gcv - self.assertEqual(self.cc.rpath_foo(), '-Wl,--enable-new-dtags,-R/foo') + assert self.cc.rpath_foo() == '-Wl,--enable-new-dtags,-R/foo' # non-GCC GNULD sys.platform = 'bar' @@ -200,7 +199,7 @@ def gcv(v): return 'yes' sysconfig.get_config_var = gcv - self.assertEqual(self.cc.rpath_foo(), '-Wl,--enable-new-dtags,-R/foo') + assert self.cc.rpath_foo() == '-Wl,--enable-new-dtags,-R/foo' # non-GCC non-GNULD sys.platform = 'bar' @@ -212,7 +211,7 @@ def gcv(v): return 'no' sysconfig.get_config_var = gcv - self.assertEqual(self.cc.rpath_foo(), '-Wl,-R/foo') + assert self.cc.rpath_foo() == '-Wl,-R/foo' @unittest.skipIf(sys.platform == 'win32', "can't test on Windows") def test_cc_overrides_ldshared(self): @@ -234,7 +233,7 @@ def gcvs(*args, _orig=sysconfig.get_config_vars): env['CC'] = 'my_cc' del env['LDSHARED'] sysconfig.customize_compiler(self.cc) - self.assertEqual(self.cc.linker_so[0], 'my_cc') + assert self.cc.linker_so[0] == 'my_cc' @unittest.skipIf(sys.platform == 'win32', "can't test on Windows") def test_cc_overrides_ldshared_for_cxx_correctly(self): @@ -270,7 +269,7 @@ def gcvs(*args, _orig=sysconfig.get_config_vars): env['CXX'] = 'my_cxx' del env['LDSHARED'] sysconfig.customize_compiler(self.cc) - self.assertEqual(self.cc.linker_so[0:2], ['ccache', 'my_cc']) + assert self.cc.linker_so[0:2] == ['ccache', 'my_cc'] self.cc.link(None, [], 'a.out', target_lang='c++') call_args = mock_spawn.call_args[0][0] expected = ['my_cxx', '-bundle', '-undefined', 'dynamic_lookup'] @@ -297,7 +296,7 @@ def gcvs(*args, _orig=sysconfig.get_config_vars): env['CC'] = 'my_cc' env['LDSHARED'] = 'my_ld -bundle -dynamic' sysconfig.customize_compiler(self.cc) - self.assertEqual(self.cc.linker_so[0], 'my_ld') + assert self.cc.linker_so[0] == 'my_ld' def test_has_function(self): # Issue https://github.com/pypa/distutils/issues/64: diff --git a/distutils/tests/test_upload.py b/distutils/tests/test_upload.py index 4435eb1fda..6b0cdecd6b 100644 --- a/distutils/tests/test_upload.py +++ b/distutils/tests/test_upload.py @@ -11,6 +11,7 @@ from distutils.log import ERROR, INFO from distutils.tests.test_config import PYPIRC, BasePyPIRCCommandTestCase +import pytest PYPIRC_LONG_PASSWORD = """\ [distutils] @@ -94,7 +95,7 @@ def test_finalize_options(self): ('realm', 'pypi'), ('repository', 'https://upload.pypi.org/legacy/'), ): - self.assertEqual(getattr(cmd, attr), waited) + assert getattr(cmd, attr) == waited def test_saved_password(self): # file with no password @@ -104,14 +105,14 @@ def test_saved_password(self): dist = Distribution() cmd = upload(dist) cmd.finalize_options() - self.assertEqual(cmd.password, None) + assert cmd.password == None # make sure we get it as well, if another command # initialized it at the dist level dist.password = 'xxx' cmd = upload(dist) cmd.finalize_options() - self.assertEqual(cmd.password, 'xxx') + assert cmd.password == 'xxx' def test_upload(self): tmp = self.mkdtemp() @@ -130,33 +131,29 @@ def test_upload(self): # what did we send ? headers = dict(self.last_open.req.headers) - self.assertGreaterEqual(int(headers['Content-length']), 2162) + assert int(headers['Content-length']) >= 2162 content_type = headers['Content-type'] - self.assertTrue(content_type.startswith('multipart/form-data')) - self.assertEqual(self.last_open.req.get_method(), 'POST') + assert content_type.startswith('multipart/form-data') + assert self.last_open.req.get_method() == 'POST' expected_url = 'https://upload.pypi.org/legacy/' - self.assertEqual(self.last_open.req.get_full_url(), expected_url) + assert self.last_open.req.get_full_url() == expected_url data = self.last_open.req.data - self.assertIn(b'xxx', data) - self.assertIn(b'protocol_version', data) - self.assertIn(b'sha256_digest', data) - self.assertIn( - b'cd2eb0837c9b4c962c22d2ff8b5441b7b45805887f051d39bf133b583baf' b'6860', - data, - ) + assert b'xxx' in data + assert b'protocol_version' in data + assert b'sha256_digest' in data + assert b'cd2eb0837c9b4c962c22d2ff8b5441b7b45805887f051d39bf133b583baf' b'6860' in \ + data if b'md5_digest' in data: - self.assertIn(b'f561aaf6ef0bf14d4208bb46a4ccb3ad', data) + assert b'f561aaf6ef0bf14d4208bb46a4ccb3ad' in data if b'blake2_256_digest' in data: - self.assertIn( - b'b6f289a27d4fe90da63c503bfe0a9b761a8f76bb86148565065f040be' - b'6d1c3044cf7ded78ef800509bccb4b648e507d88dc6383d67642aadcc' - b'ce443f1534330a', - data, - ) + assert b'b6f289a27d4fe90da63c503bfe0a9b761a8f76bb86148565065f040be' \ + b'6d1c3044cf7ded78ef800509bccb4b648e507d88dc6383d67642aadcc' \ + b'ce443f1534330a' in \ + data # The PyPI response body was echoed results = self.get_logs(INFO) - self.assertEqual(results[-1], 75 * '-' + '\nxyzzy\n' + 75 * '-') + assert results[-1] == 75 * '-' + '\nxyzzy\n' + 75 * '-' # bpo-32304: archives whose last byte was b'\r' were corrupted due to # normalization intended for Mac OS 9. @@ -180,13 +177,14 @@ def test_upload_correct_cr(self): cmd.run() headers = dict(self.last_open.req.headers) - self.assertGreaterEqual(int(headers['Content-length']), 2172) - self.assertIn(b'long description\r', self.last_open.req.data) + assert int(headers['Content-length']) >= 2172 + assert b'long description\r' in self.last_open.req.data def test_upload_fails(self): self.next_msg = "Not Found" self.next_code = 404 - self.assertRaises(DistutilsError, self.test_upload) + with pytest.raises(DistutilsError): + self.test_upload() def test_wrong_exception_order(self): tmp = self.mkdtemp() @@ -210,10 +208,10 @@ def test_wrong_exception_order(self): 'distutils.command.upload.urlopen', new=mock.Mock(side_effect=exception), ): - with self.assertRaises(raised_exception): + with pytest.raises(raised_exception): cmd = upload(dist) cmd.ensure_finalized() cmd.run() results = self.get_logs(ERROR) - self.assertIn(expected, results[-1]) + assert expected in results[-1] self.clear_logs() diff --git a/distutils/tests/test_util.py b/distutils/tests/test_util.py index 3c90b87f61..01b35e5c3d 100644 --- a/distutils/tests/test_util.py +++ b/distutils/tests/test_util.py @@ -74,25 +74,25 @@ def _get_uname(self): def test_get_host_platform(self): with unittest.mock.patch('os.name', 'nt'): with unittest.mock.patch('sys.version', '... [... (ARM64)]'): - self.assertEqual(get_host_platform(), 'win-arm64') + assert get_host_platform() == 'win-arm64' with unittest.mock.patch('sys.version', '... [... (ARM)]'): - self.assertEqual(get_host_platform(), 'win-arm32') + assert get_host_platform() == 'win-arm32' with unittest.mock.patch('sys.version_info', (3, 9, 0, 'final', 0)): - self.assertEqual(get_host_platform(), stdlib_sysconfig.get_platform()) + assert get_host_platform() == stdlib_sysconfig.get_platform() def test_get_platform(self): with unittest.mock.patch('os.name', 'nt'): with unittest.mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'x86'}): - self.assertEqual(get_platform(), 'win32') + assert get_platform() == 'win32' with unittest.mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'x64'}): - self.assertEqual(get_platform(), 'win-amd64') + assert get_platform() == 'win-amd64' with unittest.mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'arm'}): - self.assertEqual(get_platform(), 'win-arm32') + assert get_platform() == 'win-arm32' with unittest.mock.patch.dict( 'os.environ', {'VSCMD_ARG_TGT_ARCH': 'arm64'} ): - self.assertEqual(get_platform(), 'win-arm64') + assert get_platform() == 'win-arm64' def test_convert_path(self): # linux/mac @@ -103,7 +103,7 @@ def _join(path): os.path.join = _join - self.assertEqual(convert_path('/home/to/my/stuff'), '/home/to/my/stuff') + assert convert_path('/home/to/my/stuff') == '/home/to/my/stuff' # win os.sep = '\\' @@ -113,11 +113,13 @@ def _join(*path): os.path.join = _join - self.assertRaises(ValueError, convert_path, '/home/to/my/stuff') - self.assertRaises(ValueError, convert_path, 'home/to/my/stuff/') + with pytest.raises(ValueError): + convert_path('/home/to/my/stuff') + with pytest.raises(ValueError): + convert_path('home/to/my/stuff/') - self.assertEqual(convert_path('home/to/my/stuff'), 'home\\to\\my\\stuff') - self.assertEqual(convert_path('.'), os.curdir) + assert convert_path('home/to/my/stuff') == 'home\\to\\my\\stuff' + assert convert_path('.') == os.curdir def test_change_root(self): # linux/mac @@ -133,8 +135,8 @@ def _join(*path): os.path.join = _join - self.assertEqual(change_root('/root', '/old/its/here'), '/root/old/its/here') - self.assertEqual(change_root('/root', 'its/here'), '/root/its/here') + assert change_root('/root', '/old/its/here') == '/root/old/its/here' + assert change_root('/root', 'its/here') == '/root/its/here' # windows os.name = 'nt' @@ -156,14 +158,13 @@ def _join(*path): os.path.join = _join - self.assertEqual( - change_root('c:\\root', 'c:\\old\\its\\here'), 'c:\\root\\old\\its\\here' - ) - self.assertEqual(change_root('c:\\root', 'its\\here'), 'c:\\root\\its\\here') + assert change_root('c:\\root', 'c:\\old\\its\\here') == 'c:\\root\\old\\its\\here' + assert change_root('c:\\root', 'its\\here') == 'c:\\root\\its\\here' # BugsBunny os (it's a great os) os.name = 'BugsBunny' - self.assertRaises(DistutilsPlatformError, change_root, 'c:\\root', 'its\\here') + with pytest.raises(DistutilsPlatformError): + change_root('c:\\root', 'its\\here') # XXX platforms to be covered: mac @@ -173,8 +174,8 @@ def test_check_environ(self): check_environ() - self.assertEqual(os.environ['PLAT'], get_platform()) - self.assertEqual(util._environ_checked, 1) + assert os.environ['PLAT'] == get_platform() + assert util._environ_checked == 1 @unittest.skipUnless(os.name == 'posix', 'specific to posix') def test_check_environ_getpwuid(self): @@ -189,7 +190,7 @@ def test_check_environ_getpwuid(self): ) with mock.patch.object(pwd, 'getpwuid', return_value=result): check_environ() - self.assertEqual(os.environ['HOME'], '/home/distutils') + assert os.environ['HOME'] == '/home/distutils' util._environ_checked = 0 os.environ.pop('HOME', None) @@ -197,23 +198,21 @@ def test_check_environ_getpwuid(self): # bpo-10496: Catch pwd.getpwuid() error with mock.patch.object(pwd, 'getpwuid', side_effect=KeyError): check_environ() - self.assertNotIn('HOME', os.environ) + assert 'HOME' not in os.environ def test_split_quoted(self): - self.assertEqual( - split_quoted('""one"" "two" \'three\' \\four'), - ['one', 'two', 'three', 'four'], - ) + assert split_quoted('""one"" "two" \'three\' \\four') == \ + ['one', 'two', 'three', 'four'] def test_strtobool(self): yes = ('y', 'Y', 'yes', 'True', 't', 'true', 'True', 'On', 'on', '1') no = ('n', 'no', 'f', 'false', 'off', '0', 'Off', 'No', 'N') for y in yes: - self.assertTrue(strtobool(y)) + assert strtobool(y) for n in no: - self.assertFalse(strtobool(n)) + assert not strtobool(n) def test_rfc822_escape(self): header = 'I am a\npoor\nlonesome\nheader\n' @@ -221,7 +220,7 @@ def test_rfc822_escape(self): wanted = ('I am a%(8s)spoor%(8s)slonesome%(8s)s' 'header%(8s)s') % { '8s': '\n' + 8 * ' ' } - self.assertEqual(res, wanted) + assert res == wanted def test_dont_write_bytecode(self): # makes sure byte_compile raise a DistutilsError @@ -229,7 +228,8 @@ def test_dont_write_bytecode(self): old_dont_write_bytecode = sys.dont_write_bytecode sys.dont_write_bytecode = True try: - self.assertRaises(DistutilsByteCompileError, byte_compile, []) + with pytest.raises(DistutilsByteCompileError): + byte_compile([]) finally: sys.dont_write_bytecode = old_dont_write_bytecode @@ -237,4 +237,4 @@ def test_grok_environment_error(self): # test obsolete function to ensure backward compat (#4931) exc = IOError("Unable to find batch file") msg = grok_environment_error(exc) - self.assertEqual(msg, "error: Unable to find batch file") + assert msg == "error: Unable to find batch file" diff --git a/distutils/tests/test_version.py b/distutils/tests/test_version.py index c3dfb598fc..8546eac79f 100644 --- a/distutils/tests/test_version.py +++ b/distutils/tests/test_version.py @@ -15,12 +15,12 @@ def tearDown(self): def test_prerelease(self): version = StrictVersion('1.2.3a1') - self.assertEqual(version.version, (1, 2, 3)) - self.assertEqual(version.prerelease, ('a', 1)) - self.assertEqual(str(version), '1.2.3a1') + assert version.version == (1, 2, 3) + assert version.prerelease == ('a', 1) + assert str(version) == '1.2.3a1' version = StrictVersion('1.2.0') - self.assertEqual(str(version), '1.2') + assert str(version) == '1.2' def test_cmp_strict(self): versions = ( @@ -51,19 +51,13 @@ def test_cmp_strict(self): raise AssertionError( ("cmp(%s, %s) " "shouldn't raise ValueError") % (v1, v2) ) - self.assertEqual( - res, wanted, 'cmp({}, {}) should be {}, got {}'.format(v1, v2, wanted, res) - ) + assert res == wanted, 'cmp({}, {}) should be {}, got {}'.format(v1, v2, wanted, res) res = StrictVersion(v1)._cmp(v2) - self.assertEqual( - res, wanted, 'cmp({}, {}) should be {}, got {}'.format(v1, v2, wanted, res) - ) + assert res == wanted, 'cmp({}, {}) should be {}, got {}'.format(v1, v2, wanted, res) res = StrictVersion(v1)._cmp(object()) - self.assertIs( - res, - NotImplemented, - 'cmp({}, {}) should be NotImplemented, got {}'.format(v1, v2, res), - ) + assert res is \ + NotImplemented, \ + 'cmp({}, {}) should be NotImplemented, got {}'.format(v1, v2, res) def test_cmp(self): versions = ( @@ -79,16 +73,10 @@ def test_cmp(self): for v1, v2, wanted in versions: res = LooseVersion(v1)._cmp(LooseVersion(v2)) - self.assertEqual( - res, wanted, 'cmp({}, {}) should be {}, got {}'.format(v1, v2, wanted, res) - ) + assert res == wanted, 'cmp({}, {}) should be {}, got {}'.format(v1, v2, wanted, res) res = LooseVersion(v1)._cmp(v2) - self.assertEqual( - res, wanted, 'cmp({}, {}) should be {}, got {}'.format(v1, v2, wanted, res) - ) + assert res == wanted, 'cmp({}, {}) should be {}, got {}'.format(v1, v2, wanted, res) res = LooseVersion(v1)._cmp(object()) - self.assertIs( - res, - NotImplemented, - 'cmp({}, {}) should be NotImplemented, got {}'.format(v1, v2, res), - ) + assert res is \ + NotImplemented, \ + 'cmp({}, {}) should be NotImplemented, got {}'.format(v1, v2, res) From 6441714f3811d5a9852052455401439c1c4c4db3 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Sun, 31 Jul 2022 21:16:58 -0400 Subject: [PATCH 06/16] =?UTF-8?q?=E2=9A=AB=20Fade=20to=20black.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- conftest.py | 2 ++ distutils/_msvccompiler.py | 4 +--- distutils/command/bdist_dumb.py | 4 +++- distutils/cygwinccompiler.py | 4 +++- distutils/file_util.py | 8 ++++++-- distutils/msvc9compiler.py | 8 ++++++-- distutils/msvccompiler.py | 4 +++- distutils/spawn.py | 4 +++- distutils/tests/support.py | 1 - distutils/tests/test_archive_util.py | 5 ++++- distutils/tests/test_build_clib.py | 8 ++++++-- distutils/tests/test_check.py | 8 +++++--- distutils/tests/test_dir_util.py | 4 +++- distutils/tests/test_dist.py | 27 +++++++++++++++++++------- distutils/tests/test_file_util.py | 4 +++- distutils/tests/test_filelist.py | 4 +++- distutils/tests/test_log.py | 14 ++++++++------ distutils/tests/test_msvccompiler.py | 4 +++- distutils/tests/test_sdist.py | 7 +++++-- distutils/tests/test_sysconfig.py | 25 ++++++++++++++---------- distutils/tests/test_unixccompiler.py | 4 +++- distutils/tests/test_upload.py | 15 ++++++++------ distutils/tests/test_util.py | 12 +++++++++--- distutils/tests/test_version.py | 28 +++++++++++++++++---------- 24 files changed, 141 insertions(+), 67 deletions(-) diff --git a/conftest.py b/conftest.py index 94d1c27f65..1354387aaf 100644 --- a/conftest.py +++ b/conftest.py @@ -37,6 +37,7 @@ def needs_zlib(): @pytest.fixture def distutils_logging_silencer(request): from distutils import log + self = request.instance self.threshold = log.set_threshold(log.FATAL) # catching warnings @@ -56,6 +57,7 @@ def distutils_logging_silencer(request): @pytest.fixture def distutils_managed_tempdir(request): from distutils.tests import py38compat as os_helper + self = request.instance self.old_cwd = os.getcwd() self.tempdirs = [] diff --git a/distutils/_msvccompiler.py b/distutils/_msvccompiler.py index c2af5f2b3c..35c90942d2 100644 --- a/distutils/_msvccompiler.py +++ b/distutils/_msvccompiler.py @@ -425,9 +425,7 @@ def compile( # noqa: C901 continue else: # how to handle this file? - raise CompileError( - f"Don't know how to compile {src} to {obj}" - ) + raise CompileError(f"Don't know how to compile {src} to {obj}") args = [self.cc] + compile_opts + pp_opts if add_cpp_opts: diff --git a/distutils/command/bdist_dumb.py b/distutils/command/bdist_dumb.py index 9e1434deae..0f52330f67 100644 --- a/distutils/command/bdist_dumb.py +++ b/distutils/command/bdist_dumb.py @@ -105,7 +105,9 @@ def run(self): # And make an archive relative to the root of the # pseudo-installation tree. - archive_basename = "{}.{}".format(self.distribution.get_fullname(), self.plat_name) + archive_basename = "{}.{}".format( + self.distribution.get_fullname(), self.plat_name + ) pseudoinstall_root = os.path.join(self.dist_dir, archive_basename) if not self.relative: diff --git a/distutils/cygwinccompiler.py b/distutils/cygwinccompiler.py index 28c60089cb..2c6dbae83f 100644 --- a/distutils/cygwinccompiler.py +++ b/distutils/cygwinccompiler.py @@ -125,7 +125,9 @@ def __init__(self, verbose=0, dry_run=0, force=0): super().__init__(verbose, dry_run, force) status, details = check_config_h() - self.debug_print("Python's GCC status: {} (details: {})".format(status, details)) + self.debug_print( + "Python's GCC status: {} (details: {})".format(status, details) + ) if status is not CONFIG_H_OK: self.warn( "Python's pyconfig.h doesn't seem to support your compiler. " diff --git a/distutils/file_util.py b/distutils/file_util.py index 1ffe52dac2..1f1e444b1c 100644 --- a/distutils/file_util.py +++ b/distutils/file_util.py @@ -39,7 +39,9 @@ def _copy_file_contents(src, dst, buffer_size=16 * 1024): # noqa: C901 try: fdst = open(dst, 'wb') except OSError as e: - raise DistutilsFileError("could not create '{}': {}".format(dst, e.strerror)) + raise DistutilsFileError( + "could not create '{}': {}".format(dst, e.strerror) + ) while True: try: @@ -214,7 +216,9 @@ def move_file(src, dst, verbose=1, dry_run=0): # noqa: C901 if num == errno.EXDEV: copy_it = True else: - raise DistutilsFileError("couldn't move '{}' to '{}': {}".format(src, dst, msg)) + raise DistutilsFileError( + "couldn't move '{}' to '{}': {}".format(src, dst, msg) + ) if copy_it: copy_file(src, dst, verbose=verbose) diff --git a/distutils/msvc9compiler.py b/distutils/msvc9compiler.py index 160b6f2a3e..62075c0bf1 100644 --- a/distutils/msvc9compiler.py +++ b/distutils/msvc9compiler.py @@ -362,7 +362,9 @@ def initialize(self, plat_name=None): # noqa: C901 # sanity check for platforms to prevent obscure errors later. ok_plats = 'win32', 'win-amd64' if plat_name not in ok_plats: - raise DistutilsPlatformError("--plat-name must be one of {}".format(ok_plats)) + raise DistutilsPlatformError( + "--plat-name must be one of {}".format(ok_plats) + ) if ( "DISTUTILS_USE_SDK" in os.environ @@ -555,7 +557,9 @@ def compile( # noqa: C901 continue else: # how to handle this file? - raise CompileError("Don't know how to compile {} to {}".format(src, obj)) + raise CompileError( + "Don't know how to compile {} to {}".format(src, obj) + ) output_opt = "/Fo" + obj try: diff --git a/distutils/msvccompiler.py b/distutils/msvccompiler.py index f45b93ea43..51e60175ee 100644 --- a/distutils/msvccompiler.py +++ b/distutils/msvccompiler.py @@ -446,7 +446,9 @@ def compile( # noqa: C901 continue else: # how to handle this file? - raise CompileError("Don't know how to compile {} to {}".format(src, obj)) + raise CompileError( + "Don't know how to compile {} to {}".format(src, obj) + ) output_opt = "/Fo" + obj try: diff --git a/distutils/spawn.py b/distutils/spawn.py index 02d5c879dc..b18ba9db7d 100644 --- a/distutils/spawn.py +++ b/distutils/spawn.py @@ -60,7 +60,9 @@ def spawn(cmd, search_path=1, verbose=0, dry_run=0, env=None): # noqa: C901 except OSError as exc: if not DEBUG: cmd = cmd[0] - raise DistutilsExecError("command {!r} failed: {}".format(cmd, exc.args[-1])) from exc + raise DistutilsExecError( + "command {!r} failed: {}".format(cmd, exc.args[-1]) + ) from exc if exitcode: if not DEBUG: diff --git a/distutils/tests/support.py b/distutils/tests/support.py index e922faf257..1ff4a1268f 100644 --- a/distutils/tests/support.py +++ b/distutils/tests/support.py @@ -15,7 +15,6 @@ @pytest.mark.usefixtures('distutils_logging_silencer') class LoggingSilencer: - def _log(self, level, msg, args): if level not in (DEBUG, INFO, WARN, ERROR, FATAL): raise ValueError('%s wrong log level' % str(level)) diff --git a/distutils/tests/test_archive_util.py b/distutils/tests/test_archive_util.py index 1cffe9d8b5..f3a47ca608 100644 --- a/distutils/tests/test_archive_util.py +++ b/distutils/tests/test_archive_util.py @@ -285,7 +285,10 @@ def fake_zipfile(*a, **kw): def test_check_archive_formats(self): assert check_archive_formats(['gztar', 'xxx', 'zip']) == 'xxx' - assert check_archive_formats(['gztar', 'bztar', 'xztar', 'ztar', 'tar', 'zip']) is None + assert ( + check_archive_formats(['gztar', 'bztar', 'xztar', 'ztar', 'tar', 'zip']) + is None + ) def test_make_archive(self): tmpdir = self.mkdtemp() diff --git a/distutils/tests/test_build_clib.py b/distutils/tests/test_build_clib.py index 84335741a7..6ded9099c5 100644 --- a/distutils/tests/test_build_clib.py +++ b/distutils/tests/test_build_clib.py @@ -33,11 +33,15 @@ def test_check_library_dist(self): # library name may not contain directory separators with pytest.raises(DistutilsSetupError): - cmd.check_library_list([('name', 'foo1'), ('another/name', 'foo2')],) + cmd.check_library_list( + [('name', 'foo1'), ('another/name', 'foo2')], + ) # second element of each tuple must be a dictionary (build info) with pytest.raises(DistutilsSetupError): - cmd.check_library_list([('name', {}), ('another', 'foo2')],) + cmd.check_library_list( + [('name', {}), ('another', 'foo2')], + ) # those work libs = [('name', {}), ('name', {'ok': 'good'})] diff --git a/distutils/tests/test_check.py b/distutils/tests/test_check.py index c6a0cf32f4..c5b4913e4b 100644 --- a/distutils/tests/test_check.py +++ b/distutils/tests/test_check.py @@ -136,8 +136,7 @@ def test_check_restructuredtext(self): 'long_description': broken_rest, } with pytest.raises(DistutilsSetupError): - self._run(metadata, - **{'strict': 1, 'restructuredtext': 1}) + self._run(metadata, **{'strict': 1, 'restructuredtext': 1}) # and non-broken rest, including a non-ASCII character to test #12114 metadata['long_description'] = 'title\n=====\n\ntest \u00df' @@ -188,7 +187,10 @@ def foo(): assert len(msgs) == 0 else: assert len(msgs) == 1 - assert str(msgs[0][1]) == 'Cannot analyze code. Pygments package not found.' + assert ( + str(msgs[0][1]) + == 'Cannot analyze code. Pygments package not found.' + ) def test_check_all(self): with pytest.raises(DistutilsSetupError): diff --git a/distutils/tests/test_dir_util.py b/distutils/tests/test_dir_util.py index 18a18c090a..fc32c7fe74 100644 --- a/distutils/tests/test_dir_util.py +++ b/distutils/tests/test_dir_util.py @@ -129,6 +129,8 @@ def test_copy_tree_exception_in_listdir(self): """ An exception in listdir should raise a DistutilsFileError """ - with patch("os.listdir", side_effect=OSError()), pytest.raises(errors.DistutilsFileError): + with patch("os.listdir", side_effect=OSError()), pytest.raises( + errors.DistutilsFileError + ): src = self.tempdirs[-1] dir_util.copy_tree(src, None) diff --git a/distutils/tests/test_dist.py b/distutils/tests/test_dist.py index ed0bee9e9b..8c6fd7097f 100644 --- a/distutils/tests/test_dist.py +++ b/distutils/tests/test_dist.py @@ -84,8 +84,11 @@ def test_command_packages_cmdline(self): ) d = self.create_distribution() # let's actually try to load our test command: - assert d.get_command_packages() == \ - ["distutils.command", "foo.bar", "distutils.tests"] + assert d.get_command_packages() == [ + "distutils.command", + "foo.bar", + "distutils.tests", + ] cmd = d.get_command_obj("test_dist") assert isinstance(cmd, test_dist) assert cmd.sample_option == "sometext" @@ -143,7 +146,9 @@ def test_venv_install_options(self): 'root': option_tuple, } - assert sorted(d.command_options.get('install').keys()) == sorted(result_dict.keys()) + assert sorted(d.command_options.get('install').keys()) == sorted( + result_dict.keys() + ) for (key, value) in d.command_options.get('install').items(): assert value == result_dict[key] @@ -309,7 +314,9 @@ def test_provides(self): def test_provides_illegal(self): with pytest.raises(ValueError): - Distribution({"name": "package", "version": "1.0", "provides": ["my.pkg (splat)"]},) + Distribution( + {"name": "package", "version": "1.0", "provides": ["my.pkg (splat)"]}, + ) def test_requires(self): attrs = { @@ -329,7 +336,9 @@ def test_requires(self): def test_requires_illegal(self): with pytest.raises(ValueError): - Distribution({"name": "package", "version": "1.0", "requires": ["my.pkg (splat)"]},) + Distribution( + {"name": "package", "version": "1.0", "requires": ["my.pkg (splat)"]}, + ) def test_requires_to_list(self): attrs = {"name": "package", "requires": iter(["other"])} @@ -354,7 +363,9 @@ def test_obsoletes(self): def test_obsoletes_illegal(self): with pytest.raises(ValueError): - Distribution({"name": "package", "version": "1.0", "obsoletes": ["my.pkg (splat)"]},) + Distribution( + {"name": "package", "version": "1.0", "obsoletes": ["my.pkg (splat)"]}, + ) def test_obsoletes_to_list(self): attrs = {"name": "package", "obsoletes": iter(["other"])} @@ -487,7 +498,9 @@ def test_custom_pydistutils(self): # home drive should be found os.environ['USERPROFILE'] = temp_dir files = dist.find_config_files() - assert user_filename in files, '{!r} not found in {!r}'.format(user_filename, files) + assert user_filename in files, '{!r} not found in {!r}'.format( + user_filename, files + ) finally: os.remove(user_filename) diff --git a/distutils/tests/test_file_util.py b/distutils/tests/test_file_util.py index 88fb5b8ce8..e95535df05 100644 --- a/distutils/tests/test_file_util.py +++ b/distutils/tests/test_file_util.py @@ -63,7 +63,9 @@ def test_move_file_verbosity(self): def test_move_file_exception_unpacking_rename(self): # see issue 22182 - with patch("os.rename", side_effect=OSError("wrong", 1)), pytest.raises(DistutilsFileError): + with patch("os.rename", side_effect=OSError("wrong", 1)), pytest.raises( + DistutilsFileError + ): with open(self.source, 'w') as fobj: fobj.write('spam eggs') move_file(self.source, self.target, verbose=0) diff --git a/distutils/tests/test_filelist.py b/distutils/tests/test_filelist.py index a01a59351d..c42bc42b66 100644 --- a/distutils/tests/test_filelist.py +++ b/distutils/tests/test_filelist.py @@ -149,7 +149,9 @@ def test_translate_pattern(self): assert hasattr(translate_pattern('a', anchor=True, is_regex=True), 'search') # glob support - assert translate_pattern('*.py', anchor=True, is_regex=False).search('filelist.py') + assert translate_pattern('*.py', anchor=True, is_regex=False).search( + 'filelist.py' + ) def test_exclude_pattern(self): # return False if no match diff --git a/distutils/tests/test_log.py b/distutils/tests/test_log.py index 61e4e9bf96..614da574ae 100644 --- a/distutils/tests/test_log.py +++ b/distutils/tests/test_log.py @@ -34,16 +34,18 @@ def test_non_ascii(self): log.set_threshold(old_threshold) stdout.seek(0) - assert stdout.read().rstrip() == \ - ('Dεbug\tM?ss?ge' + assert stdout.read().rstrip() == ( + 'Dεbug\tM?ss?ge' if errors == 'replace' else 'Dεbug\tMssge' if errors == 'ignore' - else 'Dεbug\tM\\u0117ss\\xe3ge') + else 'Dεbug\tM\\u0117ss\\xe3ge' + ) stderr.seek(0) - assert stderr.read().rstrip() == \ - ('Fαtal\t?rr?r' + assert stderr.read().rstrip() == ( + 'Fαtal\t?rr?r' if errors == 'replace' else 'Fαtal\trrr' if errors == 'ignore' - else 'Fαtal\t\\xc8rr\\u014dr') + else 'Fαtal\t\\xc8rr\\u014dr' + ) diff --git a/distutils/tests/test_msvccompiler.py b/distutils/tests/test_msvccompiler.py index 22a36d0af8..ddca24e544 100644 --- a/distutils/tests/test_msvccompiler.py +++ b/distutils/tests/test_msvccompiler.py @@ -26,7 +26,9 @@ def _find_vcvarsall(plat_spec): _msvccompiler._find_vcvarsall = _find_vcvarsall try: with pytest.raises(DistutilsPlatformError): - _msvccompiler._get_vc_env('wont find this version',) + _msvccompiler._get_vc_env( + 'wont find this version', + ) finally: _msvccompiler._find_vcvarsall = old_find_vcvarsall diff --git a/distutils/tests/test_sdist.py b/distutils/tests/test_sdist.py index a6f1b86df4..24ec9eb608 100644 --- a/distutils/tests/test_sdist.py +++ b/distutils/tests/test_sdist.py @@ -457,8 +457,11 @@ def test_manual_manifest(self): filenames = [tarinfo.name for tarinfo in archive] finally: archive.close() - assert sorted(filenames) == \ - ['fake-1.0', 'fake-1.0/PKG-INFO', 'fake-1.0/README.manual'] + assert sorted(filenames) == [ + 'fake-1.0', + 'fake-1.0/PKG-INFO', + 'fake-1.0/README.manual', + ] @pytest.mark.usefixtures('needs_zlib') @require_unix_id diff --git a/distutils/tests/test_sysconfig.py b/distutils/tests/test_sysconfig.py index cc403242bc..39e81f1778 100644 --- a/distutils/tests/test_sysconfig.py +++ b/distutils/tests/test_sysconfig.py @@ -147,12 +147,14 @@ def test_customize_compiler(self): assert comp.exes['archiver'] == 'env_ar --env-arflags' assert comp.exes['preprocessor'] == 'env_cpp --env-cppflags' assert comp.exes['compiler'] == 'env_cc --sc-cflags --env-cflags --env-cppflags' - assert comp.exes['compiler_so'] == \ - ('env_cc --sc-cflags ' '--env-cflags ' '--env-cppflags --sc-ccshared') + assert comp.exes['compiler_so'] == ( + 'env_cc --sc-cflags ' '--env-cflags ' '--env-cppflags --sc-ccshared' + ) assert comp.exes['compiler_cxx'] == 'env_cxx --env-cxx-flags' assert comp.exes['linker_exe'] == 'env_cc' - assert comp.exes['linker_so'] == \ - ('env_ldshared --env-ldflags --env-cflags' ' --env-cppflags') + assert comp.exes['linker_so'] == ( + 'env_ldshared --env-ldflags --env-cflags' ' --env-cppflags' + ) assert comp.shared_lib_extension == 'sc_shutil_suffix' if sys.platform == "darwin": @@ -207,10 +209,12 @@ def test_parse_makefile_literal_dollar(self): def test_sysconfig_module(self): import sysconfig as global_sysconfig - assert global_sysconfig.get_config_var('CFLAGS') == \ - sysconfig.get_config_var('CFLAGS') - assert global_sysconfig.get_config_var('LDFLAGS') == \ - sysconfig.get_config_var('LDFLAGS') + assert global_sysconfig.get_config_var('CFLAGS') == sysconfig.get_config_var( + 'CFLAGS' + ) + assert global_sysconfig.get_config_var('LDFLAGS') == sysconfig.get_config_var( + 'LDFLAGS' + ) @unittest.skipIf( sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'), 'compiler flags customized' @@ -234,8 +238,9 @@ def test_sysconfig_compiler_vars(self): if sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'): self.skipTest('compiler flags customized') - assert global_sysconfig.get_config_var('LDSHARED') == \ - sysconfig.get_config_var('LDSHARED') + assert global_sysconfig.get_config_var('LDSHARED') == sysconfig.get_config_var( + 'LDSHARED' + ) assert global_sysconfig.get_config_var('CC') == sysconfig.get_config_var('CC') @unittest.skipIf( diff --git a/distutils/tests/test_unixccompiler.py b/distutils/tests/test_unixccompiler.py index f5147aa735..4be4ff2753 100644 --- a/distutils/tests/test_unixccompiler.py +++ b/distutils/tests/test_unixccompiler.py @@ -96,7 +96,9 @@ def do_darwin_test(syscfg_macosx_ver, env_macosx_ver, expected_flag): if expected_flag is not None: assert self.cc.rpath_foo() == expected_flag, msg else: - with pytest.raises(DistutilsPlatformError, match=darwin_ver_var + r' mismatch'): + with pytest.raises( + DistutilsPlatformError, match=darwin_ver_var + r' mismatch' + ): self.cc.rpath_foo() # Restore diff --git a/distutils/tests/test_upload.py b/distutils/tests/test_upload.py index 6b0cdecd6b..2ec1d53422 100644 --- a/distutils/tests/test_upload.py +++ b/distutils/tests/test_upload.py @@ -141,15 +141,18 @@ def test_upload(self): assert b'xxx' in data assert b'protocol_version' in data assert b'sha256_digest' in data - assert b'cd2eb0837c9b4c962c22d2ff8b5441b7b45805887f051d39bf133b583baf' b'6860' in \ - data + assert ( + b'cd2eb0837c9b4c962c22d2ff8b5441b7b45805887f051d39bf133b583baf' + b'6860' in data + ) if b'md5_digest' in data: assert b'f561aaf6ef0bf14d4208bb46a4ccb3ad' in data if b'blake2_256_digest' in data: - assert b'b6f289a27d4fe90da63c503bfe0a9b761a8f76bb86148565065f040be' \ - b'6d1c3044cf7ded78ef800509bccb4b648e507d88dc6383d67642aadcc' \ - b'ce443f1534330a' in \ - data + assert ( + b'b6f289a27d4fe90da63c503bfe0a9b761a8f76bb86148565065f040be' + b'6d1c3044cf7ded78ef800509bccb4b648e507d88dc6383d67642aadcc' + b'ce443f1534330a' in data + ) # The PyPI response body was echoed results = self.get_logs(INFO) diff --git a/distutils/tests/test_util.py b/distutils/tests/test_util.py index 01b35e5c3d..ac0feead55 100644 --- a/distutils/tests/test_util.py +++ b/distutils/tests/test_util.py @@ -158,7 +158,9 @@ def _join(*path): os.path.join = _join - assert change_root('c:\\root', 'c:\\old\\its\\here') == 'c:\\root\\old\\its\\here' + assert ( + change_root('c:\\root', 'c:\\old\\its\\here') == 'c:\\root\\old\\its\\here' + ) assert change_root('c:\\root', 'its\\here') == 'c:\\root\\its\\here' # BugsBunny os (it's a great os) @@ -201,8 +203,12 @@ def test_check_environ_getpwuid(self): assert 'HOME' not in os.environ def test_split_quoted(self): - assert split_quoted('""one"" "two" \'three\' \\four') == \ - ['one', 'two', 'three', 'four'] + assert split_quoted('""one"" "two" \'three\' \\four') == [ + 'one', + 'two', + 'three', + 'four', + ] def test_strtobool(self): yes = ('y', 'Y', 'yes', 'True', 't', 'true', 'True', 'On', 'on', '1') diff --git a/distutils/tests/test_version.py b/distutils/tests/test_version.py index 8546eac79f..8115faea3b 100644 --- a/distutils/tests/test_version.py +++ b/distutils/tests/test_version.py @@ -51,13 +51,17 @@ def test_cmp_strict(self): raise AssertionError( ("cmp(%s, %s) " "shouldn't raise ValueError") % (v1, v2) ) - assert res == wanted, 'cmp({}, {}) should be {}, got {}'.format(v1, v2, wanted, res) + assert res == wanted, 'cmp({}, {}) should be {}, got {}'.format( + v1, v2, wanted, res + ) res = StrictVersion(v1)._cmp(v2) - assert res == wanted, 'cmp({}, {}) should be {}, got {}'.format(v1, v2, wanted, res) + assert res == wanted, 'cmp({}, {}) should be {}, got {}'.format( + v1, v2, wanted, res + ) res = StrictVersion(v1)._cmp(object()) - assert res is \ - NotImplemented, \ - 'cmp({}, {}) should be NotImplemented, got {}'.format(v1, v2, res) + assert ( + res is NotImplemented + ), 'cmp({}, {}) should be NotImplemented, got {}'.format(v1, v2, res) def test_cmp(self): versions = ( @@ -73,10 +77,14 @@ def test_cmp(self): for v1, v2, wanted in versions: res = LooseVersion(v1)._cmp(LooseVersion(v2)) - assert res == wanted, 'cmp({}, {}) should be {}, got {}'.format(v1, v2, wanted, res) + assert res == wanted, 'cmp({}, {}) should be {}, got {}'.format( + v1, v2, wanted, res + ) res = LooseVersion(v1)._cmp(v2) - assert res == wanted, 'cmp({}, {}) should be {}, got {}'.format(v1, v2, wanted, res) + assert res == wanted, 'cmp({}, {}) should be {}, got {}'.format( + v1, v2, wanted, res + ) res = LooseVersion(v1)._cmp(object()) - assert res is \ - NotImplemented, \ - 'cmp({}, {}) should be NotImplemented, got {}'.format(v1, v2, res) + assert ( + res is NotImplemented + ), 'cmp({}, {}) should be NotImplemented, got {}'.format(v1, v2, res) From d7fa79844c812e2967ae4fd94b4c4bf703c0a0c7 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Sun, 31 Jul 2022 21:19:08 -0400 Subject: [PATCH 07/16] =?UTF-8?q?=F0=9F=91=B9=20Feed=20the=20hobgoblins=20?= =?UTF-8?q?(delint).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- distutils/tests/test_cygwinccompiler.py | 2 +- distutils/tests/test_dist.py | 6 +++--- distutils/tests/test_extension.py | 4 ++-- distutils/tests/test_install.py | 4 ++-- distutils/tests/test_msvc9compiler.py | 2 +- distutils/tests/test_upload.py | 2 +- distutils/text_file.py | 1 - 7 files changed, 10 insertions(+), 11 deletions(-) diff --git a/distutils/tests/test_cygwinccompiler.py b/distutils/tests/test_cygwinccompiler.py index 7eebd9ba86..b14ddb40c3 100644 --- a/distutils/tests/test_cygwinccompiler.py +++ b/distutils/tests/test_cygwinccompiler.py @@ -87,7 +87,7 @@ def test_get_msvcr(self): '2.6.1 (r261:67515, Dec 6 2008, 16:42:21) ' '\n[GCC 4.0.1 (Apple Computer, Inc. build 5370)]' ) - assert get_msvcr() == None + assert get_msvcr() is None # MSVC 7.0 sys.version = ( diff --git a/distutils/tests/test_dist.py b/distutils/tests/test_dist.py index 8c6fd7097f..dd3db860fc 100644 --- a/distutils/tests/test_dist.py +++ b/distutils/tests/test_dist.py @@ -227,7 +227,7 @@ def test_finalize_options(self): def test_get_command_packages(self): dist = Distribution() - assert dist.command_packages == None + assert dist.command_packages is None cmds = dist.get_command_packages() assert cmds == ['distutils.command'] assert dist.command_packages == ['distutils.command'] @@ -548,6 +548,6 @@ def test_read_metadata(self): assert metadata.description == "xxx" assert metadata.download_url == 'http://example.com' assert metadata.keywords == ['one', 'two'] - assert metadata.platforms == None - assert metadata.obsoletes == None + assert metadata.platforms is None + assert metadata.obsoletes is None assert metadata.requires == ['foo'] diff --git a/distutils/tests/test_extension.py b/distutils/tests/test_extension.py index 67de503f7c..271c245909 100644 --- a/distutils/tests/test_extension.py +++ b/distutils/tests/test_extension.py @@ -93,8 +93,8 @@ def test_extension_init(self): ): assert getattr(ext, attr) == [] - assert ext.language == None - assert ext.optional == None + assert ext.language is None + assert ext.optional is None # if there are unknown keyword options, warn about them with check_warnings() as w: diff --git a/distutils/tests/test_install.py b/distutils/tests/test_install.py index e4a38ea45f..519227d25e 100644 --- a/distutils/tests/test_install.py +++ b/distutils/tests/test_install.py @@ -167,9 +167,9 @@ def test_handle_extra_path(self): # none dist.extra_path = cmd.extra_path = None cmd.handle_extra_path() - assert cmd.extra_path == None + assert cmd.extra_path is None assert cmd.extra_dirs == '' - assert cmd.path_file == None + assert cmd.path_file is None # three elements (no way !) cmd.extra_path = 'path,dirs,again' diff --git a/distutils/tests/test_msvc9compiler.py b/distutils/tests/test_msvc9compiler.py index 3cfd3ac98e..29c5530b04 100644 --- a/distutils/tests/test_msvc9compiler.py +++ b/distutils/tests/test_msvc9compiler.py @@ -138,7 +138,7 @@ def test_reg_class(self): HKCU = winreg.HKEY_CURRENT_USER keys = Reg.read_keys(HKCU, 'xxxx') - assert keys == None + assert keys is None keys = Reg.read_keys(HKCU, r'Control Panel') assert 'Desktop' in keys diff --git a/distutils/tests/test_upload.py b/distutils/tests/test_upload.py index 2ec1d53422..e5c6649694 100644 --- a/distutils/tests/test_upload.py +++ b/distutils/tests/test_upload.py @@ -105,7 +105,7 @@ def test_saved_password(self): dist = Distribution() cmd = upload(dist) cmd.finalize_options() - assert cmd.password == None + assert cmd.password is None # make sure we get it as well, if another command # initialized it at the dist level diff --git a/distutils/text_file.py b/distutils/text_file.py index 44c0f27f8b..7274d4b16e 100644 --- a/distutils/text_file.py +++ b/distutils/text_file.py @@ -5,7 +5,6 @@ lines, and joining lines with backslashes.""" import sys -import io class TextFile: From f15fb39f42f07084bb15854aea35cd691e1e23bb Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Sun, 31 Jul 2022 21:47:39 -0400 Subject: [PATCH 08/16] Convert many tests to pytest native --- distutils/tests/test_archive_util.py | 4 +--- distutils/tests/test_bdist.py | 3 +-- distutils/tests/test_bdist_dumb.py | 4 +--- distutils/tests/test_bdist_msi.py | 12 ++++++------ distutils/tests/test_bdist_rpm.py | 3 +-- distutils/tests/test_bdist_wininst.py | 4 +--- distutils/tests/test_build_clib.py | 4 +--- distutils/tests/test_build_py.py | 4 +--- distutils/tests/test_build_scripts.py | 5 +---- distutils/tests/test_check.py | 2 +- distutils/tests/test_clean.py | 3 +-- distutils/tests/test_cmd.py | 2 +- distutils/tests/test_dep_util.py | 3 +-- distutils/tests/test_extension.py | 3 +-- distutils/tests/test_filelist.py | 5 ++--- distutils/tests/test_install_data.py | 4 +--- distutils/tests/test_install_headers.py | 4 +--- distutils/tests/test_install_lib.py | 3 +-- distutils/tests/test_install_scripts.py | 5 +---- distutils/tests/test_msvc9compiler.py | 5 ++--- distutils/tests/test_msvccompiler.py | 4 ++-- distutils/tests/test_spawn.py | 2 +- distutils/tests/test_text_file.py | 3 +-- 23 files changed, 31 insertions(+), 60 deletions(-) diff --git a/distutils/tests/test_archive_util.py b/distutils/tests/test_archive_util.py index f3a47ca608..c8c74032ae 100644 --- a/distutils/tests/test_archive_util.py +++ b/distutils/tests/test_archive_util.py @@ -56,9 +56,7 @@ def can_fs_encode(filename): return True -class ArchiveUtilTestCase( - support.TempdirManager, support.LoggingSilencer, unittest.TestCase -): +class ArchiveUtilTestCase(support.TempdirManager, support.LoggingSilencer): @pytest.mark.usefixtures('needs_zlib') def test_make_tarball(self, name='archive'): # creating something to tar diff --git a/distutils/tests/test_bdist.py b/distutils/tests/test_bdist.py index d7a7da250c..5b8774e5eb 100644 --- a/distutils/tests/test_bdist.py +++ b/distutils/tests/test_bdist.py @@ -1,13 +1,12 @@ """Tests for distutils.command.bdist.""" import os -import unittest import warnings from distutils.command.bdist import bdist from distutils.tests import support -class BuildTestCase(support.TempdirManager, unittest.TestCase): +class TestBuild(support.TempdirManager): def test_formats(self): # let's create a command and make sure # we can set the format diff --git a/distutils/tests/test_bdist_dumb.py b/distutils/tests/test_bdist_dumb.py index aa4c8db174..9c599a8d92 100644 --- a/distutils/tests/test_bdist_dumb.py +++ b/distutils/tests/test_bdist_dumb.py @@ -3,7 +3,6 @@ import os import sys import zipfile -import unittest import pytest @@ -22,10 +21,9 @@ @pytest.mark.usefixtures('save_env') -class BuildDumbTestCase( +class TestBuildDumb( support.TempdirManager, support.LoggingSilencer, - unittest.TestCase, ): def setUp(self): super().setUp() diff --git a/distutils/tests/test_bdist_msi.py b/distutils/tests/test_bdist_msi.py index 3bfb7df187..f36b398350 100644 --- a/distutils/tests/test_bdist_msi.py +++ b/distutils/tests/test_bdist_msi.py @@ -1,15 +1,15 @@ """Tests for distutils.command.bdist_msi.""" -import sys -import unittest +import pytest + from distutils.tests import support from .py38compat import check_warnings -@unittest.skipUnless(sys.platform == 'win32', 'these tests require Windows') -class BDistMSITestCase( - support.TempdirManager, support.LoggingSilencer, unittest.TestCase -): +pytest.importorskip('msilib') + + +class TestBDistMSI(support.TempdirManager, support.LoggingSilencer): def test_minimal(self): # minimal test XXX need more tests from distutils.command.bdist_msi import bdist_msi diff --git a/distutils/tests/test_bdist_rpm.py b/distutils/tests/test_bdist_rpm.py index d1de5ffe51..c4b21f60ff 100644 --- a/distutils/tests/test_bdist_rpm.py +++ b/distutils/tests/test_bdist_rpm.py @@ -25,10 +25,9 @@ @pytest.mark.usefixtures('save_env') -class BuildRpmTestCase( +class TestBuildRpm( support.TempdirManager, support.LoggingSilencer, - unittest.TestCase, ): def setUp(self): try: diff --git a/distutils/tests/test_bdist_wininst.py b/distutils/tests/test_bdist_wininst.py index 4c76b613b5..8bc217af68 100644 --- a/distutils/tests/test_bdist_wininst.py +++ b/distutils/tests/test_bdist_wininst.py @@ -17,9 +17,7 @@ getattr(bdist_wininst, '_unsupported', False), 'bdist_wininst is not supported in this install', ) -class BuildWinInstTestCase( - support.TempdirManager, support.LoggingSilencer, unittest.TestCase -): +class TestBuildWinInst(support.TempdirManager, support.LoggingSilencer): def test_get_exe_bytes(self): # issue5731: command was broken on non-windows platforms diff --git a/distutils/tests/test_build_clib.py b/distutils/tests/test_build_clib.py index 6ded9099c5..2048e29a52 100644 --- a/distutils/tests/test_build_clib.py +++ b/distutils/tests/test_build_clib.py @@ -11,9 +11,7 @@ import pytest -class BuildCLibTestCase( - support.TempdirManager, support.LoggingSilencer, unittest.TestCase -): +class TestBuildCLib(support.TempdirManager, support.LoggingSilencer): def test_check_library_dist(self): pkg_dir, dist = self.create_dist() cmd = build_clib(dist) diff --git a/distutils/tests/test_build_py.py b/distutils/tests/test_build_py.py index a60b3c2acc..cab5c65b65 100644 --- a/distutils/tests/test_build_py.py +++ b/distutils/tests/test_build_py.py @@ -13,9 +13,7 @@ @support.combine_markers -class BuildPyTestCase( - support.TempdirManager, support.LoggingSilencer, unittest.TestCase -): +class TestBuildPy(support.TempdirManager, support.LoggingSilencer): def test_package_data(self): sources = self.mkdtemp() f = open(os.path.join(sources, "__init__.py"), "w") diff --git a/distutils/tests/test_build_scripts.py b/distutils/tests/test_build_scripts.py index fbcb4372cb..00d7fc5929 100644 --- a/distutils/tests/test_build_scripts.py +++ b/distutils/tests/test_build_scripts.py @@ -1,7 +1,6 @@ """Tests for distutils.command.build_scripts.""" import os -import unittest from distutils.command.build_scripts import build_scripts from distutils.core import Distribution @@ -10,9 +9,7 @@ from distutils.tests import support -class BuildScriptsTestCase( - support.TempdirManager, support.LoggingSilencer, unittest.TestCase -): +class TestBuildScripts(support.TempdirManager, support.LoggingSilencer): def test_default_settings(self): cmd = self.get_build_scripts_cmd("/foo/bar", []) assert not cmd.force diff --git a/distutils/tests/test_check.py b/distutils/tests/test_check.py index c5b4913e4b..7ad3cdfa8c 100644 --- a/distutils/tests/test_check.py +++ b/distutils/tests/test_check.py @@ -18,7 +18,7 @@ @support.combine_markers -class CheckTestCase(support.LoggingSilencer, support.TempdirManager, unittest.TestCase): +class TestCheck(support.LoggingSilencer, support.TempdirManager): def _run(self, metadata=None, cwd=None, **options): if metadata is None: metadata = {} diff --git a/distutils/tests/test_clean.py b/distutils/tests/test_clean.py index 6193a1d9c2..4166bb7e9b 100644 --- a/distutils/tests/test_clean.py +++ b/distutils/tests/test_clean.py @@ -1,12 +1,11 @@ """Tests for distutils.command.clean.""" import os -import unittest from distutils.command.clean import clean from distutils.tests import support -class cleanTestCase(support.TempdirManager, support.LoggingSilencer, unittest.TestCase): +class TestClean(support.TempdirManager, support.LoggingSilencer): def test_simple_run(self): pkg_dir, dist = self.create_dist() cmd = clean(dist) diff --git a/distutils/tests/test_cmd.py b/distutils/tests/test_cmd.py index ecaee7e709..f5104e1db7 100644 --- a/distutils/tests/test_cmd.py +++ b/distutils/tests/test_cmd.py @@ -15,7 +15,7 @@ def initialize_options(self): pass -class CommandTestCase(unittest.TestCase): +class TestCommand(unittest.TestCase): def setUp(self): dist = Distribution() self.cmd = MyCmd(dist) diff --git a/distutils/tests/test_dep_util.py b/distutils/tests/test_dep_util.py index e5d78c58ae..2dcce1dd02 100644 --- a/distutils/tests/test_dep_util.py +++ b/distutils/tests/test_dep_util.py @@ -1,5 +1,4 @@ """Tests for distutils.dep_util.""" -import unittest import os from distutils.dep_util import newer, newer_pairwise, newer_group @@ -8,7 +7,7 @@ import pytest -class DepUtilTestCase(support.TempdirManager, unittest.TestCase): +class TestDepUtil(support.TempdirManager): def test_newer(self): tmpdir = self.mkdtemp() diff --git a/distutils/tests/test_extension.py b/distutils/tests/test_extension.py index 271c245909..f86af07376 100644 --- a/distutils/tests/test_extension.py +++ b/distutils/tests/test_extension.py @@ -1,5 +1,4 @@ """Tests for distutils.extension.""" -import unittest import os import warnings @@ -9,7 +8,7 @@ import pytest -class ExtensionTestCase(unittest.TestCase): +class TestExtension: def test_read_setup_file(self): # trying to read a Setup file # (sample extracted from the PyGame project) diff --git a/distutils/tests/test_filelist.py b/distutils/tests/test_filelist.py index c42bc42b66..2607182064 100644 --- a/distutils/tests/test_filelist.py +++ b/distutils/tests/test_filelist.py @@ -1,7 +1,6 @@ """Tests for distutils.filelist.""" import os import re -import unittest from distutils import debug from distutils.log import WARN from distutils.errors import DistutilsTemplateError @@ -36,7 +35,7 @@ def make_local_path(s): return s.replace('/', os.sep) -class FileListTestCase(support.LoggingSilencer, unittest.TestCase): +class TestFileList(support.LoggingSilencer): def assertNoWarnings(self): assert self.get_logs(WARN) == [] self.clear_logs() @@ -302,7 +301,7 @@ def test_process_template(self): self.assertWarnings() -class FindAllTestCase(unittest.TestCase): +class TestFindAll: @os_helper.skip_unless_symlink def test_missing_symlink(self): with os_helper.temp_cwd(): diff --git a/distutils/tests/test_install_data.py b/distutils/tests/test_install_data.py index 33e0de64b2..f77c790fca 100644 --- a/distutils/tests/test_install_data.py +++ b/distutils/tests/test_install_data.py @@ -1,6 +1,5 @@ """Tests for distutils.command.install_data.""" import os -import unittest import pytest @@ -9,10 +8,9 @@ @pytest.mark.usefixtures('save_env') -class InstallDataTestCase( +class TestInstallData( support.TempdirManager, support.LoggingSilencer, - unittest.TestCase, ): def test_simple_run(self): pkg_dir, dist = self.create_dist() diff --git a/distutils/tests/test_install_headers.py b/distutils/tests/test_install_headers.py index e91fe14ca0..7594f5af3c 100644 --- a/distutils/tests/test_install_headers.py +++ b/distutils/tests/test_install_headers.py @@ -1,6 +1,5 @@ """Tests for distutils.command.install_headers.""" import os -import unittest import pytest @@ -9,10 +8,9 @@ @pytest.mark.usefixtures('save_env') -class InstallHeadersTestCase( +class TestInstallHeaders( support.TempdirManager, support.LoggingSilencer, - unittest.TestCase, ): def test_simple_run(self): # we have two headers diff --git a/distutils/tests/test_install_lib.py b/distutils/tests/test_install_lib.py index 601a81ff98..d8192e06ce 100644 --- a/distutils/tests/test_install_lib.py +++ b/distutils/tests/test_install_lib.py @@ -14,10 +14,9 @@ @support.combine_markers @pytest.mark.usefixtures('save_env') -class InstallLibTestCase( +class TestInstallLib( support.TempdirManager, support.LoggingSilencer, - unittest.TestCase, ): def test_finalize_options(self): dist = self.create_dist()[1] diff --git a/distutils/tests/test_install_scripts.py b/distutils/tests/test_install_scripts.py index 8c69c646d0..0d17f11b5b 100644 --- a/distutils/tests/test_install_scripts.py +++ b/distutils/tests/test_install_scripts.py @@ -1,7 +1,6 @@ """Tests for distutils.command.install_scripts.""" import os -import unittest from distutils.command.install_scripts import install_scripts from distutils.core import Distribution @@ -9,9 +8,7 @@ from distutils.tests import support -class InstallScriptsTestCase( - support.TempdirManager, support.LoggingSilencer, unittest.TestCase -): +class TestInstallScripts(support.TempdirManager, support.LoggingSilencer): def test_default_settings(self): dist = Distribution() dist.command_obj["build"] = support.DummyCommand(build_scripts="/foo/bar") diff --git a/distutils/tests/test_msvc9compiler.py b/distutils/tests/test_msvc9compiler.py index 29c5530b04..fe5693e1d8 100644 --- a/distutils/tests/test_msvc9compiler.py +++ b/distutils/tests/test_msvc9compiler.py @@ -1,6 +1,5 @@ """Tests for distutils.msvc9compiler.""" import sys -import unittest import os from distutils.errors import DistutilsPlatformError @@ -101,8 +100,8 @@ SKIP_MESSAGE = "These tests are only for win32" -@unittest.skipUnless(SKIP_MESSAGE is None, SKIP_MESSAGE) -class msvc9compilerTestCase(support.TempdirManager, unittest.TestCase): +@pytest.mark.skipif('SKIP_MESSAGE', reason=SKIP_MESSAGE) +class Testmsvc9compiler(support.TempdirManager): def test_no_compiler(self): # makes sure query_vcvarsall raises # a DistutilsPlatformError if the compiler diff --git a/distutils/tests/test_msvccompiler.py b/distutils/tests/test_msvccompiler.py index ddca24e544..db4694e1b3 100644 --- a/distutils/tests/test_msvccompiler.py +++ b/distutils/tests/test_msvccompiler.py @@ -14,7 +14,7 @@ needs_winreg = pytest.mark.skipif('not hasattr(_msvccompiler, "winreg")') -class msvccompilerTestCase(support.TempdirManager, unittest.TestCase): +class Testmsvccompiler(support.TempdirManager): def test_no_compiler(self): # makes sure query_vcvarsall raises # a DistutilsPlatformError if the compiler @@ -85,7 +85,7 @@ def __bool__(self): return not self.exc_info -class TestSpawn(unittest.TestCase): +class TestSpawn: def test_concurrent_safe(self): """ Concurrent calls to spawn should have consistent results. diff --git a/distutils/tests/test_spawn.py b/distutils/tests/test_spawn.py index 91fb4c580b..c28b8ba594 100644 --- a/distutils/tests/test_spawn.py +++ b/distutils/tests/test_spawn.py @@ -14,7 +14,7 @@ import pytest -class SpawnTestCase(support.TempdirManager, support.LoggingSilencer, unittest.TestCase): +class TestSpawn(support.TempdirManager, support.LoggingSilencer): @unittest.skipUnless(os.name in ('nt', 'posix'), 'Runs only under posix or nt') def test_spawn(self): tmpdir = self.mkdtemp() diff --git a/distutils/tests/test_text_file.py b/distutils/tests/test_text_file.py index e53bbcbc91..7c8dc5be54 100644 --- a/distutils/tests/test_text_file.py +++ b/distutils/tests/test_text_file.py @@ -1,6 +1,5 @@ """Tests for distutils.text_file.""" import os -import unittest from distutils.text_file import TextFile from distutils.tests import support @@ -12,7 +11,7 @@ """ -class TextFileTestCase(support.TempdirManager, unittest.TestCase): +class TestTextFile(support.TempdirManager): def test_class(self): # old tests moved from text_file.__main__ # so they are really called by the buildbots From c0a4ea65ab68c8c6cb6ad54cc646c58bede6f0f4 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Sun, 31 Jul 2022 22:04:56 -0400 Subject: [PATCH 09/16] Remove compatibility shims for Setuptools. --- distutils/command/bdist.py | 31 ++++++++++--------------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/distutils/command/bdist.py b/distutils/command/bdist.py index 53f1321450..4af1b8e668 100644 --- a/distutils/command/bdist.py +++ b/distutils/command/bdist.py @@ -20,12 +20,6 @@ def show_formats(): pretty_printer.print_help("List of available distribution formats:") -class ListCompat(dict): - # adapter to allow for Setuptools compatibility in format_commands - def append(self, item): - return - - class bdist(Command): description = "create a built (binary) distribution" @@ -71,23 +65,18 @@ class bdist(Command): default_format = {'posix': 'gztar', 'nt': 'zip'} # Define commands in preferred order for the --help-formats option - format_commands = ListCompat( - { - 'rpm': ('bdist_rpm', "RPM distribution"), - 'gztar': ('bdist_dumb', "gzip'ed tar file"), - 'bztar': ('bdist_dumb', "bzip2'ed tar file"), - 'xztar': ('bdist_dumb', "xz'ed tar file"), - 'ztar': ('bdist_dumb', "compressed tar file"), - 'tar': ('bdist_dumb', "tar file"), - 'wininst': ('bdist_wininst', "Windows executable installer"), - 'zip': ('bdist_dumb', "ZIP file"), - 'msi': ('bdist_msi', "Microsoft Installer"), - } + format_commands = dict( + rpm=('bdist_rpm', "RPM distribution"), + gztar=('bdist_dumb', "gzip'ed tar file"), + bztar=('bdist_dumb', "bzip2'ed tar file"), + xztar=('bdist_dumb', "xz'ed tar file"), + ztar=('bdist_dumb', "compressed tar file"), + tar=('bdist_dumb', "tar file"), + wininst=('bdist_wininst', "Windows executable installer"), + zip=('bdist_dumb', "ZIP file"), + msi=('bdist_msi', "Microsoft Installer"), ) - # for compatibility until Setuptools references only format_commands - format_command = format_commands - def initialize_options(self): self.bdist_base = None self.plat_name = None From c899a998017bc4af1d7ed9c88c759b24f5646621 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Mon, 1 Aug 2022 21:20:20 -0400 Subject: [PATCH 10/16] Replace save/restore of argv and cwd as pytest fixtures. --- conftest.py | 19 ++++++++++++ distutils/tests/test_bdist_dumb.py | 14 ++------- distutils/tests/test_bdist_rpm.py | 25 ++++++--------- distutils/tests/test_core.py | 4 +-- distutils/tests/test_dist.py | 49 ++++++++++++------------------ 5 files changed, 52 insertions(+), 59 deletions(-) diff --git a/conftest.py b/conftest.py index 1354387aaf..90efd3230f 100644 --- a/conftest.py +++ b/conftest.py @@ -1,4 +1,5 @@ import os +import sys import platform import pytest @@ -70,3 +71,21 @@ def distutils_managed_tempdir(request): while self.tempdirs: tmpdir = self.tempdirs.pop() os_helper.rmtree(tmpdir) + + +@pytest.fixture +def save_argv(): + orig = sys.argv[:] + try: + yield + finally: + sys.argv[:] = orig + + +@pytest.fixture +def save_cwd(): + orig = os.getcwd() + try: + yield + finally: + os.chdir(orig) diff --git a/distutils/tests/test_bdist_dumb.py b/distutils/tests/test_bdist_dumb.py index 9c599a8d92..8624a4290d 100644 --- a/distutils/tests/test_bdist_dumb.py +++ b/distutils/tests/test_bdist_dumb.py @@ -20,22 +20,14 @@ """ +@support.combine_markers @pytest.mark.usefixtures('save_env') +@pytest.mark.usefixtures('save_argv') +@pytest.mark.usefixtures('save_cwd') class TestBuildDumb( support.TempdirManager, support.LoggingSilencer, ): - def setUp(self): - super().setUp() - self.old_location = os.getcwd() - self.old_sys_argv = sys.argv, sys.argv[:] - - def tearDown(self): - os.chdir(self.old_location) - sys.argv = self.old_sys_argv[0] - sys.argv[:] = self.old_sys_argv[1] - super().tearDown() - @pytest.mark.usefixtures('needs_zlib') def test_simple_built(self): diff --git a/distutils/tests/test_bdist_rpm.py b/distutils/tests/test_bdist_rpm.py index c4b21f60ff..411d09ebea 100644 --- a/distutils/tests/test_bdist_rpm.py +++ b/distutils/tests/test_bdist_rpm.py @@ -24,26 +24,21 @@ """ +@pytest.fixture(autouse=True) +def sys_executable_encodable(): + try: + sys.executable.encode('UTF-8') + except UnicodeEncodeError: + pytest.skip("sys.executable is not encodable to UTF-8") + + @pytest.mark.usefixtures('save_env') +@pytest.mark.usefixtures('save_argv') +@pytest.mark.usefixtures('save_cwd') class TestBuildRpm( support.TempdirManager, support.LoggingSilencer, ): - def setUp(self): - try: - sys.executable.encode("UTF-8") - except UnicodeEncodeError: - raise unittest.SkipTest("sys.executable is not encodable to UTF-8") - - super().setUp() - self.old_location = os.getcwd() - self.old_sys_argv = sys.argv, sys.argv[:] - - def tearDown(self): - os.chdir(self.old_location) - sys.argv = self.old_sys_argv[0] - sys.argv[:] = self.old_sys_argv[1] - super().tearDown() # XXX I am unable yet to make this test work without # spurious sdtout/stderr output under Mac OS X diff --git a/distutils/tests/test_core.py b/distutils/tests/test_core.py index 08eccdb1a2..ef085a8530 100644 --- a/distutils/tests/test_core.py +++ b/distutils/tests/test_core.py @@ -60,19 +60,17 @@ def main(): @pytest.mark.usefixtures('save_env') +@pytest.mark.usefixtures('save_argv') class CoreTestCase(unittest.TestCase): def setUp(self): super().setUp() self.old_stdout = sys.stdout self.cleanup_testfn() - self.old_argv = sys.argv, sys.argv[:] self.addCleanup(log.set_threshold, log._global_log.threshold) def tearDown(self): sys.stdout = self.old_stdout self.cleanup_testfn() - sys.argv = self.old_argv[0] - sys.argv[:] = self.old_argv[1] super().tearDown() def cleanup_testfn(self): diff --git a/distutils/tests/test_dist.py b/distutils/tests/test_dist.py index dd3db860fc..a77e8c5de6 100644 --- a/distutils/tests/test_dist.py +++ b/distutils/tests/test_dist.py @@ -5,6 +5,7 @@ import unittest import warnings import textwrap +import functools from unittest import mock @@ -42,23 +43,18 @@ def find_config_files(self): return self._config_files +@pytest.fixture +def clear_argv(): + del sys.argv[1:] + + @support.combine_markers @pytest.mark.usefixtures('save_env') -class DistributionTestCase( +@pytest.mark.usefixtures('save_argv') +class TestDistributionBehavior( support.LoggingSilencer, support.TempdirManager, - unittest.TestCase, ): - def setUp(self): - super().setUp() - self.argv = sys.argv, sys.argv[:] - del sys.argv[1:] - - def tearDown(self): - sys.argv = self.argv[0] - sys.argv[:] = self.argv[1] - super().tearDown() - def create_distribution(self, configfiles=()): d = TestDistribution() d._config_files = configfiles @@ -66,12 +62,12 @@ def create_distribution(self, configfiles=()): d.parse_command_line() return d - def test_command_packages_unspecified(self): + def test_command_packages_unspecified(self, clear_argv): sys.argv.append("build") d = self.create_distribution() assert d.get_command_packages() == ["distutils.command"] - def test_command_packages_cmdline(self): + def test_command_packages_cmdline(self, clear_argv): from distutils.tests.test_dist import test_dist sys.argv.extend( @@ -97,9 +93,9 @@ def test_command_packages_cmdline(self): 'distutils' not in Distribution.parse_config_files.__module__, 'Cannot test when virtualenv has monkey-patched Distribution.', ) - def test_venv_install_options(self): + def test_venv_install_options(self, request): sys.argv.append("install") - self.addCleanup(os.unlink, TESTFN) + request.addfinalizer(functools.partial(os.unlink, TESTFN)) fakepath = '/somedir' @@ -160,9 +156,9 @@ def test_venv_install_options(self): for key in result_dict.keys(): assert key not in d.command_options.get('install', {}) - def test_command_packages_configfile(self): + def test_command_packages_configfile(self, request, clear_argv): sys.argv.append("build") - self.addCleanup(os.unlink, TESTFN) + request.addfinalizer(functools.partial(os.unlink, TESTFN)) f = open(TESTFN, "w") try: print("[global]", file=f) @@ -184,7 +180,7 @@ def test_command_packages_configfile(self): d = self.create_distribution([TESTFN]) assert d.get_command_packages() == ["distutils.command"] - def test_empty_options(self): + def test_empty_options(self, request): # an empty options dictionary should not stay in the # list of attributes @@ -194,7 +190,8 @@ def test_empty_options(self): def _warn(msg): warns.append(msg) - self.addCleanup(setattr, warnings, 'warn', warnings.warn) + request.addfinalizer( + functools.partial(setattr, warnings, 'warn', warnings.warn)) warnings.warn = _warn dist = Distribution( attrs={ @@ -274,16 +271,8 @@ def _expander(path): @pytest.mark.usefixtures('save_env') -class MetadataTestCase(support.TempdirManager, unittest.TestCase): - def setUp(self): - super().setUp() - self.argv = sys.argv, sys.argv[:] - - def tearDown(self): - sys.argv = self.argv[0] - sys.argv[:] = self.argv[1] - super().tearDown() - +@pytest.mark.usefixtures('save_argv') +class MetadataTestCase(support.TempdirManager): def format_metadata(self, dist): sio = io.StringIO() dist.metadata.write_pkg_file(sio) From 0f95b39976d3fcc928c9c66b77ca0e1533e242e9 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Mon, 1 Aug 2022 21:31:43 -0400 Subject: [PATCH 11/16] Move setup/teardown from BuildExtTestCase into a fixture. --- distutils/tests/test_build_ext.py | 51 ++++++++++++++----------------- 1 file changed, 23 insertions(+), 28 deletions(-) diff --git a/distutils/tests/test_build_ext.py b/distutils/tests/test_build_ext.py index 3e97907f9a..16d4873886 100644 --- a/distutils/tests/test_build_ext.py +++ b/distutils/tests/test_build_ext.py @@ -2,6 +2,7 @@ import os from io import StringIO import textwrap +import site from distutils.core import Distribution from distutils.command.build_ext import build_ext @@ -11,6 +12,7 @@ LoggingSilencer, copy_xxmodule_c, fixup_build_ext, + combine_markers, ) from distutils.extension import Extension from distutils.errors import ( @@ -32,35 +34,29 @@ ALREADY_TESTED = False -class BuildExtTestCase(TempdirManager, LoggingSilencer, unittest.TestCase): - def setUp(self): - # Create a simple test environment - super().setUp() - self.tmp_dir = self.mkdtemp() - import site - - self.old_user_base = site.USER_BASE - site.USER_BASE = self.mkdtemp() - from distutils.command import build_ext +@pytest.fixture() +def user_site_dir(request): + self = request.instance + self.tmp_dir = self.mkdtemp() + from distutils.command import build_ext - build_ext.USER_BASE = site.USER_BASE + orig_user_base = site.USER_BASE - # bpo-30132: On Windows, a .pdb file may be created in the current - # working directory. Create a temporary working directory to cleanup - # everything at the end of the test. - change_cwd = os_helper.change_cwd(self.tmp_dir) - change_cwd.__enter__() - self.addCleanup(change_cwd.__exit__, None, None, None) + site.USER_BASE = self.mkdtemp() + build_ext.USER_BASE = site.USER_BASE - def tearDown(self): - import site + # bpo-30132: On Windows, a .pdb file may be created in the current + # working directory. Create a temporary working directory to cleanup + # everything at the end of the test. + with os_helper.change_cwd(self.tmp_dir): + yield - site.USER_BASE = self.old_user_base - from distutils.command import build_ext + site.USER_BASE = orig_user_base + build_ext.USER_BASE = orig_user_base - build_ext.USER_BASE = self.old_user_base - super().tearDown() +@pytest.mark.usefixtures('user_site_dir') +class TestBuildExt(TempdirManager, LoggingSilencer): def build_ext(self, *args, **kwargs): return build_ext(*args, **kwargs) @@ -458,6 +454,7 @@ def test_ext_fullpath(self): assert wanted == path @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX') + @pytest.mark.usefixtures('save_env') def test_deployment_target_default(self): # Issue 9516: Test that, in the absence of the environment variable, # an extension module is compiled with the same deployment target as @@ -465,6 +462,7 @@ def test_deployment_target_default(self): self._try_compile_deployment_target('==', None) @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX') + @pytest.mark.usefixtures('save_env') def test_deployment_target_too_low(self): # Issue 9516: Test that an extension module is not allowed to be # compiled with a deployment target less than that of the interpreter. @@ -472,6 +470,7 @@ def test_deployment_target_too_low(self): self._try_compile_deployment_target('>', '10.1') @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX') + @pytest.mark.usefixtures('save_env') def test_deployment_target_higher_ok(self): # Issue 9516: Test that an extension module can be compiled with a # deployment target higher than that of the interpreter: the ext @@ -485,10 +484,6 @@ def test_deployment_target_higher_ok(self): self._try_compile_deployment_target('<', deptarget) def _try_compile_deployment_target(self, operator, target): - orig_environ = os.environ - os.environ = orig_environ.copy() - self.addCleanup(setattr, os, 'environ', orig_environ) - if target is None: if os.environ.get('MACOSX_DEPLOYMENT_TARGET'): del os.environ['MACOSX_DEPLOYMENT_TARGET'] @@ -557,7 +552,7 @@ def _try_compile_deployment_target(self, operator, target): self.fail("Wrong deployment target during compilation") -class ParallelBuildExtTestCase(BuildExtTestCase): +class TestParallelBuildExt(TestBuildExt): def build_ext(self, *args, **kwargs): build_ext = super().build_ext(*args, **kwargs) build_ext.parallel = True From 43a44e3cba1ef5d980647c7a4cfb33b344f91949 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Tue, 2 Aug 2022 20:20:19 -0400 Subject: [PATCH 12/16] Add tests capturing failure. Ref pypa/distutils#164. --- distutils/unixccompiler.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/distutils/unixccompiler.py b/distutils/unixccompiler.py index e4d930ac91..b7713d075d 100644 --- a/distutils/unixccompiler.py +++ b/distutils/unixccompiler.py @@ -365,6 +365,22 @@ def find_library_file(self, dirs, lib, debug=0): data to go on: GCC seems to prefer the shared library, so assume that *all* Unix C compilers do, ignoring even GCC's "-static" option. + + >>> compiler = UnixCCompiler() + >>> compiler._library_root = lambda dir: dir + >>> monkeypatch = getfixture('monkeypatch') + >>> monkeypatch.setattr(os.path, 'exists', lambda d: 'existing' in d) + >>> dirs = ('/foo/bar/missing', '/foo/bar/existing') + >>> compiler.find_library_file(dirs, 'abc') + '/foo/bar/existing/libabc.dylib' + >>> compiler.find_library_file(reversed(dirs), 'abc') + '/foo/bar/existing/libabc.dylib' + >>> monkeypatch.setattr(os.path, 'exists', + ... lambda d: 'existing' in d and '.a' in d) + >>> compiler.find_library_file(dirs, 'abc') + '/foo/bar/existing/libabc.a' + >>> compiler.find_library_file(reversed(dirs), 'abc') + '/foo/bar/existing/libabc.a' """ lib_names = ( self.library_filename(lib, lib_type=type) From f700a6b5f9965b3a886827d523271a2c9388edb5 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Tue, 2 Aug 2022 20:21:53 -0400 Subject: [PATCH 13/16] Use itertools.product to compute the product of two generators. Fixes pypa/distutils#164. --- distutils/tests/test_dist.py | 3 ++- distutils/unixccompiler.py | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/distutils/tests/test_dist.py b/distutils/tests/test_dist.py index a77e8c5de6..c962d3f3ac 100644 --- a/distutils/tests/test_dist.py +++ b/distutils/tests/test_dist.py @@ -191,7 +191,8 @@ def _warn(msg): warns.append(msg) request.addfinalizer( - functools.partial(setattr, warnings, 'warn', warnings.warn)) + functools.partial(setattr, warnings, 'warn', warnings.warn) + ) warnings.warn = _warn dist = Distribution( attrs={ diff --git a/distutils/unixccompiler.py b/distutils/unixccompiler.py index b7713d075d..71aa4beaf0 100644 --- a/distutils/unixccompiler.py +++ b/distutils/unixccompiler.py @@ -17,6 +17,7 @@ import sys import re import shlex +import itertools from distutils import sysconfig from distutils.dep_util import newer @@ -389,8 +390,9 @@ def find_library_file(self, dirs, lib, debug=0): searched = ( os.path.join(root, lib_name) - for root in map(self._library_root, dirs) - for lib_name in lib_names + for root, lib_name in itertools.product( + map(self._library_root, dirs), lib_names + ) ) found = filter(os.path.exists, searched) From 107c6cfa280f979632b46ea0279a725b6d3863f9 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Tue, 2 Aug 2022 20:45:17 -0400 Subject: [PATCH 14/16] Extract 'roots' variable. --- distutils/unixccompiler.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/distutils/unixccompiler.py b/distutils/unixccompiler.py index 71aa4beaf0..67544b7cd3 100644 --- a/distutils/unixccompiler.py +++ b/distutils/unixccompiler.py @@ -388,11 +388,11 @@ def find_library_file(self, dirs, lib, debug=0): for type in 'dylib xcode_stub shared static'.split() ) + roots = map(self._library_root, dirs) + searched = ( os.path.join(root, lib_name) - for root, lib_name in itertools.product( - map(self._library_root, dirs), lib_names - ) + for root, lib_name in itertools.product(roots, lib_names) ) found = filter(os.path.exists, searched) From c397f4c164e0a6f49a1ac3a70f5c80fe05785ed6 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Tue, 2 Aug 2022 20:51:35 -0400 Subject: [PATCH 15/16] Add test compatibility on Windows. --- distutils/unixccompiler.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/distutils/unixccompiler.py b/distutils/unixccompiler.py index 67544b7cd3..4ab771a475 100644 --- a/distutils/unixccompiler.py +++ b/distutils/unixccompiler.py @@ -361,7 +361,7 @@ def _library_root(dir): return os.path.join(match.group(1), dir[1:]) if apply_root else dir def find_library_file(self, dirs, lib, debug=0): - """ + r""" Second-guess the linker with not much hard data to go on: GCC seems to prefer the shared library, so assume that *all* Unix C compilers do, @@ -372,15 +372,15 @@ def find_library_file(self, dirs, lib, debug=0): >>> monkeypatch = getfixture('monkeypatch') >>> monkeypatch.setattr(os.path, 'exists', lambda d: 'existing' in d) >>> dirs = ('/foo/bar/missing', '/foo/bar/existing') - >>> compiler.find_library_file(dirs, 'abc') + >>> compiler.find_library_file(dirs, 'abc').replace('\\', '/') '/foo/bar/existing/libabc.dylib' - >>> compiler.find_library_file(reversed(dirs), 'abc') + >>> compiler.find_library_file(reversed(dirs), 'abc').replace('\\', '/') '/foo/bar/existing/libabc.dylib' >>> monkeypatch.setattr(os.path, 'exists', ... lambda d: 'existing' in d and '.a' in d) - >>> compiler.find_library_file(dirs, 'abc') + >>> compiler.find_library_file(dirs, 'abc').replace('\\', '/') '/foo/bar/existing/libabc.a' - >>> compiler.find_library_file(reversed(dirs), 'abc') + >>> compiler.find_library_file(reversed(dirs), 'abc').replace('\\', '/') '/foo/bar/existing/libabc.a' """ lib_names = ( From 4ae3db79ed0b5d2b9417be998f5cbf1004bf7a03 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Tue, 2 Aug 2022 21:06:24 -0400 Subject: [PATCH 16/16] Update changelog --- changelog.d/3480.misc.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/3480.misc.rst diff --git a/changelog.d/3480.misc.rst b/changelog.d/3480.misc.rst new file mode 100644 index 0000000000..244f4ac08b --- /dev/null +++ b/changelog.d/3480.misc.rst @@ -0,0 +1 @@ +Merge with pypa/distutils@c397f4c